Legal Information

DirectX 8.0
Programmer's Reference

Information in this document, including URL and other Internet Web site references, is subject to change without notice. The example companies, organizations, products, people and events depicted herein are fictitious. No association with any real company, organization, product, person or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property.

© 1995-2000 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, Windows, Windows NT, ActiveX, Direct3D, DirectAnimation, DirectDraw, DirectInput, DirectMusic, DirectPlay, DirectShow, DirectSound, DirectX, Natural, and Win32 are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries.

Roland GS Sound Set/Microsoft (R) 1996 Roland Corporation U.S.

Roland is a registered trademark of the Roland Corporation.

The names of actual companies and products mentioned herein may be the trademarks of their respective owners.

Note: Manufacturers of telecommunications devices implementing this API must ensure compliance with section 255 of the telecommunications act of 1996.

Copyright Warning

Special Note and Warning The Roland GS Sound Set/Microsoft, the "Sample Set", incorporates the SoundCanvas Sound Set. Roland Corporation U.S. owns the Sample Set and all copyrights pertaining thereto and has licensed the Sample Set for use solely on Microsoft Operating Systems Products and Microsoft Application Products.

Roland reserves all rights to the Sample Set not expressly granted by Roland Corporation U.S. or by Microsoft under the terms of Microsoft's End User License Agreement.

The Sample Set may only be redistributed with your software application as an integral component of a Microsoft Operating System Product and under the terms of Microsoft's End User License Agreement. All other uses of the Sample Set require a separate written license from Roland Corporation U.S.

The Sample Set may not be used, copied or redistributed in hardware ROM or similar technology of any device without prior express written permission from an authorized representative of Roland Corporation U.S. The Sample Set may not be redistributed with any Musical Instrument. A "Musical Instrument" is any device that is capable of generating musical sounds without being directly connected to a computer with a licensed Microsoft Operating System. You may not modify the Sample Set under any circumstances.

Built on Wednesday, October 04, 2000


Introducing DirectX 8.0

Microsoft® DirectX® is a set of low-level application programming interfaces (APIs) for creating games and other high-performance multimedia applications. It includes support for two-dimensional (2-D) and three-dimensional (3-D) graphics, sound effects and music, input devices, and support for networked applications such as multiplayer games.

This document gives general introductory information about DirectX 8.0. Information is divided into the following sections.

  • What's New in DirectX 8.0
  • Using the DirectX 8.0 Documentation
  • DirectX 8.0 Components
  • DirectX Tools
  • Programming DirectX with C/C++
  • Further Information


What's New in DirectX 8.0

The following are some of the new features supported by Microsoft® DirectX® 8.0.

Complete integration of DirectDraw and Direct3D
Microsoft DirectDraw® and Microsoft Direct3D® are merged into a single DirectX Graphics component. The API has been extensively updated to make it even easier to use and to support the latest graphics hardware.
DirectMusic and DirectSound more integrated
Microsoft DirectMusic® and Microsoft DirectSound® are much more tightly integrated than with DirectX 7.0. Wave files or resources can now be loaded by the DirectMusic loader, and played through the DirectMusic performance, synchronized with MIDI notes.
DirectPlay updated
The Microsoft DirectPlay® component has been extensively updated to increase its capabilities and improve its ease-of-use. In particular, DirectPlay now supports voice communication between players.
DirectInput updated
Microsoft DirectInput® introduces one major new feature: action mapping. Action mapping enables you to establish a connection between input actions and input devices that does not depend on the existence of particular device objects. It simplifies the input loop and reduces the need for custom game drivers, custom device profilers, and custom configuration user interfaces in games.
DirectShow included in DirectX
Microsoft DirectShow® is now part of DirectX and has been updated for this release.
Debug build available
You can use the DirectX Control Panel Application to switch between the debug and retail builds of DirectInput, Direct3D, and DirectMusic. To enable this feature, select the debug option when you install the SDK. This option installs both debug and retail DLLs on your system. The retail option installs only the retail DLLs.


Using the DirectX 8.0 Documentation

The following conventions are used in the syntax of methods, functions, and other API elements, as well as typographic conventions used in explanatory material and sample code.

Convention | Meaning
Italic text | Denotes a placeholder or variable. You must provide the actual value. For example, the statement SetCursorPos(X, Y) requires you to substitute values for the X and Y parameters.
Bold text | Denotes a function, procedure, structure, macro, interface, method, data type, or other keyword in the programming interface or language.
[] | Encloses optional parameters.
... | Specifies that the preceding item may be repeated.
FULL BOLD CAPITALS | Used for most type and structure names.
FULL CAPITALS | Used for enumeration values, flags, and constants.
monospace | Used for code examples and syntax spacing.
. . . | Represents an omitted portion of a sample application.


DirectX 8.0 Components

Microsoft® DirectX® 8.0 is made up of the following components.

  • DirectX Graphics combines the Microsoft DirectDraw® and Microsoft Direct3D® components of previous DirectX versions into a single API that you can use for all graphics programming. The component includes the Direct3DX utility library that simplifies many graphics programming tasks.
  • DirectX Audio combines the Microsoft DirectSound® and Microsoft DirectMusic® components of previous DirectX versions into a single API that you can use for all audio programming.
  • Microsoft DirectInput® provides support for a variety of input devices, including full support for force-feedback technology.
  • Microsoft DirectPlay® provides support for multiplayer networked games.
  • Microsoft DirectShow® provides for high-quality capture and playback of multimedia streams.
  • Microsoft DirectSetup is a simple API that provides one-call installation of the DirectX components.


DirectX Tools

The following tools can be useful in developing and troubleshooting Microsoft® DirectX® applications.

  • DirectX Caps Viewer
  • DirectX Control Panel Application
  • DirectX Diagnostic Tool


DirectX Caps Viewer

Description

The Microsoft® DirectX® Caps Viewer tool enumerates devices and capabilities for all the components of DirectX.

Path

Executable: (SDK root)\Bin\DXUtils\DXCapsViewer.exe

User's Guide

Select items in the tree view. Information appears in the pane on the right.


DirectX Control Panel Application

You can use the Microsoft® DirectX® Control Panel utility, which is installed with the SDK, to examine and modify the properties of DirectX components. This utility contains tabs for each DirectX component. Using this utility you can:

  • Obtain version information for DirectX components.
  • Change the debug output level and debug settings to aid in troubleshooting during the development process.
  • View specific driver and hardware support information for DirectX components.
  • Toggle between debug and retail versions of the run times for Microsoft Direct3D®, DirectMusic®, and DirectInput®.


DirectX Diagnostic Tool

Description

Microsoft® DirectX® Diagnostic Tool gathers information on the system and the DirectX components installed on it, as well as providing a number of tests to ensure that components are working properly. A special version of this tool installed with the DirectX SDK enables developers to report problems directly to the DirectX development team.

Path

Executable: (SDK root)\Bin\DXUtils\Dxdiag.exe

User's Guide

To display the DirectX Diagnostic Tool Help file, click the Help button.


Programming DirectX with C/C++

Most Microsoft® DirectX® application development with C/C++ involves conventional programming techniques. However, there are several aspects of DirectX programming that may be unfamiliar to some developers. This section provides a brief overview of several specialized topics, along with some guidelines for compiling and debugging DirectX applications.

  • Using COM
  • Using Callback Functions
  • Version Checking
  • Compiling DirectX Samples and Other DirectX Applications
  • Debugging DirectX Applications


Using COM

The Component Object Model (COM) is an object-oriented programming model used by numerous applications. Because the bulk of the Microsoft® DirectX® run time is in the form of COM-compliant objects, all DirectX developers need to have at least a basic understanding of COM principles and programming techniques. However, although COM has a reputation for being difficult and complex, the COM programming required by most DirectX applications is straightforward.

There are two distinct types of COM programming:

  • Using existing COM objects. This is not much more difficult than using C++ objects.
  • Implementing your own COM objects. This can be a complicated and demanding task. Much of COM's reputation for complexity comes from this type of COM programming.

Most DirectX applications need to use only the COM objects provided by DirectX. They do not need to implement their own COM objects. In other words, most DirectX developers will need to concern themselves only with the first, and easiest, type of COM programming.

This section provides a brief introduction to using the COM objects provided by DirectX. It is primarily intended for novice COM programmers. For a more detailed discussion of how to use COM objects, or for information on how to implement your own COM objects, see Further Information.

  • What is a COM Object?
  • Creating a COM Object
  • Using COM Interfaces
  • Managing a COM Object's Lifetime
  • Using C to Access COM Objects
  • Using Macros to Call DirectX COM Methods
  • DirectX COM Documentation Conventions
  • IUnknown Interface


What is a COM Object?

COM objects are basically black boxes that can be used by applications to perform one or more tasks. They are most commonly implemented as DLLs. Like a conventional DLL, COM objects expose methods that your application can call to perform any of the supported tasks. Applications interact with COM objects in somewhat the same way they do with C++ objects. However, there are some distinct differences.

  • COM objects enforce stricter encapsulation than C++ objects. You cannot simply create the object and call any public method. A COM object's public methods are grouped into one or more interfaces. To use a method, you must create the object and obtain the appropriate interface from the object. An interface typically contains a related set of methods that provide access to a particular feature of the object. For example, the IDirect3DCubeTexture8 interface contains methods that enable you to manipulate cube texture resources. Any methods that are not part of an interface are not accessible.
  • COM objects are not created in the same way as C++ objects. There are several ways to create a COM object, but all involve COM-specific techniques. The Microsoft® DirectX® API includes a variety of helper functions and methods that simplify creating most of the DirectX objects.
  • You must use COM-specific techniques to control the lifetime of the object.
  • COM objects do not need to be explicitly loaded. COM objects are typically contained in a DLL. However, you do not need to explicitly load the DLL or link to a static library in order to use a COM object. Each COM object has a unique registered identifier that is used to create the object. COM automatically loads the correct DLL.
  • COM is a binary specification. COM objects can be written in and accessed from a variety of languages. You don't need to know anything about the object's source code. For example, Microsoft Visual Basic® applications routinely use COM objects that were written in C++.

Objects and Interfaces

It is important to understand the distinction between objects and interfaces. In casual usage, an object may sometimes be referred to by the name of its principle interface. However, strictly speaking, the two terms are not interchangeable.

  • An object may expose any number of interfaces. For example, while all objects must expose the IUnknown interface, they normally expose at least one additional interface, and they might expose many. In order to use a particular method, you must not only create the object, you must also obtain the correct interface.
  • More than one object might expose the same interface. An interface is a group of methods that perform a specified set of operations. The interface definition specifies only the syntax of the methods and their general functionality. Any COM object that needs to support a particular set of operations can do so by exposing a suitable interface. Some interfaces are highly specialized and are exposed only by a single object. Others are useful in a variety of circumstances and are exposed by many objects. The extreme case is the IUnknown interface, which must be exposed by all COM objects.

Note If an object exposes an interface, it must support every method in the interface definition. In other words, you can call any method and be confident that it exists. However, the details of how a particular method is implemented may vary from object to object. For example, different objects may use different algorithms to arrive at the final result. There is also no guarantee that a method will be supported in a non-trivial way. Sometimes an object exposes a commonly-used interface, but needs to support only a subset of the methods. You will still be able to call the remaining methods successfully, but they will return E_NOTIMPL. You should refer to the documentation to see how an interface is implemented by any particular object.

The COM standard requires that an interface definition must not change once it has been published. You cannot, for example, add a new method to an existing interface. You must instead create a new interface. While there are no restrictions on what methods must be in an interface, a common practice is to have the next-generation interface include all the of the old interface's methods, plus any new methods.

It is not unusual for an interface to have several generations. Typically, all generations perform essentially the same overall task, but they will be different in detail. Often, an object will expose every generation of interface. Doing so allows older applications to continue using the object's older interfaces, while newer applications can take advantage of the features of the newer interfaces. Typically, a family of interfaces will all have the same name, plus an integer indicating the generation. For example, if the original interface were named IMyInterface, the next two generations would be called IMyInterface2 and IMyInterface3. Microsoft DirectX® typically labels successive generations of interfaces with the DirectX version number.

GUIDs

Globally Unique Identifiers (GUIDs) are a key part of the COM programming model. At its most basic, a GUID is a 128-bit structure. However, GUIDs are created in such as way as to guarantee that no two GUIDs are the same. COM uses GUIDS extensively for two primary purposes:

  • To uniquely identify a particular COM object. A GUID that is assigned to a COM object is called a Class ID (CLSID). You use a CLSID when you want to create an instance of the associated COM object.
  • To uniquely identify a particular COM interface. The GUID that is associated with a particular COM interface is called an Interface ID (IID). You use an IID when you request a particular interface from an object. An interface's IID will be the same, regardless of which object exposes the interface.

Note For convenience, documentation normally refers to objects and interfaces by a descriptive name such as IDirect3D8. In the context of the documentation, there is rarely any danger of confusion. However, strictly speaking, there is no guarantee that another object or interface does not have the same descriptive name. The only unambiguous way to refer to a particular object or interface is by its GUID.

Although GUIDs are structures, they are often expressed as an equivalent string. The general format of the string form of a GUID is "{VVVVVVVV-WWWW-XXXX-YYYY-ZZZZZZZZZZZZ}", where each letter corresponds to a hexadecimal integer. For example, the string form of the IID for the IDirect3D8 interface is:

{1DD9E8DA-1C77-4D40-B0CF-98FEFDFF9512}

Because the actual GUID is somewhat clumsy to use and easy to mistype, an equivalent name is usually provided as well. You can use this name instead of the actual structure when you call functions such as CoCreateInstance. The customary naming convention is to prepend either IID_ or CLSID_ to the descriptive name of the interface or object, respectively. For example, the name of the IDirect3D8 interface's IID is IID_IDirect3D8.

HRESULT Values

All COM methods return a 32-bit integer called an HRESULT. With most methods, the HRESULT is essentially a structure that contains two separate pieces of information:

  • Whether the method succeeded or failed.
  • More detailed information about the outcome of the operation supported by the method.

Some methods return HRESULT values only from the standard set defined in Winerror.h. However, methods are free to return custom HRESULT values with more specialized information. These values are normally documented on the method's reference page.

Note The list of HRESULT values that you find on a method's reference page is often only a subset of the possible values that may be returned. The list typically covers only those values that are specific to the method and those standard values that have some method-specific meaning. You should assume that a method may return a variety of standard HRESULT values, even if they are not explicitly documented.

While HRESULT values are often used to return error information, you should not think of them as error codes. The fact that the bit that indicates success or failure is stored separately from the bits that contain the detailed information allows HRESULT values to have any number of success and failure codes. By convention, success codes are given names with an S_ prefix, and failure codes with an E_ prefix. For example, the two most commonly used codes are S_OK and E_FAIL, which indicate simple success or failure, respectively.

The fact that COM methods may return a variety of success or failure codes means that you have to be careful how you test the HRESULT value. For example, consider a hypothetical method with documented return values of S_OK if successful and E_FAIL if not. However, remember that the method may also return other failure or success codes. The following code fragment illustrates the danger of using a simple test. The hr value is the HRESULT that was returned by the method.

if(hr == E_FAIL)
  {
    //Handle the failure
  }
else
  {
    //Handle the success
  }

As long as the method returns only E_FAIL to indicate failure, this test will work properly. However, the method might also return an error value such as E_NOTIMPL or E_INVALIDARG. That value would be interpreted as a success, perhaps causing your application to fail.

If you need detailed information on the outcome of the method call, you will need to test each relevant HRESULT value. However, you may be interested only in whether the method succeeded or failed. A robust way to test whether an HRESULT value indicates success or failure is to pass the value to the one of the following macros, defined in Winerror.h.

  • The SUCCEEDED macro returns TRUE for a success code and FALSE for a failure code.
  • The FAILED macro returns TRUE for a failure code and FALSE for a success code.

You can fix the preceding code fragment by using the FAILED macro.

if(FAILED(hr))
  {
    //Handle the failure
  }
else
  {
    //Handle the success
  }

This code fragment properly treats E_NOTIMPL and E_INVALIDARG as failures.

Although most COM methods return structured HRESULT values, a small number use the HRESULT to return a simple integer. Implicitly, these methods are always successful. If you pass an HRESULT of this sort to the SUCCESS macro, the macro will always return TRUE. A commonly used example is the IUnknown::Release method. This method decrements an object's reference count by one and returns the current reference count. See Managing the Object's Lifetime for a discussion of reference counting.

The Address of a Pointer

If you look at a few COM method reference pages, you will probably run across something like the following:

HRESULT CreateDevice(
  ...,
  IDirect3DDevice8** ppReturnedDeviceInterface
);

While a normal pointer is quite familiar to any C/C++ developer, COM often uses an additional level of indirection. This second level of indirection is indicated by a "**" following the type declaration, and the variable name typically has a "pp" prefix. For the example given above, ppReturnedDeviceInterface parameter is typically referred to as the address of a pointer to an IDirect3DDevice8 interface.

Unlike C++, you do not access a COM object's methods directly. Instead, you must obtain a pointer to an interface that exposes the method. To invoke the method, you use essentially the same syntax that you would to invoke a pointer to a C++ method. For example, to invoke the IMyInterface::DoSomething method, you would use the following syntax.

IMyInterface *pMyIface;
...
pMyIface->DoSomething(...);

The need for a second level of indirection comes from the fact that you do not create interface pointers directly. You must call one of variety of methods, such as the CreateDevice method shown above. To use such a method to obtain an interface pointer, you declare a variable as a pointer to the desired interface, and pass the address of that variable to the method. In other words, you pass the method the address of a pointer. When the method returns, the variable will point to the requested interface, and you can use that pointer to call any of the interface's methods. See Obtaining and Using COM Interfaces for further discussion of how to use interface pointers.


Creating a COM Object

There are several ways to create COM objects. The two most common ones used in Microsoft® DirectX® programming are:

  • Directly, by passing the object's CLSID to the CoCreateInstance function. The function will create an instance of the object, and it will return a pointer to an interface that you specify.
  • Indirectly, by calling a DirectX method or function that creates the object for you. The method creates the object and returns an interface on the object. When you create an object this way, you usually cannot specify which interface should be returned.

Before you create any objects, COM must be initialized by calling the CoInitialize function. If you are creating objects indirectly, the object creation method will handle this task. If you need to create an object with CoCreateInstance, you must call CoInitialize explicitly. When you are finished, COM must be uninitialized by calling CoUninitialize. If you make a call to CoInitialize you must match it with a call to CoUninitialize. Typically, applications that need to explicitly initialize COM do so in their startup routine, and they uninitialize COM in their cleanup routine.

To create a new instance of a COM object with CoCreateInstance, you must have the object's CLSID. If this CLSID is publicly available, you will find it in the reference documentation or the appropriate header file. If the CLSID is not publicly available, you cannot create the object directly.

The CoCreateInstance function has five parameters. For the COM objects you will be using with DirectX, you can normally set the parameters as follows

  • rclsid. Set this parameter to the CLSID of the object you want to create.
  • pUnkOuter. Set this parameter to NULL. It is used only if you are aggregating objects. See Further Information for a discussion of aggregation.
  • dwClsContext. Set this parameter to CLSCTX_INPROC_SERVER. This setting indicates that the object is implemented as a DLL and will run as part of your application's process.
  • riid. Set this parameter to the IID of the interface that you would like to have returned. The function will create the object, and it will return the requested interface pointer in the ppv parameter.
  • ppv. Set this parameter to the address of a pointer that will be set to the interface specified by riid when the function returns. This variable should be declared as a pointer to the requested interface, and the reference to the pointer in the parameter list should be cast as (LPVOID *).

For example, the following code fragment creates a new instance of the DirectPlay8 object, and it returns a pointer to the IDirectPlay8Peer interface in the g_pDP variable. If an error occurs, a message box is displayed, and the application terminates.

IDirectPlay8Peer*  g_pDP = NULL;
...
CoInitialize( NULL );
...
hr = CoCreateInstance( CLSID_DirectPlay8, NULL, CLSCTX_INPROC_SERVER,
                         IID_IDirectPlay8Peer, (LPVOID*) &g_pDP );

if( FAILED( hr ) )
  {
    MessageBox( NULL, TEXT("Failed Creating IDirectPlay8Peer. "),
                  TEXT("DirectPlay Sample"), MB_OK | MB_ICONERROR );
    return FALSE;
  }

Creating an object indirectly is usually much simpler. You pass the object creation method the address of an interface pointer. The method then creates the object and returns an interface pointer. When you create an object indirectly, you typically cannot choose which interface the method will return. However, you can often specify a variety of things about how the object should be created. For example, the following code fragment calls the IDirect3D8::CreateDevice method discussed earlier to create a device object to represent a display adapter. It returns a pointer to the object's IDirect3DDevice8 interface. The first four parameters provide a variety of information needed to create the object, and the fifth parameter receives the interface pointer. See the reference documentation for details.

IDirect3DDevice8 *g_pd3dDevice = NULL;
...
if( FAILED( g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,
                                 3DDEVTYPE_HAL,
                                 hWnd,
                                 D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                 &d3dpp,
                                 &g_pd3dDevice )))
  return E_FAIL;


Using COM Interfaces

When the object is created, the creation method returns an interface pointer. You can then use that pointer to access any of the interface's methods. The syntax is identical to that used with a pointer to a C++ method. The following code fragment extends the example given in the previous section. After creating the DirectPlay8 object, the example uses the IDirectPlay8Peer interface pointer returned by CoCreateInstance to initialize the object by calling the IDirectPlay8Peer::Initialize method. Error correction code is omitted for clarity.

IDirectPlay8Peer*  g_pDP = NULL;
...
CoInitialize( NULL );
...
hr = CoCreateInstance( CLSID_DirectPlay8, NULL,CLSCTX_INPROC_SERVER,
                         IID_IDirectPlay8Peer, (LPVOID*) &g_pDP );
hr = g_pDP->Initialize( NULL, DirectPlayMessageHandler, 0 );


Requesting Additional Interfaces

In many cases, the interface pointer that you receive from the creation method may be the only one that you need. In fact, it is not uncommon for an object to export only one interface other than IUnknown. However, many objects export multiple interfaces, and you may need pointers to several of them. If you need more interfaces than the one returned by the creation method, there is no need to create a new object. Instead, you request another interface pointer by using the object's IUnknown::QueryInterface method.

If you create your object with CoCreateInstance, you can request an IUnknown interface pointer, and then call IUnknown::QueryInterface to request every interface you need. However, this approach is inconvenient if you need only a single interface, and it doesn't work at all if you use an object creation method that does not allow you to specify which interface pointer should be returned. In practice, you usually don't need to obtain an explicit IUnknown pointer because all COM interfaces inherit from or extend the IUnknown interface.

Extending an interface is similar to inheriting from a C++ class. The child interface exposes all of the parent interface's methods, plus one or more of its own. In fact, you will often see "inherits from" used instead of "extends". What you need to remember is that the inheritance is internal to the object. Your application cannot inherit from or extend an object's interface. However, you can use the child interface to call any of the child's or the parent's methods.

Because all interfaces are children of IUnknown you can use any of the interface pointers you already have for the object to call QueryInterface. When you do so, you must provide the IID of the interface you are requesting and the address of a pointer that will contain the interface pointer when the method returns. For example, the following code fragment calls IDirectSound8::CreateSoundBuffer to create a primary sound buffer object. This object exposes several interfaces. The CreateSoundBuffer method returns an IDirectSoundBuffer8 interface. The subsequent code then uses the IDirectSoundBuffer8 interface to call QueryInterface to request an IDirectSound3DListener8 interface.

IDirectSoundBuffer8* pDSBPrimary = NULL;
IDirectSound3DListener8* pDSListener;
...
if(FAILED(hr = g_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, NULL )))
  return hr;

if(FAILED(hr = pDSBPrimary->QueryInterface(IID_IDirectSound3DListener8,
                                           (LPVOID *)&pDSListener)))
  return hr;


Managing a COM Object's Lifetime

When an object is created, the system allocates the necessary memory resources. When an object is no longer needed, it should be destroyed. The system can use that memory for other purposes. With C++ objects, you can control the object's lifetime directly with the new and delete operators. COM does not enable you to create or destroy objects directly. The reason for this practice is that the same object may be used by more than one application. If one of those applications were to destroy the object, the other applications would probably fail. Instead COM uses a system of reference counting, to control an object's lifetime.

An object's reference count is the number of times one of its interfaces has been requested. Each time an interface is requested, the reference count is incremented. An application releases an interface when that interface is no longer needed, decrementing the reference count. As long as the reference count is greater than zero, the object remains in memory. When the reference count reaches zero, the object destroys itself. You don't need to know anything about the reference count of an object. As long as you obtain and release an object's interfaces properly, the object will have the appropriate lifetime.

Note Properly handling reference counting is a crucial part of COM programming. Failure to do so can easily create a memory leak. One of the most common mistakes that COM programmers make is failing to release an interface. When this happens, the reference count will never reach zero, and the object will remain in memory indefinitely.

Incrementing and Decrementing the Reference Count

Whenever you obtain a new interface pointer, the reference count must be incremented by a call to IUnknown::AddRef. However, your application does not usually need to call this method. If you obtain an interface pointer by calling an object creation method, or by calling IUnknown::QueryInterface, the object will automatically increment the reference count. However, if you create an interface pointer in some other way, such as copying an existing pointer, you must explicitly call IUnknown::AddRef. Otherwise, when you release the original interface pointer, the object may be destroyed even though you may still need to use the copy of the pointer.

You must release all interface pointers, regardless of whether you or the object incremented the reference count. When you no longer need an interface pointer, call IUnknown::Release to decrement the reference count. A common practice is to initialize all interface pointers to NULL, and set them back to NULL when they are released. That allows you to test all interface pointers in your cleanup code. Those that are non-NULL are still active and must be released before you terminate the application.

The following code fragment extends the sample discussed in Requesting Additional Interfaces to illustrate how to handle reference counting.

IDirectSoundBuffer8* pDSBPrimary = NULL;
IDirectSound3DListener8* pDSListener = NULL;
IDirectSound3DListener8* pDSListener2 = NULL;
...
//Create the object and obtain an additional interface.
//The object increments the reference count.
if(FAILED(hr = g_pDS->CreateSoundBuffer( &dsbd, &pDSBPrimary, NULL )))
  return hr;

if(FAILED(hr=pDSBPrimary->QueryInterface(IID_IDirectSound3DListener8,
                                           (LPVOID *)&pDSListener)))
  return hr;

//Make a copy of the IDirectSound3DListener8 interface pointer.
//Call AddRef to increment the reference count and to ensure that
//the object is not destroyed prematurely
pDSListener2 = pDSListener;
pDSListener2->AddRef();
...
//Cleanup code. Check to see if the pointers are still active.
//If they are, call Release to release the interface.
if(pDSBPrimary != NULL)
{
  pDSBPrimary->Release();
  pDSBPrimary = NULL;
}
if(pDSListener != NULL)
{
  pDSListener->Release();
  pDSListener = NULL;
}
if(pDSListener2 != NULL)
{
  pDSListener2->Release();
  pDSListener2 = NULL;
}


Using C to Access COM Objects

Although C++ is the most commonly used language for COM programming, you can also access COM objects using C. Doing so is relatively straightforward, but requires a somewhat more complex syntax.

  • All methods have an additional parameter added to the beginning of the parameter list. This parameter must be set to the interface pointer.
  • You must explicitly reference the object's vtable.

Every COM object has a vtable that contains a list of pointers to methods that the object exposes. An interface pointer points to the appropriate location in the vtable, which in turn contains a pointer to the particular method you are calling. The vtable is not mentioned elsewhere in this documentation because with C++, the vtable is essentially invisible. However, if you wish to call COM methods with C, you must include an additional level of indirection that explicitly references the vtable.

The following code fragment illustrates how to call the IDirectPlay8Peer::Initialize method with the C++ calling convention.

g_pDP->Initialize( NULL, DirectPlayMessageHandler, 0 );

To make the same method call from C, use the following syntax. The conventional name for the vtable pointer is lpVtbl.

g_pDP->lpVtbl->Initialize(g_pDP,NULL, DirectPlayMessageHandler, 0);

Some components have macros defined in their header files that resolve to the correct calling convention. See Using Macros to Call DirectX COM Methods for details.


Using Macros to Call DirectX COM Methods

Many of the Microsoft® DirectX® interfaces have macros defined for each method that make using the methods in your applications simpler. You can find definitions of these macros in the same header file as the interface declaration. The macros are designed to be used by both C and C++ applications. To use the C++ macros, you must define _cplusplus. Otherwise, the C macros will be used. The macro syntax is the same for both languages, but the header files include separate sets of macro definitions that expand to the appropriate calling convention.

For example, the following code fragment from the d3d.h header file shows the definitions of the C and C++ macros for the IDirect3D8::GetAdapterIdentifier method.

#if !defined(__cplusplus) || defined(CINTERFACE)

...
#define IDirect3D8_GetAdapterIdentifier(p,a,b,c) (p)->lpVtbl->GetAdapterIdentifier(p,a,b,c)
...
#else
...
#define IDirect3D8_GetAdapterIdentifier(p,a,b,c) (p)->GetAdapterIdentifier(a,b,c)
...

#endif

To use one of these macros, you must first obtain a pointer to the associated interface. The first parameter of the macro must be set to that pointer. The remaining parameters map to the method's parameters. The macro's return value is the HRESULT value that is returned by the method. The following code fragment uses a macro to call the IDirect3D8::GetAdapterIdentifier method. pD3D is a pointer to an IDirect3D8 interface.

hr = IDirect3D8_GetAdapterIdentifier(pD3D,
                                     Adapter,
                                     dwFlags,
                                     pIdentifier);


DirectX COM Documentation Conventions

By convention, COM methods and interfaces are referred to in the documentation by their equivalent C++ class names. The Initialize method of the IDirectPlay8Peer interface is thus referred to as IDirectPlay8Peer::Initialize. The primary reason for this convention is that different interfaces may export a method with the same name but with entirely different functionality and syntax. For example, many interfaces have an Init or Initialize method, but the functionality and parameters may be quite different. Using the C++ class name is a convenient way to uniquely identify the method.

The text and sample code generally uses C++ conventions for calling COM methods. See Using C to Access COM Objects, for a discussion of how to convert a C++ method call to its C equivalent.


IUnknown Interface

All COM objects support an interface called IUnknown. This interface provides Microsoft® DirectX® with control of the object's lifetime and the ability to retrieve other interfaces implemented by the object. IUnknown has three methods.

  • AddRef increments the object's reference count by 1 when an interface or another application binds itself to the object.
  • QueryInterface queries the object about the features that it supports by requesting pointers to a specific interface.
  • Release decrements the object's reference count by 1. When the count reaches 0, the object is deallocated.

The AddRef and Release methods maintain an object's reference count. For example, if you create a Microsoft Direct3D® object, the object's reference count is set to 1. Every time a function returns a pointer to an interface for that object, the function must call AddRef through that pointer to increment the reference count. Match each AddRef call with a call to Release. Before the pointer can be destroyed, you must call Release through that pointer. After an object's reference count reaches 0, the object is destroyed, and all interfaces to it become invalid.

The QueryInterface method determines whether an object supports a specific interface. If an object supports an interface, QueryInterface returns a pointer to that interface. You then can use the methods of that interface to communicate with the object. If QueryInterface successfully returns a pointer to an interface, it implicitly calls AddRef to increment the reference count, so your application must call Release to decrement the reference count before destroying the pointer to the interface.

Requirements

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Header: Declared in Unknwn.h.


IUnknown::AddRef

Increases the reference count of the object by 1.

ULONG AddRef();

Parameters

There are no parameters.

Return Values

Returns the new reference count. This value is for diagnostic and testing purposes only.

Remarks

When the object is created, its reference count is set to 1. Every time an application obtains an interface to the object or calls the AddRef method, the object's reference count is increased by 1. Use the Release method to decrease the object's reference count by 1.

Requirements

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Header: Declared in Unknwn.h.


IUnknown::QueryInterface

Determines whether the object supports a particular COM interface. If it does, the system increases the object's reference count, and the application can use that interface immediately.

HRESULT QueryInterface(
  REFIID riid,
  LPVOID* ppvObj
);

Parameters

riid
Reference identifier of the interface being requested.
ppvObj
Address of a pointer to fill with the interface pointer if the query succeeds.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value may be E_NOINTERFACE or E_POINTER. Some components also have their own definitions of these error values in their header files. In Microsoft® DirectInput®, for example, DIERR_NOINTERFACE is equivalent to E_NOINTERFACE.

Remarks

If the application does not need to use the interface retrieved by a call to this method, it must call the Release method for that interface to free it. The QueryInterface method enables Microsoft and third parties to extend objects without interfering with existing or future functionality.

Requirements

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Header: Declared in Unknwn.h.


IUnknown::Release

Decreases the reference count of the object by 1.

ULONG Release();

Parameters

There are no parameters.

Return Values

Returns the new reference count. This value is for diagnostic and testing purposes only.

Remarks

The object deallocates itself when its reference count reaches 0. Use the AddRef method to increase the object's reference count by 1.

Applications must call this method to release only interfaces that the method explicitly created in a previous call to IUnknown::AddRef, IUnknown::QueryInterface, or a creation function such as Direct3DCreate8.

Requirements

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Header: Declared in Unknwn.h.


Using Callback Functions

A callback function is essentially an event handler that is implemented by an application and called by the system. Microsoft® Windows® applications typically implement multiple callback functions, each one designed for a particular set of events. When an event occurs, the system notifies the application by calling the appropriate callback function. The callback function also usually has a parameter list that the system can use to pass the application more detailed information about the event. The most common example of a callback function is the window procedure. This function is used by the system to pass Windows messages to the applications that owns the window.

Microsoft DirectX® uses callback functions for a variety of purposes. For example, your system supports multiple devices. Microsoft DirectInput® represents each device by a device object, that contains the details of the device's capabilities. Your application will typically need to enumerate the available devices and to examine the device objects in order to handle user input properly. To do this enumeration, you must implement a DIEnumDeviceObjectsCallback callback function.

You start the enumeration process by calling IDirectInputDevice8::EnumObjects and passing the method a pointer to your DIEnumDeviceObjectsCallback callback function. The system will call this function once for each device, and it will pass in a DIDEVICEOBJECTINSTANCE structure containing information about the device's capabilities. After your callback function has processed the information, it can return DIENUM_CONTINUE to request the next device object, or DIENUM_STOP to stop the enumeration.

For more information, see Implementing a Callback Function.

DirectX uses a number of other callback functions for a variety of purposes. For details, see the documentation for the particular DirectX component.


Implementing a Callback Function

Because callback functions have different purposes and usage, they are documented in the appropriate Reference section in much the same way as a regular function. However, a callback function reference is essentially a template that describes how to implement the function, not a normal API reference. The callback function reference provides the following information:

  • How the function is used
  • The function's syntax
  • An explanation of the information that will be contained by each parameter
  • An explanation of the possible return values

You should declare the function as a CALLBACK or WINAPI type. Either type is acceptable. You can use any function name that you wish. The name used in the documentation is simply a convenient label for a particular callback function.

Implement the function according to the description in the reference. The implementation details will depend on the particular function and the requirements of your application. See the sample code for some examples of how to implement various callback functions.

Pass a pointer to the function to the appropriate Microsoft® DirectX® component. The DirectX component can then use the function pointer to call the function. The way in which you pass this pointer varies from function to function, so you should see the particular function's reference for details.

The following code fragment is borrowed from the Microsoft DirectInput® Joystick sample. It sketches out the essential elements of a DIEnumDeviceObjectsCallback implementation that is used to enumerate the axes of a joystick.

//The function declaration
BOOL CALLBACK EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,
                                VOID* pContext );
...
//Pass the function pointer to DirectInput by calling the
//IDirectInputDevice8::EnumObjects method
if ( FAILED( hr = g_pJoystick->EnumObjects( EnumAxesCallback,
                                           (VOID*)hDlg,
                                            DIDFT_AXIS )));
...
//The function implementation
BOOL CALLBACK EnumAxesCallback( const DIDEVICEOBJECTINSTANCE* pdidoi,
                                VOID* pContext )
{
//Process the information passed in through the two parameters
//Return DIENUM_CONTINUE to request the next device object
//Return DIENUM_STOP to stop the enumeration
}


Version Checking

Applications sometimes need to know which version of Microsoft® DirectX® is currently available on the system. For example, if an older version of DirectX is on the system, your application may need to scale itself to the capabilities of that version or install the most recent version.

There is no direct way to obtain the DirectX version number. However, each version has a characteristic set of objects and interfaces. Because any version of DirectX supports all previous versions, this set of interfaces and objects will be supported by the version in which they are introduced and all subsequent versions. Thus, the preferred way to determine whether your desired version is available is to test for its characteristic objects or interfaces. As long as those are present, your application will work normally even though you might be using a more recent version of DirectX.

For example, suppose you need version 6.1 support. The Microsoft DirectMusic® object (CLSID_DirectMusic) was introduced in DirectX version 6.1. You can test for the presence of the DirectMusic object by attempting to create it with CoCreateInstance. If you are successful, you have version 6.1 or later, and you will be able to use all the DirectX 6.1 capabilities.

Rather than provide a detailed list here of each version's characteristic interfaces and objects, you should refer to the DirectX Software Development kit's sample section. One of the samples is a function, GetDXVersion, that includes tests for all DirectX versions. GetDXVersion returns an integer that corresponds to the DirectX version that is present on the system. As long as this integer is greater than or equal to your desired version number, your application will run normally. You can find the sample code under your SDK root folder at \Samples\Multimedia\DXMisc\GetDXVer.

For more information, see Checking the Operating System Version.


Checking the Operating System Version

In addition to determining the Microsoft® DirectX® version, applications may also need to know what operating system they are running on, and perhaps which Service Pack has been installed. The preferred way to check the operating system version is to use the Microsoft Windows® function, GetVersionEx. This function returns an OSVERSIONINFO structure that contains a variety of information including:

  • Whether the system is Microsoft Windows NT®-based or Windows 95/98/ME
  • The major and minor version numbers
  • The service pack number, for Windows NT-based systems

The general procedure is to determine the earliest version of the operating system that your application is compliant with. If that version or later is installed, you can safely install and run your application.

Note The operating system information returned by GetVersionEx should not be used to test for the presence or version number of DirectX. In particular, the fact that a system is Windows NT-based does not necessarily mean that DirectX is absent. The Windows 2000 operating system, for example, includes DirectX 7.0 or later. Future versions of Windows NT-based operating systems can also be expected to include a version of DirectX. Use the procedures described in the previous section to determine whether DirectX is present and, if so, the version number.

The following sample function illustrates how to use GetVersionEx to test the operating system version. If the installed version is identical to or more recent than the version specified in the parameter list, the function returns TRUE. You can then safely install and execute your application. Otherwise the function returns FALSE, indicating that your application will not run properly, if at all.

#include <windows.h>
#include <stdio.h>
#include <tchar.h>

BOOL bIsWindowsVersionOK(   DWORD dwWin9xMajor, DWORD dwWin9xMinor,
                            DWORD dwWinNTMajor, DWORD dwWinNTMinor, WORD wWinNTSPMajor )
{
    OSVERSIONINFO           osvi;

    // Initialize the OSVERSIONINFO structure.
    ZeroMemory( &osvi, sizeof( osvi ) );
    osvi.dwOSVersionInfoSize = sizeof( osvi );

    GetVersionEx( &osvi );  // Assume this function succeeds.

    // Split code paths for NT and Win9x
    if( osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS )
    {
        // Check the major version.
        if( osvi.dwMajorVersion > dwWin9xMajor )
            return TRUE;
        else if( osvi.dwMajorVersion == dwWin9xMajor )
        {
            // Check the minor version.
            if( osvi.dwMinorVersion >= dwWin9xMinor )
                return TRUE;
        }
    }
    else if( osvi.dwPlatformId == VER_PLATFORM_WIN32_NT )
    {
        // Check the major version.
        if( osvi.dwMajorVersion > dwWinNTMajor )
            return TRUE;
        else if( osvi.dwMajorVersion == dwWinNTMajor )
        {
            // Check the minor version.
            if( osvi.dwMinorVersion > dwWinNTMinor )
                return TRUE;
            else if( osvi.dwMinorVersion == dwWinNTMinor )
            {
                // Check the service pack.
                DWORD dwServicePack = 0;

                if( osvi.szCSDVersion )
                {
                    _stscanf(   osvi.szCSDVersion,
                                _T("Service Pack %d"),
                                &dwServicePack );
                }
                return ( dwServicePack >= wWinNTSPMajor );
            }
        }
    }
    return FALSE;
}


Compiling DirectX Samples and Other DirectX Applications

This section provides information about considerations specific to compiling Microsoft® DirectX® applications. DirectX 8.0 supports only Microsoft Visual C++ 5.0 SP3, and later.

  • Preparing for Compilation
  • Component Version Constants


Preparing for Compilation

The samples included in this SDK use Microsoft® Visual C++® project files (DSP files) that describe the appropriate source files, project resources, and linker settings for each sample. However, you might need to make additional preparations to ensure that the samples compile and link properly, or you might need to prepare settings for a new project. The information provided here applies to the Microsoft DirectX® samples and the DirectX applications that you create.

After opening a project file in Visual C++, verify some settings before compiling the application. The following descriptions are valid for Visual C++ 5 and 6.

Note The following discussion uses the default installation paths, C:\Mssdk\Include and C:\Mssdk\Lib, to describe file locations. Your installation paths might differ.

Include search paths

Be sure that the search path for header files is correct and the directory for DirectX header files is the first path that the compiler searches. To check the include path, choose Options from the Tools menu and select the Directories tab. The following dialog box will appear.

The topmost path indicates the folder that contains the latest DirectX header files. The default path is C:\Mssdk\Include. If the path is not present, add it to the list and move it to the top of the search list by using the toolbar controls within the Directories tab.

Linker search paths

Check the search paths and search order that the linker uses to search for link libraries. The link search paths are also listed on the Directories tab. Choose Options from the Tools menu and select the Directories tab. When the dialog box appears, choose the Library files option in the Show directories for list box. The topmost path should be the folder that contains the latest DirectX link libraries. The default path is C:\Mssdk\Lib.

Project link libraries

If you are using the provided sample project files, you do not need to verify these settings. They are specified with the project files. For new applications, on the Project menu, click Settings. The following dialog box appears.

You should verify that the application is linked to the appropriate standard DirectX link libraries.


Component Version Constants

For backward compatibility with earlier versions of Microsoft® DirectX®, some DirectX components include variable API element definitions in their header files. Affected elements are typically capability structures or flag sets that are version-specific. Parts of some header files are surrounded by preprocessor conditionals that cause the preprocessor to filter out unneeded definitions. The value of the defined constant identifies a specific version of the component. If no value is defined, the headers set a value that identifies the DirectX version for which the header file was written. An example from the Microsoft Direct3D® header file, D3D8.h, is shown here.

#ifndef DIRECT3D_VERSION
#define DIRECT3D_VERSION         0x0800
#endif  //DIRECT3D_VERSION

You can define other values for these constants to use newer versions of the header files with older versions of the components. For example, to use the latest headers to compile against the DirectX 7.0 version of D3D, define DIRECT3D_VERSION to be 0x0700.


Debugging DirectX Applications

This section covers the following topics pertaining to debugging C and C++ applications.

  • Debug vs. Retail DLLs
  • The DirectX 8.0 Error Handling Utility Library


Debug vs. Retail DLLs

The Microsoft® DirectX® SDK installation program provides the option of installing either debug or retail builds of the DirectX dynamic-link libraries (DLLs).

When you develop software in C++, it is best to install the debug versions of the DLLs. This option installs both debug and retail DLLs on your system. The retail option installs only the retail DLLs. The debug DLLs have additional code that validates internal data structures and output debug error messages, using the Microsoft Win32® OutputDebugString function, while your program is executing. When an error occurs, the debug output gives you a more detailed description of the problem. The debug DLLs execute more slowly than the retail DLLs but are much more useful for debugging an application. Be sure to ship the retail version with your application.

You can use the DirectX Control Panel utility to switch between the debug and retail builds of Microsoft DirectInput®, Direct3D®, and DirectMusic®. To enable this feature, select the debug option when you install the SDK.

To see the debug messages, configure your system so that debug output appears in a window or on a remote computer. A development environment such as Visual Microsoft C++® enables you to do this. Consult the environment documentation for setup instructions.

To ensure that the debugger can find the relevant symbolic information when using debug builds, locate the symbol files as follows:

OS | Debugger | Location for .pdb file | Location for .dbg file
Windows® 95 Windows 98 | Visual C++ | Same directory as binary | Same directory as binary
Windows NT® Windows 2000 | Visual C++ | Same directory as binary | %SystemRoot%\Symbols\<binary extension>\
Windows NT Windows 2000 | NTSD/KD | %SystemRoot%\Symbols\<binary extension>\ | %SystemRoot%\Symbols\<binary extension>\

Note When debugging with the Visual C++ development system on Microsoft Windows NT/Windows 2000, do not use the WIN32API Splitsym development tool. WIN32API Splitsym copies private symbolic information from the <binary>.dbg file into the symbol directory under the binary extension—for example, %SystemRoot%\Symbols\Dll\—and deletes the original file from the binary directory. Visual C++ relies on finding a private symbolic information (<binary>.dbg) file in the same directory as the binary. Therefore, for debug builds, you must copy the private symbolic information and not delete it. This is an issue only when using Visual C++ with Windows NT/Windows 2000. Consult Visual C++ documentation and Windows 2000 Driver Development Kit (DDK) documentation for further debugging information.


The DirectX 8.0 Error Handling Utility Library

The Microsoft® DirectX® 8.0 SDK includes a pair of utility functions and several macros designed to simplify the task of debugging your application. These functions and macros are contained in the Dxerr8.lib library. The declarations are in Dxerr8.h.

  • DirectX 8.0 Error Handling Functions
  • DirectX 8.0 Error Handling Macros


DirectX 8.0 Error Handling Functions

The following functions and macros are included in the DirectX error handling utility library.

  • DXGetErrorString8
  • DXTrace


DXGetErrorString8

Returns the name associated with a Microsoft® DirectX error® code.

TCHAR* DXGetErrorString8(
  HRESULT hr
);

Parameters

hr
[in] HRESULT value returned from a DirectX method. This handles only error codes.

Return Values

If successful, this function returns a pointer to a string that contains the name of the error code. If Unicode is set, DXGetErrorString8 will return a Unicode string. Otherwise, it will return an ANSI string.

Remarks

This function is designed to retrieve the text equivalent of a DirectX error message from a Microsoft Direct3D®, D3DX, DirectPlay®, DirectInput®, DirectMusic®, or DirectSound® method. For example, if you set hr to 0x88768686, DXGetErrorString8 will return D3DERR_DEVICELOST.

If an error code maps to more than one text string, DXGetErrorString8 will return a generic string. For example, there are several DirectX error codes, such as DIERR_OUTOFMEMORY, that indicate that you are out of memory, and all map to the same value. If you set hr to any of these codes, DXGetErrorString8 will return E_OUTOFMEMORY.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Version: Requires DirectX 8.0.
Header: Declared in Dxerr8.h.
Import Library: Use Dxerr8.lib


DXTrace

Displays a message box, and passes the error code to DXGetErrorString8.

HRESULT DXTrace(
  char *strFile,
  DWORD dwLine,
  HRESULT hr,
  TCHAR *strMsg,
  BOOL bPopMsgBox
);

Parameters

strFile
[in] Pointer to the name of the current file. You can set this parameter easily with the __FILE__ macro.
dwLine
[in] Line number. You can set this parameter easily with the __LINE__ macro.
hr
[in] HRESULT containing an error code. This value will be passed to DXGetErrorString8 and converted to the equivalent name.
strMsg
[in] Pointer to an optional message that will be displayed along with the file name, line number, and HRESULT.
bPopMsgBox
[in] Specifies whether a message box should be displayed. If bPopMsgBox is set to TRUE and hr is non-zero, a message box will be displayed containing the values of the first four parameters. If bPopMsgBox is set to FALSE, the information is passed to the debugger.

Return Values

Returns zero if successful, or a non-zero value if not.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Version: Requires DirectX® 8.0.
Header: Declared in Dxerr8.h.
Import Library: Use Dxerr8.lib


DirectX 8.0 Error Handling Macros

The following macros simplify using the DXTrace function.

  • DXTRACE_MSG
  • DXTRACE_ERR
  • DXTRACE_ERR_NOMSGBOX


DXTRACE_MSG

Passes a string to the debugger.

HRESULT DXTRACE_MSG(
  char *str,
);

Parameters

str
Pointer to a string that will be passed to the debugger.

Return Values

Returns zero if successful, or a non-zero value if not.

Remarks

The string is accompanied by the file name and line number. The macro declaration is:

DXTRACE_MSG(str) DXTrace( __FILE__, (DWORD)__LINE__, 0, str, FALSE )

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Version: Requires DirectX® 8.0.
Header: Declared in Dxerr8.h.


DXTRACE_ERR

Displays a message box with error information.

HRESULT DXTRACE_ERR(
  char *str,
  HRESULT hr
);

Parameters

str
Pointer to a string to be displayed in the message box.
hr
HRESULT containing an error code. This value will be passed to DXGetErrorString8 and converted to the equivalent name.

Return Values

Returns zero if successful, or a non-zero value if not.

Remarks

The string and error name is accompanied by the file name and line number. The macro declaration is:

DXTRACE_ERR(str,hr) DXTrace(__FILE__,(DWORD)__LINE__,hr,str,TRUE )

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Version: Requires DirectX® 8.0.
Header: Declared in Dxerr8.h.


DXTRACE_ERR_NOMSGBOX

Passes error information to the debugger.

HRESULT DXTRACE_ERR_NOMSGBOX(
  char *str,
  HRESULT hr
);

Parameters

str
Pointer to a string to be passed to the debugger.
hr
HRESULT containing an error code. This value will be passed to DXGetErrorString8 and converted to the equivalent name.

Return Values

Returns zero if successful, or a non-zero value if not.

Remarks

The string and error name is accompanied by the file name and line number. The macro declaration is:

DXTRACE_ERR_NOMSGBOX(str,hr) DXTrace(__FILE__,(DWORD)__LINE__,hr,str, FALSE)

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Version: Requires DirectX® 8.0.
Header: Declared in Dxerr8.h.


Further Information

You can find further explanations of the graphics and multimedia concepts and terms discussed throughout the Microsoft® DirectX® documentation, as well as information on Microsoft Windows® programming in general, in the following sources:

  • Bargen, Bradley and Peter Donnelly, Inside DirectX, Microsoft Press®, 1998.
  • Begault, Durand R., 3-D Sound for Virtual Reality and Multimedia, Academic Press, 1994.
  • Blinn, James, Jim Blinn's Corner: A Trip Down the Graphics Pipeline, Morgan Kaufmann, 1996.
  • Dodge, Charles and Thomas A. Jerse, Computer Music: Synthesis, Composition, and Performance, Schirmer Books, 1997 (2nd edition).
  • Foley, James D., Computer Graphics: Principles and Practice, Addison-Wesley, 1991 (2nd edition).
  • Hearn, Donald and M. Pauline Baker, Computer Graphics, Prentice-Hall, 1986.
  • Kientzle, Tim, A Programmer's Guide to Sound, Addison-Wesley Developers Press, 1998.
  • Kovach, Peter J., Inside Direct3D, Microsoft Press, 2000.
  • Petzold, Charles, Programming Windows 98, Microsoft Press, 1998 (5th edition).
  • Thompson, Nigel, 3D Graphics Programming for Windows 95, Microsoft Press, 1996.
  • Watt, Alan H., and Mark Watt, Advanced Animation and Rendering Techniques, Addison-Wesley, 1992.

Additional sources for the concepts and terms associated with COM can be found in the following sources:

  • Brockschmidt, Kraig, Inside OLE 2, Microsoft Press, 1995 (2nd edition).
  • Rogerson, Dale E., Inside COM, Microsoft Press, 1997.


DirectX Graphics

This section provides information about using the Microsoft® DirectX® Graphics application programming interfaces (APIs).

As with other components of DirectX, DirectX Graphics can be used with C, C++, and Microsoft Visual Basic®.

For an overview of the organization of the DirectX Graphics Help, see Roadmap.


Roadmap

Information on Microsoft® DirectX® Graphics is presented in the following sections.

What's New in DirectX Graphics. New features and functionality of this component in DirectX 8.0. If you've used Microsoft Direct3D® or Microsoft DirectDraw® before, read this section first, because much has changed since DirectX 7.0.

Introduction to DirectX Graphics. An overview of what DirectX Graphics is and what it can do for your application, together with a look at some key principles and necessary background information.

Understanding DirectX Graphics. A deeper look at the underlying structure. This section won't teach you how to implement vertex lighting or texture mapping in your application, but it will help you understand the mechanics of the API when you get into the details.

Using DirectX Graphics. A guide to using the API. You'll probably want to familiarize yourself with the table of contents for this section and then refer to parts of it as you need specific information. Use it in conjunction with the reference section.

Advanced Topics in DirectX Graphics. Information of interest for creating applications that take full advantage of the power of DirectX Graphics.

Programming Tips and Tools. Miscellaneous information about compiling, debugging, and optimizing DirectX Graphics applications. In addition, this section contains information on issues that may be encountered when using pre-DirectX 8.0 drivers.

DirectX Graphics C/C++ Tutorials. Step-by-step implementation of basic functionality. If you learn best by doing, this is a good place to start.

DirectX Graphics C/C++ Samples. A guide to the sample applications in the SDK to point you to the sample code you need.

Direct3D C/C++ Reference. Detailed information for all the API elements declared in the Microsoft Direct3D® header files.

Direct3DX C/C++ Reference. Detailed information for all the API elements declared in the Direct3DX utility library header files.

Direct3DX Shader Assemblers Reference. Detailed reference information on the Direct3DX vertex and pixel shader assemblers.

Effect File Format. Information on the format of effect files, which consist of a set of parameter declarations, followed by descriptions of various techniques

X File C/C++ Reference. Detailed information for all the API elements declared in Dxfile.h.

X File Format Reference. Detailed information on the DirectX (.x) file format.


What's New in DirectX Graphics

Microsoft® DirectX® 8.0 maintains backward compatibility by exposing and supporting objects and interfaces offered by previous releases of DirectX. However, many new features and performance enhancements have been added as part of the DirectX 8.0 new Microsoft Direct3D® API interfaces.

Complete integration of DirectDraw and Direct3D
Simplifies application initialization and improves data allocation and management performance, which reduces the memory footprint. Also, the integration of the graphics APIs enable parallel vertex input streams for more flexible rendering.
Programmable vertex processing language
Enables you to write custom shaders for morphing and tweening animation, matrix palette skinning, user-defined lighting models, general environment mapping, procedural geometry, or any other developer-defined algorithm.
Programmable pixel processing language
Enables you to write custom hardware shaders for general texture combining expressions, per-pixel lighting (bump mapping), per-pixel environment mapping for photoreal specular effects, or any other developer-defined algorithm.
Multisampling rendering support
Enables full-scene anti-aliasing and multisampling effects, such as motion blur and depth-of-field.
Point sprites
Enables high-performance rendering of particle systems for sparks, explosions, rain, snow, and so on.
3-D volumetric textures
Enables range-attenuation in per-pixel lighting and volumetric atmospheric effects, and can be applied to more intricate geometry.
Higher-order primitive support
Enhances the appearance of 3-D content and facilitates the mapping of content from major 3-D authoring tools.
Higher-level technologies
Includes 3-D content creation tool plug-ins for export to Direct3D of skinned meshes using a variety of Direct3D techniques, multiresolution level-of-detail (LOD) geometry, and higher-order surface data.
Indexed vertex blending
Extends geometry blending support to allow the matrices used for vertex blending to be referred to using a matrix index.
Expansion of the Direct3DX Utility Library
Contains a wealth of new functionality. The Direct3DX utility library is a helper layer that sits on top of Direct3D to simplify common tasks encountered by 3-D graphics developers. Includes a skinning library, support for working with meshes, and functions to assemble vertex and pixel shaders. Note that the functionality supplied by D3D_OVERLOADS, first introduced with Microsoft DirectX® 5.0, has been moved to the Direct3DX utility library.


Introduction to DirectX Graphics

This section introduces the Microsoft® DirectX® Graphics APIs, providing a high-level overview of technology and services.

  • The Power of DirectX Graphics
  • Getting Started with DirectX Graphics


The Power of DirectX Graphics

Microsoft® Direct3D® is designed to enable world-class game and interactive three-dimensional (3-D) graphics on a computer running Microsoft Windows®. It is a drawing interface that provides device-dependent access to 3-D video-display hardware in a device-independent manner.

Direct3D is a low-level 3-D API that is ideal for developers who need to port games and other high-performance multimedia applications to the Windows operating system. Direct3D provides a device-independent way for applications to communicate with accelerator hardware at a low level.

Direct3D is a software interface that provides direct access to display devices while maintaining compatibility with the Windows graphics device interface (GDI), providing a device-independent way for games and Windows subsystem software, such as three-dimensional (3-D) graphics packages, to gain access to the features of specific display devices.

Direct3D provides excellent game graphics on computers running Windows 95 or later, or Windows 2000.

Some of the advanced features of Direct3D are:

  • Switchable depth buffering (using z-buffers or w-buffers).
  • Flat and Gouraud shading.
  • Multiple light sources and types.
  • Full material and texture support, including mipmapping.
  • Robust software emulation drivers.
  • Transformation and clipping.
  • Hardware independence.
  • Full support on Windows 95, Windows 98, Windows ME, and Windows 2000.
  • Support for the Intel MMX architecture, Intel Streaming Single-Instruction, Multiple-Data (SIMD) Extensions (SSE)®, and AMD's® 3DNow® architecture.
  • Support for a Hardware Abstraction Layer (HAL). This provides a consistent interface through which to work directly with the display hardware, getting maximum performance.
  • Support for page flipping with multiple back buffers in full-screen applications. For more information, see Page Flipping and Back Buffering.
  • Support for clipping in windowed or full-screen applications.
  • Support for 3-D z-buffers.
  • Access to image-stretching hardware.
  • Simultaneous access to standard and enhanced display-device memory areas.
  • Other features, including exclusive hardware access and resolution switching.

These features combine to enable you to write applications that easily outperform standard Windows GDI-based applications and even MS-DOS applications.

The world management of Direct3D is based on vertices, polygons, and commands that control them. It enables immediate access to the transformation, lighting, and rasterization 3-D graphics pipeline. If hardware isn't present to accelerate rendering, Direct3D offers robust software emulation.

Direct3D provides simple and straightforward methods to set up and render a 3-D scene. The key set of rendering methods is referred to as DrawPrimitive methods. They enable applications to render one or more objects in a scene with a single method call. For more information about these methods, see Rendering Primitives.

Direct3D enables a low-overhead connection to 3-D hardware. This comes at a price, however. You must provide explicit calls for transformations and lighting, you must provide all the necessary matrices, and you must determine what kind of hardware is present and its capabilities.


Getting Started with DirectX Graphics

This section provides an overview of graphics programming with Microsoft® Direct3D®. Each concept discussed here begins with a nontechnical overview, followed by specific information about how Direct3D supports it.

You don't need to be a graphics guru to benefit from this overview. In fact, if you are one, you might want to skip this section entirely and move on to the more detailed information in the Using DirectX Graphics section. When you finish reading these topics, you will have a solid understanding of basic Direct3D graphics programming concepts.

The following topics are discussed.

  • 3-D Coordinate Systems and Geometry
  • Shading Techniques
  • Matrices and Transformations
  • Vectors, Vertices, and Quaternions
  • Copying Surfaces
  • Page Flipping and Back Buffering
  • Rectangles


3-D Coordinate Systems and Geometry

Programming Microsoft® Direct3D® applications requires a working familiarity with 3-D geometric principles. This section introduces the most important geometric concepts for creating 3-D scenes. The following topics are covered.

  • 3-D Coordinate Systems
  • 3-D Primitives
  • Triangle Rasterization Rules

These topics provide you with a high-level understanding of the basic concepts employed by a Direct3D application. For more information about these topics, see Further Information.


3-D Coordinate Systems

Typically 3-D graphics applications use two types of Cartesian coordinate systems: left-handed and right-handed. In both coordinate systems, the positive x-axis points to the right, and the positive y-axis points up. You can remember which direction the positive z-axis points by pointing the fingers of either your left or right hand in the positive x-direction and curling them into the positive y-direction. The direction your thumb points, either toward or away from you, is the direction that the positive z-axis points for that coordinate system. The following illustration shows these two coordinate systems.

Microsoft® Direct3D® uses a left-handed coordinate system. If you are porting an application that is based on a right-handed coordinate system, you must make two changes to the data passed to Direct3D.

  • Flip the order of triangle vertices so that the system traverses them clockwise from the front. In other words, if the vertices are v0, v1, v2, pass them to Direct3D as v0, v2, v1.
  • Use the view matrix to scale world space by –1 in the z-direction. To do this, flip the sign of the _31, _32, _33, and _34 member of the D3DMATRIX structure that you use for your view matrix.

To obtain what amounts to a right-handed world, use the D3DXMatrixPerspectiveRH and D3DXMatrixOrthoRH functions to define the projection transform. However, be careful to use the corresponding D3DXMatrixLookAtRH function, reverse the backface-culling order, and lay out the cube maps accordingly.

Although left-handed and right-handed coordinates are the most common systems, there is a variety of other coordinate systems used in 3-D software. For example, it is not unusual for 3-D modeling applications to use a coordinate system in which the y-axis points toward or away from the viewer, and the z-axis points up. In this case, right-handedness is defined as any positive axis (x, y, or z) pointing toward the viewer. Left-handedness is defined as any positive axis (x, y, or z) pointing away from the viewer. If you are porting a left-handed modeling application where the z-axis points up, you must do a rotation on all the vertex data in addition to the previous steps.

The essential operations performed on objects defined in a 3-D coordinate system are translation, rotation, and scaling. You can combine these basic transformations to create a transform matrix. For details, see 3-D Transformations.

When you combine these operations, the results are not commutative—the order in which you multiply matrices is important.


3-D Primitives

A 3-D primitive is a collection of vertices that form a single 3-D entity. The simplest primitive is a collection of points in a 3-D coordinate system, which is called a point list.

Often, 3-D primitives are polygons. A polygon is a closed 3-D figure delineated by at least three vertices. The simplest polygon is a triangle. Microsoft® Direct3D® uses triangles to compose most of its polygons because all three vertices in a triangle are guaranteed to be coplanar. Rendering nonplanar vertices is inefficient. You can combine triangles to form large, complex polygons and meshes.

The following illustration shows a cube. Two triangles form each face of the cube. The entire set of triangles forms one cubic primitive. You can apply textures and materials to the surfaces of primitives to make them appear to be a single solid form. For details, see Materials and Textures.

You can also use triangles to create primitives whose surfaces appear to be smooth curves. The following illustration shows how a sphere can be simulated with triangles. After a material is applied, the sphere looks curved when it is rendered. This is especially true if you use Gouraud shading. For details, see Gouraud Shading.


Triangle Rasterization Rules

Often, the points specified for vertices do not precisely match the pixels on the screen. When this happens, Microsoft® Direct3D® applies triangle rasterization rules to decide which pixels apply to a given triangle.

Direct3D uses a top-left filling convention for filling geometry. This is the same convention that is used for rectangles in GDI and OpenGL. In Direct3D, the center of the pixel is the decisive point. If the center is inside a triangle, the pixel is part of the triangle. Pixel centers are at integer coordinates.

This description of triangle-rasterization rules used by Direct3D does not necessarily apply to all available hardware. Your testing may uncover minor variations in the implementation of these rules.

The following illustration shows a rectangle whose upper-left corner is at (0, 0) and whose lower-right corner is at (5, 5). This rectangle fills 25 pixels, just as you would expect. The width of the rectangle is defined as right minus left. The height is defined as bottom minus top.

In the top-left filling convention, top refers to the vertical location of horizontal spans, and left refers to the horizontal location of pixels within a span. An edge cannot be a top edge unless it is horizontal—in general, most triangles have only left and right edges.

The top-left filling convention determines the action taken by Direct3D when a triangle passes through the center of a pixel. The following illustration shows two triangles, one at (0, 0), (5, 0), and (5, 5), and the other at (0, 5), (0, 0), and (5, 5). The first triangle in this case gets 15 pixels (shown in black), whereas the second gets only 10 pixels (shown in gray) because the shared edge is the left edge of the first triangle.

If you define a rectangle with its upper-left corner at (0.5, 0.5) and its lower-right corner at (2.5, 4.5), the center point of this rectangle is at (1.5, 2.5). When the Direct3D rasterizer tessellates this rectangle, the center of each pixel is unambiguously inside each of the four triangles, and the top-left filling convention is not needed. The following illustration shows this. The pixels in the rectangle are labeled according to the triangle in which Direct3D includes them.

If you move the rectangle in the previous example so that its upper-left corner is at (1.0, 1.0), its lower-right corner at (3.0, 5.0), and its center point at (2.0, 3.0), Direct3D applies the top-left filling convention. Most pixels in this rectangle straddle the border between two or more triangles, as the next illustration shows.

For both rectangles, the same pixels are affected.


Shading Techniques

This section describes techniques used in Microsoft® Direct3D® to control the shading of 3-D polygons.

  • Shading Modes
  • Comparing Shading Modes
  • Setting the Shading Mode
  • Face and Vertex Normal Vectors
  • Triangle Interpolants


Shading Modes

The shading mode used to render a polygon has a profound effect on its appearance. Shading modes determine the intensity of color and lighting at any point on a polygon face. Microsoft® Direct3D® supports two shading modes:

  • Flat Shading
  • Gouraud Shading


Flat Shading

In the flat shading mode, the Direct3D rendering pipeline renders a polygon, using the color of the polygon material at its first vertex as the color for the entire polygon. 3-D objects that are rendered with flat shading have visibly sharp edges between polygons if they are not coplanar.

The following figure shows a teapot rendered with flat shading. The outline of each polygon is clearly visible. Flat shading is computationally the least expensive form of shading.


Gouraud Shading

When Microsoft® Direct3D® renders a polygon using Gouraud shading, it computes a color for each vertex by using the vertex normal and lighting parameters. Then, it interpolates the color across the face of the polygons The interpolation is done linearly. For example, if the red component of the color of vertex 1 is 0.8 and the red component of vertex 2 is 0.4, using the Gouraud shading mode and the RGB color model, the Direct3D lighting module assigns a red component of 0.6 to the pixel at the midpoint of the line between these vertices.

The following figure demonstrates Gouraud shading. This teapot is composed of many flat, triangular polygons. However, Gouraud shading makes the surface of the object appear curved and smooth.

Gouraud shading can also be used to display objects with sharp edges.

For more information, see Face and Vertex Normal Vectors.


Comparing Shading Modes

In flat shading mode, the pyramid below is displayed with a sharp edge between adjoining faces. In Gouraud shading mode, however, shading values are interpolated across the edge, and the final appearance is of a curved surface.

Gouraud shading lights flat surfaces more realistically than flat shading. A face in the flat shading mode is a uniform color, but Gouraud shading enables light to fall across a face more correctly. This effect is particularly obvious if there is a nearby point source.

Gouraud shading smoothes the sharp edges between polygons that are visible with flat shading. However, it can result in Mach bands, which are bands of color or light that are not smoothly blended across adjacent polygons. Your application can reduce the appearance of Mach bands by increasing the number of polygons in an object, increasing screen resolution, or increasing the color depth of the application.

Gouraud shading can miss some details. One example is the case shown by the following illustration, in which a spotlight is completely contained within a polygon face.

In this case, Gouraud shading, which interpolates between vertices, would miss the spotlight altogether; the face would be rendered as though the spotlight did not exist.


Setting the Shading Mode

Microsoft® Direct3D® enables one shading mode to be selected at a time. By default, Gouraud shading is selected. In C++, you can change the shading mode by calling the IDirect3DDevice8::SetRenderState method. Set the State parameter to D3DRS_SHADEMODE. The State parameter must be set to a member of the D3DSHADEMODE enumeration. The following sample code examples illustrate how the current shading mode of a Direct3D application can be set to flat or Gouraud shading mode.

// Set to flat shading.
// This code example assumes that pDev is a valid pointer to
// an IDirect3DDevice8 interface.
hr = pDev->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

// Set to Gouraud shading. This is the default for Direct3D.
hr = pDev->SetRenderState(D3DRS_SHADEMODE,
                            D3DSHADE_GOURAUD);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}


Face and Vertex Normal Vectors

Each face in a mesh has a perpendicular normal vector. The vector's direction is determined by the order in which the vertices are defined and by whether the coordinate system is right- or left-handed. The face normal points away from the front side of the face. In Microsoft® Direct3D®, only the front of a face is visible. A front face is one in which vertices are defined in clockwise order.

Any face that is not a front face is a back face. Direct3D does not always render back faces; therefore, back faces are said to be culled. You can change the culling mode to render back faces if you want. See Culling State for more information.

Direct3D applications do not need to specify face normals; the system calculates them automatically when they are needed. The system uses face normals in the flat shading mode. In the Gouraud shading mode, Direct3D uses the vertex normal. It also uses the vertex normal for controlling lighting and texturing effects.

When applying Gouraud shading to a polygon, Direct3D uses the vertex normals to calculate the angle between the light source and the surface. It calculates the color and intensity values for the vertices and interpolates them for every point across all the primitive's surfaces. Direct3D calculates the light intensity value by using the angle. The greater the angle, the less light is shining on the surface.

If you are creating an object that is flat, set the vertex normals to point perpendicular to the surface, as shown in the following illustration. A flat surface composed of two triangles is defined.

It is more likely, however, that your object is made up of triangle strips and the triangles are not coplanar. One simple way to achieve smooth shading across all the triangles in the strip is to first calculate the surface normal vector for each polygonal face with which the vertex is associated. The vertex normal can be set to make an equal angle with each surface normal. However, this method might not be efficient enough for complex primitives.

This method is illustrated by the following figure, which shows two surfaces, S1 and S2 seen edge-on from above. The normal vectors for S1 and S2 are shown in blue. The vertex normal vector is shown in red. The angle that the vertex normal vector makes with the surface normal of S1 is the same as the angle between the vertex normal and the surface normal of S2. When these two surfaces are lit and shaded with Gouraud shading, the result is a smoothly shaded, smoothly rounded edge between them.

If the vertex normal leans toward one of the faces with which it is associated, it causes the light intensity to increase or decrease for points on that surface, depending on the angle it makes with the light source. An example is shown in the following figure. Again, these surfaces are seen edge-on. The vertex normal leans toward S1, causing it to have a smaller angle with the light source than if the vertex normal had equal angles with the surface normals.

You can use Gouraud shading to display some objects in a 3-D scene with sharp edges. To do so, duplicate the vertex normal vectors at any intersection of faces where a sharp edge is required, as shown in the following illustration.

If you use the DrawPrimitive methods to render your scene, define the object with sharp edges as a triangle list, rather than a triangle strip. When you define an object as a triangle strip, Direct3D treats it as a single polygon composed of multiple triangular faces. Gouraud shading is applied both across each face of the polygon and between adjacent faces. The result is an object that is smoothly shaded from face to face. Because a triangle list is a polygon composed of a series of disjoint triangular faces, Direct3D applies Gouraud shading across each face of the polygon. However, it is not applied from face to face. If two or more triangles of a triangle list are adjacent, they appear to have a sharp edge between them.

Another alternative is to change to flat shading when rendering objects with sharp edges. This is computationally the most efficient method, but it may result in objects in the scene that are not rendered as realistically as the objects that are Gouraud-shaded.


Triangle Interpolants

The system interpolates the characteristics of a triangle's vertices across the triangle when it renders a face. These are the triangle interpolants:

  • Color
  • Specular
  • Alpha

All the triangle interpolants are modified by the current shading mode, as shown in the following table.

Shading mode | Description
Flat | No interpolation is done. Instead, the color of the first vertex in the triangle is applied across the entire face.
Gouraud | Linear interpolation is performed between all three vertices.

The color and specular interpolants are treated differently, depending on the color model. In the RGB color model, the system uses the red, green, and blue color components in the interpolation. In the monochromatic or ramp model, the system uses only the blue component of the vertex color.

The alpha component of a color is treated as a separate interpolant because device drivers can implement transparency in two different ways: by using texture blending or by using stippling.

Use the ShadeCaps member of the D3DCAPS8 structure to determine what forms of interpolation the current device driver supports.


Matrices and Transformations

Use matrices in Microsoft® Direct3D® to define world, view, and projection transformations. If you haven't programmed for 3-D graphics before, this section will help you familiarize yourself with the key concepts you need to understand in order to get started. If you have prior experience in 3-D programming, skip this section, or skim the following topics.

  • Matrices
  • 3-D Transformations


Matrices

Matrices in Microsoft® Direct3D® are represented by a 4´4 homogeneous matrix, defined by the D3DMATRIX structure.

The Direct3DX utility library implementation of the D3DMATRIX structure (D3DXMATRIX) implements a parentheses ("()") operator. This operator offers convenient access to values in the matrix for C++ programmers. Instead of having to refer to the structure members by name, you can refer to them by row and column number and index the numbers as needed. These indices are zero-based, so, for example, the element in the third row, second column would be M(2, 1).

You need a basic knowledge of matrices to work with Direct3D. For more information, see 3-D Transformations.


3-D Transformations

Microsoft® Direct3D® uses matrices to perform 3-D transformations. This section explains how matrices create 3-D transformations, describes some common uses for transformations, and details how you can combine matrices to produce a single matrix that encompasses multiple transformations. Information is divided into the following topics.

  • About 3-D Transformations
  • Translation
  • Rotation
  • Scaling
  • Matrix Concatenation

For more information about transformations in Direct3D, see the Direct3D Rendering Pipeline.


About 3-D Transformations

In applications that work with 3-D graphics, you can use geometrical transformations to do the following:

  • Express the location of an object relative to another object.
  • Rotate and size objects.
  • Change viewing positions, directions, and perspectives.

You can transform any point into another point by using a 4×4 matrix. In the following example, a matrix is reinterprets the point (x, y, z), producing the new point (x', y', z').

Perform the following operations on (x, y, z) and the matrix to produce the point (x', y', z').

The most common transformations are translation, rotation, and scaling. You can combine the matrices that produce these effects into a single matrix to calculate several transformations at once. For example, you can build a single matrix to translate and rotate a series of points. For more information, see Matrix Concatenation.

Matrices are written in row-column order. A matrix that evenly scales vertices along each axis, known as uniform scaling, is represented by the following matrix using mathematical notation.

In C++, Microsoft® Direct3D® declares matrices as a two-dimensional array, using the D3DMATRIX structure. The following example shows how to initialize a D3DMATRIX structure to act as a uniform scaling matrix.

// In this example, s is a variable of type float.

D3DMATRIX scale = {
    s,               0.0f,            0.0f,            0.0f,
    0.0f,            s,               0.0f,            0.0f,
    0.0f,            0.0f,            s,               0.0f,
    0.0f,            0.0f,            0.0f,            1.0f
};


Translation

The following transformation translates the point (x, y, z) to a new point (x', y', z').

You can create a translation matrix by hand in C++. The following example shows the source code for a function that creates a matrix to translate vertices.

D3DXMATRIX Translate(const float dx, const float dy, const float dz) {
    D3DXMATRIX ret;

    D3DXMatrixIdentity(&ret);  // Implemented by Direct3DX
    ret(3, 0) = dx;
    ret(3, 1) = dy;
    ret(3, 2) = dz;
    return ret;
}    // End of Translate

For convenience, the Direct3DX utility library supplies the D3DXMatrixTranslation function.


Rotation

The transformations described here are for left-handed coordinate systems, and so may be different from transformation matrices that you have seen elsewhere. For more information, see 3-D Coordinate Systems.

The following transformation rotates the point (x, y, z) around the x-axis, producing a new point (x', y', z').

The following transformation rotates the point around the y-axis.

The following transformation rotates the point around the z-axis.

In these example matrices, the Greek letter theta (θ) stands for the angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

In a C++ application, use the D3DXMatrixRotationX, D3DXMatrixRotationY, and D3DXMatrixRotationZ functions supplied by the Direct3DX utility library to create rotation matrices. The following is the code for the D3DXMatrixRotationX function.

D3DXMATRIX* WINAPI D3DXMatrixRotationX
    ( D3DXMATRIX *pOut, float angle )
{
#if DBG
    if(!pOut)
        return NULL;
#endif

    float sin, cos;
    sincosf(angle, &sin, &cos);  // Determine sin and cos of angle.

    pOut->_11 = 1.0f; pOut->_12 =  0.0f;   pOut->_13 = 0.0f; pOut->_14 = 0.0f;
    pOut->_21 = 0.0f; pOut->_22 =  cos;    pOut->_23 = sin;  pOut->_24 = 0.0f;
    pOut->_31 = 0.0f; pOut->_32 = -sin;    pOut->_33 = cos;  pOut->_34 = 0.0f;
    pOut->_41 = 0.0f; pOut->_42 =  0.0f;   pOut->_43 = 0.0f; pOut->_44 = 1.0f;

    return pOut;
}


Scaling

The following transformation scales the point (x, y, z) by arbitrary values in the x-, y-, and z-directions to a new point (x', y', z').


Matrix Concatenation

One advantage of using matrices is that you can combine the effects of two or more matrices by multiplying them. This means that, to rotate a model and then translate it to some location, you don't need to apply two matrices. Instead, you multiply the rotation and translation matrices to produce a composite matrix that contains all their effects. This process, called matrix concatenation, can be written with the following formula.

In this formula, C is the composite matrix being created, and M1 through Mn are the individual transformations that matrix C contains. In most cases, only two or three matrices are concatenated, but there is no limit.

Use the D3DXMatrixMultiply function to perform matrix multiplication.

The order in which the matrix multiplication is performed is crucial. The preceding formula reflects the left-to-right rule of matrix concatenation. That is, the visible effects of the matrices that you use to create a composite matrix occur in left-to-right order. A typical world transformation matrix is shown the following example. Imagine that you are creating the world transformation matrix for a stereotypical flying saucer. You would probably want to spin the flying saucer around its center—the y-axis of model space—and translate it to some other location in your scene. To accomplish this effect, you first create a rotation matrix, and then multiply it by a translation matrix, as shown in the following formula.

In this formula, Ry is a matrix for rotation about the y-axis, and Tw is a translation to some position in world coordinates.

The order in which you multiply the matrices is important because, unlike multiplying two scalar values, matrix multiplication is not commutative. Multiplying the matrices in the opposite order has the visual effect of translating the flying saucer to its world space position, and then rotating it around the world origin.

No matter what type of matrix you are creating, remember the left-to-right rule to ensure that you achieve the expected effects.


Vectors, Vertices, and Quaternions

Throughout Microsoft® Direct3D®, vertices describe position and orientation. Each vertex in a primitive is described by a vector that gives its position, color, texture coordinates, and a normal vector that gives its orientation.

Quaternions add a fourth element to the [x, y, z] values that define a three-component-vector. Quaternions are an alternative to the matrix methods that are typically used for 3-D rotations. A quaternion represents an axis in 3-D space and a rotation around that axis. For example, a quaternion might represent a (1,1,2) axis and a rotation of 1 radian. Quaternions carry valuable information, but their true power comes from the two operations that you can perform on them: composition and interpolation.

Performing composition on quaternions is similar to combining them. The composition of two quaternions is notated as follows:

The composition of two quaternions applied to a geometry means "rotate the geometry around axis2 by rotation2, then rotate it around axis1 by rotation1." In this case, Q represents a rotation around a single axis that is the result of applying q2, then q1 to the geometry.

Using quaternion interpolation, an application can calculate a smooth and reasonable path from one axis and orientation to another. Therefore, interpolation between q1 and q2 provides a simple way to animate from one orientation to another.

When you use composition and interpolation together, they provide you with a simple way to manipulate a geometry in a manner that appears complex. For example, imagine that you have a geometry that you want to rotate to a given orientation. You know that you want to rotate it r2 degrees around axis2, then rotate it r1 degrees around axis1, but you don't know the final quaternion. By using composition, you could combine the two rotations on the geometry to get a single quaternion that is the result. Then, you could interpolate from the original to the composed quaternion to achieve a smooth transition from one to the other.

The Direct3DX utility library includes functions that help you work with quaternions. For example, the D3DXQuaternionRotationAxis function adds a rotation value to a vector that defines an axis of rotation, and returns the result in a quaternion defined by a D3DXQUATERNION structure. Additionally, the D3DXQuaternionMultiply function composes quaternions and the D3DXQuaternionSlerp performs spherical linear interpolation between two quaternions.

Direct3D applications can use the following functions to simplify the task of working with quaternions.

  • D3DXQuaternionBaryCentric
  • D3DXQuaternionConjugate
  • D3DXQuaternionDot
  • D3DXQuaternionExp
  • D3DXQuaternionIdentity
  • D3DXQuaternionInverse
  • D3DXQuaternionIsIdentity
  • D3DXQuaternionLength
  • D3DXQuaternionLengthSq
  • D3DXQuaternionLn
  • D3DXQuaternionMultiply
  • D3DXQuaternionNormalize
  • D3DXQuaternionRotationAxis
  • D3DXQuaternionRotationMatrix
  • D3DXQuaternionRotationYawPitchRoll
  • D3DXQuaternionSlerp
  • D3DXQuaternionSquad
  • D3DXQuaternionToAxisAngle

Direct3D applications can use the following functions to simplify the task of working with three-component-vectors.

  • D3DXVec3Add
  • D3DXVec3BaryCentric
  • D3DXVec3CatmullRom
  • D3DXVec3Cross
  • D3DXVec3Dot
  • D3DXVec3Hermite
  • D3DXVec3Length
  • D3DXVec3LengthSq
  • D3DXVec3Lerp
  • D3DXVec3Maximize
  • D3DXVec3Minimize
  • D3DXVec3Normalize
  • D3DXVec3Project
  • D3DXVec3Scale
  • D3DXVec3Subtract
  • D3DXVec3Transform
  • D3DXVec3TransformCoord
  • D3DXVec3TransformNormal
  • D3DXVec3Unproject

Many additional functions that simplify tasks using two- and four-component-vectors are included among the math functions supplied by the Direct3DX utility library.


Copying Surfaces

The term blit is shorthand for "bit block transfer," which is the process of transferring blocks of data from one place in memory to another. The blitting device driver interface (DDI) continues to be used in Microsoft® DirectX® 8.0 as the primary mechanism for moving large rectangles of pixels on a per-frame basis, the mechanism behind the copy-oriented IDirect3DDevice8::Present method. The transportation of artwork in the blit operation is performed by the IDirect3DDevice8::UpdateTexture method. Artwork can also be copied in DirectX 8.0 by using the IDirect3DDevice8::CopyRects method, which copies a rectangular subset of pixels.

Note DirectX 8.0 provides D3DX functions that enable you to load artwork from files, apply color conversion, and resize artwork. For more information on the available functions see Texturing Functions.


Page Flipping and Back Buffering

Page flipping is key in multimedia, animation, and game software. Software page flipping is analogous to the way you can do animation with a pad of paper. On each page the artist changes the figure slightly, so that when you flip rapidly between sheets, the drawing appears animated.

Page flipping in software is very similar to this process. Microsoft® Direct3D® implements page flipping functionality through a swap chain which is a property of the device. Initially, you set up a series of Direct3D buffers that are designed to flip to the screen the way the artist's paper flips to the next page. The first buffer is referred to as the color front buffer and the buffers behind it are called back buffers. Your application writes to a back buffer, and then flips the color front buffer so that the back buffer appears on screen. While the system displays the image, your software is again writing to a back buffer. The process continues as long as you are animating, enabling you to animate images quickly and efficiently.

Direct3D makes it easy to set up page flipping schemes, from a relatively simple double-buffered scheme—a color front buffer with one back buffer—to more sophisticated schemes that add additional back buffers.


Rectangles

Throughout Microsoft® Direct3D® and Microsoft Windows® programming, objects on the screen are referred to in terms of bounding rectangles. The sides of a bounding rectangle are always parallel to the sides of the screen, so the rectangle can be described by two points, the top-left corner and bottom-right corner. Most applications use the RECT structure to carry information about a bounding rectangle to use when blitting to the screen or performing hit detection.

In C++, the RECT structure has the following definition.

typedef struct tagRECT {
    LONG    left;    // This is the top-left corner x-coordinate.
    LONG    top;     // The top-left corner y-coordinate.
    LONG    right;   // The bottom-right corner x-coordinate.
    LONG    bottom;  // The bottom-right corner y-coordinate.
} RECT, *PRECT, NEAR *NPRECT, FAR *LPRECT;

In the preceding example, the left and top members are the x- and y-coordinates of a bounding rectangle's top-left corner. Similarly, the right and bottom members make up the coordinates of the bottom-right corner. The following diagram illustrates how you can visualize these values.

In the interest of efficiency, consistency, and ease of use, all Direct3D presentation functions work with rectangles.


Understanding DirectX Graphics

This section describes the underlying workings of Microsoft® DirectX® Graphics.

  • Direct3D Architecture
  • Direct3D Rendering Pipeline


Direct3D Architecture

This section contains general information about the relationship between the Microsoft® Direct3D® component and the rest of Microsoft DirectX®, the operating system, and the system hardware. The following topics are discussed.

  • Architectural Overview for Direct3D
  • Hardware Abstraction Layer
  • System Integration


Architectural Overview for Direct3D

There are two programmable sections of the Microsoft® Direct3D® architecture: vertex shaders and pixel shaders. Vertex shaders are invoked prior to vertex assembly and operate on vectors. Pixel shaders are invoked after any DrawPrimitive calls and operate on pixels.

The following simplified diagram illustrates the Direct3D architecture. It is a subset of the architecture, as Direct3D supports eight sets of textures and texture coordinates.

As shown in this diagram, vertex buffers stream vertex data into the vertex shader. The vertex shader performs geometry operations using the instructions defined by the Direct3DX vertex shader assembler.

The data streamed to the vertex shader does not have to be contained in vertex buffers, but this is the ideal case. After vertex assembly, the assembled vertex data is drawn using DrawPrimitive methods. At this point, each pixel of the drawn primitive is routed to the pixel shader, including its position, color, texture, and texture coordinate. The pixel shader performs pixel operations using the instructions defined by the Direct3DX pixel shader assembler.

The inputs to the pixel processing pixel shader stage include texture surfaces and the associated texture coordinates controlling the sampling of surfaces. The output pixel is routed to the frame buffer.

For more information on the architecture of the programmable sections of the Direct3D, see Vertex Shader Architecture and Pixel Shader Architecture.

For more information on how vertex and pixel shaders fit into the rendering pipeline, see the Direct3D Rendering Pipeline.


Vertex Shader Architecture

The following diagram illustrates the vertex shader architecture.

The incoming data to the vertex data is taken from vertex data streams, and the constant data is loaded by the vertex shader declarator. For details, see the Vertex Shader Assembler Reference.


Pixel Shader Architecture

The following diagram illustrates the pixel shader architecture.

The incoming data to the pixel shader is the clip space vertex (homogeneous coordinates). The diffuse and specular color comes from the values in the color registers (v0 and v1). The texture coordinates and set textures come from the values in the texture registers (t0, t1, t2, and t3) from the texture setup stage and vertex data. For details, see the Pixel Shader Assembler Reference.


Hardware Abstraction Layer

Microsoft® Direct3D® provides device independence through the hardware abstraction layer (HAL). The HAL is a device-specific interface, provided by the device manufacturer, that Direct3D uses to work directly with the display hardware. Applications never interact with the HAL. Rather, with the infrastructure that the HAL provides, Direct3D exposes a consistent set of interfaces and methods that an application uses to display graphics. The device manufacturer implements the HAL in a combination of 16-bit and 32-bit code under Microsoft Windows®. Under Windows NT® and Windows 2000, the HAL is always implemented in 32-bit code. The HAL can be part of the display driver or a separate dynamic-link library (DLL) that communicates with the display driver through a private interface that driver's creator defines.

The Direct3D HAL is implemented by the chip manufacturer, board producer, or original equipment manufacturer (OEM). The HAL implements only device-dependent code and performs no emulation. If a function is not performed by the hardware, the HAL does not report it as a hardware capability. Additionally, the HAL does not validate parameters; Direct3D does this before the HAL is invoked.

In DirectX 8.0, the HAL can have three different vertex processing modes: software vertex processing, hardware vertex processing, and mixed vertex processing on the same device. The pure device mode is a variant of the HAL device. The pure device type supports hardware vertex processing only, and allows only a small subset of the device state to be queried by the application. Additionally, the pure device is available only on adapters that have a minimum level of capabilities.


System Integration

The following diagram shows the relationships between Microsoft® Direct3D®, the graphics device interface (GDI), the hardware abstraction layer (HAL), and the hardware.

As the preceding diagram shows, Direct3D applications exist alongside GDI applications and both have access to the graphics hardware through the device driver for the graphics card. Unlike GDI, Direct3D can take advantage of hardware features when a HAL device is selected. HAL devices provide hardware acceleration based on the feature set supported by the graphics card. You are provided with a Direct3D method to determine at run time if a device is capable of the task.

The software device, although not supporting the entire DirectX 8.0 feature set, is intended to ensure that applications can always find a working device on any system. However, in many cases an application running on a software device must be prepared to run with a downgraded set of functionality. The capabilities of the software device can be determined in the same fashion as the capabilities of a hardware device.

For more information on devices supported by Direct3D, see Device Types.


Direct3D Rendering Pipeline

The Microsoft® Direct3D® rendering pipeline is a series of processing stages that specify the behavior of the vertex transform and lighting pipeline, and the pixel and texture blending pipeline.

When you design a 3-D application, you can define the world in any units you find convenient, from microns to parsecs. Your application passes a description of that world to Direct3D. This description includes the sizes and relative positions of all the objects in your world and the position and orientation of the viewer. Direct3D transforms these descriptions (vertices) into a series of pixels on the screen. The first step of this process—the transformation of the geometry that you supply into a two-dimensional image—is the geometry pipeline, sometimes called the transformation pipeline. After vertex processing, pixel data is used to perform multitexturing and fog blending. Then alpha, stencil, and depth tests are performed. Finally, frame-buffer blending is done by the rasterizer.

The following topics provide a Direct3D-centered approach to the complete rendering pipeline. The topics introduce key concepts and make parallels from those concepts to their counterparts in the Direct3D API. The fixed-function processing section discusses techniques familiar to developers who have used earlier versions of Microsoft DirectX®, whereas the section on programmable (procedural) processing explains the new procedural model used for vertex and pixel processing in Microsoft DirectX 8.0.

  • Fixed Function Vertex and Pixel Processing
  • Programmable Vertex and Pixel Processing
  • Presenting Vertex Data to the Vertex Processor


Fixed Function Vertex and Pixel Processing

The part of Microsoft® Direct3D® that pushes geometry through the fixed function geometry pipeline is the transformation engine. It locates the model and viewer in the world, projects vertices for display on the screen, and clips vertices to the viewport. The transformation engine also performs lighting computations to determine diffuse and specular components at each vertex.

The geometry pipeline takes vertices as input. The transformation engine applies three transformations—the world, view, and projection transformations—to the vertices, clips the result, and passes everything to the rasterizer. The following image illustrates the sequence of steps.

At the head of the pipeline, no transformations have been applied, so all of a model's vertices are declared relative to a local coordinate system—this is a local origin and an orientation. This orientation of coordinates is often referred to as model space, and individual coordinates are called model coordinates.

The first stage of the geometry pipeline transforms a model's vertices from their local coordinate system to a coordinate system that is used by all the objects in a scene. The process of reorienting the vertices is called the world transformation. This new orientation is commonly referred to as world space, and each vertex in world space is declared using world coordinates.

In the next stage, the vertices that describe your 3-D world are oriented with respect to a camera. That is, your application chooses a point-of-view for the scene, and world space coordinates are relocated and rotated around the camera's view, turning world space into camera space. This is the view transformation.

The next stage is the projection transformation. In this part of the pipeline, objects are usually scaled with relation to their distance from the viewer in order to give the illusion of depth to a scene; close objects are made to appear larger than distant objects, and so on. For simplicity, this documentation refers to the space in which vertices exist after the projection transformation as projection space. Some graphics books might refer to projection space as post-perspective homogeneous space. Not all projection transformations scale the size of objects in a scene. A projection such as this is sometimes called an affine or orthogonal projection.

In the final part of the pipeline, any vertices that will not be visible on the screen are removed, so that the rasterizer doesn't take the time to calculate the colors and shading for something that will never be seen. This process is called clipping. After clipping, the remaining vertices are scaled according to the viewport parameters and converted into screen coordinates. The resulting vertices—seen on the screen when the scene is rasterized—exist in screen space.

Information on the fixed vertex and pixel processing pipeline is organized into the following topics.

  • Transformation and Lighting Engine
  • Viewports and Clipping
  • Rasterization


Transformation and Lighting Engine

The following topics explain the mechanics behind each component of the fixed function transformation and lighting engine in detail.

  • The World Transformation
  • The View Transformation
  • The Projection Transformation
  • The Lighting Engine
  • Mathematics of Direct3D Lighting


The World Transformation

The discussion of the world transformation introduces basic concepts and provides details on how to set up a world transformation matrix in a Microsoft® Direct3D® application. This information is organized into the following topics.

  • What Is the World Transformation?
  • Setting Up a World Matrix


What Is the World Transformation?

The world transformation changes coordinates from model space, where vertices are defined relative to a model's local origin, to world space, where vertices are defined relative to an origin common to all the objects in a scene. In essence, the world transformation places a model into the world; hence its name. The following diagram illustrates the relationship between the world coordinate system and a model's local coordinate system.

The world transformation can include any combination of translations, rotations, and scalings. For a discussion of the mathematics of transformations, see 3-D Transformations.


Setting Up a World Matrix

As with any other transformation, you create the world transformation by concatenating a series of transformation matrices into a single matrix that contains the sum total of their effects. In the simplest case, when a model is at the world origin and its local coordinate axes are oriented the same as world space, the world matrix is the identity matrix. More commonly, the world matrix is a combination of a translation into world space and possibly one or more rotations to turn the model as needed.

The following example, from a fictitious 3-D model class written in C++, uses the helper functions included in the Direct3DX utility library to create a world matrix that includes three rotations to orient a model and a translation to relocate it relative to its position in world space.

/*
 * For the purposes of this example, the following variables
 * are assumed to be valid and initialized.
 *
 * The m_xPos, m_yPos, m_zPos variables contain the model's
 * location in world coordinates.
 *
 * The m_fPitch, m_fYaw, and m_fRoll variables are floats that
 * contain the model's orientation in terms of pitch, yaw, and roll
 * angles, in radians.
 */

void C3DModel::MakeWorldMatrix( D3DXMATRIX* pMatWorld )
{
    D3DXMATRIX MatTemp;  // Temp matrix for rotations.
    D3DXMATRIX MatRot;   // Final rotation matrix, applied to
                         // pMatWorld.

    // Using the left-to-right order of matrix concatenation,
    // apply the translation to the object's world position
    // before applying the rotations.
    D3DXMatrixTranslation(pMatWorld, m_xPos, m_yPos, m_zPos);
    D3DXMatrixIdentity(&MatRot);

    // Now, apply the orientation variables to the world matrix
    if(m_fPitch || m_fYaw || m_fRoll) {
        // Produce and combine the rotation matrices.
        D3DXMatrixRotationX(&MatTemp, m_fPitch);         // Pitch
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);
        D3DXMatrixRotationY(&MatTemp, m_fYaw);           // Yaw
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);
        D3DXMatrixRotationZ(&MatTemp, m_fRoll);          // Roll
        D3DXMatrixMultiply(&MatRot, &MatRot, &MatTemp);

        // Apply the rotation matrices to complete the world matrix.
        D3DXMatrixMultiply(pMatWorld, &MatRot, pMatWorld);
    }
}

After you prepare the world transformation matrix, call the IDirect3DDevice8::SetTransform method to set it, specifying the D3DTS_WORLD macro for the first parameter. For more information, see Setting Transformations.

Note Microsoft® Direct3D® uses the world and view matrices that you set to configure several internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently—for example, thousands of times per frame—is computationally expensive. You can minimize the number of required calculations by concatenating your world and view matrices into a world-view matrix that you set as the world matrix, and then setting the view matrix to the identity. Keep cached copies of individual world and view matrices so that you can modify, concatenate, and reset the world matrix as needed. For clarity, in this documentation Direct3D samples rarely employ this optimization.


The View Transformation

This section introduces the basic concepts of the view transformation and provides details on how to set up a view transformation matrix in a Microsoft® Direct3D® application. This information is organized into the following topics.

  • What Is the View Transformation?
  • Setting Up a View Matrix


What Is the View Transformation?

The view transformation locates the viewer in world space, transforming vertices into camera space. In camera space, the camera, or viewer, is at the origin, looking in the positive z-direction. Recall that Microsoft® Direct3D® uses a left-handed coordinate system, so z is positive into a scene. The view matrix relocates the objects in the world around a camera's position—the origin of camera space—and orientation.

There are many ways to create a view matrix. In all cases, the camera has some logical position and orientation in world space that is used as a starting point to create a view matrix that will be applied to the models in a scene. The view matrix translates and rotates objects to place them in camera space, where the camera is at the origin. One way to create a view matrix is to combine a translation matrix with rotation matrices for each axis. In this approach, the following general matrix formula applies.

In this formula, V is the view matrix being created, T is a translation matrix that repositions objects in the world, and Rx through Rz are rotation matrices that rotate objects along the x-, y-, and z-axis. The translation and rotation matrices are based on the camera's logical position and orientation in world space. So, if the camera's logical position in the world is <10,20,100>, the aim of the translation matrix is to move objects -10 units along the x-axis, -20 units along the y-axis, and -100 units along the z-axis. The rotation matrices in the formula are based on the camera's orientation, in terms of how the much the axes of camera space are rotated out of alignment with world space. For example, if the camera mentioned earlier is pointing straight down, its z-axis is 90 degrees (pi/2 radians) out of alignment with the z-axis of world space, as shown in the following illustration.

The rotation matrices apply rotations of equal, but opposite, magnitude to the models in the scene. The view matrix for this camera includes a rotation of -90 degrees around the x-axis. The rotation matrix is combined with the translation matrix to create a view matrix that adjusts the position and orientation of the objects in the scene so that their top is facing the camera, giving the appearance that the camera is above the model.

Another approach involves creating the composite view matrix directly. The D3DXMatrixLookAtLH and D3DXMatrixLookAtRH helper functions use this technique. This approach uses the camera's world space position and a look-at point in the scene to derive vectors that describe the orientation of the camera space coordinate axes. The camera position is subtracted from the look-at point to produce a vector for the camera's direction vector (vector n). Then the cross product of the vector n and the y-axis of world space is taken and normalized to produce a right vector (vector u). Next, the cross product of the vectors u and n is taken to determine an up vector (vector v). The right (u), up (v), and view-direction (n) vectors describe the orientation of the coordinate axes for camera space in terms of world space. The x, y, and z translation factors are computed by taking the negative of the dot product between the camera position and the u, v, and n vectors.

These values are put into the following matrix to produce the view matrix.

In this matrix, u, v, and n are the up, right, and view-direction vectors, and c is the camera's world space position. This matrix contains all the elements needed to translate and rotate vertices from world space to camera space. After creating this matrix, you can also apply a matrix for rotation around the z-axis to allow the camera to roll.

For information on implementing this technique, see Setting Up a View Matrix.


Setting Up a View Matrix

The D3DXMatrixLookAtLH and D3DXMatrixLookAtRH helper functions create a view matrix based on the camera location and a look-at point. They use the D3DXVec3Cross, D3DXVec3Dot, D3DXVec3Normalize, and D3DXVec3Subtract helper functions.

The following code example, illustrates the D3DXMatrixLookAtLH function.

D3DXMATRIX* WINAPI D3DXMatrixLookAtLH
    ( D3DXMATRIX *pOut, const D3DXVECTOR3 *pEye, const D3DXVECTOR3 *pAt,
      const D3DXVECTOR3 *pUp )
{
#if DBG
    if(!pOut || !pEye || !pAt || !pUp)
        return NULL;
#endif

    D3DXVECTOR3 XAxis, YAxis, ZAxis;

    // Get the z basis vector, which points straight ahead; the
    // difference from the eye point to the look-at point. This is the
    // direction of the gaze (+z).
    D3DXVec3Subtract(&ZAxis, pAt, pEye);

    // Normalize the z basis vector.
    D3DXVec3Normalize(&ZAxis, &ZAxis);

    // Compute the orthogonal axes from the cross product of the gaze
    // and the pUp vector.
    D3DXVec3Cross(&XAxis, pUp, &ZAxis);
    D3DXVec3Normalize(&XAxis, &XAxis);
    D3DXVec3Cross(&YAxis, &ZAxis, &XAxis);

    // Start building the matrix. The first three rows contain the
    // basis vectors used to rotate the view to point at the look-at
    // point. The fourth row contains the translation values.
    // Rotations are still about the eyepoint.
    pOut->_11 = XAxis.x;
    pOut->_21 = XAxis.y;
    pOut->_31 = XAxis.z;
    pOut->_41 = -D3DXVec3Dot(&XAxis, pEye);

    pOut->_12 = YAxis.x;
    pOut->_22 = YAxis.y;
    pOut->_32 = YAxis.z;
    pOut->_42 = -D3DXVec3Dot(&YAxis, pEye);

    pOut->_13 = ZAxis.x;
    pOut->_23 = ZAxis.y;
    pOut->_33 = ZAxis.z;
    pOut->_43 = -D3DXVec3Dot(&ZAxis, pEye);

    pOut->_14 = 0.0f;
    pOut->_24 = 0.0f;
    pOut->_34 = 0.0f;
    pOut->_44 = 1.0f;

    return pOut;
}

As with the world transformation, you call the IDirect3DDevice8::SetTransform method to set the view transformation, specifying the D3DTS_VIEW flag in the first parameter. For more information, see Setting Transformations.

Performance Optimization Note Microsoft® Direct3D® uses the world and view matrices that you set to configure several internal data structures. Each time you set a new world or view matrix, the system recalculates the associated internal structures. Setting these matrices frequently—for example, 20,000 times per frame—is computationally expensive. You can minimize the number of required calculations by concatenating your world and view matrices into a world-view matrix that you set as the world matrix, and then setting the view matrix to the identity. Keep cached copies of individual world and view matrices that you can modify, concatenate, and reset the world matrix as needed. For clarity, Direct3D samples rarely employ this optimization.


The Projection Transformation

You can think of the projection transformation as controlling the camera's internals; it is analogous to choosing a lens for the camera. This is the most complicated of the three transformation types. This discussion of the projection transformation is organized into the following topics.

  • The Viewing Frustum
  • What Is the Projection Transformation?
  • Setting Up a Projection Matrix
  • A W-Friendly Projection Matrix


The Viewing Frustum

A viewing frustum is 3-D volume in a scene positioned relative to the viewport's camera. The shape of the volume affects how models are projected from camera space onto the screen. The most common type of projection, a perspective projection, is responsible for making objects near the camera appear bigger than objects in the distance. For perspective viewing, the viewing frustum can be visualized as a pyramid, with the camera positioned at the tip. This pyramid is intersected by a front and back clipping plane. The volume within the pyramid between the front and back clipping planes is the viewing frustum. Objects are visible only when they are in this volume.

If you imagine that you are standing in a dark room and looking through a square window, you are visualizing a viewing frustum. In this analogy, the near clipping plane is the window, and the back clipping plane is whatever finally interrupts your view—the skyscraper across the street, the mountains in the distance, or nothing at all. You can see everything inside the truncated pyramid that starts at the window and ends with whatever interrupts your view, and you can see nothing else.

The viewing frustum is defined by fov (field of view) and by the distances of the front and back clipping planes, specified in z-coordinates.

In this illustration, the variable D is the distance from the camera to the origin of the space that was defined in the last part of the geometry pipeline—the viewing transformation. This is the space around which you arrange the limits of your viewing frustum. For information about how this D variable is used to build the projection matrix, see What Is the Projection Transformation?


What Is the Projection Transformation?

The projection matrix is typically a scale and perspective projection. The projection transformation converts the viewing frustum into a cuboid shape. Because the near end of the viewing frustum is smaller than the far end, this has the effect of expanding objects that are near to the camera; this is how perspective is applied to the scene.

In The Viewing Frustum, the distance between the camera required by the projection transformation and the origin of the space defined by the viewing transformation is defined as D. A beginning for a matrix defining the perspective projection might use this D variable like this:

The viewing matrix puts the camera at the origin of the scene. Because the projection matrix needs to have the camera at (0, 0, -D), it translates the vector by -D in the z-direction, by using the following matrix.

Multiplying these two matrices gives the following composite matrix.

The following illustration shows how the perspective transformation converts a viewing frustum into a new coordinate space. Notice that the frustum becomes cuboid and also that the origin moves from the upper-right corner of the scene to the center.

In the perspective transformation, the limits of the x- and y-directions are -1 and 1. The limits of the z-direction are 0 for the front plane and 1 for the back plane.

This matrix translates and scales objects based on a specified distance from the camera to the near clipping plane, but it doesn't consider the field of view (fov), and the z-values that it produces for objects in the distance can be nearly identical, making depth comparisons difficult. The following matrix addresses these issues, and it adjusts vertices to account for the aspect ratio of the viewport, making it a good choice for the perspective projection.

In this matrix, Zn is the z-value of the near clipping plane. The variables w, h, and Q have the following meanings. Note that fovw and fovh represent the viewport's horizontal and vertical fields of view, in radians.

For your application, using field-of-view angles to define the x and y scaling coefficients might not be as convenient as using the viewport's horizontal and vertical dimensions (in camera space). As the math works out, the following two formulas for w and h use the viewport's dimensions, and are equivalent to the preceding formulas.

In these formulas, Zn represents the position of the near clipping plane, and the Vw and Vh variables represent the width and height of the viewport, in camera space.

For a C++ application, these two dimensions correspond directly to the Width and Height members of the D3DVIEWPORT8 structure.

Whatever formula you decide to use, it's important that you set Zn to as large a value as possible, as z-values extremely close to the camera don't vary by much. This makes depth comparisons using 16-bit z-buffers somewhat complicated.

As with the world and view transformations, you call the IDirect3DDevice8::SetTransform method to set the projection transformation; for more information, see Setting Transformations.


Setting Up a Projection Matrix

The following ProjectionMatrix sample function—written in C++—takes four input parameters that set the front and back clipping planes, as well as the horizontal and vertical field of view angles. This code parallels the approach discussed in the What Is the Projection Transformation? topic. The fields of view should be less than pi radians.

D3DMATRIX
ProjectionMatrix(const float near_plane, // Distance to near clipping
                                         // plane
                 const float far_plane,  // Distance to far clipping
                                         // plane
                 const float fov_horiz,  // Horizontal field of view
                                         // angle, in radians
                 const float fov_vert)   // Vertical field of view
                                         // angle, in radians
{
    float    h, w, Q;

    w = (float)1/tan(fov_horiz*0.5);  // 1/tan(x) == cot(x)
    h = (float)1/tan(fov_vert*0.5);   // 1/tan(x) == cot(x)
    Q = far_plane/(far_plane - near_plane);

    D3DMATRIX ret;
    ZeroMemory(&ret, sizeof(ret));

    ret(0, 0) = w;
    ret(1, 1) = h;
    ret(2, 2) = Q;
    ret(3, 2) = -Q*near_plane;
    ret(2, 3) = 1;
    return ret;
}   // End of ProjectionMatrix

After you create the matrix, you must set it in a call to the IDirect3DDevice8::SetTransform method, specifying D3DTRANSFORMSTATE_PROJECTION in the first parameter. For details, see Setting Transformations.

The Direct3DX utility library provides the following functions to help you set up your projections matrix.

  • D3DXMatrixPerspectiveLH
  • D3DXMatrixPerspectiveRH
  • D3DXMatrixPerspectiveFovLH
  • D3DXMatrixPerspectiveFovRH
  • D3DXMatrixPerspectiveOffCenterLH
  • D3DXMatrixPerspectiveOffCenterRH


A W-Friendly Projection Matrix

Microsoft® Direct3D® can use the W component of a vertex that has been transformed by the world, view, and projection matrices to perform depth-based calculations in depth-buffer or fog effects. Computations such as these require that your projection matrix normalize W to be equivalent to world-space Z. In short, if your projection matrix includes a (3,4) coefficient that is not 1, you must scale all the coefficients by the inverse of the (3,4) coefficient to make a proper matrix. If you don't provide a compliant matrix, fog effects and depth buffering are not applied correctly. The projection matrix recommended in What Is the Projection Transformation? is compliant with w-based calculations.

The following illustration shows a non-compliant projection matrix, and the same matrix scaled so that eye-relative fog will be enabled.

In the preceding matrices, all variables are assumed to be nonzero. For more information about eye-relative fog, see Eye-Relative vs. Z-based Depth. For information about w-based depth buffering, see What Are Depth Buffers?

Note Direct3D uses the currently set projection matrix in its w-based depth calculations. As a result, applications must set a compliant projection matrix to receive the desired w-based features, even if they do not use the Direct3D transformation pipeline.


The Lighting Engine

This section introduces the general concepts behind the Microsoft® Direct3D® lighting engine. The following topics are discussed.

  • Enabling and Disabling the Lighting Engine
  • Light Color Types and Sources
  • Fog Effects

For detailed information on the inner working of the lighting engine, see Mathematics of Direct3D Lighting.


Enabling and Disabling the Lighting Engine

By default, Microsoft® Direct3D® performs lighting calculations on all vertices, even those without vertex normals. This is different from the behavior in previous releases of Microsoft DirectX®, where lighting was performed only on vertices that contained a vertex normal. However, you can disable lighting through the D3DRS_LIGHTING render state. Call the IDirect3DDevice8::SetRenderState method, passing D3DRS_LIGHTING as the first parameter, and TRUE or FALSE as the second parameter. Setting the state to TRUE enables lighting (the default), and setting it to FALSE disables lighting operations.


Light Color Types and Sources

Light sources in Microsoft® Direct3D® emit diffuse, ambient, and specular colors as distinct light components that factor into lighting computations independently of each other. Similarly, the vertices that the system renders can use discrete diffuse, ambient, specular, and emissive colors, as defined by their vertex format.

For a C++ application, these vertex colors are used by the system only when you set the D3DRS_COLORVERTEX render state to TRUE. Vertex color sources are selectable; that is, you can configure the system to select the source for the vertex-color portions of lighting formulas at run time. The D3DRS_AMBIENTMATERIALSOURCE, D3DRS_DIFFUSEMATERIALSOURCE, and D3DRS_SPECULARMATERIALSOURCE render states control the source from which the system draws the associated colors during lighting calculations. You can set each render state to a member of the D3DMATERIALCOLORSOURCE enumerated type, which defines values that cause the system to use the current material, or a color from the vertex, as the color source.


Fog Effects

The Microsoft® Direct3D® transformation and lighting engine can create fog effects during lighting. This type of fog is usually referred to as vertex fog because fog information is placed in the alpha component of the vertex to be rasterized.

For more information see Fog and Vertex Fog.


Mathematics of Direct3D Lighting

This section describes the mechanics and implementation details behind the Microsoft® Direct3D® lighting engine. Direct3D models illumination by estimating how light behaves in nature. The Direct3D light model keeps track of light color, the direction and distance that light travels, the position of the viewer, and the characteristics of the current material to compute two color components for each vertex in a face. Direct3D uses these color components to compute the color it draws while rasterizing the pixels of a face.

Note All computations are made in model space by transforming the light source's position and direction, along with the camera position to model space using the inverse of the world matrix, then they are back transformed. As a result, if the world or view matrices introduce nonuniform scaling, the resultant lighting might be inaccurate.

This section presents a technical look at the formulas that Direct3D uses to come up with diffuse and specular components. By understanding the approach of Direct3D, you will be better equipped to decide if the Direct3D light model suits your needs. The Direct3D light model was designed to be accurate, efficient, and easy to use. However, if the formulas used by Direct3D don't suit your needs, you can implement your own light model, bypassing the Direct3D lighting module altogether. The following topics are discussed.

  • Lighting Notation
  • Camera Space Transformation
  • Basic Lighting Formula
  • Diffuse Formula
  • Specular Formula
  • Light Attenuation Over Distance
  • Reflectance Model
  • Spotlight Falloff Model

The parameters used for these formulas are listed in the tables below. Each table has its corresponding default value, type, and a range of accepted values.

The following table lists the position parameters.

Parameter | Default value | Type | Description
Pe | (0,0,0) | D3DVECTOR | Camera position in camera space.
Po | N/A | D3DVECTOR | Position of current model origin (0,0,0,1) in the camera space. This is the fourth row of the Mw*Mv matrix.
Mw | N/A | D3DMATRIX | World matrix, set by D3DTRANSFORMSTATE_VIEW.
Mv | N/A | D3DMATRIX | View matrix, set by D3DTRANSFORMSTATE_VIEW.
Mwv | N/A | D3DMATRIX | Mw*Mv.
Halfway | N/A | D3DVECTOR | Normalized vector, used to compute specular reflection.
La | (0.0, 0.0, 0.0, 0.0) | D3DCOLORVALUE | Ambient color in the light state. Set by D3DRENDERSTATE_AMBIENT.
V | N/A | D3DVECTOR | Vertex position in camera space.
N | N/A | D3DVECTOR | Normalized vertex normal in camera space.
Vcd | N/A | D3DCOLORVALUE | Vertex diffuse color.
Vcs | N/A | D3DCOLORVALUE | Vertex specular color.

The following table lists the material parameters.

Parameter | Default value | Type | Description
Ma | (0.0, 0.0, 0.0, 0.0) | D3DCOLORVALUE | Ambient color.
Md | (255, 255, 255, 255) | D3DCOLORVALUE | Diffuse color.
Ms | (0.0, 0.0, 0.0, 0.0) | D3DCOLORVALUE | Specular color.
Me | (0.0, 0.0, 0.0, 0.0) | D3DCOLORVALUE | Emissive color.
Mp | 0.0 | D3DVALUE | Specular exponent. Range: (-∞,+∞)

The following table lists the light source i parameters.

Parameter | Default value | Type | Description
LpI | (0.0, 0.0, 0.0) | D3DVECTOR | Position in camera space.
LdI | (0.0, 0.0, 1.0) | D3DVECTOR | Direction to the light in the camera space.
LrI | 0.0 | D3DVALUE | Distance range. Range: [0.0, D3DLIGHT_RANGE_MAX]
LcaI | (0.0, 0.0, 0.0, 0.0) | D3DCOLORVALUE | Ambient color.
LcsI | (0.0, 0.0, 0.0, 0.0) | D3DCOLORVALUE | Specular color.
LcI | (1.0, 1.0, 1.0, 0.0) | D3DCOLORVALUE | Diffuse color.
att0I | 0.0 | D3DVALUE | Constant attenuation factor. Range: (0, +∞)
att1I | 0.0 | D3DVALUE | Linear attenuation factor. Range: (0, +∞)
att2I | 0.0 | D3DVALUE | Quadratic attenuation factor. Range: (0, +∞)
falloffI | 0.0 | D3DVALUE | Falloff factor. Range: (-∞, +∞)
thetaI | 0.0 | D3DVALUE | Umbra angle of spotlight in radians. Range: [0, π)
phiI | 0.0 | D3DVALUE | Penumbra angle of spotlight in radians. Range: [thetaI, π)


Lighting Notation

The following notations are used in the lighting formulas.

The range of a D3DCOLORVALUE component is (-∞, +∞).

· - dot product is defined as d1 · d2 = max{d1·d2, 0}

norm(P) - normalized vector

V1V2 - vector from point V1 to point V2

M-1- inverse matrix

MT- transposed matrix

V1 / V2 , where V1 and V2 are of D3DVECTOR type, equals to the vector: (V1.x / V2.x, V1.y / V2.y , V1.z / V2.z).

V1 * V2 , where V1 and V2 are of D3DVECTOR type, equals to the vector: (V1.x * V2.x, V1.y * V2.y , V1.z * V2.z).


Camera Space Transformation

Vertices in the camera space are computed by multiplying the object vertices by Mwv matrix.

v = Vobject * Mwv

Normals in the camera space are computed by multiplying the object normals by inverse transposed Mwv matrix and normalizing the result.

N = Nobject * (Mwv-1)T

If D3DRENDERSTATE_NORMALIZENORMALS is set to TRUE, normals are normalized after transformation to the camera space:

N = norm(N)

Light position in the camera space (Lpi) is computed by multiplying the light source position by Mv.

Lpi = Lporiginal * Mv

Direction to light in the camera space for D3DLIGHT_DIRECTIONAL lights is computed by multiplying the light source position by Mv matrix, normalizing and negating the result.

Ldi = -norm(Ldi original * Mv)

For the D3DLIGHT_POINT and D3DLIGHT_SPOT the direction to light is computed as:

Ldi = norm(VLpi)


Basic Lighting Formula

The output of the lighting stage is diffuse (D) and specular (S) colors in RGBA format. Lighting may be in one of two states:

1. Lighting Off (D3DRENDERSTATE_LIGHTING is set to FALSE). In this state the vertex color is computed as follows:

D3DRENDERSTATE_COLORVETEX is ignored.

If the diffuse vertex color is present, the output diffuse color is equal to the vertex diffuse color. Otherwise, the diffuse color is equal to the default diffuse color (255,255,255,255). Output diffuse color is scaled and clamped to the range [0, 255].

If the specular vertex color is present, the output specular color is equal to the vertex specular color. Otherwise, the specular color is equal to the default specular (0,0,0,0). Output specular color is scaled and clamped to the range [0, 255].

2. Lighting On (D3DRENDERSTATE_LIGHTING is set to TRUE). In this state, Direct3D computes vertex colors according to the formulas below.

If normals are not present in the vertices, the part of the lighting equations that depends on dot product is set to zero. Lighting is still computed.

Lighting is done in the camera space.

alpha component is not used in the following lighting equations.


Diffuse Formula

The following explains the formula for diffuse lighting.

The specular component is set to (0, 0, 0, 0) if D3DRENDERSTATE_SPECULARENABLE is set to FALSE, otherwise it is computed as follows:

where


Specular Formula

The following explains the formula for specular lighting.

hi are half way vectors between the normal and the direction to light.

hi = norm(norm(Vpe) + Ldi)), if D3DRENDERSTATE_LOCALVIEWER = TRUE

hi = norm((0,0,-1) + Ldi)), if D3DRENDERSTATE_LOCALVIEWER = FALSE

rhoi = norm(Ldi) • norm(VLpi)

di is a distance from a vertex to the light i and is computed as follows:

Diffuse and specular components are clamped to be from 0 to 255, after all lights are processed and interpolated separately.


Light Attenuation Over Distance

Microsoft® Direct3D® determines the distance between a light source and a vertex being lit by taking the magnitude of the vector that exists between the light's position and the vertex. This is represented by the following formula.

In the preceding formula, D is the distance being calculated, V is the position of the vertex being lit, and L is the light source's position. If D is greater than the light's range, that is, the Range member of a D3DLIGHT8 structure, Direct3D makes no further attenuation calculations and applies no effects from the light to the vertex. If the distance is within the light's range, Direct3D then applies the following formula to calculate light attenuation over distance for point lights and spotlights; directional lights don't attenuate.

In this attenuation formula, A is the calculated total attenuation and D is the distance from the light source to the vertex. The dvAttenuation0, dvAttenuation1, and dvAttenuation2 values are the light's attenuation constants as specified by the members of a light object's D3DLIGHT8 structure. The corresponding structure members are Attenuation0, Attenuation1, and Attenuation2.

The attenuation constants act as coefficients in the formula—you can produce a variety of attenuation curves by making simple adjustments to them. You can set Attenuation0 to 1.0 to create a light that doesn't attenuate but is still limited by range, or you can experiment with different values to achieve various attenuation effects.

The attenuation at the maximum range of the light is not 0.0. To prevent lights from suddenly appearing when they are at the light range, an application can increase the light range. Or, the application can set up attenuation constants so that the attenuation factor is close to 0.0 at the light range. The attenuation value is multiplied by the red, green, and blue components of the light's color to scale the light's intensity as a factor of the distance light travels to a vertex.

After computing the light attenuation, Direct3D also considers spotlight effects if applicable, the angle that the light reflects from a surface, and the reflectance of the current material to calculate the diffuse and specular components for that vertex. For more information, see Spotlight Falloff Model and Reflectance Model.


Reflectance Model

After adjusting the light intensity for any attenuation effects, Microsoft® Direct3D® computes how much of the remaining light reflects from a vertex given the angle of the vertex normal and the direction of the incident light. Direct3D skips to this step for directional lights because they don't attenuate over distance.

The system considers two reflection types, diffuse and specular, and uses a different formula to determine how much light is reflected for each. After calculating the amounts of light reflected, Direct3D applies these new values to the diffuse and specular reflectance properties of the current material. The resulting color values are the diffuse and specular components that the rasterizer uses to produce Gouraud shading and specular highlighting.

Diffuse Reflection Model

Microsoft Direct3D uses the following formula to compute diffuse reflection factors.

In this formula, Rd is the diffuse reflectance factor, D is the direction that the light travels to the vertex, and N is the vertex normal. Vector D is normalized; vector N is normalized only if the D3DRS_NORMALIZENORMALS render state is enabled. The light's direction vector is reversed by multiplying it by -1 to create the proper association between the direction vector and the vertex normal. This formula produces values that range from -1.0 to 1.0, which are clamped to the range of 0.0 to 1.0 and used to scale the intensity of the light reflecting from the vertex.

After the diffuse reflection formula is applied, the scaled light is then applied to the diffuse reflectance formula to determine the diffuse component at that vertex. The formula that combines ambient and diffuse reflection to create the diffuse component for the vertex looks like this:

In the preceding formula, Dv is the diffuse component being calculated for the vertex, Ia is the ambient light level in the scene, and A is the light intensity for a light source that has been attenuated for distance and spotlight effects (attenuation from Light Attenuation Over Distance multiplied by Spotlight Falloff Model). The L variables represent the light's properties, and the V entries represent the vertex color, where the subscripts a, d, and e applied to each denote the type of color—ambient, diffuse, or emissive. As the formula notation states, the system computes IaVa + Ve once, adding A(RdVdLd + VaLa) for every active light.

If the D3DRS_COLORVERTEX render state is enabled, the system selects colors for V based on the values set for the D3DRS_AMBIENTMATERIALSOURCE and D3DRS_DIFFUSEMATERIALSOURCE render states. Set these render states to a member of the D3DMATERIALCOLORSOURCE enumerated type to cause the system to use the current material, or a color from the vertex, as the color source.

For more information, see Specular Reflection Model.

Specular Reflection Model

Modeling specular reflection requires that the system not only know the direction that light is traveling, but also the direction to the viewer's eye. The system uses a simplified version of the Phong specular-reflection model, which employs a halfway vector to approximate the intensity of specular reflection. This halfway vector exists midway between the vector to the light source and the vector to the eye. Microsoft Direct3D provides applications with two ways to compute the halfway vector, which is controlled by the D3DRS_LOCALVIEWER render state. If D3DRS_LOCALVIEWER is set to TRUE, the system calculates the halfway vector using the position of the camera and the position of the vertex, along with the light's direction vector. The following formula illustrates this.

In the preceding formula, norm is an operator that normalizes an input vector, VC is the vector that exists from the position of the vertex to the position of the viewpoint or eye, and Ld is the light's direction vector.

Determining the halfway vector in this manner can be computationally expensive. As an alternative, you can set D3DRS_LOCALVIEWER to FALSE. This instructs the system to act as though the viewpoint is infinitely distant on the z-axis. This setting is less computationally expensive, but much less accurate, so it is best used by applications that use orthogonal projection. When D3DRS_LOCALVIEWER is set to FALSE, Direct3D determines the halfway vector by the following formula.

This formula is similar to the first formula, but substitutes the vector I (0, 0, -1)—which points at a viewpoint infinitely distant on the z-axis—instead of computing the vector VC.

After determining the halfway vector, H, the system uses the following formula to compute specular reflection.

In the preceding formula, Rs is the specular reflectance, N in the vertex normal, H is the halfway vector, and p is the specular reflection power of the current material, as specified by the Power member of the material's D3DMATERIAL8 structure. Vector H is normalized, and vector N is normalized only if the D3DRS_NORMALIZENORMALS render state is enabled.

As with the diffuse reflectance formula, this formula produces values that range from -1.0 to 1.0, which are clamped to the range of 0.0 to 1.0 and used to scale the light reflecting from the vertex. Also similar to the diffuse reflection model, the remaining light is applied to a formula that derives the specular component at that vertex:

In this formula, Sv is the specular color being computed. A is the light from a single light source that has been attenuated for distance and spotlight effects; for more information, see Light Attenuation Over Distance and Spotlight Falloff Model. The Rs variable is the previously calculated specular reflectance, Vs is the specular component for the vertex, and Ls is the specular light color output by the light.

If the D3DRS_COLORVERTEX render state is enabled, the system selects the color source for V based on the value of the D3DRS_SPECULARMATERIALSOURCE render state. This render state can be set to a member of the D3DMATERIALCOLORSOURCE enumerated type to cause the system to use the current material or one of the color components for the vertex as the color source.

For more information, see Diffuse Reflection Model.


Spotlight Falloff Model

Spotlights emit a cone of light that has two parts: a bright inner cone and an outer cone. Light is brightest in the inner cone and isn't present outside the outer cone, with light intensity attenuating between the two areas. This type of attenuation is commonly referred to as falloff.

How much light a vertex receives is based on the vertex's location in the inner or outer cones. Microsoft® Direct3D® computes the dot product of the spotlight's direction vector (L) and the vector from the vertex to the light (D). This value is equal to the cosine of the angle between the two vectors, and serves as an indicator of the vertex's position that can be compared to the light's cone angles to determine where the vertex might lie in the inner or outer cones. The following illustration provides a graphical representation of the association between these two vectors.

Next, the system compares this value to the cosine of the spotlight's inner and outer cone angles. In the light's D3DLIGHT8 structure, the Theta and Phi members represent the total cone angles for the inner and outer cones. Because the attenuation occurs as the vertex becomes more distant from the center of illumination, rather than across the total cone angle, Direct3D halves these cone angles before calculating their cosines.

If the dot product of vectors L and D is less than or equal to the cosine of the outer cone angle, the vertex lies beyond the outer cone and receives no light. If the dot product of L and D is greater than the cosine of the inner cone angle, then the vertex is within the inner cone and receives the maximum amount of light, still considering attenuation over distance. If the vertex is somewhere between the two regions, Direct3D calculates falloff for the vertex by using the following formula.

In the formula, If is light intensity, after falloff, for the vertex being lit, α is the angle between vectors L and D, φ is half of the outer cone angle, θ is half of the inner cone angle, and p is the spotlight's falloff property—Falloff in the D3DLIGHT8 structure. This formula generates a value between 0.0 and 1.0 that scales the light's intensity at the vertex to account for falloff. Attenuation as a factor of the vertex's distance from the light is also applied. The p value corresponds to the Falloff member of the D3DLIGHT8 structure and controls the shape of the falloff curve. The following illustration shows how different Falloff values can affect the falloff curve.

The effect of various Falloff values on the actual lighting is subtle, and a small performance penalty is incurred by shaping the falloff curve with Falloff values other than 1.0. For these reasons, this value is typically set to 1.0.

For more information, see Light Attenuation Over Distance.


Viewports and Clipping

This section discusses clipping, the last stage of the geometry pipeline. The discussion is organized into the following topics.

  • What Is a Viewport?
  • Viewport Rectangle
  • Clipping Volumes
  • Viewport Scaling
  • Using Viewports

Microsoft® Direct3D® implements clipping by way of a set of viewport parameters set in the device.


What Is a Viewport?

Conceptually, a viewport is a 2-D rectangle into which a three-dimensional scene is projected. In Microsoft® Direct3D®, the rectangle exists as coordinates within a Direct3D surface that the system uses as a rendering target. The projection transformation converts vertices into the coordinate system used for the viewport.

You use a viewport in Direct3D to specify the following features in your application.

  • The screen-space viewport to which the rendering will be confined.
  • The range of depth values on a render-target surface into which a scene will be rendered (usually 0.0 to 1.0).


Viewport Rectangle

You define the viewport rectangle in C++ by using the D3DVIEWPORT8 structure. The D3DVIEWPORT8 structure is used with the following viewport manipulation methods exposed by the IDirect3DDevice8 interface.

  • IDirect3DDevice8::GetViewport
  • IDirect3DDevice8::SetViewport

The D3DVIEWPORT8 structure contains four members—X, Y, Width, and Height—that define the area of the render-target surface into which a scene will be rendered. These values correspond to the destination rectangle, or viewport rectangle, as shown in the following illustration.

The values you specify for the X, Y, Width, and Height members of the D3DVIEWPORT8 structure are screen coordinates relative to the upper-left corner of the render-target surface. The structure defines two additional members (MinZ and MaxZ) that indicate the depth-ranges into which the scene will be rendered.

Microsoft® Direct3D® assumes that the viewport clipping volume ranges from -1.0 to 1.0 in X, and from 1.0 to -1.0 in Y. These were the settings used most often by applications in the past. During the projection transformation, you can adjust for viewport aspect ratio before clipping. This task is covered by topics in The Projection Transformation section.

Note The D3DVIEWPORT8 structure members MinZ and MaxZ indicate the depth-ranges into which the scene will be rendered and are not used for clipping. Most applications will set these members to 0.0 and 1.0 to enable the system to render to the entire range of depth values in the depth buffer. In some cases, you can achieve special effects by using other depth ranges. For instance, to render a heads-up display in a game, you can set both values to 0.0 to force the system to render objects in a scene in the foreground, or you might set them both to 1.0 to render an object that should always be in the background.


Clipping Volumes

The results of the projection matrix determine the clipping volume in projection space. Microsoft® Direct3D® defines the clipping volume in projection space as:

In the preceding formulas, Xc, Yc, Zc, and Wc represent the vertex coordinates after the projection transformation is applied. Any vertices that have an x, y, or z component outside these ranges are clipped, if clipping is enabled (the default behavior).

With the exception of vertex buffers, applications enable or disable clipping by way of the D3DRS_CLIPPING render state. Clipping information for vertex buffers is generated during processing, for more information see Processing Vertices.

Direct3D does not clip transformed vertices of a primitive from a vertex buffer unless it comes from IDirect3DDevice8::ProcessVertices. If you are doing your own transforms and need Direct3D to do the clipping you should not use vertex buffers; in this case, the application traverses the data to transform it, Direct3D traverses the data a second time to clip it, and then the driver renders the data which is inefficient. So, if the application transforms the data is should also clip the data.


Viewport Scaling

The dimensions used in the X, Y, Width, and Height members of the D3DVIEWPORT8 structure for a viewport define the location and dimensions of the viewport on the render-target surface. These values are in screen coordinates, relative to the upper-left corner of the surface.

Microsoft® Direct3D® uses the viewport location and dimensions to scale the vertices to fit a rendered scene into the appropriate location on the target surface. Internally, Direct3D inserts these values into a matrix that is applied to each vertex:

This matrix simply scales vertices according to the viewport dimensions and desired depth range and translates them to the appropriate location on the render-target surface. The matrix also flips the y-coordinate to reflect a screen origin at the top-left corner with y increasing downward. After this matrix is applied, vertices are still homogeneous—that is, they still exist as [x,y,z,w] vertices—and they must be converted to non-homogeneous coordinates before being sent to the rasterizer. This is performed by way of simple division, as discussed in Rasterization.

Note The viewport scaling matrix incorporates the MinZ and MaxZ members of the D3DVIEWPORT8 structure to scale vertices to fit the depth range [MinZ, MaxZ]. This represents different semantics from previous releases of Microsoft DirectX, in which these members were used for clipping.

For more information, see Viewport Rectangle and Clipping Volumes. Applications typically set MinZ and MaxZ to 0.0 and 1.0 to cause the system to render to the entire depth range. However, you can use other values to achieve certain affects. You might set both values to 0.0 to force all objects into the foreground, or set both to 1.0 to render all objects into the background.


Using Viewports

This section provides details about working with viewports. Information is divided into the following topics.

  • Setting the Viewport Clipping Volume
  • Clearing a Viewport
  • Manually Transforming Vertices


Setting the Viewport Clipping Volume

The only requirement for configuring the viewport parameters for a rendering device is to set the viewport's clipping volume. To do this, you initialize and set clipping values for the clipping volume and for the render-target surface. Viewports are commonly set up to render to the full area of the render-target surface, but this isn't a requirement.

You can use the following settings for the members of the D3DVIEWPORT8 structure to achieve this in C++.

D3DVIEWPORT8 viewData = { 0, 0, width, height, 0.0f, 1.0f };

After setting values in the D3DVIEWPORT8 structure, apply the viewport parameters to the device by calling its IDirect3DDevice8::SetViewport method. The following code example shows what this call might look like.

HRESULT hr;

hr = pd3dDevice->SetViewport(&viewData);
if(FAILED(hr))
    return hr;

If the call succeeds, the viewport parameters are set and will take effect the next time a rendering method is called. To make changes to the viewport parameters, just update the values in the D3DVIEWPORT8 structure and call SetViewport again.

Note The D3DVIEWPORT8 structure members MinZ and MaxZ indicate the depth-ranges into which the scene will be rendered and are not used for clipping. Most applications set these members to 0.0 and 1.0 to enable the system to render to the entire range of depth values in the depth buffer. In some cases, you can achieve special effects by using other depth ranges. For instance, to render a heads-up display in a game, you can set both values to 0.0 to force the system to render objects in a scene in the foreground, or you might set them both to 1.0 to render an object that should always be in the background.


Clearing a Viewport

Clearing the viewport resets the contents of the viewport rectangle on the render-target surface as well as the rectangle in the depth and stencil buffer surfaces, if specified. Typically, you clear the viewport before rendering a new frame to ensure that graphics and other data is ready to accept new rendered objects without displaying artifacts.

The IDirect3DDevice8 interface offers C++ developers the IDirect3DDevice8::Clear method to clear the viewport. The method accepts one or more rectangles that define the areas on the surfaces being cleared. In cases where the scene being rendered includes motion throughout the entire viewport rectangle—in a first-person perspective game, for example—you might want to clear the entire viewport each frame. In this situation, you set the Count parameter to 1, and the pRects parameter to the address of a single rectangle that covers the entire viewport area. If it is more convenient, you can set the pRects parameter to NULL and the Count parameter to 0 to indicate that the entire viewport rectangle should be cleared.

The Clear method is flexible, and it provides support for clearing stencil bits within a depth buffer. The Flags parameter accepts three flags that determine how it clears the render target and any associated depth or stencil buffers. If you include the D3DCLEAR_TARGET flag, the method clears the viewport using an arbitrary RGBA color that you provide in the Color parameter (not the material color). If you include the D3DCLEAR_ZBUFFER flag, the method clears the depth buffer to an arbitrary depth you specify in Z:. 0.0 is the closest distance, and 1.0 is the farthest. Including the D3DCLEAR_STENCIL flag causes the method to reset the stencil bits to the value you provide in the Stencil parameter. You can use integers that range from 0 to 2n-1, where n is the stencil buffer bit depth.

Note Microsoft® DirectX® 5.0 allowed background materials to have associated textures, making it possible to clear the viewport to a texture rather than a simple color. This feature was little used, and not particularly efficient. Interfaces for DirectX 6.0 and later do not accept texture handles, meaning that you can no longer clear the viewport to a texture. Rather, applications must now draw backgrounds manually. As a result, there is rarely a need to clear the viewport on the render-target surface. As long as your application clears the depth buffer, all pixels on the render-target surface will be overwritten anyway.

In some situations, you might be rendering only to small portions of the render target and depth buffer surfaces. The clear methods also enable you to clear multiple areas of your surfaces in a single call. Do this by setting the Count parameter to the number of rectangles you want cleared, and specify the address of the first rectangle in an array of rectangles in the pRects parameter.


Manually Transforming Vertices

You can use three kinds of vertices in your Microsoft® Direct3D® application. Read Vertex Formats for more details on the vertex formats.

Untransformed and Unlit Vertices
Vertices that your application doesn't light or transform. Although you specify lighting parameters and transformation matrices, Direct3D computes these values.
Untransformed and Lit Vertices
Vertices that your application lights but does not transform.
Transformed and Lit Vertices
Vertices that your application both lights and transforms.

You can change from simple to complex vertex types by using vertex buffers. Vertex buffers are objects used to efficiently contain and process batches of vertices for rapid rendering, and are optimized to exploit processor-specific features. Use the IDirect3DDevice8::ProcessVertices method to perform vertex transformations. ProcessVertices accepts only untransformed vertices and can optionally light and clip vertices as well. Lighting is performed at the time you call the ProcessVertices methods, but clipping is performed at render time.

After processing the vertices, you can use special rendering methods to render the vertices, or you can access them directly by locking the vertex buffer memory. For more information about using vertex buffers, see Vertex Buffers.


Rasterization

After passing through the Microsoft® Direct3D® geometry pipeline, vertices have been transformed, clipped, and scaled to fit in the viewport on the render-target surface, making them almost ready to send to the rasterizer to paint on the screen. However, the vertices are still homogeneous, and the rasterizer expects to receive vertices in terms of their x-, y-, and z-locations, as well as the reciprocal-of-homogeneous-w (RHW). Direct3D converts the homogeneous vertices to non-homogeneous vertices by dividing the x-, y-, and z-coordinates by the w-coordinate. Direct3D then produces an RHW value by inverting the w-coordinate, as in the following formulas.

The resulting values are passed to the rasterizer for display. The rasterizer uses the x- and y-coordinates as the screen coordinates for the vertex, and it uses the z-coordinate for depth comparisons in the depth buffer when z-buffering is enabled. The RHW value is used in multiple ways: for calculating fog, for performing perspective-correct texture mapping, and for w-buffering—an alternate form of depth buffering.


Programmable Vertex and Pixel Processing

Microsoft® DirectX® 8.0 features a new kind of graphics pipeline, featuring a high degree of programmability. The following diagram illustrates the major components and data flow in the programmable vertex and pixel pipeline. The transformation and lighting engine and DirectX 6.0 and 7.0 multitexturing modules have been replaced in the programmable pipeline by vertex and pixel shaders.

The first new part of the pipeline is the high-order primitive module, which works to tessellate high-order primitives such as bézier and B-splines. The vertex shader is a programmable module used to execute geometric operations on the vertex data. The vertex shader can perform a variety of functions which includes standard transformation and lighting. The pixel shader module is a programmable pixel processor. Pixel shaders control the color and alpha blending operations and the texture addressing operations.

For general information on programmable shaders, see Introduction to Procedural Shaders.

For information on how the Microsoft Direct3D® pipeline for DirectX 8.0 compares to previous versions, see Integration of Vertex Shaders into the Geometry Pipeline.

For information on the nonprogrammable sections of the pipeline, which have remained unchanged from DirectX 6.0 and 7.0, see Viewports and Clipping and Rasterization.


Introduction to Procedural Shaders

In Microsoft® Direct3D® for Microsoft DirectX® 8.0, procedural models are used for specifying the behavior of the vertex transformation and lighting pipeline and the pixel texture blending pipeline. There are many advantages to a program model-based syntax for specifying the behavior of the hardware.

First, a procedural model allows a more general syntax for specifying common operations. Fixed-function, as opposed to programmable, APIs must define modes, flags, and so on for an increasing number of operations that need to be expressed. Further, with the increasing power of the hardware—more colors, more textures, more vertex streams, an so on—the token space for the operations multiplied by the data inputs becomes complex. A programmability model, on the other hand, enables even simple operations such as getting the right color and right texture into the right part of the lighting model in a more direct fashion. You do not have to search through all the possible modes; you just have to learn the machine architecture and specify the desired algorithm to be performed.

For example, the following well-known features can be supported.

  • Basic geometry transformations
  • Simple lighting models
  • Vertex blending for skinning
  • Vertex morphing (tweening)
  • Texture transforms
  • Texture generation
  • Environment mapping

Second, a procedural model provides an easy mechanism for developing new operations. There are many operations that developers find they need that are not supported in current APIs. In most cases, this is not due to limitations in the capabilities of the hardware but rather to restrictions in the APIs. In general, these operations are also simpler and therefore faster than trying to extract the same behavior by contorting a fixed function API to an extent beyond its designer's expectations.

Examples of new features expected to be commonly implemented include the following:

  • Matrix Palette Skinning. Character animation with 8-10 bones per mesh.
  • Anisotropic Lighting. Lighting that currently can be done only at the cost of textures for look-up tables.
  • Membrane Shaders. Shaders for balloons, skin, and so on (1/cos(eye DOT normal).
  • Kubelka-Munk Shaders. Shaders that take into account light that penetrates the surface.
  • Procedural Geometry. Compositing meshes with procedural ones (spheres) to simulate muscles moving under the skin.
  • Displacement Mapping. Modifying a mesh with a wave pattern or hump that can be tiled/repeated.

Third, a procedural model provides for scalability and evolvability. Hardware capabilities are continuing to evolve rapidly, and programmatic representations can help adapt the API because they scale very well. New features and capabilities can be easily exposed in an incremental way by the following operations.

  • Adding new instructions
  • Adding new data inputs
  • Adding new capabilities from the fixed-function to the programmable portion of the pipeline

Code is the representation that has the best scaling properties for representing complexity. Further, the amount of code that must change inside Direct3D is very small for new features added to the programmable shaders.

Fourth, a procedural model offers familiarity. Software developers understand programming better than they do hardware. An API that truly caters to software developers should map hardware functionality into a code paradigm.

Fifth, a procedural model follows in the footsteps of a photo-real rendering heritage. There has been a tradition of using programmable shaders in high-end photo-real rendering for many years. In general, this area is unconstrained by performance, so programmable shaders represent the ultimate no-compromise goal for rendering technologies.

Lastly, a procedural model enables direct mapping to the hardware. Most current 3-D hardware, at the vertex processing stage at least, is actually fairly programmable. The programmability through the API enables the application to map directly to this hardware. This enables an you to manage the hardware resources according to their requirements. With a limited set of registers or instructions that can be executed, it is difficult to make a fixed-function implementation that can have all its features enabled independently. If you turn on too many features that require a shared resource, they can stop working in unexpected ways. The programmable API model follows in the DirectX tradition of eliminating this problem by letting the application developer talk directly to the hardware, making any such limitations transparent.


Integration of Vertex Shaders into the Geometry Pipeline

When in operation, a programmable vertex shader replaces the transformation and lighting module in the Microsoft® Direct3D® geometry pipeline. In effect, state information regarding transformation and lighting operations are ignored. However, when the vertex shader is disabled and fixed function processing is returned, all current state settings apply.

Any tessellation of high-order primitives should be done before execution of the vertex shader. Implementations that perform surface tessellation after the shader processing must do so in a way that is not apparent to the application and shader code. Because no semantic information is normally provided before the shader, a special token is used to identify which input stream component represents the base position relative to which all other components are interpolated. No non-interpolable data channels are supported.

On output, the vertex shader must generate vertex positions in homogeneous clip space. Additional data that can be generated includes texture coordinates, colors, fog factors and so on.

The standard graphics pipeline processes the vertices output by the shader, including the following tasks.

  • Primitive assembly
  • Clipping against the frustum and user clipping planes
  • Homogeneous divide
  • Viewport scaling
  • Backface and viewport culling
  • Triangle setup
  • Rasterization

Note that the clipping space for DirectX 8.0 vertex shaders is the same as for DirectX 7.0 and DirectX 8.0 fixed function vertex processing. For details, see Clipping Volumes.

Programmable geometry is a mode within the Direct3D application programming interface (API). When it is enabled, it partially replaces the vertex pipeline. When it is disabled, the API has normal control—operating as in DirectX 6.0 and 7.0. Execution of vertex shaders does not change the internal Direct3D state, and no Direct3D state is available for shaders.

Calling IDirect3DDevice8::CreateVertexShader with the pFunction parameter equal to NULL is used to create a shader for the fixed-function pipeline. When pFunction is not NULL, the shader is programmable. A call to IDirect3DDevice8::SetVertexShader sets the current active shader, which defines whether the rendering pipeline should use programmable or fixed-function vertex processing.


Presenting Vertex Data to the Vertex Processor

Vertex data can be presented to the vertex processor using one of the following formats.

  • Legacy FVF Format
  • Programmable Stream Model

Note The vertex data format that you choose is independent of and orthogonal to the vertex processing method used (fixed function vs. programmable) For example, you can use streams with fixed function transformation and lighting pipelines and you can use FVF vertices with programmable vertex shaders.


Legacy FVF Format

To use legacy FVF formats, use an FVF instead of a handle when calling the IDirect3DDevice8::SetVertexShader method as shown in the code example below.

g_d3dDevice->SetVertexShader( CUSTOM_FVF );

This following topics cover legacy FVF format types.

  • Vertex Legacy Type
  • LVertex Legacy Type
  • TLVertex Legacy Type


Vertex Legacy Type

This topic shows the steps necessary to initialize and use vertices that have a position, a normal, and texture coordinates.

The first step is to define the custom vertex type and FVF as shown in the code example below.

struct Vertex
{
    FLOAT x, y, z;
    FLOAT nx, ny, nz;
    FLOAT tu, tv;
};

const DWORD VertexFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 );

The next step is to create a vertex buffer with enough room for four vertices by using the IDirect3DDevice8::CreateVertexBuffer method as shown in the code example below.

g_d3dDevice->CreateVertexBuffer(
                 4*sizeof(Vertex), VertexFVF,
                 D3DUSAGE_WRITEONLY,
                 D3DPOOL_DEFAULT, &pBigSquareVB);

The next step is to manipulate the values for each vertex as shown in the code example below.

Vertex * v;
pBigSquareVB->Lock( 0, 0, (BYTE**)&v, 0 );

v[0].x  = 0.0f;  v[0].y  = 10.0;  v[0].z  = 10.0f;
v[0].nx = 0.0f;  v[0].ny = 1.0f;  v[0].nz = 0.0f;
v[0].tu = 0.0f;  v[0].tv = 0.0f;

v[1].x  = 0.0f;  v[1].y  = 0.0f;  v[1].z  = 10.0f;
v[1].nx = 0.0f;  v[1].ny = 1.0f;  v[1].nz = 0.0f;
v[1].tu = 0.0f;  v[1].tv = 0.0f;

v[2].x  = 10.0f; v[2].y  = 10.0f; v[2].z  = 10.0f;
v[2].nx = 0.0f;  v[2].ny = 1.0f;  v[2].nz = 0.0f;
v[2].tu = 0.0f;  v[2].tv = 0.0f;

v[3].x  = 0.0f; v[3].y  = 10.0f;  v[3].z = 10.0f;
v[3].nx = 0.0f; v[3].ny = 1.0f;   v[3].nz = 0.0f;
v[3].tu = 0.0f; v[3].tv = 0.0f;

pBigSquareVB->Unlock();

The vertex buffer has been initialized and is ready to render. The following code example shows how to use the legacy FVF to draw a square.

g_d3dDevice->SetVertexShader( VertexFVF );
g_d3dDevice->SetStreamSource( 0, pBigSquareVB, 4*sizeof(Vertex) );
g_d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0 ,2);

Passing an FVF to the IDirect3DDevice8::SetVertexShader method tells Direct3D that a legacy FVF is being used and that stream 0 is the only valid stream.


LVertex Legacy Type

This topic shows the steps necessary to initialize and use vertices that have a position, diffuse color, specular color, and texture coordinates.

The first step is to define the custom vertex type and FVF as shown in the code example below.

struct LVertex
{
    FLOAT    x, y, z;
    D3DCOLOR specular, diffuse;
    FLOAT    tu, tv;
};

const DWORD VertexFVF = (D3DFVF_XYZ | D3DFVF_DIFFUSE |
                         D3DFVF_SPECULAR | D3DFVF_TEX1 );

The next step is to create a vertex buffer with enough room for four vertices by using the IDirect3DDevice8::CreateVertexBuffer method as shown in the code example below.

g_d3dDevice->CreateVertexBuffer(
                 4*sizeof(LVertex), VertexFVF,
                 D3DUSAGE_WRITEONLY,
                 D3DPOOL_DEFAULT, &pBigSquareVB);

The next step is to manipulate the values for each vertex as shown in the code example below.

LVertex * v;
pBigSquareVB->Lock( 0, 0, (BYTE**)&v, 0 );

v[0].x  = 0.0f;  v[0].y  = 10.0;  v[0].z  = 10.0f;
v[0].diffuse  = 0xffff0000;
v[0].specular = 0xff00ff00;
v[0].tu = 0.0f;  v[0].tv = 0.0f;

v[1].x  = 0.0f;  v[1].y  = 0.0f;  v[1].z  = 10.0f;
v[1].diffuse  = 0xff00ff00;
v[1].specular = 0xff00ffff;
v[1].tu = 0.0f;  v[1].tv = 0.0f;

v[2].x  = 10.0f; v[2].y  = 10.0f; v[2].z  = 10.0f;
v[2].diffuse  = 0xffff00ff;
v[2].specular = 0xff000000;
v[2].tu = 0.0f;  v[2].tv = 0.0f;

v[3].x  = 0.0f; v[3].y  = 10.0f;  v[3].z = 10.0f;
v[3].diffuse  = 0xffffff00;
v[3].specular = 0xffff0000;
v[3].tu = 0.0f; v[3].tv = 0.0f;

pBigSquareVB->Unlock();

The vertex buffer has been initialized and is ready to render. The following code example shows how to use the legacy FVF to draw a square.

g_d3dDevice->SetVertexShader( VertexFVF );
g_d3dDevice->SetStreamSource( 0, pBigSquareVB, 4*sizeof(LVertex) );
g_d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0 ,2);

Passing an FVF to the IDirect3DDevice8::SetVertexShader method tells Direct3D that a legacy FVF is being used and that stream 0 is the only valid stream.


TLVertex Legacy Type

The topic shows the steps necessary to initialize and use vertices that have a transformed position, diffuse color, specular color, and texture coordinates.

The first step is to define the custom vertex type and FVF as shown in the code example below.

struct TLVertex
{
    FLOAT    x, y, z, rhw;
    D3DCOLOR specular, diffuse;
    FLOAT    tu, tv;
};

const DWORD VertexFVF = (D3DFVF_XYZRHW | D3DFVF_DIFFUSE |
                         D3DFVF_SPECULAR | D3DFVF_TEX1 );

The next step is to create a vertex buffer with enough room for four vertices by using the IDirect3DDevice8::CreateVertexBuffer method as shown in the code example below.

g_d3dDevice->CreateVertexBuffer(
                 4*sizeof(TLVertex), VertexFVF,
                 D3DUSAGE_WRITEONLY,
                 D3DPOOL_DEFAULT, &pBigSquareVB);

The next step is to manipulate the values for each vertex as shown in the code example below.

TLVertex * v;
pBigSquareVB->Lock( 0, 0, (BYTE**)&v, 0 );

v[0].x  = 0.0f;  v[0].y  = 10.0;  v[0].z  = 10.0f; v[0].rhw = 1.0f;
v[0].diffuse  = 0xffff0000;
v[0].specular = 0xff00ff00;
v[0].tu = 0.0f;  v[0].tv = 0.0f;

v[1].x  = 0.0f;  v[1].y  = 0.0f;  v[1].z  = 10.0f; v[1].rhw = 1.0f;
v[1].diffuse  = 0xff00ff00;
v[1].specular = 0xff00ffff;
v[1].tu = 0.0f;  v[1].tv = 0.0f;

v[2].x  = 10.0f; v[2].y  = 10.0f; v[2].z  = 10.0f; v[2].rhw = 1.0f;
v[2].diffuse  = 0xffff00ff;
v[2].specular = 0xff000000;
v[2].tu = 0.0f;  v[2].tv = 0.0f;

v[3].x  = 0.0f; v[3].y  = 10.0f;  v[3].z = 10.0f; v[3].rhw = 1.0f;
v[3].diffuse  = 0xffffff00;
v[3].specular = 0xffff0000;
v[3].tu = 0.0f; v[3].tv = 0.0f;

pBigSquareVB->Unlock();

The vertex buffer has been initialized and is ready to render. The following code example shows how to use the legacy FVF to draw a square.

g_d3dDevice->SetVertexShader( VertexFVF );
g_d3dDevice->SetStreamSource( 0, pBigSquareVB, 4*sizeof(TLVertex) );
g_d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0 ,2);

Passing an FVF to the IDirect3DDevice8::SetVertexShader method tells Direct3D that a legacy FVF is being used and that stream 0 is the only valid stream.


Programmable Stream Model

This following sections cover shaders that can be used for the programmable stream model.

  • ColorVertex Shader
  • SingleTexture Shader
  • MultiTexture Shader


ColorVertex Shader

This topic shows the steps necessary to initialize and use a simple vertex shader that uses a position and a diffuse color.

The first step is to declare the structures that hold the position and color as shown in the code example below.

struct XYZBuff
{
    FLOAT x, y, z;
    D3DCOLOR color;
};

struct ColBuf
{
    D3DCOLOR color;
};

#define XYZBUFF (D3DFVF_XYZ)
#define COLBUFF (D3DFVF_DIFFUSE)

The next step is to create a Vertex Shader Declaration as shown in the code below.

DWORD decl[] =
{
    D3DVSD_STREAM(0),
    D3DVSD_REG( D3DVSDE_POSITION, D3DVSDT_FLOAT3 ),
    D3DVSD_STREAM(1),
    D3DVSD_REG( D3DVSDE_DIFFUSE, D3DVSDT_D3DCOLOR),
    D3DVSD_END()
};

The next step is to call the IDirect3DDevice8::CreateVertexShader method to create the vertex shader.

g_d3dDevice->CreateVertexShader( decl, NULL, &vShader, 0);

Passing NULL to the second parameter of CreateVertexShader tells Direct3D that this vertex shader will use a fixed function pipeline.

After creating the vertex buffer and vertex shader, they are ready to use. The code example below shows how to set the vertex shader, set the stream source, and then draw a triangle list that uses the new vertex shader.

g_d3dDevice->SetVertexShader( &vShader );
g_d3dDevice->SetStreamSource( 0, xyzbuf, 4 * sizeof(FLOAT));
g_d3dDevice->SetStreamSource( 1, colbuf, 2 * sizeof(FLOAT));
g_d3dDevice->SetIndices( pIB, 0 );
g_d3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, max - min + 1, 0, count / 3 );


SingleTexture Shader

This topic shows the steps necessary to initialize and use a simple vertex shader that uses a position and texture coordinates.

The first step is to declare the structures that hold the position and texture coordinates as shown in the code example below.

struct XYZBuff
{
    D3DVALUE x, y, z;
};

struct TEX0Buff
{
    D3DVALUE tu, tv;
};

#define XYZBUFF  (D3DFVF_XYZ)
#define TEX0BUFF (D3DFVF_TEX1)

The next step is to create a Vertex Shader Declaration as shown in the code below.

DWORD decl[] =
{
    D3DVSD_STREAM(0),
    D3DVSD_REG( D3DVSDE_POSITION, D3DVSDT_FLOAT3 ),
    D3DVSD_STREAM(1),
    D3DVSD_REG( D3DVSDE_TEXCOORD0, D3DVSDT_FLOAT2 ),
    D3DVSD_END()
};

The next step is to call the IDirect3DDevice8::CreateVertexShader method to create the vertex shader.

g_d3dDevice->CreateVertexShader( decl, NULL, &vShader, 0);

Passing NULL to the second parameter of CreateVertexShader tells Direct3D that this vertex shader will use a fixed function pipeline.

After creating the vertex buffer and vertex shader, they are ready to use. The code example below shows how to set the vertex shader, set the stream source, and then draw a triangle list that uses the new vertex shader.

g_d3dDevice->SetVertexShader( &vShader );
g_d3dDevice->SetStreamSource( 0, xyzbuf, 4 * sizeof(FLOAT));
g_d3dDevice->SetStreamSource( 1, tex0buf, 2 * sizeof(FLOAT));
g_d3dDevice->SetIndices( pIB, 0 );
g_d3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, max - min + 1, 0, count / 3 );


MultiTexture Shader

This topic shows the steps necessary to initialize and use a simple vertex shader that uses a position and multiple texture coordinates for multiple textures.

The first step is to declare the structures that holds the position and color as shown in the code example below.

struct XYZBuff
{
    D3DVALUE x, y, z;
};

struct Tex0Buff
{
    D3DVALUE tu, tv;
};

struct Tex1Buff
{
    D3DVALUE tu2, tv2;
};

#define XYZBUFF (D3DFVF_XYZ)
#define TEX0BUFF (D3DFVF_TEX1)
#define TEX1BUFF (D3DFVF_TEX1)

The next step is to create a Vertex Shader Declaration as shown in the code below.

DWORD decl[] =
{
    D3DVSD_STREAM(0),
    D3DVSD_REG( D3DVSDE_POSITION, D3DVSDT_FLOAT3 ),
    D3DVSD_STREAM(1),
    D3DVSD_REG( D3DVSDE_TEXCOORD0, D3DVSDT_FLOAT2),
    D3DVSD_STREAM(2),
    D3DVSD_REG( D3DVSDE_TEXCOORD1, D3DVSDT_FLOAT2),
    D3DVSD_END()
};

The next step is to call the IDirect3DDevice8::CreateVertexShader method to create the vertex shader.

g_d3dDevice->CreateVertexShader( decl, NULL, &vShader, 0);

Passing NULL to the second parameter of CreateVertexShader tells Direct3D that this vertex shader will use a fixed function pipeline.

After creating the vertex buffer and vertex shader, they are ready to use. The code example below shows how to set the vertex shader, set the stream source, and then draw a triangle list that uses the new vertex shader.

g_d3dDevice->SetVertexShader( &vShader );
g_d3dDevice->SetStreamSource( 0, xyzbuf, 4 * sizeof(FLOAT));
g_d3dDevice->SetStreamSource( 1, tex0buf, 2 * sizeof(FLOAT));
g_d3dDevice->SetStreamSource( 2, tex1buf, 2 * sizeof(FLOAT));
g_d3dDevice->SetIndices( pIB, 0 );
g_d3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0, max - min + 1, 0, count / 3 );


Using DirectX Graphics

This section is a guide to using the Microsoft® Direct3D® and Direct3DX APIs in application development.

Information is presented in the following topics.

  • Direct3D Object
  • Direct3D Device
  • Direct3D Resources
  • Surfaces
  • Lights
  • Materials
  • Vertex Formats
  • Textures
  • Depth Buffers
  • Stencil Buffers
  • Vertex Buffers
  • Index Buffers
  • Techniques and Special Effects

For a more general overview, see Getting Started with DirectX Graphics.

For an understanding of the general mechanisms of data flow and organization, see Understanding DirectX Graphics.

For information on advanced features such as programmable shaders, see Advanced Topics in DirectX Graphics.


Direct3D Object

This section contains information about the Microsoft® Direct3D® object.

  • What is a Direct3D Object?
  • Accessing Direct3D


What is a Direct3D Object?

Microsoft® Direct3D® is implemented through COM objects and interfaces. Applications written in C++ access these interfaces and objects directly, whereas Microsoft Visual Basic® applications interact with a layer of code—visible as the Microsoft DirectX® for Visual Basic Classes—that marshals data from a Visual Basic application to the DirectX run time.

The Direct3D object is the first object that your application creates and the last object that your application releases. Functions for enumerating and retrieving capabilities of a Direct3D device are accessible through the Direct3D object. This enables applications to select devices without creating them.


Accessing Direct3D

When a Microsoft® Direct3D® application written in C++ starts, it must obtain a pointer to an IDirect3D8 interface to access Direct3D functionality.

The following code example shows how to use the Direct3DCreate8 function to retrieve a pointer to the Direct3D interface.

LPDIRECT3D8 g_pD3D = NULL;

    if( NULL == (g_pD3D = Direct3DCreate8(D3D_SDK_VERSION)))
        return E_FAIL;

To navigate from the Direct3DDevice object to the Direct3D object that created the device, use the IDirect3DDevice8::GetDirect3D method.


Direct3D Device

This section provides an overview of Microsoft® Direct3D® devices. The overview is divided into the following topics.

  • What is a Direct3D Device?
  • Device Types
  • Device-Supported Primitive Types
  • Using Devices
  • Device States
  • Lost Devices


What is a Direct3D Device?

A Microsoft® Direct3D® device is the rendering component of Direct3D. It encapsulates and stores the rendering state. In addition, a Direct3D device performs transformations and lighting operations and rasterizes an image to a surface. Architecturally, Direct3D devices contain a transformation module, a lighting module, and a rasterizing module, as the following illustration shows.

Direct3D enables applications that use custom transformation and lighting models to bypass the Direct3D device's transformation and lighting modules. For details, see Vertex Shaders.


Device Types

This section introduces Microsoft® Direct3D® devices and presents information for each type of device. The following topics are discussed.

  • About Device Types
  • HAL Device
  • Reference Device
  • Pluggable Software Device
  • Device Behaviors


About Device Types

Microsoft® Direct3D® currently supports three main types of Direct3D devices: a hardware abstraction layer (HAL) device with hardware-accelerated rasterization and shading with both hardware and software vertex processing; a reference device; and a pluggable software device (providing software rasterization).

You can think of these three devices as three separate drivers. Software and reference devices are represented by software drivers, and the HAL device is represented by a hardware driver. The most common way to take advantage of these devices is to use the HAL device for shipping applications, and the reference device for feature testing. These are provided by third parties to emulate particular devices—for example, developmental hardware that has not yet been released.

The Direct3D device that an application creates must correspond to the capabilities of the hardware on which the application is running. Direct3D provides rendering capabilities, either by accessing 3-D hardware that is installed in the computer or by emulating the capabilities of 3-D hardware in software. Therefore, Direct3D provides devices for both hardware access and software emulation.

Hardware-accelerated devices give much better performance than software devices. The HAL device type is available on all Direct3D supported graphic adapters. In most cases, applications target computers that have hardware acceleration and rely on software emulation to accommodate lower-end computers.

With the exception of the reference device, software devices do not always support the same features as a hardware device. Applications should always query for device capabilities to determine which features are supported.

Because the behavior of the software and reference devices provided with Microsoft DirectX® 8.0 is identical to that of the HAL device, application code authored to work with the HAL device will work with the software or reference devices without modifications. Note that while the provided software or reference device behavior is identical to that of the HAL device, the device capabilities do vary, and a particular software device may implement a much smaller set of capabilities.


HAL Device

The primary device type is the hardware abstraction layer (HAL) device, which supports hardware accelerated rasterization and both hardware and software vertex processing. If the computer on which your application is running is equipped with a display adapter that supports Microsoft® Direct3D®, your application should use it for 3-D operations. Direct3D HAL devices implement all or part of the transformation, lighting, and rasterizing modules in hardware.

Applications do not access 3-D cards directly. They call Direct3D functions and methods. Direct3D accesses the hardware through the HAL. If the computer that your application is running on supports the HAL, it will gain the best performance by using a HAL device.

To create a HAL device from C++, call the IDirect3D8::CreateDevice method, and pass the D3DDEVTYPE_HAL constant as the device type. For details, see Creating a Device.

Note Hardware devices cannot render to 8-bit render-target surfaces.


Reference Device

Microsoft® Direct3D® supports an additional device type called a reference device or reference rasterizer. Unlike a software device, the reference rasterizer supports every Direct3D feature. Because these features are implemented for accuracy, rather than speed, and are implemented in software, the results are not very fast. The reference rasterizer does make use of special CPU instructions whenever it can, but it is not intended for retail applications. Use the reference rasterizer only for feature testing or demonstration purposes.

To create a reference device from C++, call the IDirect3D8::CreateDevice method, and pass the D3DDEVTYPE_REF constant as the device type. For details, see Creating a Device.


Pluggable Software Device

If the user's computer provides no special hardware acceleration for 3-D operations, your application might emulate 3-D hardware in software. Software rasterization devices emulate the functions of color 3-D hardware in software. Because a software device is emulated in software, it runs more slowly than a hardware abstraction layer (HAL) device. However, software devices take advantage of any special instructions supported by the user's CPU to increase performance. Instruction sets include the AMD 3D-Now! instruction set on some AMD processors and the MMX instruction set supported by many Intel processors. Microsoft® Direct3D uses the 3D-Now! instruction set to accelerate transformation and lighting operations and the MMX instruction set to accelerate rasterization.

Software rasterization for Direct3D® is provided by pluggable software devices, which enable applications to access a variety of software rasterizers through the Direct3D interfaces. Software devices are loaded by the application and registered with the Direct3D object, at which point you can create a Direct3DDevice object that will perform rendering with the software device.

Direct3D software devices communicate with Direct3D through an interface similar to the hardware device driver interface (DDI).

The Direct3D DDK provides the documentation and headers for developing pluggable software devices.


Device Behaviors

Microsoft® Direct3D® enables you to specify the behavior of a device, as well the device's type. The IDirect3D8::CreateDevice method enables a combination of one or more of the behavior flags to control the global behaviors of the Direct3D device. These behaviors specify what is and is not maintained in the run-time portion of Direct3D, and the device types specify which driver to use. Although some combinations of device behaviors are not valid, it is possible to use all device behaviors with all device types. For example, it is valid to specify D3DDEVTYPE_SW on a device created with D3DCREATE_PUREDEVICE.


Device-Supported Primitive Types

Microsoft® Direct3D® devices can create and manipulate the following types of primitives.

  • Point Lists
  • Line Lists
  • Line Strips
  • Triangle Lists
  • Triangle Strips
  • Triangle Fans

You can render primitive types from a C++ application with any of the rendering methods of the IDirect3DDevice8 interface. For more information, see Rendering.

Note that you cannot render point lists with the indexed-primitive rendering methods.


Point Lists

A point list is a collection of vertices that are rendered as isolated points. Your application can use them in 3-D scenes for star fields, or dotted lines on the surface of a polygon.

The following illustration depicts a rendered point list.

Your application can apply materials and textures to a point list. The colors in the material or texture appear only at the points drawn, and not anywhere between the points.

The following code shows how to create vertices for this point list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice8::DrawPrimitive to render this point list.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice8 interface.
//
d3dDevice->DrawPrimitive( D3DPT_POINTLIST, 0, 6 );


Line Lists

A line list is a list of isolated, straight line segments. Line lists are useful for such tasks as adding sleet or heavy rain to a 3-D scene. Applications create a line list by filling an array of vertices, and the number of vertices in a line list must be an even number greater than or equal to two.

The following illustration shows a rendered line list.

You can apply materials and textures to a line list. The colors in the material or texture appear only along the lines drawn, not at any point in between the lines.

The following code shows how to create vertices for this line list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice8::DrawPrimitive to render this line list.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice8 interface.
//
d3dDevice->DrawPrimitive( D3DPT_LINELIST, 0, 3 );


Line Strips

A line strip is a primitive that is composed of connected line segments. Your application can use line strips for creating polygons that are not closed. A closed polygon is a polygon whose last vertex is connected to its first vertex by a line segment. If your application makes polygons based on line strips, the vertices are not guaranteed to be coplanar.

The following illustration depicts a rendered line strip.

The following code shows how to create vertices for this line strip.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice8::DrawPrimitive to render this line strip.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice8 interface.
//
d3dDevice->DrawPrimitive( D3DPT_LINESTRIP, 0, 5 );


Triangle Lists

A triangle list is a list of isolated triangles. They might or might not be near each other. A triangle list must have at least three vertices. The total number of vertices must be divisible by three.

Use triangle lists to create an object that is composed of disjoint pieces. For instance, one way to create a force-field wall in a 3-D game is to specify a large list of small, unconnected triangles. Then apply a material and texture that appears to emit light to the triangle list. Each triangle in the wall appears to glow. The scene behind the wall becomes partially visible through the gaps between the triangles, as a player might expect when looking at a force field.

Triangle lists are also useful for creating primitives that have sharp edges and are shaded with Gouraud shading. See Face and Vertex Normal Vectors.

The following illustration depicts a rendered triangle list.

The following code shows how to create vertices for this triangle list.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}

};

The code example below shows how to use IDirect3DDevice8::DrawPrimitive to render this triangle list.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice8 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 2 );


Triangle Strips

A triangle strip is a series of connected triangles. Because the triangles are connected, the application does not need to repeatedly specify all three vertices for each triangle. For example, you need only seven vertices to define the following triangle strip.

The system uses vertices v1, v2, and v3 to draw the first triangle, v2, v4, and v3 to draw the second triangle, v3, v4, and v5 to draw the third, v4, v6, and v5 to draw the fourth, and so on. Notice that the vertices of the second and fourth triangles are out of order; this is required to make sure that all the triangles are drawn in a clockwise orientation.

Most objects in 3-D scenes are composed of triangle strips. This is because triangle strips can be used to specify complex objects in a way that makes efficient use of memory and processing time.

The following illustration depicts a rendered triangle strip.

The following code shows how to create vertices for this triangle strip.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    {-5.0, -5.0, 0.0},
    { 0.0,  5.0, 0.0},
    { 5.0, -5.0, 0.0},
    {10.0,  5.0, 0.0},
    {15.0, -5.0, 0.0},
    {20.0,  5.0, 0.0}
};

The code example below shows how to use IDirect3DDevice8::DrawPrimitive to render this triangle strip.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice8 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 5 );


Triangle Fans

A triangle fan is similar to a triangle strip, except that all the triangles share one vertex, as shown in the following illustration.

The system uses vertices v2, v3, and v1 to draw the first triangle, v3, v4, and v1 to draw the second triangle, v4, v5, and v1 to draw the third triangle, and so on. When flat shading is enabled, the system shades the triangle with the color from its first vertex.

This illustration depicts a rendered triangle fan.

The following code shows how to create vertices for this triangle fan.

struct CUSTOMVERTEX
{
    float x,y,z;
};

CUSTOMVERTEX Vertices[] =
{
    { 0.0, 0.0, 0.0},
    {-5.0, -5.0, 0.0},
    {-3.0,  7.0, 0.0},
    { 0.0, 10.0, 0.0},
    { 3.0,  7.0, 0.0},
    { 5.0,  5.0, 0.0},
};

The code example below shows how to use IDirect3DDevice8::DrawPrimitive to render this triangle fan.

//
// It is assumed that d3dDevice is a valid
// pointer to a IDirect3DDevice8 interface.
//
d3dDevice->DrawPrimitive( D3DPT_TRIANGLEFAN, 0, 4 );


Using Devices

This section provides information about using Microsoft® Direct3D® devices in an application. Information is divided into the following topics.

  • Determining Hardware Support
  • Selecting a Device
  • Creating a Device
  • Setting Transformations
  • Processing Vertex Data
  • Working with Mouse Cursors
  • Rendering


Determining Hardware Support

Direct3D provides the following functions to determine hardware support.

IDirect3D8::CheckDeviceFormat
Used to verify whether a surface format can be used as a texture, whether a surface format can be used as a texture and a render target, or whether a surface format can be used as a depth-stencil buffer. In addition, this method is used to verify depth buffer format support and depth-stencil buffer format support.
IDirect3D8::CheckDeviceType
Used to verify a device's ability to perform hardware acceleration, a device's ability to build a swap chain for presentation, or a device's ability to render to the current display format.
IDirect3D8::CheckDepthStencilMatch
Used to verify whether a depth-stencil buffer format is compatible with a render-target format. Note that before calling this method, the application should call CheckDeviceFormat on both the depth-stencil and render target formats.


Selecting a Device

Applications can query hardware to detect the supported Microsoft® Direct3D® device types. This section contains information on the primary tasks involved in enumerating display adapters and selecting Direct3D devices.

An application must perform a series of tasks to select an appropriate Direct3D device. Note that the following steps are intended for a full-screen application. In most cases, a windowed application can skip most of these steps.

  1. Initially, the application must enumerate the display adapters on the system. An adapter is a physical piece of hardware. Note that the graphics card might contain more than a single adapter, as is the case with a dual-head display. Applications that are not concerned with multimonitor support can disregard this step, and pass D3DADAPTER_DEFAULT to the IDirect3D8::EnumAdapterModes method in step 2.
  2. For each adapter, the application enumerates the supported display modes by calling EnumAdapterModes.
  3. If required, the application checks for the presence of hardware acceleration in each enumerated display mode by calling IDirect3D8::CheckDeviceType, as shown in the following code example. Note that this is only one of the possible uses for CheckDeviceType; for details, see Determining Hardware Support.
    D3DPRESENT_PARAMETERS Params;
// Initialize values for D3DPRESENT_PARAMETERS members.

Params.BackBufferFormat = D3DFMT_X1R5G5B5;

if(FAILED(m_pD3D->CheckDeviceType(Device.m_uAdapter,
                                  Device.m_DevType,
                                  Params.BackBufferFormat, Params.BackBufferFormat,
                                  FALSE)))
        return E_FAIL;
  4. The application checks for the desired level of functionality for the device on this adapter by calling the IDirect3D8::GetDeviceCaps method. This method filters out those devices that do not support the required functionality. The device capability returned by GetDeviceCaps is guaranteed to be constant for a device across all display modes verified by CheckDeviceType.
  5. Devices can always render to surfaces of the format of an enumerated display mode that is supported by the device. If the application is required to render to a surface of a different format, it can call IDirect3D8::CheckDeviceFormat. If the device can render to the format, then it is guaranteed that all capabilities returned by GetDeviceCaps are applicable.
  6. Lastly, the application can determine if multisampling techniques, such as full-scene antialiasing, are supported for a render format by using the IDirect3D8::CheckDeviceMultiSampleType method.

After completing the above steps, the application should have a list of display modes in which it can operate. The final step is to verify that enough device-accessible memory is available to accommodate the required number of buffers and antialiasing. This test is necessary because the memory consumption for the mode and multisample combination is impossible to predict without verifying it. Moreover, some display adapter architectures might not have a constant amount of device-accessible memory. This means that an application should be able to report out-of-video-memory failures when going into full-screen mode. Typically, an application should remove full-screen mode from the list of modes it offers to a user, or it should attempt to consume less memory by reducing the number of back buffers or using a less expensive multisampling technique.

A windowed application performs a similar set of tasks.

  1. It determines the desktop rectangle covered by the client area of the window.
  2. It enumerates adapters, looking for the adapter whose monitor covers the client area. If the client area is owned by more than one adapter, then the application can choose to drive each adapter independently, or to drive a single adapter and have Direct3D transfer pixels from one device to another at presentation. The application can also disregard the above two steps and use the D3DADAPTER_DEFAULT adapter. Note that this might result in slower operation when the window is placed on a secondary monitor.
  3. The application should call CheckDeviceType to determine if the device can support rendering to a back buffer of the specified format while in desktop mode. IDirect3D8::GetAdapterDisplayMode can be used to determine the desktop display format, as shown in the following code example.
    D3DPRESENT_PARAMETERS Params;
// Initialize values for D3DPRESENT_PARAMETERS members.

// Use the current display mode.
D3DDISPLAYMODE mode;

if(FAILED(m_pD3D->GetAdapterDisplayMode(Device.m_uAdapter , &mode)))
        return E_FAIL;

Params.BackBufferFormat = mode.Format;

if(FAILED(m_pD3D->CheckDeviceType(Device.m_uAdapter, Device.m_DevType,
Params.BackBufferFormat, Params.BackBufferFormat, FALSE)))
       return E_FAIL;


Creating a Device

Note All rendering devices created by a given Microsoft® Direct3D® object share the same physical resources. Although your application can create multiple rendering devices from a single Direct3D object, because they share the same hardware, extreme performance penalties will be incurred.

To create a Direct3D device in a C++ application, your application must first create a Direct3D object, as explained in Accessing Direct3D.

First, initialize values for the D3DPRESENT_PARAMETERS structure that is used to create the Direct3D device. The following code example specifies a windowed application where the back buffer is flipped to the front buffer on VSYNC only.

LPDIRECT3DDEVICE8 d3dDevice = NULL;

D3DPRESENT_PARAMETERS d3dpp;

ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed   = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_COPY_VSYNC;

Next, create the Direct3D device. The following IDirect3D8::CreateDevice call specifies the default adapter, a hardware abstraction layer (HAL) device, and software vertex processing.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                      &d3dpp, &d3dDevice ) ) )
    return E_FAIL;

Note that a call to create, release, or reset the device should happen only on the same thread as the window procedure of the focus window.

After creating the device, set its state.


Setting Transformations

In C++, transformations are applied by using the Direct3DDevice8.SetTransform method. For example, you can use code like the following to set the view transformation.

HRESULT    hr;
D3DMATRIX  view;

// Fill in the view matrix.

hr = pDev->SetTransform(D3DTS_VIEW, &view);

if(FAILED(hr))
{
    // Code to handle the error goes here.
}

There are several possible settings for the first parameter in a call to SetTransform. The most common are D3DTS_WORLD, D3DTS_VIEW, and D3DTS_PROJECTION. These transformation states are defined by the D3DTRANSFORMSTATETYPE enumerated type. This enumeration also contains the states D3DTS_TEXTURE1 through D3DTS_TEXTURE7, which you can use to apply transformations to texture coordinates.


Processing Vertex Data

The IDirect3DDevice8 interface supports vertex processing in both software and hardware. In general, the device capabilities for software and hardware vertex processing are not identical. Hardware capabilities are variable, depending on the display adapter and driver, while software capabilities are fixed.

The following flags control vertex processing behavior for the hardware abstraction layer (HAL) and reference devices.

  • D3DCREATE_SOFTWARE_VERTEXPROCESSING
  • D3DCREATE_HARDWARE_VERTEXPROCESSING
  • D3DCREATE_MIXED_VERTEXPROCESSING

Specify one of the vertex processing behavior flags when calling IDirect3D8::CreateDevice. The mixed-mode flag enables the device to perform both software and hardware vertex processing. Only one vertex processing flag may be set for a device at any one time. Note that the D3DCREATE_HARDWARE_VERTEXPROCESSING flag is required to be set when creating a pure device (D3DCREATE_PUREDEVICE).

To avoid dual vertex processing capabilities on a single device, only the hardware vertex processing capabilities can be queried at run time. Software vertex processing capabilities are fixed and cannot be queried at run time.

You can consult the VertexProcessingCaps member of the D3DCAPS8 structure to determine the hardware vertex processing capabilities of the device. For software vertex processing the following capabilities are supported.

  • D3DVTXPCAPS_DIRECTIONALLIGHTS
  • D3DVTXPCAPS_LOCALVIEWER
  • D3DVTXPCAPS_MATERIALSOURCE7
  • D3DVTXPCAPS_POSITIONALLIGHTS
  • D3DVTXPCAPS_TEXGEN
  • D3DVTXPCAPS_TWEENING

In addition, the following table lists the values that are set for members of the D3DCAPS8 structure for a device in software vertex processing mode.

Member | Software Vertex Processing Capabilities
MaxActiveLights | Unlimited
MaxUserClipPlanes | 6
MaxVertexBlendMatrices | 4
MaxStreams | 16
MaxVertexIndex | 0xFFFFFFFF

Software vertex processing provides a guaranteed set of vertex processing capabilities, including an unbounded number of lights and full support for programmable vertex shaders. You can toggle between software and hardware vertex processing at any time when using the HAL Device, the only device type that supports both hardware and software vertex processing. The only requirement is that vertex buffers used for software vertex processing must be allocated in system memory.

Note The performance of hardware vertex processing is comparable to that of software vertex processing. For this reason, it's a good idea to provide, within a single device type, both hardware- and software-emulation functionality for vertex processing. This is not the case for rasterization, for which host processors are much slower than specialized graphics hardware. Thus both hardware- and software-emulated rasterization is not provided within a single device type. Software vertex processing is the only instance of functionality duplicated between the run time and the hardware (driver) within a single device. Thus all other device capabilities represent potentially variable functionality provided by the driver.


Working with Mouse Cursors

The mouse cursor methods enable the application to specify a color cursor by providing a surface that contains an image. The system will ensure that this cursor will be updated at half the display rate or more if the application's frame rate is slow. However, the cursor will never be updated more frequently than the display refresh rate.

The mouse cursor position is tied to the system cursor, appropriately scaled for the current display mode spatial resolution, but it can be moved explicitly by the application. This is analogous to the behavior of the Microsoft® Win32® API–supported system mouse cursor. For more information on how to use a mouse cursor in your Microsoft® Direct3D® application, see the following reference topics.

  • IDirect3DDevice8::ShowCursor
  • IDirect3DDevice8::SetCursorPosition
  • IDirect3DDevice8::SetCursorProperties

Direct3D ensures that the mouse is supported either by hardware implementations or by the Direct3D run time that performs hardware-accelerated blitting operations when calling IDirect3DDevice8::Present.


Rendering

Applications use the DrawPrimitive family of methods to render a 3-D scene. The following topics discuss rendering with DrawPrimitive.

  • Clearing Surfaces
  • Beginning and Ending a Scene
  • Presenting a Scene
  • Rendering Primitives


Clearing Surfaces

Before rendering objects in a scene, clear the viewport on the render-target surface or a subset of the viewport. Clearing the viewport causes the system to set the desired portion of the render-target surface and any attached depth or stencil buffers to a desired state. This resets the areas of the surface that will be rendered again, and it resets the corresponding areas of the depth and stencil buffers, if any are in use. Clearing a render-target surface can set the desired region to a default color or texture. For depth and stencil buffers, this can set a depth or stencil value.

Use the IDirect3DDevice8::Clear method to clear the viewport.

For more information about using this method, see Clearing a Viewport.

Optimization Note Applications that render scenes covering the entire area of the render-target surface can improve performance by clearing the attached depth and stencil buffer surfaces, if any, instead of the render target. In this case, clearing the depth buffer causes Microsoft® Direct3D® to rewrite the render target on the next rendered frame, making an explicit clear operation on the render target redundant. However, if your application renders only to a portion of the render-target surface, explicit clear operations are required.


Beginning and Ending a Scene

Applications written in C++ notify Microsoft® Direct3D® that scene rendering is about to begin by calling the IDirect3DDevice8::BeginScene method. BeginScene causes the system to check its internal data structures and the availability and validity of rendering surfaces. It also sets an internal flag to signal that a scene is in progress. After you begin a scene, you can call the various rendering methods to render the primitives or individual vertices that make up the objects in the scene. Attempts to call rendering methods when a scene is not in progress fail. For more information, see Rendering Primitives.

After you complete the scene, call the IDirect3DDevice8::EndScene method. The EndScene method flushes cached data, verifies the integrity of rendering surfaces, and clears an internal flag that signals when a scene is in progress.

All rendering methods must be bracketed by calls to the BeginScene and EndScene methods. If surfaces are lost or internal errors occur, the scene methods return error values. If BeginScene fails, the scene does not begin, and subsequent calls to EndScene will fail.

To summarize these cases:

  • If BeginScene returns any error, you must not call EndScene because the scene has not successfully begun.
  • If BeginScene succeeds, but you get an error while rendering the scene, you must call EndScene.
  • If EndScene fails, for any reason, you need not call it again.

For example, some simple scene code might look like the following example.

HRESULT hr;

if(SUCCEEDED(pDevice->BeginScene()))
{
    // Render primitives only if the scene
    // starts successfully.

    // Close the scene.
    hr = pDevice->EndScene();
    if(FAILED(hr))
        return hr;
}

You cannot embed scenes; that is, you must complete rendering a scene before you can begin another one. Calling EndScene when BeginScene has not been called returns an error value. Likewise, calling BeginScene when a previous scene has not been completed with the EndScene method results in an error.

Do not attempt to call GDI functions on Direct3D surfaces, such as the render target or textures, while a scene is being rendered—is between BeginScene and EndScene calls. Attempts to do so can prevent the results of the GDI operations from being visible. If your application uses GDI functions, be sure that all GDI calls are made outside the scene functions.


Presenting a Scene

This section introduces the presentation application programming interfaces (APIs) and discusses the issues involved in presenting a scene to the display.

Information is divided into the following topics.

  • Introduction to Presenting a Scene
  • Multiple Views in Windowed Mode
  • Multiple-Monitor Operations
  • Manipulating the Depth Buffer
  • Accessing the Color Front Buffer


Introduction to Presenting a Scene

The presentation application programming interfaces (APIs) are a set of methods that control the state of the device that affects what the user sees on the monitor. These methods include setting display modes and once-per-frame methods that are used to present images to the user.

  • IDirect3DDevice8::Present
  • IDirect3DDevice8::Reset
  • IDirect3DDevice8::GetGammaRamp
  • IDirect3DDevice8::SetGammaRamp
  • IDirect3DDevice8::GetRasterStatus

Familiarity with the following terms is necessary to understand the presentation APIs.

  • Front Buffer. A rectangle of memory that is translated by the graphics adapter and displayed on the monitor or other output device.
  • Back Buffer. A surface whose contents can be promoted to the front buffer.
  • Swap Chain. A collection of back buffers that can be serially presented to the front buffer. Typically, a full-screen swap chain presents subsequent images with the flipping DDI, and a windowed swap chain presents images with the blitting DDI.

Because Microsoft® Direct3D® for Microsoft DirectX® 8.0 has one swap chain as a property of the device, there is always at least one swap chain per device. The IDirect3DDevice8 interface has a set of methods that manipulate the implicit swap chain and are a copy of the swap chain's own interface. Applications can create additional swap chains; however, this is not necessary for the typical single window or full-screen application.

The front buffer is not directly exposed in the Direct3D API for DirectX 8.0. As a result, applications cannot lock or render to the front buffer. For details, see Accessing the Color Front Buffer.

Note DirectX 7.x provided a number of presentation APIs that were called together. A good example of this is the IDirectDraw7::SetCooperativeLevel, IDirectDraw7::SetDisplayMode, and IDirectDraw7::CreateSurface sequence. Additionally, the IDirectDrawSurface7::Flip and IDirectDrawSurface7::Blt methods signaled the transport of rendered frames to the monitor. DirectX 8.0 collapses these groups of APIs into two main methods, Reset and Present. Reset subsumes SetCooperativeLevel, SetDisplayMode, CreateSurface, and some of the parameters to Flip. Present subsumes Flip and the presentation uses of Blt.

A call to IDirect3D8::CreateDevice represents an implicit reset of the device. The DirectX 8.0 API has no notion of a primary surface; you cannot create an object that represents the primary surface. It is considered to be an internal property of the device.

Gamma ramps are associated with a swap chain and are manipulated with the IDirect3DDevice8::GetGammaRamp and IDirect3DDevice8::SetGammaRamp methods.


Multiple Views in Windowed Mode

In addition to the swap chain that is owned and manipulated through the Direct3DDevice object, an application can use the IDirect3DDevice8::CreateAdditionalSwapChain method to create additional swap chains to present multiple views from the same device.

Typically, the application creates one swap chain per view, and it associates each swap chain with a particular view. The application renders images in the back buffers of each swap chain, and then uses the IDirect3DDevice8::Present method to present them individually. Note that only one swap chain at a time can be full-screen on each adapter.


Multiple-Monitor Operations

When a device is successfully reset (IDirect3DDevice8::Reset) or created (IDirect3D8::CreateDevice) in full-screen operations, the Microsoft® Direct3D® object that created the device is marked as owning all adapters on that system. This state is known as exclusive mode, and the Direct3D object owns exclusive mode. Exclusive mode means that devices created by any other Direct3D object can neither assume full-screen operations nor allocate video memory. In addition, when a Direct3D object assumes exclusive mode, all devices other than the one that went full-screen are placed in lost state. For details, see Lost Devices.

Along with exclusive mode, the Direct3D object is informed of the focus window that the device will use. Exclusive mode is released when the final full-screen device owned by that Direct3D object is either reset to windowed mode or destroyed.

Devices can be divided into two categories when a Direct3D object owns exclusive mode. The first category of devices have the following characteristics.

  • They are created by the same Direct3D object that created the device that is full-screen.
  • They have the same focus window as the device that is full-screen.
  • They represent a different adapter from any full-screen device.

Devices in this category have no restrictions concerning their ability to be reset or created, and they are not placed in lost state. Devices in this category can even be put into full-screen mode.

Devices that do not fall in the first category—devices created by another Direct3D object, created with a different focus window, and created for an adapter with a device that is already full-screen—cannot be reset and remain in lost state until the exclusive mode is lost. As a result, a multiple-monitor application can place several devices in full-screen mode, but only if all these devices are for different adapters, were created by the same Direct3D object, and share the same focus window.


Manipulating the Depth Buffer

Depth buffers are associated with the device. Applications are required to move the depth buffers when they set render targets. The IDirect3DDevice8::GetDepthStencilSurface and IDirect3DDevice8::SetRenderTarget methods are used to manipulate depth buffers.


Accessing the Color Front Buffer

Accessing the front buffer is allowed through the IDirect3DDevice8::GetFrontBuffer method. Although this method is provided, it is intended explicitly for testing requirements. Thus, its functionality is not guaranteed.


Rendering Primitives

The following topics introduce the DrawPrimitive rendering methods and provide information about using them in your application.

  • Vertex Data Streams
  • Setting the Stream Source
  • Rendering from Vertex and Index Buffers
  • Rendering from User Memory Pointers


Vertex Data Streams

The rendering interfaces for Microsoft® Direct3D® consist of methods that render primitives from vertex data stored in one or more data buffers. Vertex data consists of vertex elements combined to form vertex components. Vertex elements, the smallest unit of a vertex, represent entities such as position, normal, or color.

Vertex components are one or more vertex elements stored contiguously (interleaved per vertex) in a single memory buffer. A complete vertex consists of one or more components, where each component is in a separate memory buffer. To render a primitive, multiple vertex components are read and assembled so that complete vertices are available for vertex processing. The illustration below shows the process of rendering primitives using vertex components.

Rendering primitives consists of two steps. First, set up one or more vertex component streams; second, invoke a DrawPrimitive method to render from those streams. Identification of vertex elements within these component streams is specified by the vertex shader. For details, see Vertex Shaders.

The DrawPrimitive methods specify an offset in the vertex data streams so that an arbitrary contiguous subset of the primitives within one set of vertex data can be rendered with each draw invocation. This enables you to change the device rendering state between groups of primitives that are rendered from the same vertex buffers.

Both indexed and nonindexed drawing methods are supported. For more information, see Rendering from Vertex and Index Buffers.

A secondary set of rendering interfaces supports passing vertex and index data directly from user memory pointers. For more information, see Rendering from User Memory Pointers.


Setting the Stream Source

The IDirect3DDevice8::SetStreamSource method binds a vertex buffer to a device data stream, creating an association between the vertex data and one of several data stream ports that feed the primitive processing functions. The actual references to the stream data do not occur until a drawing method, such as IDirect3DDevice8::DrawPrimitive, is called.

A stream is defined as a uniform array of component data, where each component consists of one or more elements representing a single entity such as position, normal, color, and so on. The Stride parameter specifies the size of the component, in bytes.


Rendering from Vertex and Index Buffers

Both indexed and nonindexed drawing methods are supported by Microsoft® Direct3D®. The indexed methods use a single set of indices for all vertex components. Vertex data is presented to the Direct3D application programming interface (API) in vertex buffers, and index data for the indexed drawing methods is presented in index buffers. For more information, see the following reference topics.

  • IDirect3DDevice8::DrawPrimitive
  • IDirect3DDevice8::DrawIndexedPrimitive

These methods draw primitives from the current set of data input streams. For details on setting the current index array to an index buffer, see the IDirect3DDevice8::SetIndices method.


Rendering from User Memory Pointers

A secondary set of rendering interfaces supports passing vertex and index data directly from user memory pointers. These interfaces support a single stream of vertex data only. For more information, see the following reference topics.

  • IDirect3DDevice8::DrawPrimitiveUP
  • IDirect3DDevice8::DrawIndexedPrimitiveUP

These methods render with data specified by user memory pointers, instead of vertex and index buffers.


Device States

A Microsoft® Direct3D® device is a state computer; applications set up the state of the lighting, rendering, and transformation modules and then pass data through them during rendering.

This section describes render states, provides details about each render state used in Direct3D, and contains information about device state blocks, which applications can use to manipulate groups of devices states in a single call. The following topics are discussed.

  • Render States
  • Texture Stage States
  • State Blocks


Render States

This section introduces the concept of render states and discusses the various render states in detail. Information in this section is organized into the following topics.

  • About Render States
  • Alpha Blending State
  • Alpha Testing State
  • Ambient Lighting State
  • Antialiasing State
  • Culling State
  • Depth Buffering State
  • Fog State
  • Lighting State
  • Outline and Fill State
  • Per-Vertex Color State
  • Primitive Clipping State
  • Shading State
  • Stencil Buffer State
  • Texture Wrapping State


About Render States

Device render states control the behavior of the Microsoft® Direct3D® device's rasterization module. They do this by altering the attributes of the rendering state, what type of shading is used, fog attributes, and other rasterizer operations.

Applications written in C++ control the characteristics of the rendering state by invoking the IDirect3DDevice8::SetRenderState method. The D3DRENDERSTATETYPE enumerated type specifies all possible rendering states. Your application passes a value from the D3DRENDERSTATETYPE enumeration as the first parameter to the SetRenderState method.

Fixed function vertex processing is controlled by the SetRenderState method and the following device render states. Most of these controls do not have any effect when using programmed vertex shaders.

  • D3DRS_SPECULARENABLE
  • D3DRS_FOGSTART
  • D3DRS_FOGEND
  • D3DRS_FOGDENSITY
  • D3DRS_RANGEFOGENABLE
  • D3DRS_LIGHTING
  • D3DRS_AMBIENT
  • D3DRS_FOGVERTEXMODE
  • D3DRS_COLORVERTEX
  • D3DRS_LOCALVIEWER
  • D3DRS_NORMALIZENORMALS
  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE
  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE
  • D3DRS_VERTEXBLEND

In addition, the fixed-function vertex processing pipeline uses the following methods to set transforms, materials, and lights.

  • IDirect3DDevice8::SetTransform
  • IDirect3DDevice8::SetMaterial
  • IDirect3DDevice8::SetLight
  • IDirect3DDevice8::LightEnable

Note D3DRS_SPECULARENABLE controls the addition of specular color in the pixel pipeline. D3DRS_FOGSTART, D3DRS_FOGEND, and D3DRS_FOGDENSITY control the start, end, and density of pixel fog density computation.


Alpha Blending State

The alpha value of a color controls its transparency. Enabling alpha blending allows colors, materials, and textures on a surface to be blended with transparency onto another surface.

For more information, see Alpha Texture Blending and Multiple Texture Blending.

Applications written in C++ use the D3DRS_ALPHABLENDENABLE render state to enable alpha transparency blending. The Microsoft® Direct3D® API allows many types of alpha blending. However, it is important to note the user's 3-D hardware might not support all the blending states allowed by Direct3D.

The type of alpha blending that is done depends on the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states. Source and destination blend states are used in pairs. The following code example demonstrates how the source blend state is set to D3DBLEND_SRCCOLOR and the destination blend state is set to D3DBLEND_INVSRCCOLOR.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice8 interface.

// Set the source blend state.
d3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCCOLOR);

// Set the destination blend state.
d3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCCOLOR);

As a result of the calls in the preceding code example, Direct3D performs a linear blend between the source color—the color of the primitive that is rendered at the current location—and the destination color—the color at the current location in the frame buffer. This gives an appearance similar to tinted glass. Some of the color of the destination object seems to be transmitted through the source object. The rest of the color appears to be absorbed.

Altering the source and destination blend states can give the appearance of emissive objects in a foggy or dusty atmosphere. For instance, if your application models flames, force fields, plasma beams, or similarly radiant objects in a foggy environment, set the source and destination blend states to D3DBLEND_ONE.

Another application of alpha blending is to control the lighting in a 3-D scene, also called light mapping. Setting the source blend state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCALPHA darkens a scene according to the source alpha information. The source primitive is used as a light map that scales the contents of the frame buffer to darken it when appropriate. This produces monochrome light mapping.

You can achieve color light mapping by setting the source alpha blending state to D3DBLEND_ZERO and the destination blend state to D3DBLEND_SRCCOLOR.


Alpha Testing State

C++ applications can use alpha testing to control when pixels are written to the render-target surface. By using the D3DRS_ALPHATESTENABLE render state, your application sets the current Microsoft® Direct3D® device so that it tests each pixel according to an alpha test function. If the test succeeds, the pixel is written to the surface. If it does not, Direct3D ignores the pixel. Select the alpha test function with the D3DRS_ALPHAFUNC render state. Your application can set a reference alpha value for all pixels to compare against by using the D3DRS_ALPHAREF render state.

The most common use for alpha testing is to improve performance when rasterizing objects that are nearly transparent. If the color data being rasterized is more opaque than the color at a given pixel (D3DPCMPCAPS_GREATEREQUAL), then the pixel is written. Otherwise, the rasterizer ignores the pixel altogether, saving the processing required to blend the two colors. The following code example checks if a given comparison function is supported and, if so, it sets the comparison function parameters required to improve performance during rendering.

// This code example assumes that pCaps is a
// D3DCAPS8 structure that was filled with a
// previous call to IDirect3D8::GetDeviceCaps.
if (pCaps.AlphaCmpCaps & D3DPCMPCAPS_GREATEREQUAL)
{
    dev->SetRenderState(D3DRS_ALPHAREF, (DWORD)0x00000001);
    dev->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
    dev->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
}

// If the comparison is not supported, render anyway.
// The only drawback is no performance gain.

Not all hardware supports all alpha-testing features. You can check the device capabilities by calling the IDirect3D8::GetDeviceCaps method. After retrieving the device capabilities, check the AlphaCmpCaps member of the associated D3DCAPS8 structure for the desired comparison function. If the AlphaCmpCaps member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests.


Ambient Lighting State

Ambient light is surrounding light that radiates from all directions.

For specific information on how Microsoft® Direct3D® uses ambient light, see Direct Light vs. Ambient Light, and Mathematics of Direct3D Lighting.

A C++ application sets the color of ambient lighting by invoking the IDirect3DDevice8::SetRenderState method and passing the enumerated value D3DRS_AMBIENT as the first parameter. The second parameter is a color value. The default value is zero.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice8 interface.

// Set the ambient light.
d3dDevice->SetRenderState(D3DRS_AMBIENT, 0x00202020);


Antialiasing State

Antialiasing is a method of making lines and edges appear smoother on the screen. Microsoft® Direct3D® supports two antialiasing methods: edge antialiasing and full-scene antialiasing.

For details about these techniques, see Antialiasing.

By default, Direct3D does not perform antialiasing. To enable edge-antialiasing, which requires a second rendering pass, set the D3DRS_EDGEANTIALIAS render state to TRUE. To disable it, set D3DRS_EDGEANTIALIAS to FALSE.

To enable full-scene antialiasing, set the D3DRS_MULTISAMPLEANTIALIAS render state to TRUE. To disable it, set D3DRS_MULTISAMPLEANTIALIAS to FALSE.


Culling State

As Microsoft® Direct3D® renders primitives, it culls primitives that are facing away from the user.

C++ applications set the culling mode by using the D3DRS_CULLMODE render state, which can be set to a member of the D3DCULL enumerated type. By default, Direct3D culls back faces with counterclockwise vertices.

The following code sample illustrates the process of setting the culling mode to cull back faces with clockwise vertices.

// This code example assumes that d3dDevice is a valid
// pointer to an IDirect3DDevice8 interface.

// Set the culling state.
d3dDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_CW);


Depth Buffering State

Depth buffering is a method of removing hidden lines and surfaces. By default, Microsoft® Direct3D® does not use depth buffering.

For a conceptual overview of depth buffers, see What Are Depth Buffers?.

C++ applications update the depth-buffering state with the D3DRS_ZENABLE render state, using a member of the D3DZBUFFERTYPE enumeration to specify the new state value.

If your application needs to prevent Direct3D from writing to the depth buffer, it can use the D3DRS_ZWRITEENABLE enumerated value, specifying D3DZB_FALSE as the second parameter for the call to IDirect3DDevice8::SetRenderState.

The following code example shows how the depth-buffer state is set to enable z-buffering.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice8 interface.

// Enable z-buffering.
d3dDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);

Your application can also use the D3DRS_ZFUNC render state to control the comparison function that Direct3D uses when performing depth buffering.

Z-biasing is a method of displaying one surface in front of another, even if their depth values are the same. You can use this technique for a variety of effects. A common example is rendering shadows on walls. Both the shadow and the wall have the same depth value. However, you want your application to show the shadow on the wall. Giving a z-bias to the shadow makes Direct3D display them properly (see D3DRS_ZBIAS).


Fog State

Fog effects can give a 3-D scene greater realism. You can use fog effects for more than simulating fog. They can also decrease the clarity of a scene with distance. This mirrors what happens in the real world; as objects become more distant from the user, their detail is less distinct.

For more information about using fog in your application, see Fog.

A C++ application controls fog through device rendering states. The D3DRENDERSTATETYPE enumerated type includes states to control whether pixel (table) or vertex fog is used, what color it is, the fog formula the system applies, and the parameters of the formula.

You enable fog by setting the D3DRS_FOGENABLE render state to TRUE. The fog color can be set to any color value by using the D3DRS_FOGCOLOR render state; the alpha component of the fog color is ignored, .

The D3DRS_FOGTABLEMODE and D3DRS_FOGVERTEXMODE render states control the fog formula applied for fog calculations, and they indirectly control which type of fog is applied. Both render states can be set to a member of the D3DFOGMODE enumerated type. Setting either render state to D3DFOG_NONE disables pixel or vertex fog, respectively. If both render states are set to valid modes, the system applies only pixel fog effects.

The D3DRS_FOGSTART and D3DRS_FOGEND render states control fog formula parameters for the D3DFOG_LINEAR mode. The D3DRS_FOGDENSITY render state controls fog density in the exponential fog modes.

For more information, see Fog Parameters.


Lighting State

Applications that use the Microsoft® Direct3D® geometry pipeline can enable or disable lighting calculations. Only vertices that contain a vertex normal are properly lit; vertices with no normal will use a dot product of zero in all lighting computations. Therefore, a vertex that does not use a normal receives no light.

For more information, see Mathematics of Direct3D Lighting.

Applications enable Direct3D lighting by setting the D3DRS_LIGHTING render state to TRUE, which is the default setting, and they disable Direct3D lighting by setting the render state to FALSE.

The lighting render state is entirely independent of lighting computations that can be performed on vertices within a vertex buffer. The IDirect3DDevice8::ProcessVertices method accepts its own flags to control lighting calculations during vertex processing.


Outline and Fill State

Primitives that have no textures are rendered with the color specified by their material, or with the colors specified for the vertices, if any. You can select the method to fill them by specifying a value defined by the D3DFILLMODE enumerated type for the D3DRS_FILLMODE render state.

To enable dithering, your application must pass the D3DRS_DITHERENABLE enumerated value as the first parameter to IDirect3DDevice8::SetRenderState. It must set the second parameter to TRUE to enable dithering, and FALSE to disable it.

At times, drawing the last pixel in a line can cause unsightly overlap with surrounding primitives. You can control this using the D3DRS_LASTPIXEL enumerated value. However, do not alter this setting without some forethought. Under some conditions, suppressing the rendering of the last pixel can cause unsightly gaps between primitives.

By default, Microsoft® Direct3D® devices use a solid outline for primitives. The outline pattern can be changed using the D3DLINEPATTERN structure. For details, see the D3DRS_LINEPATTERN render state.


Per-Vertex Color State

When using flexible vertex format (FVF) codes, vertices can contain both vertex color and vertex normal information. By default, Microsoft® Direct3D® uses this information when it calculates lighting. To disable use of vertex color lighting information, invoke the IDirect3DDevice8::SetRenderState method and pass D3DRS_COLORVERTEX as the first parameter. Set the second parameter to FALSE to disable vertex color lighting, or TRUE to enable it.

If per-vertex color is enabled, applications can configure the source from which the system retrieves color information for a vertex. The D3DRS_AMBIENTMATERIALSOURCE, D3DRS_DIFFUSEMATERIALSOURCE, D3DRS_EMISSIVEMATERIALSOURCE, and D3DRS_SPECULARMATERIALSOURCE render states control the ambient, diffuse, emissive, and specular color component sources, respectively. Each state can be set to members of the D3DMATERIALCOLORSOURCE enumerated type, which defines constants that instruct the system to use the current material, diffuse color, or specular color as the source for the specified color component.


Primitive Clipping State

Microsoft® Direct3D® can clip primitives that render partially outside the viewport. When using C++, Direct3D clipping is controlled by the D3DRS_CLIPPING render state. Set this render state to TRUE (the default value) to enable primitive clipping. Set it to FALSE to disable Direct3D clipping services.

The primitive clipping render state is entirely independent of clipping operations that can be performed on vertices within a vertex buffer. The IDirect3DDevice8::ProcessVertices method accepts its own flags to control primitive clipping during vertex processing.


Shading State

Microsoft® Direct3D® supports both flat and Gouraud shading. The default is Gouraud shading. To control the current shading mode, your C++ application specifies a member of the D3DSHADEMODE enumerated type for the D3DRS_SHADEMODE render state.

The following C++ code example demonstrates the process of setting the shading state to flat shading mode.

// This code example assumes that d3dDevice is a
// valid pointer to a IDirect3DDevice8 interface.

// Set the shading state.
d3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT);


Stencil Buffer State

Applications use the stencil buffer to determine whether a pixel is written to the rendering target surface.

For details, see Stencil Buffers.

Applications written in C++ enable or disable stenciling by calling the IDirect3DDevice8::SetRenderState method. Pass D3DRS_STENCILENABLE as the value of the first parameter. Set the value of the second parameter to TRUE or FALSE to enable or disable stenciling, respectively.

Set the comparison function that Microsoft® Direct3D® uses to perform the stencil test by calling SetRenderState. Set the value of the first parameter to D3DRS_STENCILFUNC. Pass a member of the D3DCMPFUNC enumerated type as the value of the second parameter.

The stencil reference value is the value in the stencil buffer that the stencil function uses for its test. By default, the stencil reference value is zero. Your application can set the value by calling SetRenderState. Pass D3DRS_STENCILREF as the value of the first parameter. Set the value of the second parameter to the new reference value.

Before the Direct3D module performs the stencil test for any pixel, it performs a bitwise AND operation of the stencil reference value and a stencil mask value. The result is compared against the contents of the stencil buffer using the stencil comparison function. Your application can set the stencil mask by calling SetRenderState. Pass D3DRS_STENCILMASK as the value of the first parameter. Set the value of the second parameter to the new stencil mask.

To set the action that Direct3D takes when the stencil test fails, call SetRenderState and pass D3DRS_STENCILFAIL as the first parameter. The second parameter must be a member of the D3DSTENCILOP enumerated type.

Your application can also control how Direct3D responds when the stencil test passes but the z-buffer test fails. Call SetRenderState and pass D3DRS_STENCILZFAIL as the first parameter and use a member of the D3DSTENCILOP enumerated type for the second parameter.

In addition, your application can control what Direct3D does when both the stencil test and the z-buffer test pass. Call SetRenderState and pass D3DRS_STENCILPASS as the first parameter. Again, the second parameter must be a member of the D3DSTENCILOP enumerated type.


Texture Wrapping State

The D3DRS_WRAP0 through D3DRS_WRAP7 render states enable and disable u- and v-wrapping for various textures in the device's multitexture cascade. You can set these render states to a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags to enable wrapping in first, second, third, and fourth directions of the texture. Use a value of zero to disable wrapping altogether. Texture wrapping is disabled in all directions for all texture stages by default.

For a conceptual overview, see Texture Wrapping.


Texture Stage States

This section introduces the concept of texture stage states and discusses the various texture stage states in detail. Information in this section is organized into the following topics.

  • About Texture Stage States
  • Texture Addressing State
  • Texture Border State
  • Texture Filtering State
  • Texture Blending State


About Texture Stage States

Texture stage states control the style of texturing and how texture filtering is done.

Applications written in C++ control the characteristics of the texture-related render states by invoking the IDirect3DDevice8::SetTextureStageState method. The D3DTEXTURESTAGESTATETYPE enumerated type specifies all the possible texture-related rendering states. Your application passes a value from the D3DTEXTURESTAGESTATETYPE enumeration as the first parameter to the SetTextureStageState method.

Applications set the texture for a stage by calling the IDirect3DDevice8::SetTexture method.


Texture Addressing State

C++ applications use the D3DTSS_ADDRESSU, D3DTSS_ADDRESSV, and D3DTSS_ADDRESSW texture stage states to set the texture addressing.


Texture Border State

C++ applications use the D3DTSS_BORDERCOLOR texture stage state to set border color texture addressing.

For more information, see Border Color Texture Address Mode.


Texture Filtering State

C++ applications use the D3DTSS_MAGFILTER, D3DTSS_MINFILTER, and D3DTSS_MIPFILTER, and texture-stage states to control texture filtering.


Texture Blending State

C++ applications use the texture blending states defined by the D3DTSS_COLOROP and D3DTSS_ALPHAOP texture stage states to control texture blending.

For more information, see Multiple Texture Blending.


State Blocks

The following topics in this section describe the key concepts of device state blocks and provide information about how applications use state blocks.

  • About State Blocks
  • Recording State Blocks
  • Capturing State Blocks
  • Applying State Blocks
  • Creating Predefined State Blocks
  • Deleting State Blocks


About State Blocks

A state block in Microsoft® Direct3D® is a group of device states—render states, lighting and material parameters, transformation states, texture stage states, and current texture information. The state block is a snapshot of the device's current state, or it is explicitly recorded. The snapshot can be applied to a device in a single call. Device-state blocks can be optimized by the rendering device to accelerate the common sequences of state changes that your application requires, or they can simply make applying device states easier.

In C++, you receive a state-block handle when you finish recording a state block by calling the IDirect3DDevice8::EndStateBlock method, and when you capture a predefined set of device state data by calling the IDirect3DDevice8::CreateStateBlock method.


Recording State Blocks

The IDirect3DDevice8 interface provides the IDirect3DDevice8::BeginStateBlock method to record device states in a state block as your application calls for them. The BeginStateBlock method causes the system to start recording device state changes in a state block, rather than applying them to the device. After you call BeginStateBlock, calls to any of the following methods are recorded in a device state block.

  • IDirect3DDevice8::LightEnable
  • IDirect3DDevice8::SetClipPlane
  • IDirect3DDevice8::SetLight
  • IDirect3DDevice8::SetMaterial
  • IDirect3DDevice8::SetRenderState
  • IDirect3DDevice8::SetTexture
  • IDirect3DDevice8::SetTextureStageState
  • IDirect3DDevice8::SetTransform
  • IDirect3DDevice8::SetViewport

When you're done recording the state block, notify the system to stop recording by calling the IDirect3DDevice8::EndStateBlock method. The EndStateBlock method places the handle of the state block in the variable whose address you pass in the pToken parameter. Your application uses this handle to apply the state block to the device as needed, to capture new state data into the block, and to delete the state block when it is no longer required.

Performance Note For best results, group all state changes tightly between a BeginStateBlock and EndStateBlock pair.

It is important to check the error code from the EndStateBlock method. If the method fails, it is likely because the display mode has changed. Design your application to recover from this type of failure by recreating its surfaces and recording the state block again.


Capturing State Blocks

The IDirect3DDevice8::CaptureStateBlock method updates the values within an existing state block to reflect the current state of the device. The method accepts a single parameter, Token, that identifies the state block that will receive the current state of the device if the call succeeds.

The CaptureStateBlock method is especially useful to update a state block that your application has already recorded to include slightly different state settings. To do so, apply the existing state block, change the necessary settings, then capture the state of the system back to the state block, as shown in the following code example.

// The token variable contains a handle to a device-state block for
// a previously recorded set of device states.

// Set the current state block.
d3dDevice->ApplyStateBlock(token);

// Change device states as needed.
.
.
.

// Capture the modified device state data back to the existing block.
d3dDevice->CaptureStateBlock(token);

The CaptureStateBlock method doesn't capture the entire state of the device; it only updates the values for the states already in the state block. For example, imagine a state block that contains the two operations shown in the following code example.

d3dDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD);
d3dDevice->SetTexture(0, pTexture);

If your application changed either of these settings since the state block was originally recorded, the CaptureStateBlock method will update the states within the block—and only those states—to their new values.


Applying State Blocks

The IDirect3DDevice8::ApplyStateBlock method applies an existing state block to the device. The ApplyStateBlock method accepts a single parameter, Token, that identifies the state block to apply.

Note You cannot apply a state block while recording another state block—that is, between calls to IDirect3DDevice8::BeginStateBlock and IDirect3DDevice8::EndStateBlock. Attempts to do so will fail.


Creating Predefined State Blocks

The IDirect3DDevice8::CreateStateBlock method creates a new state block that contains the entire set of device states or only those device states related to vertex or pixel processing. The CreateStateBlock method accepts two parameters. The first parameter identifies the type of state information to capture in the new state block, and the second parameter is the address of a variable that will receive a valid state-block handle if the call succeeds.

Valid values for the first parameter are defined by the D3DSTATEBLOCKTYPE enumerated type, which includes members that you can use to capture the entire set of device states (D3DSBT_ALL), or only those states that pertain to vertex or pixel processing (D3DSBT_VERTEXSTATE or D3DSBT_PIXELSTATE). The following list summarizes the states that the system captures when you pass the D3DSBT_VERTEXSTATE or D3DSBT_PIXELSTATE values.

  • Vertex-related states (D3DSBT_VERTEXSTATE)
  • State (enabled or disabled) of all lights
  • Transformation matrices
  • User-defined clipping planes
    These values are set for the following render states.
    D3DRS_AMBIENT

    D3DRS_AMBIENTMATERIALSOURCE

    D3DRS_CLIPPING

    D3DRS_CLIPPLANEENABLE

    D3DRS_COLORVERTEX

    D3DRS_CULLMODE

    D3DRS_DIFFUSEMATERIALSOURCE

    D3DRS_EMISSIVEMATERIALSOURCE

    D3DRS_FOGCOLOR

    D3DRS_FOGDENSITY

    D3DRS_FOGENABLE

    D3DRS_FOGEND

    D3DRS_FOGSTART

    D3DRS_FOGTABLEMODE

    D3DRS_FOGVERTEXMODE

    D3DRS_INDEXEDVERTEXBLENDENABLE

    D3DRS_LIGHTING

    D3DRS_LOCALVIEWER

    D3DRS_NORMALIZENORMALS

    D3DRS_POINTSCALE_A

    D3DRS_POINTSCALE_B

    D3DRS_POINTSCALE_C

    D3DRS_POINTSIZE

    D3DRS_POINTSIZE_MAX

    D3DRS_POINTSIZE_MIN

    D3DRS_POINTSCALEENABLE

    D3DRS_POINTSPRITEENABLE

    D3DRS_PATCHEDGESTYLE

    D3DRS_PATCHSEGMENTS

    D3DRS_RANGEFOGENABLE

    D3DRS_SHADEMODE

    D3DRS_SOFTWAREVERTEXPROCESSING

    D3DRS_SPECULARENABLE

    D3DRS_SPECULARMATERIALSOURCE

    D3DRS_TWEENFACTOR

    D3DRS_VERTEXBLEND

    These values are set for the following texture-stage states.
    D3DTSS_TEXCOORDINDEX

    D3DTSS_TEXTURETRANSFORMFLAGS

  • Pixel-related states (D3DSBT_PIXELSTATE)
    These values are set for the following render states.
    D3DRS_ALPHABLENDENABLE

    D3DRS_ALPHAFUNC

    D3DRS_ALPHAREF

    D3DRS_ALPHATESTENABLE

    D3DRS_COLORWRITEENABLE

    D3DRS_DESTBLEND

    D3DRS_DITHERENABLE

    D3DRS_EDGEANTIALIAS

    D3DRS_FILLMODE

    D3DRS_FOGDENSITY

    D3DRS_FOGEND

    D3DRS_FOGSTART

    D3DRS_LASTPIXEL

    D3DRS_LINEPATTERN

    D3DRS_MULTISAMPLEANTIALIAS

    D3DRS_MULTISAMPLEMASK

    D3DRS_SHADEMODE

    D3DRS_SRCBLEND

    D3DRS_STENCILENABLE

    D3DRS_STENCILFAIL

    D3DRS_STENCILFUNC

    D3DRS_STENCILMASK

    D3DRS_STENCILPASS

    D3DRS_STENCILREF

    D3DRS_STENCILWRITEMASK

    D3DRS_STENCILZFAIL

    D3DRS_TEXTUREFACTOR

    D3DRS_WRAP0 through D3DRS_WRAP7

    D3DRS_ZBIAS

    D3DRS_ZENABLE

    D3DRS_ZFUNC

    D3DRS_ZWRITEENABLE

    These values are set for the following texture-stage states.
    D3DTSS_ADDRESSU

    D3DTSS_ADDRESSV

    D3DTSS_ADDRESSW

    D3DTSS_ALPHAARG1

    D3DTSS_ALPHAARG2

    D3DTSS_ALPHAOP

    D3DTSS_BORDERCOLOR

    D3DTSS_BUMPENVLOFFSET

    D3DTSS_BUMPENVLSCALE

    D3DTSS_BUMPENVMAT00

    D3DTSS_BUMPENVMAT01

    D3DTSS_BUMPENVMAT10

    D3DTSS_BUMPENVMAT11

    D3DTSS_COLORARG1

    D3DTSS_COLORARG2

    D3DTSS_COLOROP

    D3DTSS_MAGFILTER

    D3DTSS_MAXANISOTROPY

    D3DTSS_MAXMIPLEVEL

    D3DTSS_MINFILTER

    D3DTSS_MIPFILTER

    D3DTSS_MIPMAPLODBIAS

    D3DTSS_TEXCOORDINDEX

    D3DTSS_TEXTURETRANSFORMFLAGS

Note It is important to check the error code from the CreateStateBlock method. If the method fails, it is likely because the display mode has changed. Your application should recover from this type of failure by recreating its surfaces, and then recreating the state block.


Deleting State Blocks

The IDirect3DDevice8::DeleteStateBlock deletes a state block, deallocating the memory used to contain it. The DeleteStateBlock method accepts the handle to the state block to delete at its only parameter. After deleting a state block, any handles to it are invalid, and can no longer be used.


Lost Devices

This section provides information about lost devices in Microsoft® Direct3D®. Information is divided into the following topics.

  • What is a Lost Device?
  • Responding to a Lost Device
  • Lost Devices and Locking Operations
  • Lost Devices and Resources
  • Lost Devices and Retrieved Data


What is a Lost Device?

A Microsoft® Direct3D® device can be in either an operational state or a lost state. The operational state is the normal state of the device; the device executes and presents all rendering as expected. The device makes a transition to the lost state when an event—such as the loss of keyboard focus in a full-screen application—causes rendering to become impossible. The lost state is characterized by the silent failure of all rendering operations, which means that the rendering methods can return success codes even though the rendering operations fail. In this situation, the error code D3DERR_DEVICELOST is returned by IDirect3DDevice8::Present.

By design, the full set of scenarios that can cause a device to become lost is not specified. Some typical examples include loss of focus, such as when the user presses ALT+TAB or when a system dialog is initialized. Devices can also be lost due to a power management event, or when another application assumes full-screen operation. In addition, any failure from IDirect3DDevice8::Reset puts the device into a lost state.


Responding to a Lost Device

If a device is lost, the application queries the device to see if it can be restored to the operational state. If not, the application waits until the device can be restored.

If the device can be restored, the application prepares the device by destroying all video-memory resources and any swap chains. Then, the application calls the IDirect3DDevice8::Reset method. Reset is the only method that has an effect when a device is lost, and is the only method by which an application can change the device from a lost to an operational state. Reset will fail unless the application releases all resources that are allocated in D3DPOOL_DEFAULT, including those created by the IDirect3DDevice8::CreateRenderTarget and IDirect3DDevice8::CreateDepthStencilSurface methods.

For the most part, the high-frequency calls of Microsoft® Direct3D® do not return any information about whether the device has been lost. The application can continue to call rendering methods, such as IDirect3DDevice8::DrawPrimitive, without receiving notification of a lost device. Internally, these operations are discarded until the device is reset to the operational state.

The application can determine what to do on encountering a lost device by querying the return value of the IDirect3DDevice8::TestCooperativeLevel method.

  • If the method returns D3D_OK, the device is operational.
  • If the device is lost but cannot be restored at the current time, the return value is D3DERR_DEVICELOST. This is the case when the user presses ALT+TAB, causing a full-screen device to lose focus. Applications should respond by pausing until the device can be reset. A D3DERR_DEVICENOTRESET return code from TestCooperativeLevel indicates this situation.
  • If the device is lost and can be restored, the return code from TestCooperativeLevel is D3DERR_DEVICENOTRESET. Note that the return code from the IDirect3DDevice8::Present method is still D3DERR_DEVICELOST.

In all cases, destroying video-memory resources is a prerequisite to calling Reset, even if the device has not been lost.


Lost Devices and Locking Operations

Internally, Microsoft® Direct3D® does enough work to ensure that a lock operation will succeed after a device is lost. However, it is not guaranteed that the video-memory resource's data will be accurate during the lock operation. It is guaranteed that no error code will be returned. This allows applications to be written without concern for device loss during a lock operation.

For more information, see Lost Devices and Retrieved Data.


Lost Devices and Resources

Resources can consume video memory. Because a lost device is disconnected from the video memory owned by the adapter, it is not possible to guarantee allocation of video memory when the device is lost. As a result, all resource creation methods are implemented to succeed by returning D3D_OK, but do in fact allocate only dummy system memory. Because any video-memory resource must be destroyed before the device is resized, there is no issue of over-allocating video memory. These dummy surfaces allow lock and copy operations to appear to function normally until the application calls IDirect3DDevice8::Present and discovers that the device has been lost.

All video memory must be released before a device can be reset from a lost state to an operational state. This means that the application should release any swap chains created with IDirect3DDevice8::CreateAdditionalSwapChain and any resources placed in the D3DPOOL_DEFAULT memory class. The application need not release resources in the D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM memory classes. Other state data is automatically destroyed by the transition to an operational state.

You are encouraged to develop applications with a single code path to respond to device loss. This code path is likely to be similar, if not identical, to the code path taken to initialize the device at startup.


Lost Devices and Retrieved Data

Microsoft® Direct3D® allows applications to copy generated or previously written images from video-memory resources to nonvolatile system-memory resources. Because the source images of such transfers might be lost at any time, Direct3D allows such copy operations to fail when the device is lost.

The copy operations, IDirect3DDevice8::UpdateTexture and IDirect3DDevice8::CopyRects, can return D3DERR_DEVICELOST when the source object is in volatile memory (D3DPOOL_DEFAULT) and the destination object is in nonvolatile memory (D3DPOOL_SYSTEMMEM or D3DPOOL_MANAGED). Another copy operation, IDirect3DDevice8::GetFrontBuffer, can fail due to retrieving data from the primary surface. Note that these cases are the only instance of D3DERR_DEVICELOST outside of the IDirect3DDevice8::Present, IDirect3DDevice8::TestCooperativeLevel, and IDirect3DDevice8::Reset methods.


Direct3D Resources

This section discusses resources and gives a general overview on how they are used in your application. Information is divided into the following topics.

  • What Are Resources?
  • Resource Properties
  • Resource Relationships
  • Using Resources


What Are Resources?

Resources are the textures and buffers that are used to render a scene. Applications need to create, load, copy, and use resources. This section gives a brief introduction to resources and the steps and methods used by applications when working with resources. For more information on specific resource types, see Textures, Vertex Buffers, and Index Buffers.

All resources, including the geometry resources IDirect3DIndexBuffer8 and IDirect3DVertexBuffer8, inherit from the IDirect3DResource8 interface. The texture resources, IDirect3DCubeTexture8, IDirect3DTexture8, and IDirect3DVolumeTexture8, also inherit from the IDirect3DBaseTexture8 interface.


Resource Properties

All resources share the following properties.

  • Usage. The way a resource is used—for example, as a texture or a render target.
  • Format. The format of the data—for example, the pixel format of a 2-D surface.
  • Pool. The type of memory where the resource is allocated.
  • Type. The type of resource—for example, a vertex buffer or render target.

Resource uses are enforced. An application that will use a resource in a certain operation must specify that operation at resource creation time. The following usages are defined for resources.

  • D3DUSAGE_DEPTHSTENCIL
  • D3DUSAGE_DONOTCLIP
  • D3DUSAGE_DYNAMIC
  • D3DUSAGE_RTPATCHES
  • D3DUSAGE_NPATCHES
  • D3DUSAGE_POINTS
  • D3DUSAGE_RENDERTARGET
  • D3DUSAGE_SOFTWAREPROCESSING
  • D3DUSAGE_WRITEONLY

The D3DUSAGE_RTPATCHES, D3DUSAGE_NPATCHES, and D3DUSAGE_POINTS flags indicate to the driver that the data in these buffers is likely to be used for triangular or grid patches, N patches, or point sprites, respectively. These flags are provided in case the hardware cannot perform these operations without host processing. Therefore, the driver will want to allocate these surfaces in system memory so that the CPU can access them. If the driver can perform these operations entirely in hardware, then it can allocate these surfaces in video or /AGP memory to avoid a host copy and improve performance at least twofold. Note that the information provided by these flags is not absolutely required. A driver can detect that such operations are being performed on the data, and it will move the buffer back to system memory for subsequent frames.

For details on the usage flags and how they relate to specific resources, see the reference pages on the individual resource creation methods.

For information on the surface format of resources, see the D3DFORMAT enumerated type.

The class of memory that holds a resource's buffers is called a pool. Pool values are defined by the D3DPOOL enumerated type. A pool cannot be mixed for different objects contained in a single resource—that is, mip levels in a mipmap—and once a pool is chosen for a resource, the pool cannot be changed.

The resources types are set implicitly at run time when the application calls a resource creation method such as IDirect3DDevice8::CreateCubeTexture. Resource types are defined by the D3DRESOURCETYPE enumerated type. Applications can query these types at run time; however, it is expected that most scenarios will not require run-time type checking.


Resource Relationships

The following diagram illustrates the operations that are syntactically possible on specific resources and their contents. For more information on how to use resources, see Manipulating Resources.

Arrows running from left to right indicate that the target types are created by the given methods, while arrows running from right to left indicate that those resource types can be passed as arguments to the given methods.


Using Resources

The following topics discuss common tasks that applications perform when working with resources.

  • Managing Resources
  • Application-Managed Resources and Allocation Strategies
  • Manipulating Resources
  • Locking Resources


Managing Resources

Resource management is the process where resources are promoted from system-memory storage to device-accessible storage and discarded from device-accessible storage. The Microsoft® Direct3D® run time has its own management algorithm based on a least-recently-used priority technique. Direct3D switches to a most-recently-used priority technique when it detects that more resources than can coexist in device-accessible memory are used in a single frame—between IDirect3DDevice8::BeginScene and IDirect3DDevice8::EndScene calls.

Use the D3DPOOL_MANAGED flag at creation time to specify a managed resource. Managed resources persist through transitions between the lost and operational states of the device. The device can be restored with a call to IDirect3DDevice8::Reset, and such resources continue to function normally without being reloaded with artwork. However, if the device must be destroyed and recreated, all resources created using D3DPOOL_MANAGED must be recreated.

Use the D3DPOOL_DEFAULT flag at creation time to specify that a resource be placed in the default pool. Resources in the default pool do not persist through transitions between the lost and operational states of the device. These resources must be released before calling Reset and must then be recreated.

For more information on the lost state of a device, see Lost Devices.

Note that resource management is not supported for all types and usages. For example, objects created with the D3DUSAGE_RENDERTARGET flag are not supported. In addition, resource management is not recommended for objects whose contents are changing with high frequency. For example, a managed vertex buffer that changes every frame can significantly degrade performance for some hardware. However, this is not a problem for texture resources.


Application-Managed Resources and Allocation Strategies

Managed vertex-buffer or index-buffer resources cannot be declared dynamic by specifying D3DUSAGE_DYNAMIC at creation time. This would require an additional copy for every modification to the vertex buffer contents. Dynamic vertex buffers are intended for rendering dynamic geometry as well as data pulled in from BSP trees or other visibility data structures. This can be accomplished by pre-allocating buffers of the desired format. These resources are then parceled out to support application needs by a resource manager within the application. Because there are only a few different vertex strides that an application will use simultaneously, and a different vertex buffer is required only for each unique stride, the total number of dynamic vertex buffers is small. When managing dynamic resources in this way, it is important to ensure that high-frequency demands on the resources do not significantly decrease the application's performance.

When simultaneously using both D3D-managed and application-managed resources, all application managed resources should be allocated in D3DPOOL_DEFAULT memory prior to creating any managed resources. Allocating resources in D3DPOOL_DEFAULT memory after allocating resources in D3DPOOL_MANAGED memory will give the D3D memory manager an inaccurate account of available memory.


Manipulating Resources

Your application manipulates resources in order to render a scene. First, the application creates texture resources by using the following methods.

  • IDirect3DDevice8::CreateCubeTexture
  • IDirect3DDevice8::CreateTexture
  • IDirect3DDevice8::CreateVolumeTexture

The texture objects returned by the texture creation methods are containers for surfaces or volumes; these containers are generically known as buffers. The buffers owned by the resource inherit the usages, format, and pool of the resource but have their own type. For more information, see Resource Properties.

The application gains access to the contained surfaces, for the purpose of loading artwork, by calling the following methods. For details, see Locking Resources.

  • IDirect3DCubeTexture8::LockRect
  • IDirect3DTexture8::LockRect
  • IDirect3DVolumeTexture8::LockBox

The lock methods take arguments denoting the contained surface—for example, the mipmap sub-level or cube face of the texture—and return pointers to the pixels. The typical application never uses a surface object directly.

In addition, the application creates geometry-oriented resources by using the following methods.

  • IDirect3DDevice8::CreateIndexBuffer
  • IDirect3DDevice8::CreateVertexBuffer

Your application locks and fills the buffer resources by calling the following methods.

  • IDirect3DIndexBuffer8::Lock
  • IDirect3DVertexBuffer8::Lock

If your application is allowing the Microsoft® Direct3D® run time to manage these resources, then the resource creation process ends here. Otherwise, the application manages the promotion of system memory resources to device-accessible resources, where the hardware accelerator can use them, by calling the IDirect3DDevice8::UpdateTexture method.

To present images rendered from resources, the application also needs color and depth-stencil buffers. For typical applications, the color buffer is owned by the device's swap chain, which is a collection of back buffer surfaces, and is implicitly created with the device. Depth-stencil surfaces can be implicitly created, or explicitly created by using the IDirect3DDevice8::CreateDepthStencilSurface method. The application associates a device and its depth and color buffer with a call to IDirect3DDevice8::SetRenderTarget.

For details on presenting the final image, see Presenting a Scene.


Locking Resources

Locking a resource means granting CPU access to its storage. The following locking methods are defined for resources.

  • D3DLOCK_DISCARD
  • D3DLOCK_READONLY
  • D3DLOCK_NOOVERWRITE
  • D3DLOCK_NOSYSLOCK
  • D3DLOCK_NO_DIRTY_UPDATE

For details on locking flags and how they relate to specific resources, see the reference pages on the individual resource locking methods. Application developers should note that the D3DLOCK_DISCARD, D3DLOCK_READONLY, and D3DLOCK_NOOVERWRITE flags are only hints. The run time does not check that applications are following the functionality specified by these flags. An application that specifies D3DLOCK_READONLY but then writes to the resource should expect undefined results. An application that specifies D3DUSAGE_WRITEONLY but then reads from the resource should expect a significant performance penalty. In general, working against locking flags, including the locking usage flags, is not guaranteed to work in the future and may incur a significant performance penalty both now and in the future.

A lock operation is followed by an unlock operation. For example, after locking a texture, the application subsequently relinquishes direct access to locked textures by unlocking them. In addition to granting processor access, any other operations involving that resource are serialized for the duration of a lock. Only a single lock for a resource is allowed, even for non-overlapping regions, and no accelerator operations on a surface can be ongoing while a lock operation is outstanding on that surface.

Each resource interface has methods for locking the contained buffers. Each texture resource can also lock a sub-portion of that resource. Two-dimensional resources (surfaces) allow the locking of sub-rectangles, and volume resources allow the locking of sub-volumes or boxes. Each lock method returns a structure that contains a pointer to the storage backing the resource and values representing the distances between rows or planes of data, depending on the resource type. For details, see the method lists for the resource interfaces. The returned pointer always points to the top-left byte in the locked sub-regions.

When working with index and vertex buffers, you can make multiple lock calls; however, you must ensure that the number of lock calls matches the number of unlock calls.

The DXT set of compressed texture formats, which store pixels in encoded 4×4 blocks, can only be locked on 4×4 boundaries.


Surfaces

This section contains information about Microsoft® Direct3D® surfaces. The following topics are discussed.

  • Basic Concepts of Surfaces
  • Gamma Controls
  • Accessing Surface Memory Directly
  • Private Surface Data


Basic Concepts of Surfaces

This section contains information about the basic concepts associated with Microsoft® Direct3D® surfaces. The following topics are discussed.

  • Surface Interfaces
  • Width vs. Pitch
  • Surface Formats
  • Flipping Surfaces
  • Copying to Surfaces


Surface Interfaces

A surface represents a linear area of display memory. A surface usually resides in the display memory of the display card, although surfaces can exist in system memory. Surface objects are contained within the IDirect3DSurface8 interface.

An IDirect3DSurface8 interface is obtained by calling one of the following methods.

  • IDirect3DCubeTexture8::GetCubeMapSurface
  • IDirect3DDevice8::CreateDepthStencilSurface
  • IDirect3DDevice8::CreateImageSurface
  • IDirect3DDevice8::CreateRenderTarget
  • IDirect3DDevice8::GetBackBuffer
  • IDirect3DDevice8::GetDepthStencilSurface
  • IDirect3DDevice8::GetFrontBuffer
  • IDirect3DDevice8::GetRenderTarget
  • IDirect3DSwapChain8::GetBackBuffer
  • IDirect3DTexture8::GetSurfaceLevel

The IDirect3DSurface8 interface enables you to indirectly access memory through the IDirect3DDevice8::CopyRects method. This method allows you to copy a rectangular region of pixels from one IDirect3DSurface8 interface to another IDirect3DSurface8 interface. The surface interface also has methods to directly access display memory. For example, you can use the IDirect3DSurface8::LockRect method to lock a rectangular region of display memory. It is important to call IDirect3DSurface8::UnlockRect after you are done working with the locked rectangular region on the surface.


Width vs. Pitch

Although the terms width and pitch are often used informally, they have very important, and distinctly different, meanings. As a result, you should understand the meanings for each, and how to interpret the values that Microsoft® Direct3D® uses to describe them.

Direct3D uses the D3DSURFACE_DESC structure to carry information describing a surface. Among other things, this structure is defined to contain information about a surface's dimensions, as well as how those dimensions are represented in memory. The structure uses the Height and Width members to describe the logical dimensions of the surface. Both members are measured in pixels. Therefore, the Height and Width values for a 640×480 surface are the same whether it is an 8-bit surface or a 24-bit RGB surface.

When you lock a surface using the IDirect3DSurface8::LockRect method, the method fills in a D3DLOCKED_RECT structure that contains the pitch of the surface and a pointer to the locked bits. The value in the Pitch member describes the surface's memory pitch, also called stride. Pitch is the distance, in bytes, between two memory addresses that represent the beginning of one bitmap line and the beginning of the next bitmap line. Because pitch is measured in bytes rather than pixels, a 640×480×8 surface has a very different pitch value than a surface with the same dimensions but a different pixel format. Additionally, the pitch value sometimes reflects bytes that Direct3D has reserved as a cache, so it is not safe to assume that pitch is simply the width multiplied by the number of bytes per pixel. Rather, visualize the difference between width and pitch as shown in the following illustration.

In this figure, the front buffer and back buffer are both 640×480×8, and the cache is 384×480×8.

Pitch values are only useful when you are directly accessing surface memory. For example, after calling the LockRect method, the pBits member of the associated D3DLOCKED_RECT structure contains the address of the top-left pixel of the locked area of the surface, and the Pitch member is the surface pitch. You access pixels horizontally by incrementing or decrementing the surface pointer by the number of bytes per pixel, and you move up or down by adding the pitch value to, or subtracting it from, the current surface pointer.

When accessing surfaces directly, take care to stay within the memory allocated for the dimensions of the surface and stay out of any memory reserved for cache. Additionally, when you lock only a portion of a surface, you must stay within the rectangle you specify when locking the surface. Failing to follow these guidelines will have unpredictable results. When rendering directly into surface memory, always use the pitch returned by the LockRect method. Do not assume a pitch based solely on the display mode. If your application works on some display adapters but looks garbled on others, this may be the cause of the problem.

For more information, see Accessing Surface Memory Directly.


Surface Formats

Surface formats dictate how data for each pixel in surface memory is interpreted. Microsoft® Direct3D® uses the D3DFORMAT member of the D3DSURFACE_DESC structure to describe the surface format. You can retrieve the format of an existing surface by calling the IDirect3DSurface8::GetDesc method.


Flipping Surfaces

A Microsoft® Direct3D® application typically displays an animated sequence by generating the frames of the animation in back buffers and presenting them in sequence. Back buffers are organized into swap chains. A swap chain is a series of buffers that "flip" to the screen one after another. This can be used to render one scene in memory and then flip the scene to the screen when rendering is complete. This avoids the phenomenon known as tearing and allows for smoother animation.

Each device created in Direct3D has at least one swap chain. When you initialize the first Direct3D device, you set the BackBufferCount member of the D3DPRESENT_PARAMETERS structure, which tells Direct3D the number of back buffers that will be in the swap chain. The call to IDirect3D8::CreateDevice then creates the Direct3D device and corresponding swap chain.

When you use the IDirect3DDevice8::Present method to request a surface flip operation, the pointers to surface memory for the front buffer and back buffers are swapped. Flipping is performed by switching pointers that the display device uses for referencing memory, not by copying surface memory. When a flipping chain contains a front buffer and more than one back buffer, the pointers are switched in a circular pattern, as shown in the following illustration.

You can create addition swap chains for a device by calling IDirect3DDevice8::CreateAdditionalSwapChain. An application can create one swap chain per view and associate each swap chain with a particular window. The application renders images in the back buffers of each swap chain, and then presents them individually. The two parameters that CreateAdditionalSwapChain takes are a pointer to a D3DPRESENT_PARAMETERS structure and the address of a pointer to an IDirect3DSwapChain8 interface. You can then use IDirect3DSwapChain8::Present to display the contents of the next back buffer to the front buffer. Note that a device can only have one full-screen swap chain.

You can gain access to a specific back buffer by calling the IDirect3DDevice8::GetBackBuffer or IDirect3DSwapChain8::GetBackBuffer methods, which return a pointer to a IDirect3DSurface8 interface that represents the returned back buffer surface. Note that calling this method increases the internal reference count on the IDirect3DDevice8 interface so be sure to call IUnknown::Release when you are done using this surface or you will have a memory leak.

Remember, Direct3D flips surfaces by swapping surface memory pointers within the swap chain, not by swapping the surfaces themselves. This means that you will always render to the back buffer that will be displayed next.

It is important to note the distinction between a "flipping operation", as performed by a display adapter driver, and a "Present" operation applied to a swap chain created with D3DSWAPEFFECT_FLIP.

The term "flip" conventionally denotes an operation that alters the range of video memory addresses that a display adapter uses to generate its output signal, thus causing the contents of a previously hidden back buffer to be displayed. In DirectX 8, the term is often used more generally to describe the presentation of a back buffer in any swap chain created with the D3DSWAPEFFECT_FLIP swap effect.

While such "Present" operations are almost invariably implemented by flip operations when the swap chain is a full-screen one, they are necessarily implemented by copy operations when the swap chain is windowed. Furthermore, a display adapter driver may use flipping to implement Present operations against full-screen swap chains based on the D3DSWAPEFFECT_DISCARD, D3DSWAPEFFECT_COPY and D3DSWAPEFFECT_COPY_VSYNC swap effects.

The discussion above applies to the commonly used case of a full-screen swap chain created with D3DSWAPEFFECT_FLIP.

For a more general discussion of the different swap effects for both windowed and full-screen swap chains, see D3DSWAPEFFECT.


Copying To Surfaces

When using the IDirect3DDevice8::CopyRects method, you pass an array of rectangles on the source surface or NULL to specify the entire surface. You also pass an array of points on the destination surface to which the top-left position of each rectangle on the source image is copied. This method does not support clipping. The operation will fail unless all the source rectangles and their corresponding destination rectangles are completely contained within the source and destination surfaces respectively. This method does not support alpha blending, color keys, or format conversion. Note that the destination and source surfaces must be distinct.

CopyRects Example

The following example copies two rectangles from the source surface to a destination surface. The first rectangle is copied from (0, 0, 50, 50) on the source surface to the same location on the destination surface, and the second rectangle is copied from (50, 50, 100, 100) on the source surface to (150 ,150, 200, 200) on the destination surface.

//The following assumptions are made:
//-d3dDevice is a valid Direct3DDevice8 object.
//-pSource and pDest are valid IDirect3DSurface8 pointers.

RECT  rcSource[] = {  0,  0,  50,  50,
                     50, 50, 100, 100 };
POINT ptDest[]   = {  0,  0, 150, 150 };

d3dDevice->CopyRect( pSource, rcSource, 2, pDest, ptDest);

The following methods are also available in C++/C for copying images to a Microsoft® Direct3D® surface.

  • D3DXLoadSurfaceFromFileA
  • D3DXLoadSurfaceFromFileInMemory
  • D3DXLoadSurfaceFromFileW
  • D3DXLoadSurfaceFromMemory
  • D3DXLoadSurfaceFromResourceA
  • D3DXLoadSurfaceFromResourceW
  • D3DXLoadSurfaceFromSurface
  • IDirect3DDevice8::CopyRects


Gamma Controls

This section contains information about gamma controls used with Microsoft® Direct3D®. Information is organized into the following topics.

  • What Are Gamma Controls?
  • Using Gamma Controls


What Are Gamma Controls?

Gamma controls allow you to change how the system displays the contents of the surface, without affecting the contents of the surface itself. Think of these controls as very simple filters that Microsoft® Direct3D® applies to data as it leaves a surface and before it is rendered on the screen.

Gamma controls are simply a property of a swap chain. Gamma controls make it possible to dynamically change how a surface's red, green, and blue levels map to the actual levels that the system displays. By setting gamma levels, you can cause the user's screen to flash colors—red when the user's character is shot, green when the character picks up a new item, and so on—without copying new images to the frame buffer to achieve the effect. Or, you might adjust color levels to apply a color bias to the images in the back buffer.

There is always at least one swap chain (the implicit swap chain) for each device because Microsoft® Direct3D® for Microsoft DirectX® 8.0 has one swap chain as a property of the device. Because the gamma ramp is a property of the swap chain, the gamma ramp can be applied when the swap chain is windowed. The gamma ramp takes effect immediately. There is no waiting for a VSYNC operation.

For details on how to use gamma controls, see Using Gamma Controls.


Using Gamma Controls

The IDirect3DDevice8::SetGammaRamp and IDirect3DDevice8::GetGammaRamp methods allow you to manipulate ramp levels that affect the red, green, and blue color components of pixels from the surface before they are sent to the digital-to-analog converter (DAC) for display.

In the following topics describe the general concept of ramp levels and provide information about working with those levels.

  • About Gamma Ramp Levels
  • Detecting Gamma Ramp Support
  • Setting and Retrieving Gamma Ramp Levels


About Gamma Ramp Levels

In Microsoft® Direct3D®, the term gamma ramp describes a set of values that map the level of a particular color component—red, green, blue—for all pixels in the frame buffer to new levels that are received by the digital-to-analog converter (DAC) for display. The remapping is performed by way of three look-up tables, one for each color component.

Here's how it works: Direct3D takes a pixel from the frame buffer and evaluates its individual red, green, and blue color components. Each component is represented by a value from 0 to 65535. Direct3D takes the original value and uses it to index a 256-element array (the ramp), where each element contains a value that replaces the original one. Direct3D performs this look-up and replace process for each color component of each pixel in the frame buffer, thereby changing the final colors for all the on-screen pixels.

It's handy to visualize the ramp values by graphing them. The left graph of the two following graphs shows a ramp that doesn't modify colors at all. The right graph shows a ramp that imposes a negative bias to the color component to which it is applied.

The array elements for the graph on the left contain values identical to their index—0 in the element at index 0, and 65535 at index 255. This type of ramp is the default, as it doesn't change the input values before they're displayed. The right graph provides more variation; its ramp contains values that range from 0 in the first element to 32768 in the last element, with values ranging uniformly in between. The effect is that the color component that uses this ramp appears muted on the display. You are not limited to using linear graphs; if your application can assign arbitrary mapping if needed. You can even set the entries to all zeroes to remove a color component completely from the display.


Detecting Gamma Ramp Support

If the device does not support gamma ramps in the swap chain's current presentation mode (full-screen or windowed), no error value is returned. Applications can check the D3DCAPS2_FULLSCREENGAMMA and D3DCAPS2_CANCALIBRATEGAMMA capability bits in the Caps2 member of the D3DCAPS8 type to determine the capabilities of the device and whether a calibrator is installed.


Setting and Retrieving Gamma Ramp Levels

Gamma ramp levels are effectively look-up tables that Microsoft® Direct3D® uses to map the frame buffer color components to new levels that will be displayed. For more information, see About Gamma Ramp Levels. You can set and retrieve ramp levels for the primary surface by calling the IDirect3DDevice8::SetGammaRamp and IDirect3DDevice8::GetGammaRamp methods. SetGammaRamp accepts two parameters and GetGammaRamp accepts one parameter. For SetGammaRamp, the first parameter is either D3DSGR_CALIBRATE or D3DSGR_NO_CALIBRATION. The second parameter, pRamp, is a pointer to a D3DGAMMARAMP structure. The D3DGAMMARAMP structure contains three 256-element arrays of WORDs, one array each to contain the red, green, and blue gamma ramps. GetGammaRamp has one parameter that takes a pointer to a D3DGAMMARAMP type that will be filled with the current gamma ramp.

You can include the DDSGR_CALIBRATE value for the first parameter of SetGammaRamp to invoke the calibrator when setting new gamma levels. Calibrating gamma ramps incurs some processing overhead, and should not be used frequently. Setting a calibrated gamma ramp provides a consistent and absolute gamma value for the user, regardless of the display adapter and monitor.

Not all systems support gamma calibration. To determine if gamma calibration is supported, call IDirect3DDevice8::GetDeviceCaps, and examine the Caps2 member of the associated D3DCAPS8 structure after the method returns. If the D3DCAPS2_CANCALIBRATEGAMMA capability flag is present, then gamma calibration is supported.

When setting new ramp levels, keep in mind that that the levels you set in the arrays are only used when your application is in full-screen, exclusive mode. Whenever your application changes to normal mode, the ramp levels are set aside, taking effect again when the application reinstates full-screen mode.


Accessing Surface Memory Directly

You can directly access the surface memory by using the IDirect3DSurface8::LockRect method. When you call this method, the pRect parameter is a pointer to a RECT structure that describes the rectangle on the surface to access directly. To request that the entire surface be locked, set pRect to NULL. Also, you can specify a RECT that covers only a portion of the surface. Providing that no two rectangles overlap, two threads or processes can simultaneously lock multiple rectangles in a surface. Note that a multisample back buffer cannot be locked.

The LockRect method fills a D3DLOCKED_RECT structure with all the information to properly access the surface memory. The structure includes information about the pitch and has a pointer to the locked bits. When you finish accessing the surface memory, call the IDirect3DSurface8::UnlockRect method to unlock it.

While you have a surface locked, you can directly manipulate the contents. The following list describes some tips for avoiding common problems with directly rendering surface memory.

  • Never assume a constant display pitch. Always examine the pitch information returned by the LockRect method. This pitch can vary for a number of reasons, including the location of the surface memory, the display card type, or even the version of the Microsoft® Direct3D® driver. For more information, see Width vs. Pitch.
  • Make certain you copy to unlocked surfaces. Direct3D copy methods will fail if called on a locked surface.
  • Limit your application's activity while a surface is locked.
  • Always copy data aligned to display memory. Microsoft® Windows® 95 and Windows 98 use a page fault handler, Vflatd.386, to implement a virtual flat-frame buffer for display cards with bank-switched memory. The handler allows these display devices to present a linear frame buffer to Direct3D. Copying data unaligned to display memory can cause the system to suspend operations if the copy spans memory banks.
  • A surface may not be locked if it belongs to a resource assigned to the D3DPOOL_DEFAULT memory pool. Back buffer surfaces, which may be accessed using the IDirect3DDevice8::GetBackBuffer and IDirect3DSwapChain8::GetBackBuffer methods, may be locked only if the swap chain was created with the Flags member of the D3DPRESENT_PARAMETERS structure set to include D3DPRESENTFLAG_LOCKABLE_BACKBUFFER.


Private Surface Data

You can store any kind of application-specific data with a surface. For example, a surface representing a map in a game might contain information about terrain.

A surface can have more than one private data buffer. Each buffer is identified by a GUID that you supply when attaching the data to the surface.

To store private surface data, use the IDirect3DSurface8::SetPrivateData method, passing a pointer to the source buffer, the size of the data, and an application-defined GUID for the data. Optionally, the source data can exist in the form of a COM object; in this case, you pass a pointer to the object's IUnknown interface pointer and you set the D3DSPD_IUNKNOWNPOINTER flag.

SetPrivateData allocates an internal buffer for the data and copies it. You can then safely free the source buffer or object. The internal buffer or interface reference is released when IDirect3DSurface8::FreePrivateData is called. This happens automatically when the surface is freed.

To retrieve private data for a surface, you must allocate a buffer of the correct size and then call the IDirect3DSurface8::GetPrivateData method, passing the GUID that was assigned to the data by SetPrivateData. You are responsible for freeing any dynamic memory you use for this buffer. If the data is a COM object, this method retrieves the IUnknown pointer.

If you don't know how big a buffer to allocate, first call GetPrivateData with zero in SizeOfData. If the method fails with D3DERR_MOREDATA, it returns the necessary number of bytes for the buffer in SizeOfData.


Lights

Lights are used to illuminate objects in a scene. This section describes lights and how they are used in Microsoft® Direct3D® applications. The following topics are discussed.

  • Introduction to Lighting and Materials
  • Direct3D Light Model vs. Nature
  • Color Values for Lights and Materials
  • Direct Light vs. Ambient Light
  • Light Objects
  • Light Properties
  • Using Lights


Introduction to Lighting and Materials

When lighting is enabled, as Microsoft® Direct3D® rasterizes a scene in the final stage of rendering, it determines the color of each rendered pixel based on a combination of the current material color and the texels in an associated texture map; the diffuse and specular colors at the vertex, if specified; and the color and intensity of light produced by light sources in the scene or the scene's ambient light level. When you use Direct3D lighting and materials, you allow Direct3D to handle the details of illumination for you. Advanced users can perform lighting on their own, if desired.

How you work with lighting and materials makes a big difference in the appearance of the rendered scene. Materials define how light reflects off a surface. Direct light and ambient light levels define the light that is reflected. You must use materials to render a scene if lighting is enabled. Lights are not required to render a scene, but details in a scene rendered without light are not visible. At best, rendering an unlit scene results in a silhouette of the objects in the scene. This is not enough detail for most purposes.


Direct3D Light Model vs. Nature

In nature, when light is emitted from a source, it is reflect off of hundreds, if not thousands or millions, of objects before reaching the user's eye. Each time it is reflected, some light is absorbed by a surface, some is scattered in random directions, and the rest goes on to another surface or to the user's eye. This process continues until the light is reduced to nothing or a user perceives the light.

Obviously, the calculations required to perfectly simulate the natural behavior of light are too time-consuming to use for real-time 3-D graphics. Therefore, with speed in mind, the Microsoft® Direct3D® light model approximates the way light works in the natural world. Direct3D describes light in terms of red, green, and blue components that combine to create a final color. For more information, see Color Values for Lights and Materials.

In Direct3D, when light reflects off a surface, the light color interacts mathematically with the surface itself to create the color eventually displayed on the screen. For specific information about the algorithms Direct3D uses, see Mathematics of Direct3D Lighting.

The Direct3D light model generalizes light into two types: ambient light and direct light. Each has different attributes, and each interacts with the material of a surface in different ways. Ambient light is light that has been scattered so much that its direction and source are indeterminate: it maintains a low-level of intensity everywhere. The indirect lighting used by photographers is a good example of ambient light. Ambient light in Direct3D, as in nature, has no real direction or source, only a color and intensity. In fact, the ambient light level is completely independent of any objects in a scene that generate light. Ambient light does not contribute to specular reflection.

Direct light is the light generated by a source within a scene; it always has color and intensity, and it travels in a specified direction. Direct light interacts with the material of a surface to create specular highlights, and its direction is used as a factor in shading algorithms, including Gouraud shading. When direct light is reflected, it does not contribute to the ambient light level in a scene. The sources in a scene that generate direct light have different characteristics that affect how they illuminate a scene. For more information, see Lights.

Additionally, a polygon's material has properties that affect how that polygon reflects the light it receives. You set a single reflectance trait that describes how the material reflects ambient light, and you set individual traits to determine the material's specular and diffuse reflectance. For more information, see Materials.


Color Values for Lights and Materials

Microsoft® Direct3D® describes color in terms of four components—red, green, blue, and alpha—that combine to make a final color. The D3DCOLORVALUE C++ structure is defined to contain values for each component. Each member is a floating-point value that typically ranges from 0.0 to 1.0, inclusive. Although both lights and materials use the same structure to describe color, the values in the structure are used a little differently by each.

Color values for light sources represent the amount of a particular light component it emits. Because lights don't use an alpha component, only the red, green, and blue components of the color are relevant. You can visualize the three components as the red, green, and blue lenses on a projection television. Each lens might be off (a 0.0 value in the appropriate member), it might be as bright as possible (a 1.0 value), or it might be some level in between. The colors coming through the lenses combine to make the light's final color. A combination like R: 1.0, G: 1.0, B: 1.0 creates a white light, where R: 0.0, G: 0.0, B: 0.0 doesn't emit light at all. You can make a light that emits only one component, resulting in a pure red, green, or blue light, or, the light could use combinations to emit colors like yellow or purple. You can even set negative color component values to create a "dark light" that actually removes light from a scene. Or, you might set the components to some value larger than 1.0 to create an extremely bright light.

With materials, on the other hand, color values represent how much of a light component is reflected by a surface that is rendered with that material. A material whose color components are R: 1.0, G: 1.0, B: 1.0, A: 1.0 reflects all the light that comes its way. Likewise, a material with R: 0.0, G: 1.0, B: 0.0, A: 1.0 reflects all the green light that is directed at it. Materials have multiple reflectance values to create various types of effects; for more information, see Material Properties.

Color values for ambient light are different from those used for direct light sources and materials. For more information, see Direct Light vs. Ambient Light.


Direct Light vs. Ambient Light

Although both direct and ambient light illuminate objects in a scene, they are independent of one another, they have very different effects, and they require that you work with them in completely different ways.

Direct light is just that: direct. Direct light always has direction and color, and it is a factor for shading algorithms, such as Gouraud shading. Different types of lights emit direct light in different ways, creating special attenuation effects. You create a set of light parameters for direct light by calling the IDirect3DDevice8::SetLight method. For more information, see Lights.

Ambient light is effectively everywhere in a scene. You can think of it as a general level of light that fills an entire scene, regardless of the objects and their locations in that scene. Ambient light, being everywhere, has no position or direction, only color and intensity. Set the ambient light level with a call to the IDirect3DDevice8::SetRenderState method, specifying D3DRS_AMBIENT as the State parameter, and the desired RGBA color as the Value parameter.

Ambient light color takes the form of an RGBA value, where each component is an integer value from 0 to 255. This is unlike most color values in Microsoft® Direct3D®. For more information, see Color Values for Lights and Materials.

You can use the D3DCOLOR_RGBA macro to generate RGBA values. The red, green, and blue components combine to make the final color of the ambient light. The alpha component controls the transparency of the color. When using hardware acceleration or RGB emulation, the alpha component is ignored.


Light Objects

Microsoft® Direct3D® employs three types of lights: point lights, spotlights, and directional lights. You choose the type of light you want when you create a set of light properties. The illumination properties and the resulting computational overhead varies with each type of light source. The following types of light sources, supported by the Direct3D lighting module, are discussed.

  • Point Lights
  • Spotlights
  • Directional Lights

Do not confuse light sources in a scene with the concept of an ambient light level. For more information, see Direct Light vs. Ambient Light, Light Properties and Using Lights.


Point Lights

Point lights have color and position within a scene, but no single direction. They give off light equally in all directions, as shown in the following illustration.

A light bulb is a good example of a point light. Point lights are affected by attenuation and range, and illuminate a mesh on a vertex-by-vertex basis. During lighting, Microsoft® Direct3D® uses the point light's position in world space and the coordinates of the vertex being lit to derive a vector for the direction of the light, and the distance that the light has traveled. Both are used, along with the vertex normal, to calculate the contribution of the light to the illumination of the surface.


Spotlights

Spotlights have color, position, and direction in which they emit light. Light emitted from a spotlight is made up of a bright inner cone and a larger outer cone, with the light intensity diminishing between the two, as shown in the following illustration.

Spotlights are affected by falloff, attenuation, and range. These factors, as well as the distance light travels to each vertex, are figured in when computing lighting effects for objects in a scene. Computing these effects for each vertex makes spotlights the most computationally expensive of all lights in Microsoft Direct3D®.


Directional Lights

Directional lights have only color and direction, not position. They emit parallel light. This means that all light generated by directional lights travels through a scene in the same direction. Imagine a directional light as a light source at near infinite distance, such as the sun. Directional lights are not affected by attenuation or range, so the direction and color you specify are the only factors considered when Microsoft® Direct3D® calculates vertex colors. Because of the small number of illumination factors, these are the least computationally intensive lights to use.


Light Properties

Light properties describe a light source's type and color. Depending on the type of light being used, a light can have properties for attenuation and range, or for spotlight effects. But, not all types of lights use all properties. Microsoft® Direct3D® uses the D3DLIGHT8 structure to carry information about light properties for all types of light sources. This section contains information for all light properties. Information is divided into the following groups.

  • Light Type
  • Light Color
  • Color Vertices
  • Light Position, Range, and Attenuation
  • Light Direction
  • Spotlight Properties

Light properties affect how a light source illuminates objects in a scene.

For more information, see Using Lights, Setting Light Properties, and Mathematics of Direct3D Lighting.


Light Type

The light type property defines which type of light source you're using. The light type is set by using a value from the D3DLIGHTTYPE C++ enumeration in the Type member of the light's D3DLIGHT8 structure. There are three types of lights in Microsoft® Direct3D®—point lights, spotlights, and directional lights. Each type illuminates objects in a scene differently, with varying levels of computational overhead. For general information about how each type of light works, see Light Objects.


Light Color

Lights in Microsoft® Direct3D® emit three colors that are used independently in the system's lighting computations: a diffuse color, an ambient color, and a specular color. Each is incorporated by the Direct3D lighting module, interacting with a counterpart from the current material, to produce a final color used in rendering. The diffuse color interacts with the diffuse reflectance property of the current material, the specular color with the material's specular reflectance property, and so on. For specifics about how Direct3D applies these colors, see Mathematics of Direct3D Lighting.

In a C++ application, the D3DLIGHT8 structure includes three members for these colors—Diffuse, Ambient, and Specular—each one is a D3DCOLORVALUE structure that defines the color being emitted.

The type of color that applies most heavily to the system's computations is the diffuse color. The most common diffuse color is white (R:1.0 G:1.0 B:1.0), but you can create colors as needed to achieve desired effects. For example, you could use red light for a fireplace, or you could use green light for a traffic signal set to "Go."

Generally, you set the light color components to values between 0.0 and 1.0, inclusive, but this isn't a requirement. For example, you might set all the components to 2.0, creating a light that is "brighter than white." This type of setting can be especially useful when you use attenuation settings other than constant.

Note that although Direct3D uses RGBA values for lights, the alpha color component is not used. For more information, see Color Values for Lights and Materials.


Color Vertices

Usually material colors are used for lighting. However, you can specify that material colors—emissive, ambient, diffuse, and specular—are to be overridden by diffuse or specular vertex colors. This is done by calling IDirect3DDevice8::SetRenderState and setting the device state variables listed in the following table.

Device state variable | Meaning | Type | Default
D3DRS_AMBIENTMATERIALSOURCE | Defines where to get ambient material color. | D3DMATERIALCOLORSOURCE | D3DMCS_MATERIAL
D3DRS_DIFFUSEMATERIALSOURCE | Defines where to get diffuse material color. | D3DMATERIALCOLORSOURCE | D3DMCS_COLOR1
D3DRS_SPECULARMATERIALSOURCE | Defines where to get specular material color. | D3DMATERIALCOLORSOURCE | D3DMCS_COLOR2
D3DRS_EMISSIVEMATERIALSOURCE | Defines where to get emissive material color. | D3DMATERIALCOLORSOURCE | D3DMCS_MATERIAL
D3DRS_COLORVERTEX | Disables or enables use of vertex colors. | BOOL | TRUE

The alpha/transparency value always comes only from the diffuse color's alpha channel.

The fog value always comes only from the specular color's alpha channel.

D3DMATERIALCOLORSOURCE can have the following values.

  • D3DMCS_MATERIAL - Material color is used as source.
  • D3DMCS_COLOR1 - Diffuse vertex color is used as source.
  • D3DMCS_COLOR2 - Specular vertex color is used as source.


Light Position, Range and Attenuation

Microsoft DirectX 8.0 (C++)

Light Position, Range, and Attenuation

The position, range, and attenuation properties define a light's location in world space, and how the light it emits behaves over distance. As with all light properties you use in C++, these are contained in a light's D3DLIGHT8 structure.

Position

Light position is described using a D3DVECTOR structure in the Position member of the D3DLIGHT8 structure. The x-, y-, and z-coordinates are assumed to be in world space. Directional lights are the only type of light that don't use the position property.

Range

A light's range property determines the distance, in world space, at which meshes in a scene no longer receive light emitted by that object. The Range member contains a floating-point value that represents the light's maximum range, in world space. Directional lights don't use the range property.

Attenuation

Attenuation controls how a light's intensity decreases toward the maximum distance specified by the range property. Three D3DLIGHT8 structure members represent light attenuation: Attenuation0, Attenuation1, and Attenuation2. These members contain floating-point values ranging from 0.0 through infinity, controlling a light's attenuation. Some applications set the Attenuation1 member to 1.0 and the others to 0.0, resulting in light intensity that changes as 1 / D, where D is the distance from the light source to the vertex. The maximum light intensity is at the source, decreasing to 1 / (Light Range) at the light's range. Typically, an application sets Attenuation0 to 0.0, Attenuation1 to a constant value, and Attenuation2 to 0.0.

You can combine attenuation values to get more complex attenuation effects. Or, you might set them to values outside the normal range to create even stranger attenuation effects; negative attenuation values make a light that gets brighter over distance.

For more information about the mathematical model that Microsoft® Direct3D® uses to calculate attenuation, see Light Attenuation Over Distance. Like the range property, directional lights don't use the attenuation property.


Light Direction

A light's direction property determines the direction that the light emitted by the object travels, in world space. Direction is used only by directional lights and spotlights, and is described with a vector.

C++ applications set the light direction in the Direction member of the light's D3DLIGHT8 structure. The Direction member is of type D3DVECTOR. Direction vectors are described as distances from a logical origin, regardless of the light's position in a scene. Therefore, a spotlight that points straight into a scene—along the positive z-axis—has a direction vector of <0,0,1> no matter where its position is defined to be. Similarly, you can simulate sunlight shining directly on a scene by using a directional light whose direction is <0,-1,0>. Obviously, you don't have to create lights that shine along the coordinate axes; you can mix and match values to create lights that shine at more interesting angles.

Note Although you don't need to normalize a light's direction vector, always be sure that it has magnitude. In other words, don't use a <0,0,0> direction vector.


Spotlight Properties

The D3DLIGHT8 C++ structure contains three members that are used only by spotlights. These members—Falloff, Theta, and Phi—control how large or small a spotlight object's inner and outer cones are, and how light decreases between them. For general information about these characteristics, see Spotlights.

The Theta value is the radian angle of the spotlight's inner cone, and the Phi value is the angle for the outer cone of light. The Falloff value controls how light intensity decreases between the outer edge of the inner cone and the inner edge of the outer cone. Most applications set Falloff to 1.0 to create falloff that occurs evenly between the two cones, but you can set other values as needed.

For more information about the mathematical model used by Microsoft® Direct3D® for calculating falloff, see Spotlight Falloff Model.

The following illustration shows the relationship between the values for these members and how they can affect a spotlight's inner and outer cones of light.


Using Lights

This section provides information about using lights in a Microsoft® Direct3D® application. Information is divided into the following topics.

  • Setting Light Properties
  • Enabling and Disabling Lights
  • Retrieving Light Properties


Setting Light Properties

You set lighting properties in a C++ application by preparing a D3DLIGHT8 structure and then calling the IDirect3DDevice8::SetLight method. The SetLight method accepts the index at which the device should place the set of light properties to its internal list of light properties, and the address of a prepared D3DLIGHT8 structure that defines those properties. You can call SetLight with new information as needed to update the light's illumination properties.

The system allocates memory to accommodate a set of lighting properties each time you call the SetLight method with an index that has never been assigned properties. Applications can set a number of lights, with only a subset of the assigned lights enabled at a time. Check the MaxActiveLights member of the D3DCAPS8 structure when you retrieve device capabilities to determine the maximum number of active lights supported by that device. If you no longer need a light, you can disable it or overwrite it with a new set of light properties.

The following C++ code example prepares and sets properties for a white point-light whose emitted light will not attenuate over distance.

/*
 * For the purposes of this example, the d3dDevice variable
 * is a valid pointer to an IDirect3DDevice8 interface.
 */
D3DLIGHT8 d3dLight;
HRESULT   hr;

// Initialize the structure.
ZeroMemory(&d3dLight, sizeof(D3DLIGHT8));

// Set up a white point light.
d3dLight.Type = D3DLIGHT_POINT;
d3dLight.Diffuse.r  = 1.0f;
d3dLight.Diffuse.g  = 1.0f;
d3dLight.Diffuse.b  = 1.0f;
d3dLight.Ambient.r  = 1.0f;
d3dLight.Ambient.g  = 1.0f;
d3dLight.Ambient.b  = 1.0f;
d3dLight.Specular.r = 1.0f;
d3dLight.Specular.g = 1.0f;
d3dLight.Specular.b = 1.0f;

// Position it high in the scene and behind the user.
// Remember, these coordinates are in world space, so
// the user could be anywhere in world space, too.
// For the purposes of this example, assume the user
// is at the origin of world space.
d3dLight.Position.x = 0.0f;
d3dLight.Position.y = 1000.0f;
d3dLight.Position.z = -100.0f;

// Don't attenuate.
d3dLight.Attenuation0 = 1.0f;
d3dLight.dvRange      = 1000.0f;

// Set the property information for the first light.
hr = d3dDevice->SetLight(0, &d3dLight);
if (FAILED(hr))
{
    // Code to handle the error goes here.
}

You can update a set of light properties with another call to SetLight at any time. Just specify the index of the set of light properties to update and the address of the D3DLIGHT8 structure that contains the new properties.

Note Assigning a set of light properties to the device does not enable the light source whose properties are being added. Enable a light source by calling the IDirect3DDevice8::LightEnable method for the device.


Enabling and Disabling Lights

Once you assign a set of light properties for a light source in a scene, the light source can be activated by calling the IDirect3DDevice8::LightEnable method for the device. New light sources are disabled by default. The LightEnable method accepts two parameters. Set the first parameter to the zero-based index of the light source to be affected by the method, and set the second parameter to TRUE to enable the light or FALSE to disable it.

The following code example illustrates the use of this method by enabling the first light source in the device's list of light source properties.

/*
 * For the purposes of this example, the d3dDevice variable
 * is a valid pointer to an IDirect3DDevice8 interface.
 */
HRESULT hr;

hr = pd3dDevice->LightEnable(0, TRUE);
if (FAILED(hr))
{
    // Code to handle the error goes here.
}

If you enable or disable a light that has no properties that are set with IDirect3DDevice8::SetLight, the LightEnable method creates a light source with the properties listed in following table and enables or disables it.

Member | Default
Type | D3DLIGHT_DIRECTIONAL
Diffuse | (R:1, G:1, B:1, A:0)
Specular | (R:0, G:0, B:0, A:0)
Ambient | (R:0, G:0, B:0, A:0)
Position | (0, 0, 0)
Direction | (0, 0, 1)
Range | 0
Falloff | 0
Attenuation0 | 0
Attenuation1 | 0
Attenuation2 | 0
Theta | 0
Phi | 0


Retrieving Light Properties

You can retrieve all the properties for an existing light source from C++ by calling the IDirect3DDevice8::GetLight method for the device. When calling the GetLight method, pass in the first parameter the zero-based index of the light source for which the properties will be retrieved, and supply the address of a D3DLIGHT8 structure in the second parameter. The device fills the D3DLIGHT8 structure to describe the lighting properties it uses for the light source at that index.

The following code example illustrates this process.

/*
 * For the purposes of this example, the pd3dDevice variable
 * is a valid pointer to an IDirect3DDevice8 interface.
 */
HRESULT hr;
D3DLIGHT8 light;

// Get the property information for the first light.
hr = pd3dDevice->GetLight(0, &light);
if (FAILED(hr))
{
    // Code to handle the error goes here.
}

If you supply an index outside the range of the light sources assigned in the device, the GetLight method fails, returning D3DERR_INVALIDCALL.


Materials

This section describes materials and how they are used in Microsoft® Direct3D® applications. The following topics are discussed.

  • What Are Materials?
  • Material Properties
  • Using Materials

Default Material Properties Note If your application does not specify material properties for rendering, the system uses a default material. The default material reflects all diffuse light—white, for example—with no ambient or specular reflection, and no emissive color.


What Are Materials?

Materials describe how polygons reflect light or appear to emit light in a 3-D scene. Essentially, a material is a set of properties that tell Microsoft® Direct3D® the following things about the polygons it is rendering.

  • How they reflect ambient and diffuse light
  • What their specular highlights look like
  • Whether the polygons appear to emit light

Direct3D applications written in C++ use the D3DMATERIAL8 structure to describe material properties. For more information, see Material Properties.


Material Properties

Material properties detail a material's diffuse reflection, ambient reflection, light emission, and specular highlight characteristics. Microsoft® Direct3D® uses the D3DMATERIAL8 structure to carry all material property information. Material properties affect the colors that Direct3D uses to rasterize polygons that use the material. With the exception of the specular property, each property is described as an RGBA color that represents how much of the red, green, and blue parts of a given type of light it reflects, and an alpha blending factor—the alpha component of the RGBA color. The material's specular property is described in two parts: color and power. For more information, see Color Values for Lights and Materials.

Diffuse and Ambient Reflection

The Diffuse and Ambient members of the D3DMATERIAL8 structure describe how a material reflects the ambient and diffuse light in a scene. Because most scenes contain much more diffuse light than ambient light, diffuse reflection plays the largest part in determining color. Additionally, because diffuse light is directional, the angle of incidence for diffuse light affects the overall intensity of the reflection. Diffuse reflection is greatest when the light strikes a vertex parallel to the vertex normal. As the angle increases, the effect of diffuse reflection diminishes. The amount of light reflected is the cosine of the angle between the incoming light and the vertex normal, as shown here.

Ambient reflection, like ambient light, is nondirectional. Ambient reflection has a lesser impact on the apparent color of a rendered object, but it does affect the overall color and is most noticeable when little or no diffuse light reflects off the material. A material's ambient reflection is affected by the ambient light set for a scene by calling the IDirect3DDevice8::SetRenderState method with the D3DRS_AMBIENT flag.

Diffuse and ambient reflection work together to determine the perceived color of an object, and are usually identical values. For example, to render a blue crystalline object, you create a material that reflects only the blue component of diffuse and ambient light. When placed in a room with a white light, the crystal appears to be blue. However, in a room that has only red light, the same crystal would appear to be black, because its material doesn't reflect red light.

Emission

Materials can be used to make a rendered object appear to be self-luminous. The Emissive member of the D3DMATERIAL8 structure is used to describe the color and transparency of the emitted light. Emission affects an object's color and can, for example, make a dark material brighter and take on part of the emitted color.

You can use a material's emissive property to add the illusion that an object is emitting light, without incurring the computational overhead of adding a light to the scene. In the case of the blue crystal, the emissive property is useful if you want to make the crystal appear to light up, but not cast light on other objects in the scene. Remember, materials with emissive properties don't emit light that can be reflected by other objects in a scene. To achieve this reflected light, you need to place an additional light within the scene.

Specular Reflection

Specular reflection creates highlights on objects, making them appear shiny. The D3DMATERIAL8 structure contains two members that describe the specular highlight color as well as the material's overall shininess. You establish the color of the specular highlights by setting the Specular member to the desired RGBA color—the most common colors are white or light gray. The values you set in the Power member control how sharp the specular effects are.

Specular highlights can create dramatic effects. Drawing again on the blue crystal analogy: a larger Power value creates sharper specular highlights, making the crystal appear to be quite shiny. Smaller values increase the area of the effect, creating a dull reflection that make the crystal look frosty. To make an object truly matte, set the Power member to zero and the color in Specular to black. Experiment with different levels of reflection to produce a realistic appearance for your needs. The following illustration shows two identical models. The one on the left uses a specular reflection power of 10; the model on the right has no specular reflection.


Using Materials

This section contains information about using materials in a Microsoft® Direct3D® application. Information is divided into the following topics.

  • Setting Material Properties
  • Retrieving Material Properties


Setting Material Properties

Microsoft® Direct3D® rendering devices can render with one set of material properties at a time.

In a C++ application, you set the material properties that the system uses by preparing a D3DMATERIAL8 structure, and then calling the IDirect3DDevice8::SetMaterial method.

To prepare the D3DMATERIAL8 structure for use, set the property information in the structure to create the desired effect during rendering. The following code example sets up the D3DMATERIAL8 structure for a purple material with sharp white specular highlights.

D3DMATERIAL8 mat;

// Set the RGBA for diffuse reflection.
mat.Diffuse.r = 0.5f;
mat.Diffuse.g = 0.0f;
mat.Diffuse.b = 0.5f;
mat.Diffuse.a = 1.0f;

// Set the RGBA for ambient reflection.
mat.Ambient.r = 0.5f;
mat.Ambient.g = 0.0f;
mat.Ambient.b = 0.5f;
mat.Ambient.a = 1.0f;

// Set the color and sharpness of specular highlights.
mat.Specular.r = 1.0f;
mat.Specular.g = 1.0f;
mat.Specular.b = 1.0f;
mat.Specular.a = 1.0f;
mat.Power = 50.0f;

After preparing the D3DMATERIAL8 structure, you apply the properties by calling the IDirect3DDevice8::SetMaterial method of the rendering device. This method accepts the address of a prepared D3DMATERIAL8 structure as its only parameter. You can call SetMaterial with new information as needed to update the material properties for the device. The following code example shows how this might look in code.

// This code example uses the material properties defined for
// the mat variable earlier in this topic. The pd3dDev is assumed
// to be a valid pointer to an IDirect3DDevice8 interface.
HRESULT hr;
hr = pd3dDev->SetMaterial(&mat);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}

When you create a Direct3D device, the current material is automatically set to the default shown in the following table.

Member | Value
Diffuse | (R:1, G:1, B:1, A:0)
Specular | (R:0, G:0, B:0, A:0)
Ambient | (R:0, G:0, B:0, A:0)
Emissive | (R:0, G:0, B:0, A:0)
Power | (0.0)


Retrieving Material Properties

You retrieve the material properties that the rendering device is currently using by calling the IDirect3DDevice8::GetMaterial method for the device. Unlike the IDirect3DDevice8::SetMaterial method, GetMaterial doesn't require preparation. The GetMaterial method accepts the address of a D3DMATERIAL8 structure, and fills the provided structure with information describing the current material properties before returning.

// For this example, the pd3dDev variable is assumed to
// be a valid pointer to an IDirect3DDevice8 interface.
HRESULT hr;
D3DMATERIAL8 mat;

hr = pd3dDev->GetMaterial(&mat);
if(FAILED(hr))
{
    // Code to handle the error goes here.
}


Vertex Formats

This section describes the concepts you need to understand to specify vertices in Microsoft® Direct3D®, and provides information about the various formats your application can use to declare vertices. The following topics are discussed.

  • About Vertex Formats
  • Untransformed and Unlit Vertices
  • Untransformed and Lit Vertices
  • Transformed and Lit Vertices
  • Transformed and Lit Vertex Functionality
  • Flexible Vertex Formats and Vertex Shaders


About Vertex Formats

A flexible vertex format (FVF) code describes the contents of vertices stored interleaved in a single data stream. It generally specifies data to be processed by the fixed function vertex processing pipeline.

Microsoft® Direct3D® applications can define model vertices in several different ways. Support for flexible vertex definitions, also known as flexible vertex formats or flexible vertex format codes, makes it possible for your application to use only the vertex components it needs, eliminating those components that aren't used. By using only the needed vertex components, your application can conserve memory and minimize the processing bandwidth required to render models. You describe how your vertices are formatted by using a combination of Flexible Vertex Format Flags.

The FVF specification includes formats for point size, specified by D3DFVF_PSIZE. This size is expressed in camera space units for non-TL vertices, and in device-space units for TL vertices.

The rendering methods of the IDirect3DDevice8 interface provides C++ applications with methods that accept a combination of these flags, and uses them to determine how to render primitives. Basically, these flags tell the system which vertex components—position, vertex blending weights, normal, colors, the number and format of texture coordinates—your application uses and, indirectly, which parts of the rendering pipeline you want Direct3D to apply to them. In addition, the presence or absence of a particular vertex format flag communicates to the system which vertex component fields are present in memory and which you've omitted.

To determine device limitations, you can query a device for the D3DFVFCAPS_DONOTSTRIPELEMENTS and D3DFVFCAPS_TEXCOORDCOUNTMASK flexible vertex format flags. For more information, see the FVFCaps member of the D3DCAPS8 structure.

One significant requirement that the system places on how you format your vertices is on the order in which the data appears. The following illustration depicts the required order for all possible vertex components in memory, and their associated data types.

Note Texture coordinates can be declared in different formats, allowing textures to be addressed using as few as one coordinate or as many as four texture coordinates (for 2-D projected texture coordinates). For more information, see Texture Coordinate Formats. Use the D3DFVF_TEXCOORDSIZEn set of macros to create bit patterns that identify the texture coordinate formats that your vertex format uses.

No application will use every component—the reciprocal homogeneous W (RHW) and vertex normal fields are mutually exclusive. Nor will most applications try to use all eight sets of texture coordinates, but Direct3D has this capacity. There are several restrictions on which flags you can use with other flags. For example, you cannot use the D3DFVF_XYZ and D3DFVF_XYZRHW flags together, as this would indicate that your application is describing a vertex's position with both untransformed and transformed vertices.

To use indexed vertex blending, the D3DFVF_LASTBETA_UBYTE4 flag should appear at the end of the FVF. The presence of this flag indicates that the fifth blending weight will be treated as a DWORD instead of float. For more information, see Indexed Vertex Blending.

The following code samples shows the difference between an FVF code that uses the D3DFVF_LASTBETA_UBYTE4 flag and one that doesn't. The FVF defined below does not use the D3DFVF_LASTBETA_UBYTE4 flag. The flag D3DFVF_XYZ3 is present when four blending indices are used because you always use (1 - the sum of the first three) for the fourth.

#define D3DFVF_BLENDVERTEX (D3DFVF_XYZB3|D3DFVF_NORMAL|D3DFVF_TEX1)

struct BLENDVERTEX
{
    D3DXVECTOR3 v;       // Referenced as v0 in the vertex shader
    FLOAT       blend1;  // Referenced as v1.x in the vertex shader
    FLOAT       blend2;  // Referenced as v1.y in the vertex shader
    FLOAT       blend3;  // Referenced as v1.z in the vertex shader
                         // v1.w = 1.0 - (v1.x + v1.y + v1.z)
    D3DXVECTOR3 n;       // Referenced as v3 in the vertex shader
    FLOAT       tu, tv;  // Referenced as v7 in the vertex shader
};

The FVF defined below uses the D3DFVF_LAST_UBYTE4 flag.

#define D3DFVF_BLENDVERTEX (D3DFVF_XYZB4 | D3DFVF_LASTBETA_UBYTE4 |D3DFVF_NORMAL|D3DFVF_TEX1)

struct BLENDVERTEX
{
    D3DXVECTOR3 v;       // Referenced as v0 in the vertex shader
    FLOAT       blend1;  // Referenced as v1.x in the vertex shader
    FLOAT       blend2;  // Referenced as v1.y in the vertex shader
    FLOAT       blend3;  // Referenced as v1.z in the vertex shader
                         // v1.w = 1.0 - (v1.x + v1.y + v1.z)
    DWORD       indices; // Referenced as v2.xyzw in the vertex shader
    D3DXVECTOR3 n;       // Referenced as v3 in the vertex shader
    FLOAT       tu, tv;  // Referenced as v7 in the vertex shader
};

For more information, see Flexible Vertex Format Flags.


Untransformed and Unlit Vertices

The presence of the D3DFVF_XYZ, or any D3DFVF_XYZBn flag, and D3DFVF_NORMAL flags in the vertex description that you pass to rendering methods identifies the untransformed and unlit vertex type. By using untransformed and unlit vertices, your application effectively requests that Microsoft® Direct3D® perform all transformation and lighting operations using its internal algorithms. You can disable the Direct3D lighting engine for the primitives being rendered by setting the D3DRS_LIGHTING render state to FALSE.

Many applications use this vertex type, as it frees them from implementing their own transformation and lighting engines. However, because the system is making calculations for you, it requires that you provide a certain amount of information with each vertex.

  • You are required to specify vertices in untransformed model coordinates. The system then applies world, view, and projection transformations to the model coordinates to position them in your scene and determine their final locations on the screen.
  • You can include a vertex normal for more realistic lighting effects. Vertices lit by the system that don't include a vertex normal will use a dot product of 0 in all lighting calculations. These vertices are assumed to receive no incident light. The system uses the vertex normal, along with the current material, in its lighting calculations. For details, see Face and Vertex Normal Vectors, Lights, Materials, and Mathematics of Direct3D Lighting.

Other than these requirements, you have the flexibility to use or disregard the other vertex components. For example, you can include a diffuse or specular color with your untransformed vertices. This was not possible before Microsoft DirectX® 6.0. Including individual colors for each vertex makes it possible to achieve shading effects that are more subtle and flexible than lighting calculations that use only the material color. Keep in mind that you must enable per-vertex color through the D3DRS_COLORVERTEX render state. Untransformed, unlit vertices can also include up to eight sets of texture coordinates.

When you define your own vertex format, remember which vertex components your application needs, and make sure they appear in the required order by declaring a properly ordered structure. The following code example declares a valid vertex format structure that includes a position, a vertex normal, a diffuse color, and two sets of texture coordinates.

//
// The vertex format description for this vertex would be:
// (D3DFVF_XYZ | D3DFVF_NORMAL |  D3DFVF_DIFFUSE | D3DFVF_TEX2)
//
typedef struct _UNLITVERTEX
{
    float x, y, z;     // position
    float nx, ny, nz;  // normal
    DWORD Diffuse;     // diffuse color
    float tu1, tv1;    // texture coordinates
    float tu2, tv2;
  tv2;
} UNLITVERTEX, *LPUNLITVERTEX;

The vertex description for the preceding structure is a combination of the D3DFVF_XYZ, D3DFVF_NORMAL, D3DFVF_DIFFUSE, and D3DFVF_TEX2 flexible vertex format flags.

For more information, see About Vertex Formats.


Untransformed and Lit Vertices

If you include the D3DFVF_XYZ flag, but not the D3DFVF_NORMAL flag, in the vertex format description you use with the Microsoft® Direct3D® rendering methods, you are identifying your vertices as untransformed but already lit. For information about other dependencies and exclusions, see the description for the Flexible Vertex Format Flags.

By using untransformed and lit vertices, your application requests that Direct3D not perform any lighting calculations on your vertices, but it should still transform them using the previously set world, view, and projection matrices. Because the system isn't doing lighting calculations, it doesn't need a vertex normal. The system uses the diffuse and specular components at each vertex for shading. These colors might be arbitrary, or they might be computed using your own lighting formulas. If you don't include a diffuse or specular component, the system uses the default colors. The default value for the diffuse color is 0xFFFFFFFF, and the default value for the specular color is 0x0.

Like the other vertex types, except for including a position and some amount of color information, you are free to include or disregard the texture coordinate sets in the unlit vertex format.

When you define your own vertex format, remember which vertex components your application needs, and make sure they appear in the required order by declaring a properly ordered structure. The following code example declares a valid untransformed and lit vertex, with diffuse and specular vertex colors, and three sets of texture coordinates.

//
// The vertex format description for this vertex would be:
// (D3DFVF_XYZ | D3DFVF_DIFFUSE |  D3DFVF_SPECULAR | D3DFVF_TEX3)
//
typedef struct _LITVERTEX {
    float x, y, z;   // position
    DWORD Diffuse;   // diffuse color
    DWORD Specular;  // specular color
    float tu1, tv1;  // texture coordinates
    float tu2, tv2;
    float tu3, tv3;
} LITVERTEX, *LPLITVERTEX;

The vertex description for the preceding structure is a combination of the D3DFVF_XYZ, D3DFVF_DIFFUSE, D3DFVF_SPECULAR, and D3DFVF_TEX3 flexible vertex format flags.

For more information, see About Vertex Formats.


Transformed and Lit Vertices

If you include the D3DFVF_XYZRHW flag in your vertex format description, you are telling the system that your application is using transformed and lit vertices. This means that Microsoft® Direct3D® doesn't transform your vertices with the world, view, or projection matrices, nor does it perform any lighting calculations. It assumes that your application has taken care of these steps. This fact makes transformed and lit vertices common when porting existing 3-D applications to Direct3D. In short, Direct3D does not modify transformed and lit vertices at all. It passes them directly to the driver to be rasterized.

The vertex format flags associated with untransformed vertices and lighting (D3DFVF_XYZ and D3DFVF_NORMAL) are not allowed if D3DFVF_XYZRHW is present. For more about flag dependencies and exclusions, see the description for each of the Flexible Vertex Format Flags.

The system requires that the vertex position you specify be already transformed. The x and y values must be in screen coordinates, and z must be the depth value of the pixel to be used in the z-buffer. Z values can range from 0.0 to 1.0, where 0.0 is the closest possible position to the user, and 1.0 is the farthest position still visible within the viewing area. Immediately following the position, transformed and lit vertices must include a reciprocal of homogeneous W (RHW) value. RHW is the reciprocal of the W coordinate from the homogeneous point (x,y,z,w) at which the vertex exists in projection space. This value often works out to be the distance from the eyepoint to the vertex, taken along the z-axis.

Other than the position and RHW requirements, this vertex format is similar to an untransformed and lit vertex. To recap:

  • The system doesn't do any lighting calculations with this format, so it doesn't need a vertex normal.
  • You can specify a diffuse or specular color. If you don't, the system uses 0x0 for specular color and 0xFFFFFFFF for diffuse color.
  • You can use up to eight sets of texture coordinates, or none at all.

When you define your own vertex format, remember which vertex components your application needs, and make sure they appear in the required order by declaring a properly ordered structure. The following code example declares a valid transformed and lit vertex, with diffuse and specular vertex colors, and one set of texture coordinates.

//
// The vertex format description for this vertex would be
// (D3DFVF_XYZRHW | D3DFVF_DIFFUSE |  D3DFVF_SPECULAR | D3DFVF_TEX1)
//
typedef struct _TRANSLITVERTEX {
    float x, y;      // screen position
    float z;         // Z-buffer depth
    float rhw;       // reciprocal homogeneous W
    DWORD Diffuse;   // diffuse color
    DWORD Specular;  // specular color
    float tu1, tv1;  // texture coordinates
} TRANSLITVERTEX, *LPTRANSLITVERTEX;

The vertex description for the preceding structure would be a combination of the D3DFVF_XYZRHW, D3DFVF_DIFFUSE, D3DFVF_SPECULAR, and D3DFVF_TEX1 flexible vertex format flags.

For more information, see About Vertex Formats.


Transformed and Lit Vertex Functionality

Vertex data specified with a flexible vertex format (FVF) code has the property of being either transformed or nontransformed. The terminology used for FVF-specified transformed vertices is TL (transformed and lit) vertices. Microsoft® Direct3D® for Microsoft DirectX® 8.0 continues to support TL vertex data, as in previous releases. However, TL vertices are subject to some conditions that are not applicable to nontransformed vertices.

TL vertex data is possible only for vertices specified by an FVF code, and it is not valid as input for a programmable vertex shader. Programmable vertex shaders have the flexibility to take various forms of transformed vertex data, but this is different from FVF-TL vertex data because the interpretation is part of the shader, not a property of the vertex data. Because it is defined by an FVF code, TL vertex data is also inherently single stream.

TL vertex data is not guaranteed to be clipped by Direct3D, thus it is required that TL vertex primitives be clipped prior to sending them to Direct3D for rendering. The x and y values are required to be clipped to the viewport, or, if available, the device guardband. The z values for TL vertices are required to be between 0. and 1, inclusive. It is also required that the RHW values be within the range [0 < 1/D3DCAPS8.MaxVertexW]. The RHW requirement is to guarantee that the w values are within the supported range of the hardware rasterization device. Note that the w, and RHW, range of vertices resulting from a perspective projection transformation can be modified by applying a scale to all values in the projection matrix.

Note If D3DPMISCCAPS_CLIPTLVERTS is set, then the device clips post-transformed vertex data to the z and (x, y) viewport limits. Clipping to user-defined clip planes is not supported for post-transformed vertex data. If the D3DPMISCCAPS_CLIPTLVERTS capability is not set, then the application is required to clip these primitives to the z limit and at least to the guardband extent in x and y. On the other hand, clipping for pre-transformed vertices is fully supported in both drawing and vertex processing calls to a destination vertex buffer followed by another drawing call. This includes user-defined clip planes as well as the z and (x, y) viewport limits.

TL vertex data is always passed directly to the driver for rendering. When using vertex buffers with TL vertex data, there can be significant performance advantages to having the driver allocate these vertex buffers in AGP or video memory. Note that the allocation of a TL vertex buffer may be driver-allocated even when non-TL vertex data —either FVF or non-FVF—is not allowed to be driver-allocated, as would be the case when running on a hardware device that does not support transformation and lighting.

For more information, see Transformed and Lit Vertices.


Flexible Vertex Formats and Vertex Shaders

Microsoft® Direct3D® for Microsoft DirectX® 8.0 has a simplified programming model for using the fixed function vertex processing pipeline with a single input stream, providing functionality very similar to that of previous DirectX releases. In this case, the vertex shader consists of a flexible vertex format (FVF) code that is passed in place of a vertex shader handle when setting the current vertex shader. The handle space for vertex shaders is managed by the run-time library so that handles that are valid FVF codes are reserved for this usage.

Setting an FVF code as the current vertex shader causes the vertex processing to load from stream zero only, and to interpret the vertex elements as defined in the FVF code.

The following code example illustrates how to use an FVF code as a vertex shader in your C++ application.

First, define a structure for your custom vertex type and initialize the vertices. In this case, three vertices are initialized for rendering a triangle.

// This code example assumes that d3dDevice is a
// valid pointer to an IDirect3DDevice8 interface.

struct CUSTOMVERTEX
{
    FLOAT x, y, z, rhw; // The transformed position for the vertex
    DWORD color;        // The vertex color
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE)

CUSTOMVERTEX g_Vertices[] =
{
    { 150.0f,  50.0f, 0.5f, 1.0f, 0xffff0000, }, // x, y, z, rhw, color
    { 250.0f, 250.0f, 0.5f, 1.0f, 0xff00ff00, },
    {  50.0f, 250.0f, 0.5f, 1.0f, 0xff00ffff, },
};

Then, render the primitive using stream zero.

d3dDevice->SetStreamSource( 0, g_pVB, sizeof(CUSTOMVERTEX) );
d3dDevice->SetVertexShader( D3DFVF_CUSTOMVERTEX );
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 );

For more information, see Vertex Shaders.


Textures

Textures are a powerful tool in creating realism in computer-generated 3-D images. Microsoft® Direct3D® supports an extensive texturing feature set, providing developers with easy access to advanced texturing techniques. This section discusses the purposes and uses of textures in Direct3D. The information is presented in the following topics.

  • Basic Texturing Concepts
  • Texture Coordinates
  • Texture Resources
  • Texture Filtering
  • Texture Wrapping
  • Texture Blending
  • Compressed Texture Resources
  • Volume Texture Resources
  • Automatic Texture Management
  • Hardware Considerations for Texturing


Basic Texturing Concepts

This section presents the most fundamental concepts required for an understanding of texturing in Microsoft® Direct3D®. The information in this section is presented in the following topics.

  • What Is a Texture?
  • Texture Addressing Modes
  • Texture Dirty Regions
  • Texture Palettes


What Is a Texture?

Early computer-generated 3-D images, although generally advanced for their time, tended to have a shiny plastic look. They lacked the types of markings—such as scuffs, cracks, fingerprints, and smudges—that give 3-D objects realistic visual complexity. In recent years, textures have gained popularity among developers as a tool for enhancing the realism of computer-generated 3-D images.

In its everyday use, the word texture refers to an object's smoothness or roughness. In computer graphics, however, a texture is a bitmap of pixel colors that give an object the appearance of texture.

Because Microsoft® Direct3D® textures are bitmaps, any bitmap can be applied to a Direct3D primitive. For instance, applications can create and manipulate objects that appear to have a wood grain pattern in them. Grass, dirt, and rocks can be applied to a set of 3-D primitives that form a hill. The result is a realistic-looking hillside. You can also use texturing to create effects such as signs along a roadside, rock strata in a cliff, or the appearance of marble on a floor.

In addition, Direct3D supports more advanced texturing techniques such as texture blending—with or without transparency—and light mapping. For more information, see Texture Blending and Light Mapping with Textures.

If your application creates a hardware abstraction layer (HAL) device or a software device (see Device Types), it can use 8-, 16-, 24-, or 32-bit textures.


Texture Addressing Modes

This section describes the purpose and use of Microsoft® Direct3D® texture addressing modes. It is organized into the following topics.

  • What Are Texture Addressing Modes?
  • Wrap Texture Address Mode
  • Mirror Texture Address Mode
  • Clamp Texture Address Mode
  • Border Color Texture Address Mode
  • Setting and Retrieving Texture Addressing Modes
  • Texture Addressing Modes and Texture Wrapping
  • Device Limitations for Texture Addressing


What Are Texture Addressing Modes?

Your Microsoft® Direct3D® application can assign texture coordinates to any vertex of any primitive. For details, see Texture Coordinates. Typically, the u- and v-texture coordinates that you assign to a vertex are in the range of 0.0 to 1.0 inclusive. However, by assigning texture coordinates outside that range, you can create certain special texturing effects.

You control what Direct3D does with texture coordinates that are outside the [0.0, 1.0] range by setting the texture addressing mode. For instance, you can have your application set the texture addressing mode so that a texture is tiled across a primitive. The following topics contain additional details.

  • Wrap Texture Address Mode
  • Mirror Texture Address Mode
  • Clamp Texture Address Mode
  • Border Color Texture Address Mode


Wrap Texture Address Mode

The wrap texture address mode, identified by the D3DTADDRESS_WRAP member of the D3DTEXTUREADDRESS enumerated type, makes Microsoft® Direct3D® repeat the texture on every integer junction. Suppose, for example, your application creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_WRAP results in the texture being applied three times in both the u-and v-directions.

This is illustrated in the following figure.

The effects of this texture address mode are similar to, but distinct from, those of the mirror mode. For more information, see Mirror Texture Address Mode.


Mirror Texture Address Mode

The mirror texture address mode, identified by the D3DTADDRESS_MIRROR member of the D3DTEXTUREADDRESS enumerated type, causes Microsoft® Direct3D® to mirror the texture at every integer boundary. Suppose, for example, your application creates a square primitive and specifies texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0). Setting the texture addressing mode to D3DTADDRESS_MIRROR results in the texture being applied three times in both the u- and v-directions. Every other row and column that it is applied to is a mirror image of the preceding row or column.

This is illustrated in the following figure.

The effects of this texture address mode are similar to, but distinct from, those of the wrap mode. For more information, see Wrap Texture Address Mode.


Clamp Texture Address Mode

The clamp texture address mode, identified by the D3DTADDRESS_CLAMP member of the D3DTEXTUREADDRESS enumerated type, causes Microsoft® Direct3D® to clamp your texture coordinates to the [0.0, 1.0] range. That is, it applies the texture once, then smears the color of edge pixels. For example, suppose that your application creates a square primitive and assigns texture coordinates of (0.0,0.0), (0.0,3.0), (3.0,3.0), and (3.0,0.0) to the primitive's vertices. Setting the texture addressing mode to D3DTADDRESS_CLAMP results in the texture being applied once. The pixel colors at the top of the columns and the end of the rows are extended to the top and right of the primitive respectively.

This is illustrated in the following figure.


Border Color Texture Address Mode

The border color texture address mode, identified by the D3DTADDRESS_BORDER member of the D3DTEXTUREADDRESS enumerated type, causes Microsoft® Direct3D® to use an arbitrary color, known as the border color, for any texture coordinates outside the range of 0.0 through 1.0, inclusive.

This is shown in the following figure in which the application specifies that the texture be applied to the primitive using a red border.

Applications set the border color by calling IDirect3DDevice8::SetTextureStageState. Set the first parameter for the call to the desired texture stage identifier, the second parameter to the D3DTSS_BORDERCOLOR stage state value, and the third parameter to the new RGBA border color.


Setting and Retrieving Texture Addressing Modes

You can set texture addressing modes for individual texture stages by calling the IDirect3DDevice8::SetTextureStageState method. Specify the desired texture stage identifier in the first parameter. Set the second parameter to D3DTSS_ADDRESSU, D3DTSS_ADDRESSV, or D3DTSS_ADDRESSW values to update the u-, v-, or v-addressing modes individually. The third parameter you pass to SetTextureStageState determines which mode is being set. This can be any member of the D3DTEXTUREADDRESS enumerated type. To retrieve the current texture address mode for a texture stage, call IDirect3DDevice8::GetTextureStageState, using the D3DTSS_ADDRESSU, D3DTSS_ADDRESSV, or D3DTSS_ADDRESSW members of the D3DTEXTURESTAGESTATETYPE enumeration to identify the address mode about which you want information.


Texture Addressing Modes and Texture Wrapping

Direct3D enables applications to perform texture wrapping. It is important to note that setting the texture addressing mode to D3DTADDRESS_WRAP is not the same as performing texture wrapping. Setting the texture addressing mode to D3DTADDRESS_WRAP results in multiple copies of the source texture being applied to the current primitive, and enabling texture wrapping changes how the system rasterizes textured polygons. For details, see Texture Wrapping.

Enabling texture wrapping effectively makes texture coordinates outside the [0.0, 1.0] range invalid, and the behavior for rasterizing such delinquent texture coordinates is undefined in this case. When texture wrapping is enabled, texture addressing modes are not used. Take care that your application does not specify texture coordinates lower than 0.0 or higher than 1.0 when texture wrapping is enabled.


Device Limitations for Texture Addressing

Although the system generally allows texture coordinates outside the range of 0.0 and 1.0, inclusive, hardware limitations often affect how far outside that range texture coordinates can be. A rendering device communicates this limit in the MaxTextureRepeat member of the D3DCAPS8 structure when you retrieve device capabilities. The value in this member describes the full range of texture coordinates allowed by the device. For instance, if this value is 128, then the input texture coordinates must be kept in the range -128.0 to +128.0. Passing vertices with texture coordinates outside this range is invalid. The same restriction applies to the texture coordinates generated as a result of automatic texture coordinate generation and texture coordinate transformations.

The interpretation of MaxTextureRepeat is also affected by the D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE capability bit. When this bit is set, the value in the MaxTextureRepeat member of D3DCAPS8 is used precisely as described. However, when D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is not set, texture repeating limitations depend on the size of the texture indexed by the texture coordinates. In this case, MaxTextureRepeat must be scaled by the current texture size at the largest level of detail to compute the valid texture coordinate range. For example, given a texture dimension of 32 and MaxTextureRepeat value of 512, the actual valid texture coordinate range is 512/32 = 16, so the texture coordinates for this device must be within the range of -16.0 to +16.0.


Texture Dirty Regions

Applications can optimize what subset of a texture is copied by specifying dirty regions on textures. Only those regions marked as dirty are copied by a call to IDirect3DDevice8::UpdateTexture. However, the dirty regions may be expanded to optimize alignment. When a texture is created, the entire texture is considered dirty. Only the following four operations affect the dirty state of a texture.

  • Adding a dirty region to a texture
  • Locking some buffer in the texture. This operation adds the locked region as a dirty region. The application can turn off this automatic dirty region update if it has better knowledge of the actual dirty regions.
  • Using the texture as a destination in IDirect3DDevice8::CopyRects marks the entire texture as dirty.
  • Using the texture as a source in UpdateTexture clears all the dirty regions on the source texture.

Dirty regions are set on the top level of a mipmapped texture, and UpdateTexture can expand the dirty region down the mip chain in order to minimize the number of bytes copied for each sublevel. Note that the sublevel dirty region coordinates are rounded outward, that is, their fractional parts are rounded toward the nearest edge of the texture.

Because each type of texture has different types of dirty regions, there are methods on each texture type. 2-D textures use dirty rectangle, and volume textures use boxes.

  • IDirect3DCubeTexture8::AddDirtyRect
  • IDirect3DTexture8::AddDirtyRect
  • IDirect3DVolumeTexture8::AddDirtyBox

Passing NULL for the pDirtyRect or pDirtyBox parameters for the above methods expands the dirty region to cover the entire texture.

Each lock method can take D3DLOCK_NO_DIRTY_UPDATE, which prevents any changes to the dirty state of the texture. For more information, see Locking Resources.

Applications should use D3DLOCK_NO_DIRTY_UPDATE when further information about the true set of regions changed during a lock operation is available. You should note that a lock or copy to only a sublevel—that is, without locking or copying to the top level—of texture does not update the dirty regions for that texture. Applications assume the same responsibility for updating dirty regions when they lock lower levels without locking the topmost level.


Texture Palettes

Microsoft® Direct3D® for Microsoft DirectX® 8.0 supports paletted textures through a set of 256 entry palettes associated with the IDirect3DDevice8 object. A palette is made current by calling the IDirect3DDevice8::SetCurrentTexturePalette method. The current palette is used for translating all paletted textures for all active texture stages. IDirect3DDevice8::SetPaletteEntries updates all of a palette's 256 entries. Each entry is a PALETTEENTRY structure of the format D3DFMT_A8R8G8B8. All entries default to 0xFFFFFFFF. Note that as of DirectX 8.0, the peFlags member of the PALLETTEENTRY structure does not work as documented in the Microsoft Platform Software Development Kit (SDK). The peFlags member is now the alpha channel for 8-bit palettized formats.

The IDirect3DDevice8 palettes contain an alpha channel. This alpha channel can be used when the D3DPTEXTURECAPS_ALPHAPALETTE device capability flag is set, indicating that the device supports alpha from the palette. The palette alpha channel is used when the texture format does not have an alpha channel. If the device does not support alpha from the palette and the texture format does not have an alpha channel, then a value of 0xFF is used for alpha.

There is a maximum of 16,384 palettes. Because memory resources associated with the set of palettes are proportional to the maximum palette number that an application references, use contiguous palette numbers starting at zero.


Texture Coordinates

The following topics introduce the concept of texture coordinates, their formats, and the Microsoft® Direct3D® services used to manipulate them.

  • Understanding Texture Coordinates
  • Directly Mapping Texels to Pixels
  • Texture Coordinate Formats
  • Texture Coordinate Processing


Understanding Texture Coordinates

Most textures, like bitmaps, are a two-dimensional array of color values. Cubic-environment map textures are an exception. For details, see Cubic Environment Mapping. The individual color values are called a texture element, or texel. Each texel has a unique address in the texture. The address can be thought of as a column and row number, which are labeled u and v respectively.

Texture coordinates are in texture space. That is, they are relative to the location (0,0) in the texture. When a texture is applied to a primitive in 3-D space, its texel addresses must be mapped into object coordinates. They must then be translated into screen coordinates, or pixel locations.

Microsoft® Direct3D® maps texels in texture space directly to pixels in screen space, skipping the intermediate step for greater efficiency. This mapping process is actually an inverse mapping. That is, for each pixel in screen space, the corresponding texel position in texture space is calculated. The texture color at or around that point is sampled. The sampling process is called texture filtering. For more information, see Texture Filtering.

Each texel in a texture can be specified by its texel coordinate. However, in order to map texels onto primitives, Direct3D requires a uniform address range for all texels in all textures. Therefore, it uses a generic addressing scheme in which all texel addresses are in the range of 0.0 to 1.0 inclusive. Direct3D applications specify texture coordinates in terms of u,v values, much like 2-D Cartesian coordinates are specified in terms of x,y coordinates. Technically, the system can actually process texture coordinates outside the range of 0.0 and 1.0, and does so by using the parameters you set for texture addressing. For more information, see Texture Addressing Modes.

A result of this is that identical texture addresses can map to different texel coordinates in different textures. In the following illustration, the texture address being used is (0.5,1.0). However, because the textures are different sizes, the texture address maps to different texels. Texture 1, on the left, is 5x5. The texture address (0.5,1.0) maps to texel (2,4). Texture 2, on the right, is 7x7. The texture address (0.5,1.0) maps to texel (3,6).

A simplified version of the texel mapping process is shown in the following diagram. Admittedly, this example is extremely simple. For more detailed information, see Directly Mapping Texels to Pixels.

For this example, a pixel, shown at the left of the illustration, is idealized into a square of color. The addresses of the four corners of the pixel are mapped onto the 3-D primitive in object space. The shape of the pixel is often distorted because of the shape of the primitive in 3-D space and because of the viewing angle. The corners of the surface area on the primitive that correspond the corners of the pixel are then mapped into texture space. The mapping process distorts the pixel's shape again, which is common. The final color value of the pixel is computed from the texels in the region to which the pixel maps. You determine the method that Direct3D uses to arrive at the pixel color when you set the texture filtering method. For more information, see Texture Filtering.

Your application can assign texture coordinates directly to vertices. This capability gives you control over which portion of a texture is mapped onto a primitive. For instance, suppose you create a rectangular primitive that is exactly the same size as the texture in the following illustration. In this example, you want your application to map the whole texture onto the whole wall. The texture coordinates your application assigns to the vertices of the primitive are (0.0,0.0), (1.0,0.0), (1.0,1.0), and (0.0,1.0).

If you decide to decrease the height of the wall by one-half, you can distort the texture to fit onto the smaller wall, or you can assign texture coordinates that cause Direct3D to use the bottom half of the texture.

If you decide to distort or scale the texture to fit the smaller wall, the texture filtering method that you use will influence the quality of the image. For more information, see Texture Filtering.

If, instead, you decide to assign texture coordinates to make Direct3D use the bottom half of the texture for the smaller wall, the texture coordinates your application assigns to the vertices of the primitive in this example are (0.0,0.0), (1.0,0.0), (1.0,0.5), and (0.0,0.5). Direct3D applies the bottom half of the texture to the wall.

It is possible for texture coordinates of a vertex to be greater than 1.0. When you assign texture coordinates to a vertex that are not in the range of 0.0 to 1.0 inclusive, you should also set the texture addressing mode. For further information, see Texture Addressing Modes.


Directly Mapping Texels to Pixels

Applications often need to apply textures to geometry in a scene so that texels map directly to on-screen pixels. For example, take an application that needs to display text within a texture on an object within a scene. In order to clearly display textual information in a texture, the application needs some way to ensure that the textured geometry receives texels undisrupted by texture filtering. Failing this, the resulting image is often blurred, or in the case of point-sampled texture filtering, can cause rough edges.

Because the Microsoft® Direct3D® pixel and texture sampling rules are carefully defined to unify pixel and texture sampling while supporting image and texture filtering, getting the texels in a texture to map directly to on-screen pixels can be a significant and often frustrating challenge. Overcoming this challenge requires a clear understanding of how Direct3D maps the floating-point texture coordinates for a vertex to the integer pixel coordinates used by the rasterizer.

Direct3D performs the following computations to map floating point texture coordinates to texel addresses.

In these formulas, Tx and Ty are the horizontal and vertical output texel coordinates, and u and v are the horizontal and vertical texture coordinates supplied for the vertex. The Mx and My elements represent the number of horizontal or vertical texels at the current mipmap level. The remainder of this discussion targets horizontal mapping of texels to pixels; keep in mind that mapping in the vertical is identical to the horizontal case.

Placing the texture coordinate limits 0.0 and 1.0 into these formulas maps a texture coordinate of 0.0 halfway between the first and last texels of a repeated texture map. The coordinate 1.0 is mapped halfway between the last texel of the current iteration of the texture map and the next iteration. For a repeated texture that's four texels wide, at mipmap level 0, the following illustration shows where the system maps the coordinates 0.0 and 1.0.

Given an understanding of this mapping, you can apply a simple bias to your screen-space geometry coordinates to force the system to map each texel to a corresponding pixel. For example, to draw a four-sided polygon that maps each texel from the preceding texture to one, and only one, pixel on the screen, you must force geometry coordinates to overlap the pixels, effectively placing the center of each texel at the center of each pixel. The result is the 1-to-1 mapping often sought-after by applications.

To map the texture with a 4-texel width to the pixel coordinates 0 through 3, draw a four-sided polygon, from two triangles, that has screen-space coordinates of –0.5 to 3.5 and texture coordinates of 0.0 to 1.0. For example, take the pixel at screen coordinate 0.0. Because 0.0 is one-half pixel away from the first vertex, at -0.5, and the total width is 4.0, the iterated texture coordinate is 0.125. Scaling this by the texture size, which is 4, results in the coordinate 0.5. Subtracting this 0.5 bias produces a texture address of 0.0, which fully maps to the first texel in the map.

To summarize, texture coordinates overlap the texture map evenly on both sides. The following illustration shows the mapping of a texture that is four texels wide.

The system normalizes pixel coordinates in the same way it normalizes texel coordinates. Therefore, if the vertices overlap the pixels into which to render, and if the vertices use texture coordinates of 0.0 and 1.0, the pixels and texels line up. If both are of similar size and properly aligned, they match exactly, texel to pixel, as shown in the following figure.


Texture Coordinate Formats

Texture coordinates in Microsoft® Direct3D® can include one, two, three, or four floating point elements to address textures with varying levels of dimension. A 1-D texture—a texture surface with dimensions of 1-by-n texels—is addressed by one texture coordinate. The most common case, 2-D textures, are addressed with two texture coordinates commonly called u and v. Direct3D supports a single type of 3-D texture, called a cubic-environment map. Cubic environment maps aren't truly 3-D, but they are addressed with a 3-element vector. For details, see Cubic Environment Mapping.

As described in About Vertex Formats, applications encode texture coordinates in the vertex format. The vertex format can include multiple sets of texture coordinates. Use the D3DFVF_TEX0 through D3DFVF_TEX8 flexible vertex format flags to describe a vertex format that includes no texture coordinates, or as many as eight sets.

Each texture coordinate set can have between one and four elements. The D3DFVF_TEXTUREFORMAT1 through D3DFVF_TEXTUREFORMAT4 flags describe the number of elements in a texture coordinate in a set, but these flags aren't used by themselves. Rather, the D3DFVF_TEXCOORDSIZEn set of macros use these flags to create bit patterns that describe the number of elements used by a particular set of texture coordinates in the vertex format. These macros accept a single parameter that identifies the index of the coordinate set whose number of elements is being defined. The following example illustrates how these macros are used.

// This vertex format contains two sets of texture coordinates.
// The first set (index 0) has 2 elements, and the second set
// has 1 element. The description for this vertex format would be:
//     dwFVF = D3DFVF_XYZ  | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_TEX2 |
//             D3DFVF_TEXCOORDSIZE2(0) | D3DFVF_TEXCOORDSIZE1(1);
//
typedef struct CVF
{
    D3DVECTOR position;
    D3DVECTOR normal;
    D3DCOLOR  diffuse;
    float     u, v;   // 1st set, 2-D
    float     t;      // 2nd set, 1-D
} CustomVertexFormat;

Note With the exception of cubic-environment maps, rasterizers cannot address textures by using any more than two elements. Applications can supply up to three elements for a texture coordinate, but only if the texture is a cube map, or the D3DTTFF_PROJECTED texture transform flag is used. The D3DTTFF_PROJECTED flag causes the rasterizer to divide the first two elements by the third (or nth) element. For more information, see Texture Coordinate Transformations.


Texture Coordinate Processing

This section describes Microsoft® Direct3D® support for processing texture coordinates. Information is organized into the following topics.

  • Texture Coordinate Processing Path
  • Automatically Generated Texture Coordinates
  • Texture Coordinate Transformations
  • Using Texture Coordinate Processing


Texture Coordinate Processing Path

The following figure shows the path taken by the texture coordinates from their source, through processing, and to the rasterizer.

There are two sources from which the system can draw texture coordinates. For a given texture stage, you can use texture coordinates included in the vertex format (D3DFVF_TEX1 through D3DFVF_TEX8), or you can use texture coordinates automatically generated by Microsoft® Direct3D®. For details about the latter case, see Automatically Generated Texture Coordinates. If the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state for the current texture stage is set to D3DTTFF_DISABLE (the default setting), input coordinates are not transformed. If D3DTSS_TEXTURETRANSFORMFLAGS is set to any other value, the transformation matrix for that stage is applied to the input coordinates.

The D3DTEXTURETRANSFORMFLAGS enumerated type defines valid values for the D3DTSS_TEXTURETRANSFORMFLAGS texture-stage state. With the exception of the D3DTTFF_DISABLE flag, which bypasses texture coordinate transformation, the values defined in this enumeration configure the number of output coordinates that the system passes to the rasterizer. The D3DTTFF_COUNT1 through D3DTTFF_COUNT4 flags instruct the system to pass one, two, three, or four elements from the output coordinates to the rasterizer. Currently 1-D texture coordinates aren't supported.

The D3DTTFF_PROJECTED flag is special: it tells the system that the texture coordinates are for a projected texture. Combine the D3DTTFF_PROJECTED flag with another member of D3DTEXTURETRANSFORMFLAGS to instruct the rasterizer to divide all the elements by the last element before rasterization takes place. For example, when explicitly using three-element texture coordinates, or when transformation results in a three-element texture coordinate, you can combine the D3DTTFF_COUNT3 and D3DTTFF_PROJECTED flags to cause the rasterizer to divide the first two elements by the last, producing 2-D texture coordinates required to address a 2-D texture.

Note With the exception of cubic-environment maps, rasterizers cannot address textures by using texture coordinates with more than two elements. If you specify more elements than can be used to address the current texture for that stage, the extraneous elements are ignored. This also applies when using 2-D texture coordinates for a 1-D texture.


Automatically Generated Texture Coordinates

Microsoft® Direct3D® can automatically generate the texture coordinates for a vertex. This section describes the services offered by the system and includes details on how the services are used. The following topics are discussed.

  • About Automatically Generated Texture Coordinates
  • Configuring Automatically Generated Texture Coordinates


About Automatically Generated Texture Coordinates

The system can use the transformed camera-space position or the normal from a vertex as texture coordinates, or it can compute the three element vectors used to address a cubic environment map. Like texture coordinates that you explicitly specify in a vertex, you can use automatically generated texture coordinates as input for texture coordinate transformations.

Automatically generated texture coordinates can significantly reduce the bandwidth required for geometry data by eliminating the need for explicit texture coordinates in the vertex format. In many cases, the texture coordinates that the system generates can be used with transformations to produce special effects. Of course, this is a special-purpose feature, and you will use explicit texture coordinates for many occasions.


Configuring Automatically Generated Texture Coordinates

In C++, the D3DTSS_TEXCOORDINDEX texture-stage state (from the D3DTEXTURESTAGESTATETYPE enumerated type) controls how the system generates texture coordinates.

Normally, this state instructs the system to use a particular set of texture coordinates encoded in the vertex format. When you include the D3DTSS_TCI_CAMERASPACENORMAL, D3DTSS_TCI_CAMERASPACEPOSITION, or D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flags in the value that you assign to this state, the system behavior is quite different. If any of these flags are present, the texture stage ignores the texture coordinates within the vertex format in favor of coordinates that the system generates. The meanings for each flag are shown in the following list.

D3DTSS_TCI_CAMERASPACENORMAL
Use the vertex normal, transformed to camera space, as input texture coordinates.
D3DTSS_TCI_CAMERASPACEPOSITION
Use the vertex position, transformed to camera space, as input texture coordinates.
D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR
Use the reflection vector, transformed to camera space, as input texture coordinates. The reflection vector is computed from the input vertex position and normal vector.

The preceding flags are mutually exclusive. If you include one flag, you can still specify an index value, which the system uses to determine the texture wrapping mode.

The following code example shows how these flags are used in C++.

/*
 * For this example, the d3dDevice variable is a valid
 * pointer to an IDirect3DDevice8 interface.
 *
 * Use the vertex position (camera-space) as the input
 * texture coordinates for this texture stage, and the
 * wrap mode set in the D3DRENDERSTATE_WRAP1 render state.
 */
d3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX,
                                   D3DTSS_TCI_CAMERASPACEPOSITION | 1 );

Note Automatically generated texture coordinates are most useful as input values for a texture coordinate transformation, or to eliminate the need for your application to compute three-element vectors for cubic-environment maps.

See Also

Texture Coordinate Transformations, Cubic Environment Mapping


Texture Coordinate Transformations

The following topics provide information about working with the texture coordinate transformation features offered by Microsoft® Direct3D® Immediate Mode.

  • About Texture Coordinate Transformations
  • Setting and Retrieving Texture Coordinate Transformations
  • Enabling Texture Coordinate Transformations


About Texture Coordinate Transformations

Microsoft® Direct3D® devices can transform the texture coordinates for vertices by applying a 4×4 matrix. The system applies transformations to texture coordinates in the same manner as geometry, and any transformations that can be communicated in a 4×4 matrix—scales, rotations, translations, projections, shears, or any combination of these—can be applied.

Note Direct3D does not modify transformed and lit vertices. As a result, an application using transformed and lit vertices cannot use Direct3D to transform the texture coordinates of the vertices.

Devices that support hardware-accelerated transformation and lighting operations (TnLHAL Device) also accelerate the transformation of texture coordinates. When hardware acceleration of transformations isn't available, platform-specific optimizations in the Direct3D geometry pipeline apply to texture coordinate transformations.

Texture coordinate transformations are useful for producing special effects while avoiding the need to directly modify the texture coordinates of your geometry. You could use simple translation or rotation matrices to animate textures on an object, or you can transform texture coordinates that are automatically generated by Direct3D to simplify and perhaps accelerate advanced effects such as projected textures and dynamic light-mapping. Additionally, you might use texture coordinate transforms to reuse a single set of texture coordinates for multiple purposes, in multiple texture stages.

For more information, see Using Texture Coordinate Processing.


Setting and Retrieving Texture Coordinate Transformations

Like the matrices that your application uses for geometry, you set and retrieve texture coordinate transformations by calling the IDirect3DDevice8::SetTransform and IDirect3DDevice8::GetTransform methods. These methods accept the D3DTS_TEXTURE0 through D3DTS_TEXTURE7 members of the D3DTRANSFORMSTATETYPE enumerated type to identify the transformation matrices for texture stages 0 through 7, respectively.

The following code sets a matrix to apply to the texture coordinates for texture stage 0.

// For this example, the d3dDevice variable contains a
// valid pointer to an IDirect3DDevice8 interface.
//
D3DMATRIX matTrans = D3DXMatrixIdentity( NULL );

// Set-up the matrix for the desired transformation.
d3dDevice->SetTransform( D3DTS_TEXTURE0, &matTrans );


Enabling Texture Coordinate Transformations

The D3DTSS_TEXTURETRANSFORMFLAGS texture stage state controls the application of texture coordinate transformations. Values for this texture stage state are defined by the D3DTEXTURETRANSFORMFLAGS enumerated type.

Texture coordinate transformations are disabled when D3DTSS_TEXTURETRANSFORMFLAGS is set to D3DTTFF_DISABLE (the default value). Assuming that texture coordinate transformations were enabled for stage 0, the following code disables them.

// For this example, the d3dDevice variable contains a
// valid pointer to an IDirect3DDevice8 interface.

D3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_DISABLE );

The other values defined in D3DTEXTURETRANSFORMFLAGS are used to enable texture coordinate transformations, and to control how many resulting texture coordinate elements are passed to the rasterizer. For example, take the following code.

// For this example, the d3dDevice variable contains a
// valid pointer to an IDirect3DDevice8 interface.

D3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2 );

The D3DTTFF_COUNT2 value instructs the system to apply the transformation matrix set for texture stage 0, and then pass the first two elements of the modified texture coordinates to the rasterizer.

The D3DTTFF_PROJECTED texture transformation flag indicates coordinates for a projected texture. When this flag is specified, the rasterizer divides the elements passed-in by the last element. Take the following code, for example.

// For this example, the d3dDevice variable contains a
// valid pointer to an IDirect3DDevice8 interface.

d3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS,
                                   D3DTTFF_COUNT3 | D3DTTFF_PROJECTED );

This example informs the system to pass three texture coordinate elements to the rasterizer. The rasterizer divides the first two elements by the third, producing the 2-D texture coordinates needed to address the texture.


Using Texture Coordinate Processing

The following list contains examples of ways you might use texture coordinate processing to achieve special texturing effects.

Animating textures (by translation or rotation) on a model

  • Define 2-D texture coordinates in your vertex format.
    // Use a single texture, with 2-D texture coordinates. This
// bit-pattern should be expanded to include position, normal,
// and color information as needed.
DWORD dwFVFTex = D3FVF_TEX1 | D3DFVF_TEXCOORDSIZE2(0);
  • Configure the rasterizer to use 2-D texture coordinates.
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
  • Define and set an appropriate texture coordinate transformation matrix.
    // M is a D3DMATRIX being set to translate texture
// coordinates in the U and V directions.
//      1   0  0  0
//      0   1  0  0
//      du dv  1  0 (du and dv change each frame)
//      0   0  0  1

D3DMATRIX M = D3DXMatrixIdentity(); // declared in d3dutil.h
M._31 = du;
M._32 = dv;

Creating texture coordinates as a linear function of a model's camera-space position

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position, in camera space, as input to a texture transformation.
    // The input vertices have no texture coordinates, saving
// bandwidth. Three texture coordinates are generated by
// using vertex position in camera space (x, y, z).
SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
  • Instruct the rasterizer to expect 2-D texture coordinates.
    // Two output coordinates are used.
SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2);
  • Define and set a matrix that applies a linear function.
    // Generate texture coordinates as linear functions
// so that:
//      u = Ux*x + Uy*x + Uz*x + Uw
//      v = Vx*x + Vy*x + Vz*x + Vw
// The matrix M for this case is:
//      Ux  Vx  0  0
//      Uy  Vy  0  0
//      Uz  Vz  0  0
//      Uw  Vw  0  0

SetTransform(D3DTS_TEXTURE0, &M);

Performing environment mapping with a cubic environment map

  • Use the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flag to instruct the system to automatically generate texture coordinates as reflection vectors for cubic mapping.
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR);
  • Instruct the rasterizer to expect texture coordinates with three elements.
    SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT3);

Performing projective texturing

  • Use the D3DTSS_TCI_CAMERASPACEPOSITION flag to instruct the system to pass the vertex position as input to a texture transformation matrix.
    SetTextureStageState(0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION);
  • Create and apply the texture projection matrix. This is beyond the scope of this documentation, and is the topic of several industry articles.
  • Instruct the rasterizer to expect three-element projected texture coordinates.
    // Two output coordinates are used.
SetTextureStageState(0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTF_PROJECTED | D3DTTFF_COUNT3);


Texture Resources

This section presents information on creating and rendering with texture interface pointers. The information is organized in the following topics.

  • Obtaining a Texture Surface Object
  • Rendering with Texture Resources


Obtaining a Texture Surface Object

Texture resources are implemented in the IDirect3DTexture8 interface. To obtain a pointer to a texture interface, call the IDirect3DDevice8::CreateTexture method or any of the following D3DX functions.

  • D3DXCreateTexture
  • D3DXCreateTextureFromFileA
  • D3DXCreateTextureFromFileExA
  • D3DXCreateTextureFromFileExW
  • D3DXCreateTextureFromFileInMemory
  • D3DXCreateTextureFromFileInMemoryEx
  • D3DXCreateTextureFromFileW
  • D3DXCreateTextureFromResourceA
  • D3DXCreateTextureFromResourceExA
  • D3DXCreateTextureFromResourceExW
  • D3DXCreateTextureFromResourceW

The following code example uses D3DXCreateTextureFromFileA to load a texture from Tiger.bmp.

// The following code example assumes that d3dDevice
// is a valid pointer to an IDirect3DDevice8 interface.

LPDIRECT3DTEXTURE8 pTexture;

D3DXCreateTextureFromFile( d3dDevice, "tiger.bmp", &pTexture);

The first parameter that D3DXCreateTextureFromFile accepts is a pointer to a IDirect3DDevice8 interface. The second parameter tells Microsoft® Direct3D® the name of the file from which to load the texture. The third parameter takes the address of a pointer to a IDirect3DTexture8 interface, representing the created texture object.


Rendering with Texture Surfaces

Microsoft DirectX 8.0 (C++)

Rendering with Texture Resources

Microsoft® Direct3D® supports multiple texture blending through the concept of texture stages. Each texture stage contains a texture and operations that can be performed on the texture. The textures in the texture stages form the set of current textures. For more information, see Multiple Texture Blending. The state of each texture is encapsulated in its texture stage.

In a C++ application, the state of each texture must be set with the IDirect3DDevice8::SetTextureStageState method. Pass the stage number (0-7) as the value of the first parameter. Set the value of the second parameter to a member of the D3DTEXTURESTAGESTATETYPE enumerated type. The final parameter is the state value for the particular texture state.

Using texture interface pointers, your application can render a blend of up to eight textures. Set the current textures by invoking the IDirect3DDevice8::SetTexture method. Direct3D blends all current textures onto the primitives that it renders.

Note The SetTexture method increments the reference count of the texture surface being assigned. When the texture is no longer needed, you should set the texture at the appropriate stage to NULL. If you fail to do this, the surface will not be released, resulting in a memory leak.

Your application can set the texture wrapping state for the current textures by calling the IDirect3DDevice8::SetRenderState method. Pass a value from D3DRS_WRAP0 through D3DRR_WRAP7 as the value of the first parameter, and use a combination of the D3DWRAPCOORD_0, D3DWRAPCOORD_1, D3DWRAPCOORD_2, and D3DWRAPCOORD_3 flags to enable wrapping in the u, v, or w directions.

Your application can also set the texture perspective and texture filtering states. See Texture Filtering and Texture Filtering State.


Texture Filtering

When Microsoft® Direct3D® renders a primitive, it maps the 3-D primitive onto a 2-D screen. If the primitive has a texture, Direct3D must use that texture to produce a color for each pixel in the primitive's 2-D rendered image. For every pixel in the primitive's on-screen image, it must obtain a color value from the texture. This process is called texture filtering.

When a texture filter operation is performed, the texture being used is typically also being magnified or minified. In other words, it is being mapped onto a primitive image that is larger or smaller than itself. Magnification of a texture can result in many pixels being mapped to one texel. The result can be a chunky appearance. Minification of a texture often means that a single pixel is mapped to many texels. The resulting image can be blurry or aliased. To resolve these problems, some blending of the texel colors must be performed to arrive at a color for the pixel.

Direct3D simplifies the complex process of texture filtering. It provides you with three types of texture filtering—linear filtering, anisotropic filtering, and mipmap filtering. If you select no texture filtering, Direct3D uses a technique called nearest-point sampling.

Each type of texture filtering has advantages and disadvantages. For instance, linear texture filtering can produce jagged edges or a chunky appearance in the final image. However, it is a computationally low-overhead method of texture filtering. Filtering with mipmaps usually produces the best results, especially when combined with anisotropic filtering. However, it requires the most memory of the techniques that Direct3D supports.

Applications that use texture interface pointers should set the current texture filtering method by calling the IDirect3Ddevice8::SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DTEXTUREMAGFILTER, D3DTEXTUREMINFILTER, or D3DTEXTUREMIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass a member of the D3DTEXTUREFILTERTYPE enumerated type as the value in the third parameter to set the magnification, minification, or mipmapping filter.

This section presents the texture filtering methods that Direct3D supports. It is organized into the following topics.

  • Nearest-Point Sampling
  • Linear Texture Filtering
  • Anisotropic Texture Filtering
  • Texture Filtering With Mipmaps

Note Although the texture-filtering render states present in the D3DRENDERSTATETYPE enumerated type are superseded by texture stage states, the IDirect3DDevice8::SetRenderState, as opposed to the IDirect3DDevice2 version, does not fail if you attempt to use them. Rather, the system maps the effects of these render states to the first stage in the multitexture cascade, stage 0. Applications should not mix the legacy render states with their corresponding texture stage states, as unpredictable results can occur.


Nearest-Point Sampling

Applications are not required to use texture filtering. Microsoft® Direct3D® can be set so that it computes the texel address, which often does not evaluate to integers, and simply copies the color of the texel with the closest integer address. This process is called nearest-point sampling. This can be a fast and efficient way to process textures if the size of the texture is similar to the size of the primitive's image on the screen. If not, the texture must be magnified or minified. The result can be a chunky, aliased, or blurred image.

Your C++ application can select nearest-point sampling by calling the IDirect3DDevice8::SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DTEXTUREMAGFILTER, D3DTEXTUREMINFILTER, or D3DTEXTUREMIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Pass a member of the D3DTEXTUREFILTERTYPE enumerated type as the value in the third parameter to set the magnification, minification, or mipmapping filter.

For more information, see Texture Filtering State.

You should use nearest-point sampling carefully, as it can sometimes cause graphic artifacts when the texture is sampled at the boundary between two texels. This boundary is the position along the texture (u or v) at which the sampled texel transitions from one texel to the next. When point sampling is used, the system chooses one sample texel or the other, and the result can change abruptly from one texel to the next texel as the boundary is crossed. This effect can appear as undesired graphic artifacts in the displayed texture. When linear filtering is used, the resulting texel is computed from both adjacent texels and smoothly blends between them as the texture index moves through the boundary.

This effect can be seen when mapping a very small texture onto a very large polygon: an operation often called magnification. For example, when using a texture that looks like a checkerboard, nearest-point sampling results in a larger checkerboard that shows distinct edges. By contrast, linear texture filtering results in an image where the checkerboard colors vary smoothly across the polygon.

In most cases, applications receive the best results by avoiding nearest-point sample wherever possible. The majority of hardware today is optimized for linear filtering, so your application should not suffer degraded performance. If the effect you desire absolutely requires the use of the nearest-point sampling—such as when using textures to display readable text characters—then your application should be extremely careful to avoid sampling at the texel boundaries, which might result in undesired effects. The following image shows what these artifacts can look like.

Notice that the two squares in the top-right of the group appear different than their neighbors, with diagonal offsets running through them. To avoid graphic artifacts like these, you must be familiar with Direct3D texture sampling rules for nearest-point filtering. Direct3D maps a floating-point texture coordinate ranging from [0.0, 1.0] (0.0 to 1.0, inclusive) to an integer texel space value ranging from [–0.5, n – 0.5], where n is the number of texels in a given dimension on the texture. The resulting texture index is rounded to the nearest integer. This mapping can introduce sampling inaccuracies at texel boundaries.

For a simple example, imagine an application that renders polygons with the D3DTADDRESS_WRAP texture addressing mode. Using the mapping employed by Direct3D, the u texture index maps as follows for a texture with a width of 4 texels.

Notice that the texture coordinates—0.0 and 1.0—for this illustration are exactly at the boundary between texels. Using the method by which Direct3D maps values, the texture coordinates range from [–0.5, 4 – 0.5], where 4 is the width of the texture. For this case, the sampled texel is the 0th texel for a texture index of 1.0. However, if the texture coordinate was only slightly less than 1.0, the sampled texel would be the nth texel instead of the 0th texel.

The implication of this is that magnifying a small texture using texture coordinates of exactly 0.0 and 1.0 with nearest-point filtering on a screen-space aligned triangle results in pixels for which the texture map is sampled at the boundary between texels. Any inaccuracies in the computation of texture coordinates, however small, results in artifacts along the areas in the rendered image which correspond to the texel edges of the texture map.

Performing this mapping of floating point texture coordinates to integer texels with perfect accuracy is difficult, computationally expensive, and generally not necessary. Most hardware implementations use an iterative approach for computing texture coordinates at each pixel location within a triangle. Iterative approaches tend to hide these inaccuracies because the errors are accumulated evenly during iteration.

The Direct3D reference rasterizer uses a direct-evaluation approach for computing texture indexes at each pixel location. Direct evaluation differs from the iterative approach in that any inaccuracy in the operation exhibits a more random error distribution. The result of this is that the sampling errors that occur at the boundaries can be more noticeable because the reference rasterizer does not perform this operation with perfect accuracy.

The best approach is to use nearest-point filtering only when necessary. When you must use it, it is recommended that you offset texture coordinates slightly from the boundary positions to avoid artifacts.


Linear Texture Filtering

Microsoft® Direct3D® uses a form of linear texture filtering called bilinear filtering. Like nearest-point sampling, bilinear texture filtering first computes a texel address, which is usually not an integer address. Bilinear filtering then finds the texel whose integer address is closest to the computed address. In addition, the Direct3D rendering module computes a weighted average of the texels that are immediately above, below, to the left of, and to the right of the nearest sample point.

Select bilinear texture filtering by invoking the IDirect3DDevice8::SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DTEXTUREMAGFILTER, D3DTEXTUREMINFILTER, or D3DTEXTUREMIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Set the third parameter to D3DTEXF_LINEAR. For more information, see Texture Filtering State.


Anisotropic Texture Filtering

Anisotropy is the distortion visible in the texels of a 3-D object whose surface is oriented at an angle with respect to the plane of the screen. When a pixel from an anisotropic primitive is mapped to texels, its shape is distorted. Microsoft® Direct3D® measures the anisotropy of a pixel as the elongation—that is, length divided by width—of a screen pixel that is inverse-mapped into texture space.

You can use anisotropic texture filtering in conjunction with linear texture filtering or mipmap texture filtering to improve rendering results. Your application enables anisotropic texture filtering by calling the IDirect3DDevice8::SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are selecting a texture filtering method. Pass D3DTEXTUREMAGFILTER, D3DTEXTUREMINFILTER, or D3DTEXTUREMIPFILTER for the second parameter to set the magnification, minification, or mipmapping filter. Set the third parameter to D3DTEXF_ANISOTROPIC. For more information, see Texture Filtering State.

Your application must also set the degree of anisotropy to a value greater than one. Do this by calling the IDirect3DDevice8::SetTextureStageState method. Set the value of the first parameter to the integer index number (0-7) of the texture for which you are setting the degree of isotropy. Pass D3DTSS_MAXANISOTROPY as the value of the second parameter. The final parameter should be the degree of isotropy.

You can disable isotropic filtering by setting the degree of isotropy to one; any value larger than one enables it. Check the MaxAnisotropy flag in the D3DCAPS8 structure to determine the possible range of values for the degree of anisotropy.


Texture Filtering with Mipmaps

Mipmap textures are used in 3-D scenes to decrease the time required to render a scene. They also improve the scene's realism. However, they often require large amounts of memory.

This section presents the fundamentals of using mipmap textures in 3-D scenes. Information is organized in the following topics.

  • What Is a Mipmap?
  • Creating a Set of Mipmaps
  • Selecting and Displaying a Mipmap


What Is a Mipmap?

A mipmap is a sequence of textures, each of which is a progressively lower resolution representation of the same image. The height and width of each image, or level, in the mipmap is a power of two smaller than the previous level. Mipmaps do not have to be square.

A high-resolution mipmap image is used for objects that are close to the user. Lower-resolution images are used as the object appears farther away. Mipmapping improves the quality of rendered textures at the expense of using more memory.

Microsoft® Direct3D® represents mipmaps as a chain of attached surfaces. The highest resolution texture is at the head of the chain and has the next level of the mipmap as an attachment. In turn, that level has an attachment that is the next level in the mipmap, and so on, down to the lowest resolution level of the mipmap.

The following illustrations shows an example of these levels. The bitmap textures represent a sign on a container in a 3-D, first-person game. When created as a mipmap, the highest-resolution texture is first in the set. Each succeeding texture in the mipmap set is smaller in height and width by a power of 2. In this case, the maximum-resolution mipmap is 256 pixels by 256 pixels. The next, texture is 128x128. The last texture in the chain is 64x64.

This sign has a maximum distance from which it is visible. If the user begins far away from the sign, the game displays the smallest texture in the mipmap chain, which in this case the 64x64 texture.

As the user moves the point of view closer to the sign, progressively higher-resolution textures in the mipmap chain are used. The resolution in the following illustration is 128x128.

The highest-resolution texture is used when the user's point of view is at the minimum allowable distance from the sign.

This is a computationally lower-overhead way of simulating perspective for textures. Rather than render a single texture at many resolutions, it is faster to use multiple textures at varying resolutions.

Direct3D can assess which texture in a mipmap set is the closest resolution to the desired output, and it can map pixels into its texel space. If the resolution of the final image is between the resolutions of the textures in the mipmap set, Direct3D can examine texels in both mipmaps and blend their color values together.

To use mipmaps, your application must build a set of mipmaps. For details, see Creating a Set of Mipmaps. Applications apply mipmaps by selecting the mipmap set as the first texture in the set of current textures. For more information, see Multiple Texture Blending.

Next, your application must set the filtering method that Direct3D uses to sample texels. The fastest method of mipmap filtering is to have Direct3D select the nearest texel. Use the D3DTFP_POINT enumerated value to select this. Direct3D can produce better filtering results if your application uses the D3DTFP_LINEAR enumerated value. This selects the nearest mipmap, and then computes a weighted average of the texels surrounding the location in the texture to which the current pixel maps.


Creating a Set of Mipmaps

The following example shows how your application can call the IDirect3DDevice8::CreateTexture method to build a chain of five mipmap levels: 256×256, 128×128, 64×64, 32×32, and 16×16.

// This code example assumes that the variable d3dDevice is a
// valid pointer to a IDirect3DDevice8 interface.

IDirect3DTexture8 * pMipMap;

d3dDevice->CreateTexture(256, 256, 5, 0, D3DFMT_R8G8B8, D3DPOOL_MANAGED, &pMipMap);

The first two parameters that are accepted by CreateTexture are the size and width of the top-level texture. The third parameter specifies the number of levels in the texture. If you set this to zero, Microsoft® Direct3D® creates a chain of surfaces, each a power of two smaller than the previous one, down to the smallest possible size of 1x1. The fourth parameter specifies the usage for this resource; in this case, 0 is specified to indicate no specific usage for the resource. The fifth parameter specifies the surface format for the texture. Use a value from the D3DFORMAT enumerated type for this parameter. The sixth parameter specifies a member of the D3DPOOL enumerated type indicating the memory class into which to place the created resource. Unless you are using dynamic textures, D3DPOOL_MANAGED is recommended. The final parameter takes the address of a pointer to a IDirect3DTexture8 interface.

Note Each surface in a mipmap chain has dimensions that are one-half that of the previous surface in the chain. If the top-level mipmap has dimensions of 256×128, the dimensions of the second-level mipmap are 128×64, the third-level is 64×32, and so on, down to 1×1. You cannot request a number of mipmap levels in Levels that would cause either the width or height of any mipmap in the chain to be smaller than 1. In the simple case of a 4×2 top-level mipmap surface, the maximum value allowed for Levels is three. The top-level dimensions are 4×2, the second-level dimensions are 2×1, and the dimensions for the third level are 1×1. A value larger than 3 in Levels results in a fractional value in the height of the second-level mipmap, and is therefore disallowed.


Selecting and Displaying a Mipmap

Call the IDirect3DDevice8::SetTexture method to set the mipmap texture set as the first texture in the list of current textures. For more information, see Multiple Texture Blending.

After your application selects the mipmap texture set, it must assign values from the D3DTEXTUREFILTERTYPE enumerated type to the D3DTSS_MIPFILTER texture stage state. Microsoft® Direct3D® then automatically performs mipmap texture filtering. Enabling mipmap texture filtering is demonstrated in the following code example.

d3dDevice->SetTexture(0, pMipMap);
d3dDevice->SetTextureStageState(0, D3DTSS_MIPFILTER, D3DTEXF_POINT);

Your application can also manually traverse a chain of mipmap surfaces by using the IDirect3DTexture8::GetSurfaceLevel method and specifying the mipmap level to retrieve. The following example traverses a mipmap chain from highest to lowest resolutions.

IDirect3DSurface8 * pSurfaceLevel;

for (int iLevel = 0; iLevel < pMipMap->GetLevelCount(); iLevel++)
{
    pMipMap->GetSurfaceLevel(iLevel, &pSurfaceLevel);

    //Process this level.

    pSurfaceLevel->Release();
}

Applications need to manually traverse a mipmap chain to load bitmap data into each surface in the chain. This is typically the only reason to traverse the chain. An application can retrieve the number of levels in a mipmap by calling IDirect3DBaseTexture8::GetLevelCount.


Texture Wrapping

This section presents information on wrapping textures around 3-D primitives. The discussion is divided into the following topics.

  • What Is Texture Wrapping?
  • Using Texture Wrapping

Note Do not confuse texture wrapping with the similarly named texture addressing modes. For more information, see Texture Addressing Modes and Texture Wrapping and Texture Addressing Modes.


What Is Texture Wrapping?

In short, texture wrapping changes the basic way that Microsoft® Direct3D® rasterizes textured polygons using the texture coordinates specified for each vertex. While rasterizing a polygon, the system interpolates between the texture coordinates at each of the polygon's vertices to determine the texels that should be used for every pixel of the polygon. Normally, the system treats the texture as a 2-D plane, interpolating new texels by taking the shortest route from point A within a texture to point B. If point A represents the u, v position (0.8, 0.1), and point B is at (0.1,0.1), the line of interpolation looks like the following illustration.

Note that the shortest distance between A and B in this illustration runs roughly through the middle of the texture. Enabling u- or v-texture coordinate wrapping changes how Direct3D perceives the shortest route between texture coordinates in the u- and v-directions. By definition, texture wrapping causes the rasterizer to take the shortest route between texture coordinate sets, assuming that 0.0 and 1.0 are coincident. The last bit is the tricky part: you can imagine that enabling texture wrapping in one direction causes the system to treat a texture as though it were wrapped around a cylinder. For example, consider the following illustration.

This diagram shows how wrapping in the u- direction affects how the system interpolates texture coordinates. Using the same points as in the example for normal, or nonwrapped, textures, you can see that the shortest route between points A and B is no longer across the middle of the texture; it's now across the border where 0.0 and 1.0 exist together. Wrapping in the v-direction is similar, except that it wraps the texture around a cylinder that is lying on its side. Wrapping in both the u- and v-directions is a more complex. In this situation, you can envision the texture as a torus, or doughnut.

The most common practical application for texture wrapping is to perform environment mapping. Usually, an object textured with an environment map appears very reflective, showing a mirrored image of the object's surroundings in the scene. For the sake of this discussion, picture a room with four walls, each one painted with a letter R, G, B, Y and the corresponding colors: red, green, blue, and yellow. The environment map for such a simple room might look like the following illustration.

Imagine that the room's ceiling is held up by a perfectly reflective, four-sided, pillar. Mapping the environment map texture to the pillar is simple; making the pillar look as though it's reflecting the letters and colors is not as easy. The following diagram shows a wire frame of the pillar with the applicable texture coordinates listed near the top vertices. The seam where wrapping will cross the edges of the texture is shown with a dotted line.

With wrapping enabled in the u- direction, the textured pillar shows the colors and symbols from the environment map appropriately and, at the seam in the front of the texture, the rasterizer properly chooses the shortest route between the texture coordinates, assuming that u-coordinates 0.0 and 1.0 share the same location. The textured pillar looks like the following illustration.

If texture wrapping isn't enabled, the rasterizer does not interpolate in the direction needed to generate a believable, reflected image. Rather, the area at the front of the pillar contains a horizontally compressed version of the texels between u- coordinates 0.175 and 0.875, as they pass through the center of the texture. The wrap effect is ruined.


Using Texture Wrapping

To enable texture wrapping, call the IDirect3DDevice8::SetRenderState method as shown in the code example below.

d3dDevice->SetRenderState(D3DRS_WRAP0, D3DWRAPCOORD_0);

The first parameter accepted by SetRenderState is a render state to set. Specify one of the D3DRS_WRAP0 through D3DRS_WRAP7 enumerated values which specify which texture level to set the wrapping for. Specify the D3DWRAPCOORD_0 through D3DWRAPCOORD_3 flags in the second parameter to enable texture wrapping in the corresponding direction, or combine them to enable wrapping in multiple directions. If you omit a flag, texture wrapping in the corresponding direction is disabled. To disable texture wrapping for a set of texture coordinates, set the value for the corresponding render state to 0.


Texture Blending

Microsoft® Direct3D® can produce transparency effects by blending a texture with a primitive's color. It can also blend multiple textures onto a primitive. This section presents information on how texture blending is done. It is divided into the following topics.

  • Alpha Texture Blending
  • Multipass Texture Blending
  • Multiple Texture Blending
  • Light Mapping With Textures

To use texture blending, your application should first check if the user's hardware supports it. This information is found in the TextureCaps member of the D3DCAPS8 structure. For details on how to query the user's hardware for texture blending capabilities, see IDirect3DDevice8::GetDeviceCaps.


Alpha Texture Blending

When Microsoft® Direct3D® renders a primitive, it generates a color for the primitive based on the primitive's material, or the colors of its vertices, and lighting information. For details, see Introduction to Lighting and Materials. If an application enables texture blending, Direct3D must then combine the color value of the processed polygon pixel with the pixel already stored in the frame buffer. Direct3D uses the following formula to determine the final color for each pixel in the primitive's image.

FinalColor = TexelColor × SourceBlendFactor + PixelColor × DestBlendFactor

In this formula, FinalColor is the final pixel color that is output to the target rendering surface. TexelColor represents the incoming color value, after texture filtering, that corresponds to the current pixel. For details on how Direct3D maps texels to pixels, see Texture Filtering. SourceBlendFactor is a calculated value that Direct3D uses to determine the percentage of the incoming color value to apply to the final color. PixelColor is the color of the pixel currently stored in the primitive's image. DestBlendFactor represents the percentage of the current pixel's color that will be used in the final rendered pixel. The values of SourceBlendFactor and DestBlendFactor range from 0.0 to 1.0 inclusive.

As you can see from the preceding formula, the final rendered pixel is not rendered as transparent if the SourceBlendFactor is D3DBLEND_ONE and the DestBlendFactor is D3DBLEND_ZERO. It is completely transparent if the SourceBlendFactor is D3DBLEND_ZERO and the DestBlendFactor is D3DBLEND_ONE. If an application sets these factors to any other values, the resulting final rendered pixel is blended with some degree of transparency.

After texture filtering, every pixel color value has red, green, and blue color values. By default, Direct3D uses D3DBLEND_SRCALPHA as the SourceBlendFactor and D3DBLEND_INVSRCALPHA as the DestBlendFactor. Therefore, applications can control the transparency of processed pixels by setting the alpha values in textures.

A C++ application controls the blending factors with the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states. Invoke the IDirect3DDevice8::SetRenderState method and pass either render state value as the value of the first parameter. The second parameter must be a member of the D3DBLEND enumerated type.


Multipass Texture Blending

Microsoft® Direct3D® applications can achieve numerous special effects by applying various textures to a primitive over the course of multiple rendering passes. The common term for this is multipass texture blending. A typical use for multipass texture blending is to emulate the effects of complex lighting and shading models by applying multiple colors from several different textures. One such application is called light mapping. For more information, see Light Mapping With Textures.

Note Some devices are capable of applying multiple textures to primitives in a single pass. For details, see Multiple Texture Blending.

If the user's hardware does not support multiple texture blending, your application can use multipass texture blending to achieve the same visual effects. However, the application cannot sustain the frame rates that are possible when using multiple texture blending.

To perform multipass texture blending in a C++ application

  1. Set a texture in texture stage 0 by calling the IDirect3DDevice8::SetTexture method.
  2. Select the desired color and alpha blending arguments and operations with the IDirect3DDevice8::SetTextureStageState method. The default settings are well-suited for multipass texture blending.
  3. Render the appropriate objects in the scene.
  4. Set the next texture in texture stage 0.
  5. Set the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states to adjust the source and destination blending factors as needed. The system blends the new textures with the existing pixels in the render-target surface according to these parameters.
  6. Repeat Steps 3, 4, and 5 with as many textures as needed.


Multiple Texture Blending

Microsoft® Direct3D® can blend as many as eight textures onto primitives in a single pass. The use of multiple texture blending can profoundly increase the frame rate of a Direct3D application. An application employs multiple texture blending to apply textures, shadows, specular lighting, diffuse lighting, and other special effects in a single pass.

To blend multiple textures, an application assigns textures to the set of current textures, and then creates blending stages. The following topics contain information on how these steps are accomplished.

  • Texture Stages and the Texture Blending Cascade
  • Texture Blending Operations and Arguments
  • Assigning the Current Textures
  • Creating Blending Stages


Texture Stages and the Texture Blending Cascade

Microsoft® Direct3D® supports single-pass multiple texture blending through the use of texture stages. A texture stage takes two arguments and performs a blending operation on them, passing on the result for further processing or for rasterization. You can visualize a texture stage as shown in the following illustration.

As the preceding illustration shows, texture stages blend two arguments by using a specified operator. Common operations include simple modulation or addition of the color or alpha components of the arguments, but more than two dozen operations are supported. The arguments for a stage can be an associated texture, the iterated color or alpha (iterated during Gouraud shading), arbitrary color and alpha, or the result from the previous texture stage. For more information, see Texture Blending Operations and Arguments.

Note Direct3D distinguishes color blending from alpha blending. Applications set blending operations and arguments for color and alpha individually, and the results of those settings are independent of one another.

The combination of arguments and operations used by multiple blending stages define a simple flow-based blending language. The results from one stage flow down to another stage, from that stage to the next, and so on. The concept of results flowing from stage to stage to eventually be rasterized on a polygon is often called the texture blending cascade. The following illustration shows how individual texture stages make up the texture blending cascade.

Each stage in a device has a zero-based index. Direct3D allows up to eight blending stages, although you should always check device capabilities to determine how many stages the current hardware supports. The first blending stage is at index 0, the second is at 1, and so on, up to index 7. The system blends stages in increasing index order.

Use only the number of stages you need; the unused blending stages are disabled by default. So, if your application only uses the first two stages, it need only set operations and arguments for stage 0 and 1. The system blends the two stages, and ignores the disabled stages.

Optimization Note If your application varies the number of stages it uses for different situations—such as four stages for some objects, and only two for others—you don't need to explicitly disable all previously used stages. If you disable the color operation for the first unused stage, all stages with a higher index will not be applied. You can disable texture mapping altogether by setting the color operation for the first texture stage (stage 0).


Texture Blending Operations and Arguments

Applications associate a blending stage with each texture in the set of current textures. As mentioned in Texture Stages and the Texture Blending Cascade, Microsoft® Direct3D® evaluates each blending stage in order, beginning with the first texture in the set and ending with the eighth.

Direct3D applies the information from each texture in the set of current textures to the blending stage that is associated with it. Applications control what information from a texture stage is used by calling IDirect3DDevice8::SetTextureStageState. You can set separate operations for the color and alpha channels, and each operation uses two arguments. Specify color channel operations by using the D3DTSS_COLOROP stage state; specify alpha operations by using D3DTSS_ALPHAOP. Both stage states use values from the D3DTEXTUREOP enumerated type.

Texture blending arguments use the D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHARG1, and D3DTSS_ALPHARG2 members of the D3DTEXTURESTAGESTATETYPE enumerated type. The corresponding argument values are identified using texture argument flags.

Note You can disable a texture stage—and any subsequent texture blending stages in the cascade—by setting the color operation for that stage to D3DTOP_DISABLE. Disabling the color operation effectively disables the alpha operation as well. Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.

To determine the supported texture blending operations of a device, query the TextureCaps member of the D3DCAPS8 structure.


Assigning the Current Textures

Microsoft® Direct3D® maintains a list of up to eight current textures. It blends these textures onto all the primitive it renders. Only textures created as texture interface pointers can be used in the set of current textures.

Applications call the IDirect3DDevice8::SetTexture method to assign textures into the set of current textures. The first parameter must be from the a number in the range of 0-7, inclusive. Pass the texture interface pointer as the second parameter.

The following C++ code example demonstrates how a texture can be assigned to the set of current textures.

// This code example assumes that the variable lpd3dDev is a
// valid pointer to an IDirect3DDevice8 interface and pTexture
// is a valid pointer to an IDirect3DBaseTexture8 interface.

// Set the third texture.
d3dDevice->SetTexture(2, pTexture);

Note Software devices do not support assigning a texture to more than one texture stage at a time.


Creating Blending Stages

A blending stage is a set of texture operations and their arguments that define how textures are blended. When making a blending stage, C++ applications invoke the IDirect3DDevice8::SetTextureStageState method. The first call specifies the operation that is performed. Two additional invocations define the arguments to which the operation is applied. The following code example illustrates the creation of a blending stage.

// This example assumes that lpD3DDev is a valid pointer to an
// IDirect3DDevice8 interface.

// Set the operation for the first texture.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_ADD);

// Set argument 1 to the texture color.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE);

// Set argument 2 to the iterated diffuse color.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE);

Texel data in textures contain color and alpha values. Applications can define separate operations for both color and alpha values in a single blending stage. Each operation, color and alpha, has its own arguments. For details, see D3DTEXTURESTAGESTATETYPE.

Although not part of the Microsoft® Direct3D® API, you can insert the following macros into your application to abbreviate the code required for creating texture blending stages.

#define SetTextureColorStage( dev, i, arg1, op, arg2 )     \
   dev->SetTextureStageState( i, D3DTSS_COLOROP, op);      \
   dev->SetTextureStageState( i, D3DTSS_COLORARG1, arg1 ); \
   dev->SetTextureStageState( i, D3DTSS_COLORARG2, arg2 );

#define SetTextureAlphaStage( dev, i, arg1, op, arg2 )     \
   dev->SetTextureStageState( i, D3DTSS_ALPHAOP, op);      \
   dev->SetTextureStageState( i, D3DTSS_ALPHARG1, arg1 );  \
   dev->SetTextureStageState( i  D3DTSS_ALPHARG2, arg2 );


Light Mapping with Textures

For an application to realistically render a 3-D scene, it must take into account the effect that light sources have on the appearance of the scene. Although techniques such as flat and Gouraud shading are valuable tools in this respect, they can be insufficient for your needs. Microsoft® Direct3D® supports multipass and multiple texture blending. These capabilities enable your application to render scenes with a more realistic appearance than scenes rendered with shading techniques alone. By applying one or more light maps, your application can map areas of light and shadow onto its primitives.

A light map is a texture or group of textures that contains information about lighting in a 3-D scene. You can store the lighting information in the alpha values of the light map, in the color values, or in both.

If you implement light mapping using multipass texture blending, your application should render the light map onto its primitives on the first pass. It should use a second pass to render the base texture. The exception to this is specular light mapping. In that case, render the base texture first; then add the light map.

Multiple texture blending enables your application to render the light map and the base texture in one pass. If the user's hardware provides for multiple texture blending, your application should take advantage of it when performing light mapping. This significantly improves your application's performance.

Using light maps, a Direct3D application can achieve a variety of lighting effects when it renders primitives. It can map not only monochrome and colored lights in a scene, but it can also add details such as specular highlights and diffuse lighting.

Information on using Direct3D texture blending to perform light mapping is presented in the following topics.

  • Monochrome Light Maps
  • Color Light Maps
  • Specular Light Maps
  • Diffuse Light Maps


Monochrome Light Maps

Some older 3-D accelerator boards do not support texture blending using the alpha value of the destination pixel. See Alpha Texture Blending for more information. These adapters also generally do not support multiple texture blending. If your application is running on an adapter such as this, it can use multipass texture blending to perform monochrome light mapping.

To perform monochrome light mapping, an application stores the lighting information in the alpha data of its light map textures. The application uses the texture filtering capabilities of Microsoft® Direct3D® to perform a mapping from each pixel in the primitive's image to a corresponding texel in the light map. It sets the source blending factor to the alpha value of the corresponding texel.

The following C++ code example illustrates how an application can use a texture as a monochrome light map.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice7 interface and that lptexLightMap is a valid
// pointer to a texture that contains monochrome light map data.

// Set the light map texture as the current texture.
d3dDevice->SetTexture(0, lptexLightMap);

// Set the color operation.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);

// Set argument 1 to the color operation.
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1,
       D3DTA_TEXTURE | D3DTA_ALPHAREPLICATE);

Because display adapters that do not support destination alpha blending usually do not support multiple texture blending, this example sets the light map as the first texture, which is available on all 3-D accelerator cards. The sample code sets the color operation for the texture's blending stage to blend the texture data with the primitive's existing color. It then selects the first texture and the primitive's existing color as the input data.


Color Light Maps

Your application will usually render 3-D scenes more realistically if it uses colored light maps. A colored light map uses the RGB data in the light map for its lighting information.

The following C++ code example demonstrates light mapping with RGB color data.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice8 interface and that lptexLightMap is a valid
// pointer to a texture that contains RGB light map data.

// Set the light map texture as the first texture.
d3dDevice->SetTexture(0, lptexLightMap);

d3dDevice->SetTextureStageState( 0,D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState( 0,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState( 0,D3DTSS_COLORARG2, D3DTA_DIFFUSE );

This example sets the light map as the first texture. It then sets the state of the first blending stage to modulate the incoming texture data. It uses the first texture and the current color of the primitive as the arguments to the modulate operation.


Specular Light Maps

When illuminated by a light source, shiny objects—those that use highly reflective materials—receive specular highlights. In some cases, the specular highlights produced by the lighting module is not accurate. To produce a more appealing highlight, many Microsoft® Direct3D® applications apply specular light maps to primitives.

To perform specular light mapping, first modulate the specular light map with the primitive's existing texture. Then add the monochrome or RGB light map.

The following code example illustrates this process in C++.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice8 interface.
// lptexBaseTexture is a valid pointer to a texture.
// lptexSpecLightMap is a valid pointer to a texture that contains RGB
// specular light map data.
// lptexLightMap is a valid pointer to a texture that contains RGB
// light map data.

// Set the base texture.
d3dDevice->SetTexture(0, lptexBaseTexture );

// Set the base texture operation and arguments.
d3dDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );

// Set the specular light map.
d3dDevice->SetTexture(1, lptexSpecLightMap);

// Set the specular light map operation and args.
d3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_ADD );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT );

// Set the RGB light map.
d3dDevice->SetTexture(2, lptexLightMap);

// Set the RGB light map operation and arguments.
d3dDevice->SetTextureStageState(2,D3DTSS_COLOROP, D3DTOP_MODULATE);
d3dDevice->SetTextureStageState(2,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(2,D3DTSS_COLORARG2, D3DTA_CURRENT );


Diffuse Light Maps

When illuminated by a light source, matte surfaces display diffuse light reflection. The brightness of diffuse light depends on the distance from the light source and the angle between the surface normal and the light source direction vector. The diffuse lighting effects simulated by lighting calculations produce only general effects.

Your application can simulate more complex diffuse lighting with texture light maps. Do this by adding the diffuse light map to the base texture, as shown in the following C++ code example.

// This example assumes that d3dDevice is a valid pointer to an
// IDirect3DDevice8 interface.
// lptexBaseTexture is a valid pointer to a texture.
// lptexDiffuseLightMap is a valid pointer to a texture that contains
// RGB diffuse light map data.

// Set the base texture.
d3dDevice->SetTexture(0,lptexBaseTexture );

// Set the base texture operation and args.
d3dDevice->SetTextureStageState(0,D3DTSS_COLOROP,
       D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(0,D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(0,D3DTSS_COLORARG2, D3DTA_DIFFUSE );

// Set the diffuse light map.
d3dDevice->SetTexture(1,lptexDiffuseLightMap );

// Set the blend stage.
d3dDevice->SetTextureStageState(1, D3DTSS_COLOROP, D3DTOP_MODULATE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
d3dDevice->SetTextureStageState(1, D3DTSS_COLORARG2, D3DTA_CURRENT );


Compressed Texture Resources

Microsoft® Direct3D® provides services to compress surfaces that are used for texturing 3-D models. This section provides information on creating and manipulating the data in a compressed texture surface.

Information is contained in the following topics.

  • What Are Compressed Textures?
  • Compressed Texture Formats
  • Using Compressed Textures


What Are Compressed Textures?

Texture maps are digitized images drawn on three-dimensional shapes to add visual detail. They are mapped onto these shapes during rasterization, and the process can consume large amounts of both the system bus and memory. To reduce the amount of memory consumed by textures, Microsoft® Direct3D® supports the compression of texture surfaces. Some Direct3D devices support compressed texture surfaces natively. On such devices, once you have created a compressed surface and loaded the data into it, the surface can be used in Direct3D like any other texture surface. Direct3D handles decompression when the texture is mapped to a 3-D object.


Compressed Texture Formats

This section contains information on the internal organization of compressed texture formats. You do not need these details to use compressed textures, because you can use D3DX functions for conversion to and from compressed formats. However, this information is useful if you want to operate on compressed surface data directly.

Direct3D uses a compression format that divides texture maps into 4x4 texel blocks. If the texture contains no transparency—is opaque—or if the transparency is specified by a one-bit alpha, an 8-byte block represents the texture map block. If the texture map does contain transparent texels, using an alpha channel, a 16-byte block represents it.

  • Opaque and One-Bit Alpha Textures
  • Textures with Alpha Channels
  • Understanding Storage Efficiency and Texture Compression
  • Mixing Formats Within a Single Texture

Note Any single texture must specify that its data is stored as 64 or 128 bits per group of 16 texels. If 64-bit blocks—that is, format DXT1—are used for the texture, it is possible to mix the opaque and one-bit alpha formats on a per-block basis within the same texture. In other words, the comparison of the unsigned integer magnitude of color_0 and color_1 is performed uniquely for each block of 16 texels.

When 128-bit blocks are used, the alpha channel must be specified in either explicit (format DXT2 or DXT3) or interpolated mode (format DXT4 or DXT5) for the entire texture. As with color, once interpolated mode is selected, either eight interpolated alphas or six interpolated alphas mode can be used on a block-by-block basis. Again the magnitude comparison of alpha_0 and alpha_1 is done uniquely on a block-by-block basis.

The pitch for DXTn formats is different from what was returned in DirectX 7. It now refers the pitch of a row of blocks. For example, if you have a width of 16, then you will have a pitch of four blocks (4*8 for DXT1, 4*16 for DXT2-5.)


Opaque and One-Bit Alpha Textures

Texture format DXT1 is for textures that are opaque or have a single transparent color.

For each opaque or one-bit alpha block, two 16-bit values (RGB 5:6:5 format) and a 4x4 bitmap with 2-bits-per-pixel are stored. This totals 64 bits for 16 texels, or four bits per texel. In the block bitmap, there are two bits per texel to select between the four colors, two of which are stored in the encoded data. The other two colors are derived from these stored colors by linear interpolation. This layout is shown in the following diagram.

The one-bit alpha format is distinguished from the opaque format by comparing the two 16-bit color values stored in the block. They are treated as unsigned integers. If the first color is greater than the second, it implies that only opaque texels are defined. This means four colors are used to represent the texels. In four-color encoding, there are two derived colors and all four colors are equally distributed in RGB color space. This format is analogous to RGB 5:6:5 format. Otherwise, for one-bit alpha transparency, three colors are used and the fourth is reserved to represent transparent texels.

In three-color encoding, there is one derived color and the fourth two-bit code is reserved to indicate a transparent texel (alpha information). This format is analogous to RGBA 5:5:5:1, where the final bit is used for encoding the alpha mask.

The following code example illustrates the algorithm for deciding whether three- or four-color encoding is selected.

if (color_0 > color_1)
{
    // Four-color block: derive the other two colors.
    // 00 = color_0, 01 = color_1, 10 = color_2, 11 = color_3
    // These 2-bit codes correspond to the 2-bit fields
    // stored in the 64-bit block.
    color_2 = (2 * color_0 + color_1 + 1) / 3;
    color_3 = (color_0 + 2 * color_1 + 1) / 3;
}
else
{
    // Three-color block: derive the other color.
    // 00 = color_0,  01 = color_1,  10 = color_2,
    // 11 = transparent.
    // These 2-bit codes correspond to the 2-bit fields
    // stored in the 64-bit block.
     color_2 = (color_0 + color_1) / 2;
     color_3 = transparent;

}

It is recommended that you set the RGBA components of the transparency pixel to zero before blending.

The following tables show the memory layout for the 8-byte block. It is assumed that the first index corresponds to the y-coordinate and the second corresponds to the x-coordinate. For example, Texel[1][2] refers to the texture map pixel at (x,y) = (2,1).

This table contains the memory layout for the 8-byte (64-bit) block.

Word address | 16-bit word
0 | Color_0
1 | Color_1
2 | Bitmap Word_0
3 | Bitmap Word_1

Color_0 and Color_1—the colors at the two extremes—are laid out as follows:

Bits | Color
4:0 (LSB) | Blue color component
10:5 | Green color component
15:11 | Red color component

Bitmap Word_0 is laid out as follows:

Bits | Texel
1:0 (LSB) | Texel[0][0]
3:2 | Texel[0][1]
5:4 | Texel[0][2]
7:6 | Texel[0][3]
9:8 | Texel[1][0]
11:10 | Texel[1][1]
13:12 | Texel[1][2]
15:14 (MSB) | Texel[1][3]

Bitmap Word_1 is laid out as follows:

Bits | Texel
1:0 (LSB) | Texel[2][0]
3:2 | Texel[2][1]
5:4 | Texel[2][2]
7:6 | Texel[2][3]
9:8 | Texel[3][0]
11:10 | Texel[3][1]
13:12 | Texel[3][2]
15:14 (MSB) | Texel[3][3]

Example of Opaque Color Encoding

As an example of opaque encoding, assume that the colors red and black are at the extremes. Red is color_0, and black is color_1. There are four interpolated colors that form the uniformly distributed gradient between them. To determine the values for the 4x4 bitmap, the following calculations are used.

00 ? color_0
01 ? color_1
10 ? 2/3 color_0 + 1/3 color_1
11 ? 1/3 color_0 + 2/3 color_1

The bitmap then looks like the following graphic.

This looks like the following series of colors.

Example of One-Bit Alpha Encoding

This format is selected when the unsigned 16-bit integer, color_0, is less than the unsigned 16-bit integer, color_1. An example of where this format can be used is leaves on a tree, shown against a blue sky. Some texels can be marked as transparent while three shades of green are still available for the leaves. Two colors fix the extremes, and the third is an interpolated color.

Here is an example of such a picture.

Note that where the image is shown as white, the texel would be encoded as transparent. Also note that the RGBA components of the transparent texels should be set to zero before blending.

The bitmap encoding for the colors and the transparency is determined using the following calculations.

00 ? color_0
01 ? color_1
10 ? 1/2 color_0 + 1/2 color_1
11   ?   Transparent

The bitmap then looks like the following graphic.


Textures with Alpha Channels

There are two ways to encode texture maps that exhibit more complex transparency. In each case, a block that describes the transparency precedes the 64-bit block already described. The transparency is either represented as a 4x4 bitmap with four bits per pixel (explicit encoding), or with fewer bits and linear interpolation that is analogous to what is used for color encoding.

The transparency block and the color block are arranged as shown in the following table.

Word Address | 64-bit Block
3:0 | Transparency block
7:4 | Previously described 64-bit block

Explicit Texture Encoding

For explicit texture encoding (DXT2 and DXT3 formats), the alpha components of the texels that describe transparency are encoded in a 4x4 bitmap with 4 bits per texel. These four bits can be achieved through a variety of means such as dithering or by simply using the four most significant bits of the alpha data. However they are produced, they are used just as they are, without any form of interpolation.

The following diagram shows a 64-bit transparency block.

Note The compression method of Microsoft® Direct3D® uses the four most significant bits.

The following tables illustrate how the alpha information is laid out in memory, for each 16-bit word.

This table contains the layout for Word 0.

Bits | Alpha
3:0 (LSB) | [0][0]
7:4 | [0][1]
11:8 | [0][2]
15:12 (MSB) | [0][3]

This table contains the layout for Word 1.

Bits | Alpha
3:0 (LSB) | [1][0]
7:4 | [1][1]
11:8 | [1][2]
15:12 (MSB) | [1][3]

This table contains the layout for Word 2.

Bits | Alpha
3:0 (LSB) | [2][0]
7:4 | [2][1]
11:8 | [2][2]
15:12 (MSB) | [2][3]

This table contains the layout for Word 3.

Bits | Alpha
3:0 (LSB) | [3][0]
7:4 | [3][1]
11:8 | [3][2]
15:12 (MSB) | [3][3]

The difference between DXT2 and DXT3 is that in the DXT2 format it is assumed that the color data has been premultiplied by alpha. In the DXT3 format it is assumed the color is not premultiplied by alpha. These two formats are needed because in most cases by the time a texture is used, simply examining the data is not sufficient to determine if the color values have been multiplied by alpha. Because this information is needed at run time, the two FOURCC codes are used to differentiate these cases. However, the data and interpolation method used for these two formats is identical.

The color compare used in DXT1 to determine if the texel is transparent is not used in this format. It is assumed that without the color compare the color data is always treated as if in 4-color mode. In other words, the if statement at the top of the DXT1 code should be the following:

if ((color_0 > color_1) OR !DXT1) {

Three-Bit Linear Alpha Interpolation

The encoding of transparency for the DXT4 and DXT5 formats is based on a concept similar to the linear encoding used for color. Two 8-bit alpha values and a 4x4 bitmap with three bits per pixel are stored in the first eight bytes of the block. The representative alpha values are used to interpolate intermediate alpha values. Additional information is available in the way the two alpha values are stored. If alpha_0 is greater than alpha_1, then six intermediate alpha values are created by the interpolation. Otherwise, four intermediate alpha values are interpolated between the specified alpha extremes. The two additional implicit alpha values are 0 (fully transparent) and 255 (fully opaque).

The following code example illustrates this algorithm.

// 8-alpha or 6-alpha block?
if (alpha_0 > alpha_1) {
    // 8-alpha block:  derive the other six alphas.
    // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated.
    alpha_2 = (6 * alpha_0 + 1 * alpha_1 + 3) / 7;    // bit code 010
    alpha_3 = (5 * alpha_0 + 2 * alpha_1 + 3) / 7;    // bit code 011
    alpha_4 = (4 * alpha_0 + 3 * alpha_1 + 3) / 7;    // bit code 100
    alpha_5 = (3 * alpha_0 + 4 * alpha_1 + 3) / 7;    // bit code 101
    alpha_6 = (2 * alpha_0 + 5 * alpha_1 + 3) / 7;    // bit code 110
    alpha_7 = (1 * alpha_0 + 6 * alpha_1 + 3) / 7;    // bit code 111
}
else {
    // 6-alpha block.
    // Bit code 000 = alpha_0, 001 = alpha_1, others are interpolated.
    alpha_2 = (4 * alpha_0 + 1 * alpha_1 + 2) / 5;    // Bit code 010
    alpha_3 = (3 * alpha_0 + 2 * alpha_1 + 2) / 5;    // Bit code 011
    alpha_4 = (2 * alpha_0 + 3 * alpha_1 + 2) / 5;    // Bit code 100
    alpha_5 = (1 * alpha_0 + 4 * alpha_1 + 2) / 5;    // Bit code 101
    alpha_6 = 0;                                      // Bit code 110
    alpha_7 = 255;                                    // Bit code 111
}

The memory layout of the alpha block is as follows:

Byte | Alpha
0 | Alpha_0
1 | Alpha_1
2 | [0][2] (2 LSBs), [0][1], [0][0]
3 | [1][1] (1 LSB), [1][0], [0][3], [0][2] (1 MSB)
4 | [1][3], [1][2], [1][1] (2 MSBs)
5 | [2][2] (2 LSBs), [2][1], [2][0]
6 | [3][1] (1 LSB), [3][0], [2][3], [2][2] (1 MSB)
7 | [3][3], [3][2], [3][1] (2 MSBs)

The difference between DXT4 and DXT5 is that in the DXT4 format it is assumed that the color data has been premultiplied by alpha. In the DXT5 format, it is assumed the color is not premultiplied by alpha. These two formats are needed because, in most cases, by the time a texture is used simply examining the data is not sufficient to determine if the color values have been multiplied by alpha. Because this information is needed at run time, the two FOURCC codes are used to differentiate these cases. However, the data and interpolation method used for these two formats is identical.

The color compare used in DXT1 to determine if the texel is transparent is not used with these formats. It is assumed that without the color compare the color data is always treated as if in 4-color mode. In other words the if statement at the top of the DXT1 code should be:

if ((color_0 > color_1) OR !DXT1) {


Understanding Storage Efficiency and Texture Compression

All texture compression formats are powers of 2. While this does not mean that a texture is necessarily square, it does mean that both X and Y are powers of 2. For example, if a texture is originally 512×128 bytes, then the next mipmapping would be 256×64 and so on, with each level decreasing by a power of 2. At lower levels, where the texture is filtered to 16×2 and 8×1, there will be wasted bits because the compression block is always a 4×4 block of texels. Unused portions of the block are padded. Although there are wasted bits at the lowest levels, the overall gain is still significant. The worst case is, in theory, a 2K×1 texture (20 power). Here, only a single row of pixels is encoded per block, while the rest of the block is unused.


Mixing Formats Within a Single Texture

It is important to note that any single texture must specify that its data is stored as 64 or 128 bits per group of 16 texels. If 64-bit blocks—that is, format DXT1—are used for the texture, it is possible to mix the opaque and one-bit alpha formats on a per-block basis within the same texture. In other words, the comparison of the unsigned integer magnitude of color_0 and color_1 is performed uniquely for each block of 16 texels.

Once the 128-bit blocks are used, the alpha channel must be specified in either explicit (format DXT2 and DXT3) or interpolated mode (format DXT4 and DXT5) for the entire texture. As with color, once interpolated mode (format DXT4 and DXT5) is selected, then either eight interpolated alphas or six interpolated alphas mode can be used on a block-by-block basis. Again the magnitude comparison of alpha_0 and alpha_1 is done uniquely on a block-by-block basis.


Using Compressed Textures

This section explains how to use compressed textures in a Microsoft® Direct3D® application.

Information is divided into the following topics.

  • Determining Support for Compressed Textures
  • Creating Compressed Textures
  • Decompressing Compressed Textures


Determining Support for Compressed Textures

Before your application creates a rendering device, it can determine if the device supports texturing from compressed texture surfaces by calling the IDirect3D8::CheckDeviceFormat method. This method determines whether a surface format can be used as a texture on a device representing the adapter. To test the adapter, specify any pixel format that uses the DXT1, DXT2, DXT3, DXT4, or DXT5 four character codes (FOURCCs). If CheckDeviceFormat returns D3D_OK, the device can create texture directly from a compressed texture surface that uses that format. If so, you can use compressed texture surfaces directly with Microsoft® Direct3D® by calling the IDirect3DDevice8::SetTexture method. The following code example shows how to determine if the adapter supports the D3DFMT_DXT1 compressed texture format.

BOOL IsCompressedTextureFormatOk( D3DFORMAT TextureFormat,
                                  D3DFORMAT AdapterFormat ) {
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          0,
                                          D3DRTYPE_TEXTURE,
                                          D3DFMT_DXT1);

    return SUCCEEDED( hr );
}

If the device does not support texturing from compressed texture surfaces, you can still store texture data in a compressed format surface, but you must convert any compressed textures to a supported format before they can be used for texturing.


Creating Compressed Textures

After creating a device that supports a compressed texture format on the adapter, you can create a compressed texture resource. Call IDirect3DDevice8::CreateTexture and specify a compressed texture format for the Format parameter.

Before loading an image into a texture object, retrieve a pointer to the texture surface by calling the IDirect3DTexture8::GetSurfaceLevel method.

Now you can use any D3DX function that begins with D3DXLoadSurface to load an image into the surface that was retrieved by using GetSurfaceLevel. These functions handle conversion to and from compressed texture formats.

You can create and convert compressed texture (DDS) files using the DXTex Tool supplied with the SDK. You can also create your own DDS files.

The advantage of this behavior is that an application can copy the contents of a compressed surface to a file without calculating how much storage is required for a surface of a particular width and height in the specific format.

The following table shows the five types of compressed textures. For more information on how the data is stored, see Compressed Texture Formats. You only need this information if you are writing your own compression routines.

FOURCC | Description | Alpha-premultiplied?
DXT1 | Opaque / one-bit alpha | N/A
DXT2 | Explicit alpha | Yes
DXT3 | Explicit alpha | No
DXT4 | Interpolated alpha | Yes
DXT5 | Interpolated alpha | No

Note When you transfer data from a non-premultiplied format to a premultiplied format, Direct3D scales the colors based on the alpha values. Transferring data from a premultiplied format to a non-premultiplied format is not supported. If you try to transfer data from a premultiplied-alpha source to a non-premultiplied-alpha destination, the method returns D3DERR_INVALIDCALL. If you transfer data from a premultiplied-alpha source to a destination that has no alpha, the source color components, which have been scaled by alpha, are copied as is.


Decompressing Compressed Textures

As with compressing a texture surface, decompressing a compressed texture is performed through Microsoft® Direct3D® copying services.

If the driver supports the creation of compressed video-memory surfaces, then the driver can also decompress copies from a compressed video-memory surface to an uncompressed video- or system-memory surface.

Copies from compressed system-memory surfaces to uncompressed video-memory surfaces are largely unsupported and should not be attempted, even when the driver supports compressed textures. This does not mean that it is impossible to decompress a compressed system-memory surface and move its contents into a video-memory surface; it merely requires an additional step.

To decompress a system-memory surface into video memory

  1. Create an uncompressed, off-screen plain surface in system memory of the desired dimensions and pixel format.
  2. Copy from the compressed system-memory surface to the uncompressed system-memory surface.
  3. Copy the uncompressed surface to the uncompressed video-memory surface.


Volume Texture Resources

Volume textures are discussed in the following topics.

  • What Are Volume Textures?
  • Using Volume Textures


What Are Volume Textures?

Volume textures are three-dimensional collections of pixels (texels) that can be used to paint a two-dimensional primitive such as a triangle or a line. Three-element texture coordinates are required for each vertex of a primitive that is to be textured with a volume. As the primitive is drawn, each contained pixel is filled with the color value from some pixel within the volume, in accordance with rules analogous to the two-dimensional texture case. Volumes are not rendered directly because there are no three-dimensional primitives that can be painted with them.

You can use volume textures for special effects such as patchy fog, explosions, and so on.

Volumes are organized into slices and can be thought of as width x height 2-D surfaces stacked to make a width x height x depth volume. Each slice is a single row. Volumes can have subsequent levels, in which the dimensions of each level are truncated to half the dimensions of the previous level. The illustration below gives an idea of what a volume texture with multiple levels looks like.


Using Volume Textures

The code examples below show the steps required to use a volume texture.

First, specify a custom vertex type that has three texture coordinates for each vertex, as shown in this code example.

struct VOLUMEVERTEX
{
    FLOAT x, y, z;
    DWORD color;
    FLOAT tu, tv, tw;
};

#define D3DFVF_VOLUMEVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|
                             D3DFVF_TEX1|D3DFVF_TEXCOORDSIZE3(0))

Next, fill the vertices with data.

VOLUMEVERTEX g_vVertices[4] =
{
    { 1.0f, 1.0f, 0.0f, 0xffffffff, 1.0f, 1.0f, 0.0f },
    {-1.0f, 1.0f, 0.0f, 0xffffffff, 0.0f, 1.0f, 0.0f },
    { 1.0f,-1.0f, 0.0f, 0xffffffff, 1.0f, 0.0f, 0.0f },
    {-1.0f,-1.0f, 0.0f, 0xffffffff, 0.0f, 0.0f, 0.0f }
};

Now, create a vertex buffer and fill it with data from the vertices.

The next step is to use the IDirect3DDevice8::CreateVolumeTexture method to create a volume texture, as shown in this code example.

LPDIRECT3DVOLUMETEXTURE8 volTexture;

d3dDevice->CreateVolumeTexture( 8, 4, 4, 1, 0, D3DFMT_R8G8B8,
                                D3DPOOL_MANAGED, &volTexture );

Before rendering the primitive, set the current texture to the volume texture created above. The code example below shows the entire rendering process for a strip of triangles.

if( SUCCEEDED( d3dDevice->BeginScene() ) )
{
    // Draw the quad, with the volume texture.
    d3dDevice->SetTexture( 0, pVolumeTexture );
    d3dDevice->SetVertexShader( D3DFVF_VOLUMEVERTEX );
    d3dDevice->SetStreamSource( 0, pVB, sizeof(VOLUMEVERTEX) );
    d3dDevice->DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2);

   // End the scene.
   d3dDevice->EndScene();
}


Automatic Texture Management

Texture management is the process of determining which textures are needed for rendering at a given time and ensuring that those textures are loaded into video memory. As with any algorithm, texture management schemes vary in complexity, but any approach to texture management involves the following key tasks.

  • Tracking the amount of available texture memory.
  • Calculating which textures are needed for rendering, and which are not.
  • Determining which existing texture resources can be reloaded with another texture image, and which surfaces should be destroyed and replaced with new texture resources.

Microsoft® Direct3D® implements system-supported texture management to ensure that textures are loaded for optimal performance. Texture resources that Direct3D manages are referred to as managed textures.

The texture manager tracks textures with a time-stamp that identifies when the texture was last used. It then uses a least-recently-used algorithm to determine which textures should be removed. Texture priorities are used as tie breakers when two textures are targeted for removal from memory. If two textures have the same priority value, the least-recently-used texture is removed. However, if two textures have the same time-stamp, the texture that has a lower priority is removed first.

You request automatic texture management for texture surfaces when you create them. To retrieve a managed texture in a C++ application, create a texture resource by calling IDirect3DDevice8::CreateTexture and specifying the D3DPOOL_MANAGED for the Pool parameter. You are not allowed to specify where you want the texture created. You cannot use the D3DPOOL_DEFAULT or D3DPOOL_SYSTEMMEM flags when creating a managed texture. After creating the managed texture, you can call the IDirect3DDevice8::SetTexture method to set it to a stage in the rendering device's texture cascade.

You can assign a priority to managed textures by calling the IDirect3DResource8::SetPriority method for the texture surface.

Direct3D automatically downloads textures into video memory as needed. The system might cache managed textures in local or nonlocal video memory, depending on the availability of nonlocal video memory or other factors. The cache location of your managed textures is not communicated to your application, nor is this information required to use automatic texture management. If your application uses more textures than can fit in video memory, Direct3D removes older textures from video memory to make room for the new textures. If you use a removed texture again, the system uses the original system-memory texture surface to reload the texture in the video-memory cache. Although reloading the texture is necessary, it also decreases the application's performance.

You can dynamically modify the original system-memory copy of the texture by updating or locking the texture resource. When the system detects a dirty surface—after an update is completed, or when the surface is unlocked—the texture manager automatically updates the video-memory copy of the texture. The performance hit incurred is similar to reloading a removed texture.

When entering a new level in a game, your application might need to flush all managed textures from video memory. You can explicitly request to remove all managed textures by calling the IDirect3DDevice8::ResourceManagerDiscardBytes method and specifying a value of 0 for the Bytes parameter. When you call this method, Direct3D destroys any cached local and nonlocal video-memory textures, but leaves the original system-memory copies untouched.

For more information on resource management, see Managing Resources.


Hardware Considerations for Texturing

Current hardware does not necessarily implement all the functionality that the Microsoft® Direct3D® interface enables. Your application must test user hardware and adjust its rendering strategies accordingly.

Many 3-D accelerator cards do not support diffuse iterated values as arguments to blending units. However, your application can introduce iterated color data when it performs texture blending.

Some 3-D hardware may not have a blending stage associated with the first texture. On these adapters, your application must perform blending in the second and third texture stages in the set of current textures.

Due to limitations in much of today's hardware, few display adapters can perform trilinear mipmap interpolation through the multiple texture blending interface offered by IDirect3DDevice8. Specifically, there is little support for setting the D3DTSS_MIPFILTER texture stage state to D3DTEXF_LINEAR. Your application can use multipass texture blending to achieve the same effects, or degrade to the D3DTEXF_POINT mipmap filter mode, which is widely supported.


Depth Buffers

This section presents information on using depth buffers for hidden line and hidden surface removal. It is organized into the following topics.

  • What Are Depth Buffers?
  • Using Depth Buffers


What Are Depth Buffers?

A depth buffer, often called a z-buffer or a w-buffer, is a property of the device that stores depth information to be used by Microsoft® Direct3D®. When Direct3D renders a 3-D scene to a target surface, it can use the memory in an associated depth-buffer surface as a workspace to determine how the pixels of rasterized polygons occlude one another. Direct3D uses an off-screen Direct3D surface as the target to which final color values are written. The depth-buffer surface that is associated with the render-target surface is used to store depth information that tells Direct3D how deep each visible pixel is in the scene.

When a 3-D scene is rasterized with depth buffering enabled, each point on the rendering surface is tested. The values in the depth buffer can be a point's z-coordinate or its homogeneous w-coordinate—from the point's (x,y,z,w) location in projection space. A depth buffer that uses z values is often called a z-buffer, and one that uses w values is called a w-buffer. Each type of depth buffer has advantages and disadvantages, which are discussed later.

At the beginning of the test, the depth value in the depth buffer is set to the largest possible value for the scene. The color value on the rendering surface is set to either the background color value or the color value of the background texture at that point. Each polygon in the scene is tested to see if it intersects with the current coordinate (x,y) on the rendering surface. If it does, the depth value—which will be the z coordinate in a z-buffer, and the w coordinate in a w-buffer—at the current point is tested to see if it is smaller than the depth value stored in the depth buffer. If the depth of the polygon value is smaller, it is stored in the depth buffer and the color value from the polygon is written to the current point on the rendering surface. If the depth value of the polygon at that point is larger, the next polygon in the list is tested. This process is shown in the following illustration.

Note Although most applications don't use this feature, you can change the comparison that Direct3D uses to determine which values are placed in the depth buffer and subsequently the render-target surface. To do so, change the value for the D3DRS_ZFUNC render state.

Nearly all 3-D accelerators on the market support z-buffering, making z-buffers the most common type of depth buffer today. However ubiquitous, z-buffers have their drawbacks. Due to the mathematics involved, the generated z values in a z-buffer tend not to be distributed evenly across the z-buffer range (typically 0.0 to 1.0, inclusive). Specifically, the ratio between the far and near clipping planes strongly affects how unevenly z values are distributed. Using a far-plane distance to near-plane distance ratio of 100, 90% of the depth buffer range is spent on the first 10% of the scene depth range. Typical applications for entertainment or visual simulations with exterior scenes often require far-plane/near-plane ratios of anywhere between 1000 to 10000. At a ratio of 1000, 98% of the range is spent on the 1st 2% of the depth range, and the distribution becomes worse with higher ratios. This can cause hidden surface artifacts in distant objects, especially when using 16-bit depth buffers, the most commonly supported bit-depth.

A w-based depth buffer, on the other hand, is often more evenly distributed between the near and far clip planes than a z-buffer. The key benefit is that the ratio of distances for the far and near clipping planes is no longer an issue. This allows applications to support large maximum ranges, while still getting relatively accurate depth buffering close to the eye point. A w-based depth buffer isn't perfect, and can sometimes exhibit hidden surface artifacts for near objects. Another drawback to the w-buffered approach is related to hardware support: w-buffering isn't supported as widely in hardware as z-buffering.

Z-buffering requires overhead during rendering. Various techniques can be used to optimized rendering when using z-buffers. For details, see Z-Buffer Performance.

Note The actual interpretation of a depth value is specific to the 3-D renderer.


Using Depth Buffers

The following topics discuss common usage scenarios for depth buffers.

  • Querying for Depth Buffer Support
  • Creating a Depth Buffer
  • Enabling Depth Buffering
  • Retrieving a Depth Buffer
  • Clearing Depth Buffers
  • Changing Depth Buffer Write Access
  • Changing Depth Buffer Comparison Functions
  • Using Z-Bias

See Also

What Are Depth Buffers?


Querying for Depth Buffer Support

As with any feature, the driver that your application uses might not support all types of depth buffering. Always check the driver's capabilities. Although most drivers support z-based depth buffering, not all will support w-based depth buffering. Drivers do not fail if you attempt to enable an unsupported scheme. They fall back on another depth buffering method instead, or sometimes disable depth buffering altogether, which can result in scenes rendered with extreme depth-sorting artifacts.

You can check for general support for depth buffers by querying Microsoft® Direct3D® for the display device that your application will use before you create a Direct3D device. If the Direct3D object reports that it supports depth buffering, any hardware devices you create from this Direct3D object will support z-buffering.

To query for general depth buffering support in a C++ application

To query for depth buffering support, you can use the IDirect3D8::CheckDeviceFormat method, as shown in the following code example.

// The following example assumes that pCaps is a valid pointer to an
// initialized D3DCAPS8 structure.
    if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal,
                                           pCaps->DeviceType, Format,
                                           D3DUSAGE_DEPTHSTENCIL,
                                           D3DRTYPE_SURFACE,
                                           D3DFMT_D16 ) ) )
        return E_FAIL;

CheckDeviceFormat allows you to choose a device to create based on the capabilities of that device. In this case, devices that do not support 16-bit depth buffers are rejected.

In addition, you can use IDirect3D8::CheckDepthStencilMatch to determine whether a supported depth-stencil format is compatible with the render target format in the display mode, particularly if a depth format must be equal to the render target format.

Using CheckDepthStencilMatch to determine depth-stencil compatibility with a render target is illustrated in the following code example.

// Reject devices that cannot create a render target of RTFormat while
// the back buffer is of RTFormat and the depth-stencil buffer is
// at least 8 bits of stencil.
if( FAILED( m_pD3D->CheckDepthStencilMatch( pCaps->AdapterOrdinal,
                                            pCaps->DeviceType,
                                            AdapterFormat,
                                            RTFormat,
                                            D3DFMT_D24S8 ) ) )
        return E_FAIL;

Once you know that the driver supports depth buffers, you can verify w-buffer support. Although depth buffers are supported for all software rasterizers, w-buffers are supported only by the reference rasterizer, which is not suited for use by real-world applications. Regardless of the type of device your application uses, verify support for w-buffers before you attempt to enable w-based depth buffering.

To determine support for w-buffers in a C++ application

  1. After creating your device, call the IDirect3DDevice8::GetDeviceCaps method, passing an initialized D3DCAPS8 structure.
  2. After the call, the LineCaps member contains information about the driver's support for rendering primitives.
  3. If the RasterCaps member of this structure contains the D3DPRASTERCAPS_WBUFFER flag, then the driver supports w-based depth buffering for that primitive type.

For general information about depth buffering, see What Are Depth Buffers?


Creating a Depth Buffer

A depth buffer is a property of the device. To create a depth buffer that is managed by Microsoft® Direct3D®, set the appropriate members of the D3DPRESENT_PARAMETERS structure as shown in the following code example.

    D3DPRESENT_PARAMETERS d3dpp;

    ZeroMemory( &d3dpp, sizeof(d3dpp) );
    d3dpp.Windowed               = TRUE;
    d3dpp.SwapEffect             = D3DSWAPEFFECT_COPY_VSYNC;
    d3dpp.EnableAutoDepthStencil = TRUE;
    d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

By setting the EnableAutoDepthStencil member to TRUE, you instruct Direct3D to manage depth buffers for the application. Note that AutoDepthStencilFormat must be set to a valid depth buffer format. The D3DFMT_D16 flag specifies a 16-bit depth buffer, if one is available.

The following call to the IDirect3D8::CreateDevice method creates a device that then creates a depth buffer.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                  &d3dpp, &d3dDevice ) ) )
    return E_FAIL;

The depth buffer is automatically set as the render target of the device. When the device is reset, the depth buffer is automatically destroyed and recreated in the new size.

To create a new depth buffer surface, use the IDirect3DDevice8::CreateDepthStencilSurface method.

To set a new depth-buffer surface for the device, use the IDirect3DDevice8::SetRenderTarget method.

To use the depth buffer in your application, you need to enable the depth buffer. For details, see Enabling Depth Buffering.


Enabling Depth Buffering

After you create a depth buffer, as described in Creating a Depth Buffer, you enable depth buffering by calling the IDirect3DDevice8::SetRenderState method. Set the D3DRS_ZENABLE render state to enable depth-buffering. Use the D3DZB_TRUE member of the D3DZBUFFERTYPE enumerated type (or TRUE) to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE (or FALSE) to disable depth buffering.

Note To use w-buffering, your application must set a compliant projection matrix even if it doesn't use the Microsoft® Direct3D® transformation pipeline. For information about providing an appropriate projection matrix, see A W-Friendly Projection Matrix. The projection matrix discussed in What Is the Projection Transformation? is compliant.


Retrieving a Depth Buffer

The following code example shows how to use the IDirect3DDevice8::GetDepthStencilSurfacemethod to retrieve a pointer to the depth-buffer surface owned by the device.

    LPDIRECT3DSURFACE8 pZBuffer;

    m_d3dDevice->GetDepthStencilSurface( &pZBuffer );


Clearing Depth Buffers

Many C++ applications clear the depth buffer before rendering each new frame. You can explicitly clear the depth buffer through Microsoft® Direct3D® by calling IDirect3DDevice8::Clear and specifying D3DCLEAR_ZBUFFER for the Flags parameter. The Clear method allows you to specify an arbitrary depth value in the Z parameter.


Changing Depth Buffer Write Access

By default, the Microsoft® Direct3D® system is allowed to write to the depth buffer. Most applications leave writing to the depth buffer enabled, but you can achieve some special effects by not allowing the Direct3D system to write to the depth buffer.

You can disable depth buffer writes in C++ by calling the IDirect3DDevice8::SetRenderState method with the State parameter set to D3DRS_ZWRITEENABLE and the Value parameter set to 0.


Changing Depth Buffer Comparison Functions

By default, when depth-testing is performed on a rendering surface, the Microsoft® Direct3D® system updates the render-target surface if the corresponding depth value (z or w) for each point is less than the value in the depth buffer. In a C++ application, you change how the system performs comparisons on depth values by calling the IDirect3DDevice8::SetRenderState method with the State parameter set to D3DRS_ZFUNC. The Value parameter should be set to a value in the D3DCMPFUNC enumerated type.


Using Z-Bias

Polygons that are coplanar in your 3-D space can be made to appear as if they are not coplanar by adding a z-bias to each one. This is a technique commonly used to ensure that shadows in a scene are displayed properly. For instance, a shadow on a wall will likely have the same depth value as the wall does. If you render the wall first and then the shadow, the shadow might not be visible, or depth artifacts might be visible. You can reverse the order in which you render the coplanar objects in hopes of reversing the effect, but depth artifacts are still likely.

A C++ application can help ensure that coplanar polygons are rendered properly by adding a bias to the z-values that the system uses when rendering the sets of coplanar polygons. To add a z-bias to a set of polygons, call the IDirect3DDevice8::SetRenderState method just before rendering them, setting the State parameter to D3DRS_ZBIAS, and the Value parameter to a value between 0-16 inclusive. A higher z-bias value increases the likelihood that the polygons you render will be visible when displayed with other coplanar polygons.


Stencil Buffers

This section presents a discussion of the purpose and use stencil buffers. It is divided into the following topics.

  • What Is a Stencil Buffer?
  • How the Stencil Buffer Works
  • Customizing the Stencil Buffer


What Is a Stencil Buffer?

The stencil buffer enables or disables drawing to the rendering target surface on a pixel-by-pixel basis. At its most fundamental level, it enables applications to mask sections of the rendered image so that they are not displayed. Applications often use stencil buffers for special effects such as dissolves, decaling, and outlining. For details, see Stencil Buffer Techniques.

Stencil buffer information is embedded in the z-buffer data. Your application can use the IDirect3D8::CheckDeviceFormat method to check for hardware stencil support, as shown in the following code example.

// Reject devices that cannot perform 8-bit stencil buffering.
// The following example assumes that pCaps is a valid pointer
// to an initialized D3DCAPS8 structure.

if( FAILED( m_pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal,
                                       pCaps->DeviceType,
                                       Format,
                                       D3DUSAGE_DEPTHSTENCIL,
                                       D3DRTYPE_SURFACE,
                                       D3DFMT_D24S8 ) ) )
        return E_FAIL;

CheckDeviceFormat allows you to choose a device to create based on the capabilities of that device. In this case, devices that do not support 8-bit stencil buffers are rejected. Note that this is only one possible use for CheckDeviceFormat; for details see Determining Hardware Support.

To determine the stencil buffer limitations of a device, query the StencilCaps member of the D3DCAPS8 structure for its supported stencil buffer operations.


How the Stencil Buffer Works

Microsoft® Direct3D® performs a test on the contents of the stencil buffer on a pixel-by-pixel basis. For each pixel in the target surface, it performs a test using the corresponding value in the stencil buffer, a stencil reference value, and a stencil mask value. If the test passes, Direct3D performs an action. The test is performed using the following steps.

  1. Perform a bitwise AND operation of the stencil reference value with the stencil mask.
  2. Perform a bitwise AND operation of the stencil buffer value for the current pixel with the stencil mask.
  3. Compare the result of step 1 to the result of step 2, using the comparison function.

These steps are shown in the following code example.

(StencilRef & StencilMask) CompFunc (StencilBufferValue & StencilMask)

StencilBufferValue is the contents of the stencil buffer for the current pixel. This code example uses the ampersand (&) symbol to represent the bitwise AND operation. StencilMask represents the value of the stencil mask, and StencilRef represents the stencil reference value. CompFunc is the comparison function.

The current pixel is written to the target surface if the stencil test passes, and is ignored otherwise. The default comparison behavior is to write the pixel, no matter how each bitwise operation turns out (D3DCMP_ALWAYS). You can change this behavior by changing the value of the D3DRS_STENCILFUNC render state, passing a member of the D3DCMPFUNC enumerated type to identify the desired comparison function.


Customizing the Stencil Buffer

Your application can customize the operation of the stencil buffer. It can set the comparison function, the stencil mask, and the stencil reference value. It can also control the action that Microsoft® Direct3D® takes when the stencil test passes or fails. For more information, see Stencil Buffer State.


Vertex Buffers

This section introduces the concepts necessary to understand and use vertex buffers in a Microsoft® Direct3D® application. Information is divided into the following sections.

  • What Are Vertex Buffers?
  • Vertex Buffer Descriptions
  • Pool and Usage for Vertex Buffers
  • FVF Vertex Buffers
  • Device Types and Vertex Processing Requirements
  • Using Vertex Buffers


What Are Vertex Buffers?

Vertex buffers, represented by the IDirect3DVertexBuffer8 interface, are memory buffers that contain vertex data. Vertex buffers can contain any vertex type—transformed or untransformed, lit or unlit—that can be rendered through the use of the rendering methods in the IDirect3DDevice8 interface. You can process the vertices in a vertex buffer to perform operations such as transformation, lighting, or generating clipping flags. Transformation is always performed.

The flexibility of vertex buffers make them ideal staging points for reusing transformed geometry. You could create a single vertex buffer, transform, light, and clip the vertices in it, and render the model in the scene as many times as needed without re-transforming it, even with interleaved render state changes. This is useful when rendering models that use multiple textures: the geometry is transformed only once, and then portions of it can be rendered as needed, interleaved with the required texture changes. Render state changes made after vertices are processed take effect the next time the vertices are processed. For more information, see Processing Vertices.


Vertex Buffer Descriptions

A vertex buffer is described in terms of its capabilities: if it can exist only in system memory, if it is only used for write operations, and the type and number of vertices it can contain. All these traits are held in a D3DVERTEXBUFFER_DESC structure.

Vertex buffer descriptions tell your application how an existing buffer was created and if it has been optimized since being created. You provide an empty description structure for the system to fill with the capabilities of a previously created vertex buffer. For more information about this task, see Retrieving Vertex Buffer Descriptions.

The Format member is set to D3DFMT_VERTEXDATA to indicate that this is a vertex buffer. The Type identifies the resource type of the vertex buffer. The Usage structure member contains general capability flags. The D3DUSAGE_SOFTWAREPROCESSING flag indicates that the vertex buffer is to be used with software vertex processing. The presence of the D3DUSAGE_WRITEONLY flag in Usage indicates that the vertex buffer memory is used only for write operations. This frees the driver to place the vertex data in the best memory location to enable fast processing and rendering. If the D3DUSAGE_WRITEONLY flag is not used, the driver is less likely to put the data in a location that is inefficient for read operations. This sacrifices some processing and rendering speed. If this flag is not specified, it is assumed that applications perform read and write operations on the data within the vertex buffer.

Pool specifies the memory class that is allocated for the vertex buffer. The D3DPOOL_SYSTEMMEM flag indicates that the system created the vertex buffer in system memory.

The Size member simply stores the size, in bytes, of the vertex buffer data. The FVF member contains a combination of Flexible Vertex Format Flags that identify the type of vertices that the buffer contains.


Pool and Usage for Vertex Buffers

You can create vertex buffers with the IDirect3DDevice8::CreateVertexBuffer method, which takes pool (memory class) and usage parameters. CreateVertexBuffer can also be created with a specified flexible vertex format (FVF) code for use in fixed function vertex processing, or as the output of process vertices. For details, see FVF Vertex Buffers and FVF Usage Settings for Destination Vertex Buffers.

The D3DUSAGE_SOFTWAREPROCESSING flag can be set when mixed-mode or software vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING / D3DCREATE_SOFTWARE_VERTEXPROCESSING) is enabled for that device. D3DUSAGE_SOFTWAREPROCESSING must be set for buffers to be used with software vertex processing in mixed mode, but it should not be set for the best possible performance when using hardware vertex processing in mixed mode.(D3DCREATE_HARDWARE_VERTEXPROCESSING). However, setting D3DUSAGE_SOFTWAREPROCESSING is the only option when a single buffer is to be used with both hardware and software vertex processing. D3DUSAGE_SOFTWAREPROCESSING is allowed for mixed as well as for software devices.

It is possible to force vertex and index buffers into system memory by specifying D3DPOOL_SYSTEMMEM, even when the vertex processing is done in hardware. This is a way to avoid overly large amounts of page-locked memory when a driver is putting these buffers into AGP memory.


FVF Vertex Buffers

Setting the FVF parameter of the IDirect3DDevice8::CreateVertexBuffer method to a nonzero value, which must be a valid FVF code, indicates that the buffer content is to be characterized by an FVF code. A vertex buffer that is created with an FVF code is referred to as an FVF vertex buffer. Some methods or uses of IDirect3DDevice8 require FVF vertex buffers, and others require non-FVF vertex buffers. FVF vertex buffers are required as the destination vertex buffer argument for IDirect3DDevice8::ProcessVertices.

FVF vertex buffers can be bound to a source data stream for any stream number. However, FVF vertex buffers are not allowed to be used for inputs to programmed vertex shaders

The presence of the D3DFVF_XYZRHW component on FVF vertex buffers indicates that the vertices in that buffer have been processed. Vertex buffers used for ProcessVertices destination vertex buffers must be post-processed. Vertex buffers used for fixed function shader inputs can be either pre- or post-processed. If the vertex buffer is post-processed, then the shader is effectively bypassed and the data is passed directly to the primitive clipping and setup module.

FVF vertex buffers can be used with vertex shaders. Also, vertex streams can represent the same vertex formats that non-FVF vertex buffers can. They do not have to be used to input data from separate vertex buffers. The additional flexibility of the new vertex streams enables applications that need to keep their data separate to work better, but it is not required. If the application can maintain interleaved data in advance, then that is a performance boost. If the application will only interleave the data before every rendering call, then it should enable the application programming interface (API) or hardware to do this with multiple streams.

The most important things with vertex performance is to use a 32-byte vertex, and to maintain good cache ordering.


Device Types and Vertex Processing Requirements

The performance of vertex processing operations, including transformation and lighting, depends heavily on where the vertex buffer exists in memory and what type of rendering device is being used. Applications control the memory allocation for vertex buffers when they are created. When the D3DPOOL_SYSTEMMEM memory flag is set, the vertex buffer is created in system memory. When the D3DPOOL_DEFAULT memory flag is used, the device driver determines where the memory for the vertex buffer is best allocated, often referred to as driver-optimal memory. Driver-optimal memory can be local video memory, nonlocal video memory, or system memory.

Setting the D3DUSAGE_SOFTWAREPROCESSING behavior flag when calling the IDirect3DDevice8::CreateVertexBuffer method specifies that the vertex buffer is to be used with software vertex processing. This flag is required for software vertex processing in mixed vertex processing mode. This flag is allowed in software vertex processing mode and disallowed in hardware vertex processing mode. Vertex buffers used with software vertex processing include the following:

  • All input streams for IDirect3DDevice8::ProcessVertices.
  • All input streams for IDirect3DDevice8::DrawPrimitive and IDirect3DDevice8::DrawIndexedPrimitive when software vertex processing. For more information, see D3DRS_SOFTWAREVERTEXPROCESSING.

The reasoning you use to determine the memory location—system or driver optimal—for vertex buffers is the same as that for textures. Vertex processing, including transformation and lighting, in hardware works best when the vertex buffers are allocated in driver-optimal memory, while software vertex processing works best with vertex buffers allocated in system memory. For textures, hardware rasterization works best when textures are allocated in driver-optimal memory, while software rasterization works best with system-memory textures.

Note Microsoft® Direct3D® for Microsoft DirectX® 8.0 supports standalone processing of vertices, without rendering any primitive with the ProcessVertices method. This standalone vertex processing is always performed in software on the host processor. Because of this, vertex buffers used as sources set with IDirect3DDevice8::SetStreamSource must be created with the D3DUSAGE_SOFTWAREPROCESSING flag. The functionality provided by ProcessVertices is identical to that of the IDirect3DDevice8::DrawPrimitive and IDirect3DDevice8::DrawIndexedPrimitive methods while using software vertex processing. For more information, see Processing Vertices.

If your application performs its own vertex processing and passes transformed, lit, and clipped vertices to rendering methods, then the application can directly write vertices to a vertex buffer allocated in driver-optimal memory. This technique prevents a redundant copy operation later. Note that this technique will not work well if your application reads data back from a vertex buffer, because read operations done by the host from driver-optimal memory can be very slow. Therefore, if your application needs to read during processing or writes data to the buffer erratically, a system-memory vertex buffer is a better choice.

When using the Direct3D vertex processing features (by passing untransformed vertices to vertex-buffer rendering methods), processing can occur in either hardware or software depending on the device type and device creation flags. It is recommended that vertex buffers be allocated in pool D3DPOOL_DEFAULT for best performance in virtually all cases. When a device is using hardware vertex processing, there is a number of additional optimizations that may be done based on the flags D3DUSAGE_DYNAMIC and D3DUSAGE_WRITEONLY. See IDirect3DDevice8::CreateVertexBuffer for more information on using these flags.


Using Vertex Buffers

The following topics discuss common tasks that applications perform when working with vertex buffers.

  • Creating a Vertex Buffer
  • Accessing the Contents of a Vertex Buffer
  • Processing Vertices
  • Rendering from a Vertex Buffer
  • Retrieving Vertex Buffer Descriptions


Creating a Vertex Buffer

You create a vertex buffer object by calling the IDirect3DDevice8::CreateVertexBuffer method, which accepts five parameters. The first parameter specifies the vertex buffer length, in bytes. Use the sizeof operator to determine the size of a vertex format, in bytes. Consider the following custom vertex format.

struct CUSTOMVERTEX {
        FLOAT x, y, z;
        FLOAT rhw;
        DWORD color;
        FLOAT tu, tv;   // The texture coordinates.
};

// Custom FVF, which describes the custom vertex structure.
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1)

To create a vertex buffer to hold four CUSTOMVERTEX structures, specify [4*sizeof(CUSTOMVERTEX)] for the Length parameter.

The second parameter is a set of usage controls. Among other things, its value determines whether the vertex buffer is capable of containing clipping information—in the form of clip flags—for vertices that exist outside the viewing area. To create a vertex buffer that cannot contain clip flags, include the D3DUSAGE_DONOTCLIP flag for the Usage parameter. The D3DUSAGE_DONOTCLIP flag is applied only if you also indicate that the vertex buffer will contain transformed vertices—the D3DFVF_XYZRHW flag is included in the FVF parameter. The CreateVertexBuffer method ignores the D3DUSAGE_DONOTCLIP flag if you indicate that the buffer will contain untransformed vertices (the D3DFVF_XYZ flag). Clipping flags occupy additional memory, making a clipping-capable vertex buffer slightly larger than a vertex buffer incapable of containing clipping flags. Because these resources are allocated when the vertex buffer is created, you must request a clipping-capable vertex buffer ahead of time.

The third parameter, FVF, is a combination of Flexible Vertex Format Flags that describe the vertex format of the vertex buffer. If you specify 0 for this parameter, then the vertex buffer is a non-FVF vertex buffer. For more information, see FVF Vertex Buffers. The fourth parameter describes the memory class into which to place the vertex buffer.

The final parameter that CreateVertexBuffer accepts is the address of a variable that will be filled with a pointer to the new IDirect3DVertexBuffer8 interface of the vertex buffer object, if the call succeeds.

Note You cannot produce clip flags for a vertex buffer that was created without support for them.

The following C++ code example shows what creating a vertex buffer might look like in code.

    // For the purposes of this example, the d3dDevice variable is
    // the address of an IDirect3DDevice8 interface exposed by a
    // Direct3DDevice object, g_pVB is a variable of type
    // LPDIRECT3DVERTEXBUFFER8.

// The custom vertex type
struct CUSTOMVERTEX {
        FLOAT x, y, z;
        FLOAT rhw;
        DWORD color;
        FLOAT tu, tv;   // The texture coordinates
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1)

    // Create a clipping-capable vertex buffer. Allocate enough memory
    // in the  default memory pool to hold three CUSTOMVERTEX
    // structures.
    if( FAILED( d3dDevice->CreateVertexBuffer( 3*sizeof(CUSTOMVERTEX),
                                                  0 /* Usage */, D3DFVF_CUSTOMVERTEX,
                                                  D3DPOOL_DEFAULT, &g_pVB ) ) )
        return E_FAIL;


Accessing the Contents of a Vertex Buffer

Vertex buffer objects enable applications to directly access the memory allocated for vertex data. You can retrieve a pointer to vertex buffer memory by calling the IDirect3DVertexBuffer8::Lock method, and then accessing the memory as needed to fill the buffer with new vertex data or to read any data it already contains. The Lock method accepts four parameters. The first, OffsetToLock, is the offset into the vertex data. The second parameter is the size, measured in bytes, of the vertex data. The third parameter accepted by the Lock method, ppbData, is the address of a BYTE pointer that points to the vertex data, if the call succeeds.

The last parameter, Flags, tells the system how the memory should be locked. You can use it to indicate how the application will access the data in the buffer. Specify constants for the Flags parameter according to the way the vertex data will be accessed. This allows the driver to lock the memory and provide the best performance, given the requested access type. Use D3DLOCK_READONLY flag if your application will read only from the vertex buffer memory. Including this flag enables Microsoft® Direct3D® to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

After you finish filling or reading the vertex data, call the IDirect3DVertexBuffer8::Unlock method, as shown in the following code example.

// This code example assumes the g_pVB is a variable of type
// LPDIRECT3DVERTEXBUFFER8 and that g_Vertices has been properly
// initialized with vertices.

// To fill the vertex buffer, you need to lock the buffer to
// gain access to the vertices. This mechanism is required because
// vertex buffers may be in device memory.
VOID* pVertices;

if( FAILED( g_pVB->Lock( 0,                  // Fill from the start of
                                             // the buffer.
                         sizeof(g_Vertices), // Size of the data to
                                             // load.
                         (BYTE**)&pVertices, // Returned vertex data.
                         0 ) ) )             // Send default flags to
                                             // the lock.
    return E_FAIL;

memcpy( pVertices, g_Vertices, sizeof(g_Vertices) );
g_pVB->Unlock();

Performance Notes If you create a vertex buffer with the D3DUSAGE_WRITEONLY flag, do not use the D3DLOCK_READONLY locking flag. Use the D3DLOCK_READONLY flag if your application will read only from the vertex buffer memory. Including this flag enables Direct3D to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

See Using Dynamic Vertex and Index Buffers for information on using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the Lock method.

In C++, because you directly access the memory allocated for the vertex buffer, make sure your application properly accesses the allocated memory. Otherwise, you risk rendering that memory invalid. Use the stride of the vertex format that your application uses to move from one vertex in the allocated buffer to another. The vertex buffer memory is a simple array of vertices specified in flexible vertex format. Use the stride of whatever vertex format structure you define. You can calculate the stride of each vertex at run time by examining the Flexible Vertex Format Flags contained in the vertex buffer description. The following table shows the size for each vertex component.

Vertex Format Flag | Size
D3DFVF_DIFFUSE | sizeof(DWORD)
D3DFVF_NORMAL | sizeof(float) × 3
D3DFVF_SPECULAR | sizeof(DWORD)
D3DFVF_TEXn | sizeof(float) × n × t
D3DFVF_XYZ | sizeof(float) × 3
D3DFVF_XYZRHW | sizeof(float) × 4

The number of texture coordinates present in the vertex format is described by the D3DFVF_TEXn flags (where n is a value from 0 to 8). Multiply the number of texture coordinate sets by the size of one set of texture coordinates, which can range from one to four floats, to calculate the memory required for that number of texture coordinates.

Use the total vertex stride to increment and decrement the memory pointer as needed to access particular vertices.


Processing Vertices

Processing the vertices in a vertex buffer applies the current transformation matrices for the device. Vertex operations such as lighting, generating clip flags, and updating extents can also be applied, optionally. Information is divided into the following topics.

  • Fixed Function Processing Vertices
  • Programmable Processing Vertices


Fixed Function Processing Vertices

This section discusses fixed function vertex processing. The following topics are discussed.

  • About Fixed Function Processing Vertices
  • FVF Usage Settings for Destination Vertex Buffers


About Fixed Function Processing Vertices

In the fixed function vertex pipeline, processing the vertices in a vertex buffer applies the current transformation matrices for the device. Vertex operations such as lighting, generating clip flags, and updating extents can also be applied, optionally. When using fixed function vertex processing, modifying the elements in the destination vertex buffer is controlled by the D3DPV_DONOTCOPYDATA flag. This flag applies only to fixed function vertex processing. The IDirect3DDevice8 interface exposes the IDirect3DDevice8::ProcessVertices method to process vertices. You process vertices from a vertex shader to the set of input data streams, generating a single stream of interleaved vertex data to the destination vertex buffer by calling the ProcessVertices method. The method accepts five parameters that describe the location and quantity of vertices that the method targets, the destination vertex buffer, and the processing options. After the call, the destination buffer contains the processed vertex data.

The first, second, and third parameters, SrcStartIndex, DestIndex, and VertexCount, reflect the index of the first vertex to load, the index within the destination buffer at which the vertices will be placed, and the total number of vertices to process and place in the destination buffer. The fourth parameter, pDestBuffer, should be set to the address of the IDirect3DVertexBuffer8 of the vertex buffer object that will receive the source vertices. The SrcStartIndex specifies the index at which the method should start processing vertices.

The final parameter, Flags, determines special processing options for the method. You can set this parameter to 0 for default vertex processing, or to D3DPV_DONOTCOPYDATA to optimize processing in some situations. When you set Flags to 0, vertex components of the destination vertex buffer's vertex format that are not affected by the vertex operation are still copied from the vertex shader or set to 0. However, when using D3DPV_DONOTCOPYDATA, ProcessVertices does not overwrite color and texture coordinate information in the destination buffer unless this data is generated by Microsoft® Direct3D®. Diffuse color is generated when lighting is enabled, that is, D3DRS_LIGHTING is set to TRUE. Specular color is generated when lighting is enabled and specular is enabled, that is, D3DRS_SPECULARENABLE and D3DRS_LIGHTING are set to TRUE. Specular color is also generated when fog is enabled. Texture coordinates are generated when texture transform or texture generation is enabled. ProcessVertices uses the current render states to determine what vertex processing should be done.

To determine the vertex processing limitations of a device, query the VertexProcessingCaps member of the D3DCAPS8 structure for its supported vertex processing capabilities.


FVF Usage Settings for Destination Vertex Buffers

The IDirect3DDevice8::ProcessVertices method requires specific settings for the Flexible Vertex Format Flags of the destination vertex buffer. The flexible vertex format (FVF) usage settings must be compatible with the current settings for vertex processing.

For fixed function vertex processing, ProcessVertices requires the following FVF settings.

  • Position type is always D3DFVF_XYZRHW; so, D3DFVF_XYZ and D3DFVF_XYZB1 through D3DFVF_XYZB5 are invalid.
  • The D3DFVF_NORMAL, D3DFVF_RESERVED0, and D3DFVF_RESERVED2 flags must not be set.
  • The D3DFVF_DIFFUSE flag must be set if an OR operation of the following conditions returns true.
    • Lighting is enabled, that is, D3DRS_LIGHTING is true.
    • Lighting is disabled, and diffuse color is present in the input vertex streams, and D3DPV_DONOTCOPYDATA is not set.
  • The D3DFVF_SPECULAR flag must be set if an OR operation of the following conditions returns true.
    • Lighting is enabled and specular color is enabled, that is, D3DRS_SPECULARENABLE is true.
    • Lighting is disabled, and specular color is present in the input vertex streams, and D3DPV_DONOTCOPYDATA is not set.
    • Vertex fog is enabled, that is, D3DRS_FOGVERTEXMODE is not set to D3DFOG_NONE.

In addition, the texture coordinate count must be set in the following manner.

  • If texture transform and texture generation are disabled for all active texture stages, and the D3DPV_DONOTCOPYDATA is not set, then the number and type of output texture coordinates are required to match those of the input vertex texture coordinates. If D3DPV_DONOTCOPYDATA is set and texture transform and texture generation are disabled, then the output texture coordinates are ignored.
  • If texture transform or texture generation is enabled for any active texture stages, the output vertex might need to contain more texture coordinate sets than the input vertex. This is due to the proliferation of texture coordinates from those being generated by texture generation or derived by texture transforms. Note that a similar proliferation of texture coordinates occurs during DrawPrimitive calls, but is not visible to the application programmer. In this case, Microsoft® Direct3D® generates a new set of texture coordinates. The new set of texture coordinates is derived by stepping through the texture stages and analyzing the settings for texture generation, texture transformation, and texture coordinate index to determine if a unique set of texture coordinates is required for that stage. Each time a new set is required it is allocated in increasing order. Note that the maximum, and typical, requirement is one set per stage, although it might be less due to sharing of nontransformed texture coordinates through D3DTSS_TEXCOORDINDEX.

Thus, for each texture stage, a new set of texture coordinates is generated if a texture is bound to that stage and any of the following conditions are true.

  • Texture generation is enabled for that stage.
  • Texture transformation is enabled for that stage.
  • Nontransformed input texture coordinates are referenced through D3DTSS_TEXCOORDINDEX for the first time.

When Direct3D is generating texture coordinates, the application is required to perform the following actions.

  1. Use a destination vertex buffer with the appropriate FVF usage.
  2. Reprogram the D3DTSS_TEXCOORDINDEX of the texture stage according to the placement of the post -processed texture coordinates. Note that the reprogramming of the D3DTSS_TEXCOORDINDEX setting occurs when the processed vertex buffer is used in subsequent IDirect3DDevice8::DrawPrimitive and IDirect3DDevice8::DrawIndexedPrimitive calls.

Finally, texture coordinate dimensionality (D3DFVF_TEX0 through D3DFVF_TEX8) must be set in the following manner.

  • For each texture coordinate set, if texture transform and texture generation are disabled, then the output texture coordinate dimensionality must match the input. If the texture transform is enabled, then the output dimensionality must match the count defined by the D3DTTFF_COUNT1, D3DTTFF_COUNT2, D3DTTFF_COUNT3, or D3DTTFF_COUNT4 settings. If the texture transform is disabled and texture generation is enabled, then the output dimensionality must match the settings for the texture generation mode; currently all modes generate 3 float values.

When ProcessVertices fails due to an incompatible destination vertex buffer FVF code, the expected code is printed to the debug output (debug builds only).


Programmable Processing Vertices

When using a programmed vertex shader, the elements updated in the destination vertex buffer are controlled by the shader function program. When the application writes to one of the destination vertex registers, the corresponding element within each vertex of the destination vertex buffer is updated. Elements in the destination vertex buffer that are not written to by the application are not modified. IDirect3DDevice8::ProcessVertices will fail if the application writes to elements that are not present in the destination vertex buffer.


Rendering from a Vertex Buffer

Rendering vertex data from a vertex buffer requires a few steps. First, you need to set the stream source by calling the IDirect3DDevice8::SetStreamSource method, as shown in the following example.

d3dDevice->SetStreamSource( 0, g_pVB, sizeof(CUSTOMVERTEX) );

The first parameter of SetStreamSource tells Microsoft® Direct3D® the source of the device data stream. The second parameter is the vertex buffer to bind to the data stream. The third parameter is the size of the component, in bytes. In the sample code above, the size of a CUSTOMVERTEX is used for the size of the component.

The next step is to inform Direct3D which vertex shader to use by calling the IDirect3DDevice8::SetVertexShader method. The following sample code sets an FVF code for the vertex shader. This informs Direct3D of the types of vertices it is dealing with.

d3dDevice->SetVertexShader( D3DFVF_CUSTOMVERTEX );

After setting the stream source and vertex shader, any draw methods will use the vertex buffer. The code example below shows how to render vertices from a vertex buffer with the IDirect3DDevice8::DrawPrimitive method.

d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 );

The second parameter that DrawPrimitive accepts is the index of the first vector in the vertex buffer to load.


Retrieving Vertex Buffer Descriptions

You can retrieve information about a vertex buffer by calling the IDirect3DVertexBuffer8::GetDesc method. This method fills the members of the D3DVERTEXBUFFER_DESC structure with information about the vertex buffer.


Index Buffers

This section introduces the concepts necessary to understand and use index buffers in a Microsoft® Direct3D® application. Information is divided into the following sections.

  • What Are Index Buffers?
  • Index Buffer Descriptions
  • Pool and Usage for Index Buffers
  • Device Types and Index Processing Requirements
  • Using Index Buffers


What Are Index Buffers?

Index buffers, represented by the IDirect3DIndexBuffer8 interface, are memory buffers that contain index data. Index data, or indices, are integer offsets into vertex buffers and are used to render primitives using the IDirect3DDevice8::DrawIndexedPrimitive method.


Index Buffer Descriptions

An index buffer is described in terms of its capabilities: if it can exist only in system memory, if it is only used for write operations, and the type and number of indices it can contain. These traits are held in a D3DINDEXBUFFER_DESC structure.

Index buffer descriptions tell your application how an existing buffer was created. You provide an empty description structure for the system to fill with the capabilities of a previously created index buffer. For more information about this task, see Retrieving Index Buffer Descriptions.

The Format member describes the surface format of the index buffer data.

The Type identifies the resource type of the index buffer.

The Usage structure member contains general capability flags. The D3DUSAGE_SOFTWAREPROCESSING flag indicates that the index buffer is to be used with software vertex processing. The presence of the D3DUSAGE_WRITEONLY flag in Usage indicates that the index buffer memory is used only for write operations. This frees the driver to place the index data in the best memory location to enable fast processing and rendering. If the D3DUSAGE_WRITEONLY flag is not used, the driver is less likely to put the data in a location that is inefficient for read operations. This sacrifices some processing and rendering speed. If this flag is not specified, it is assumed that applications perform read and write operations on the data in the index buffer.

Pool specifies the memory class allocated for the index buffer. The D3DPOOL_SYSTEMMEM flag indicates that the system created the index buffer in system memory.

The Size member simply stores the size, in bytes, of the vertex buffer data.


Pool and Usage for Index Buffers

You can create index buffers with the IDirect3DDevice8::CreateIndexBuffer method, which takes pool (memory class) and usage parameters.

The D3DUSAGE_SOFTWAREPROCESSING flag can be set when mixed-mode or software vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING / D3DCREATE_SOFTWARE_VERTEXPROCESSING) is enabled for that device. D3DUSAGE_SOFTWAREPROCESSING must be set for buffers to be used with software vertex processing in mixed mode, but it should not be set for the best possible performance when using hardware index processing in mixed mode (D3DCREATE_HARDWARE_VERTEXPROCESSING). However, setting D3DUSAGE_SOFTWAREPROCESSING is the only option when a single buffer is used with both hardware and software vertex processing. D3DUSAGE_SOFTWAREPROCESSING is allowed for mixed and software devices.

It is possible to force vertex and index buffers into system memory by specifying D3DPOOL_SYSTEMMEM, even when the index processing is being done in hardware. This is a way to avoid overly large amounts of page-locked memory when a driver is putting these buffers into AGP memory.


Device Types and Index Processing Requirements

The performance of index processing operations depends heavily on where the index buffer exists in memory and what type of rendering device is being used. Applications control the memory allocation for index buffers when they are created. When the D3DPOOL_SYSTEMMEM memory flag is set, the index buffer is created in system memory. When the D3DPOOL_DEFAULT memory flag is used, the device driver determines where the memory for the index buffer is best allocated, often referred to as driver-optimal memory. Driver-optimal memory can be local video memory, nonlocal video memory, or system memory.

Setting the D3DUSAGE_SOFTWAREPROCESSING behavior flag when calling the IDirect3DDevice8::CreateIndexBuffer method specifies that the index buffer is to be used with software vertex processing. This flag is required in mixed mode vertex processing (D3DCREATE_MIXED_VERTEXPROCESSING) when software vertex processing is used.

The application can directly write indices to a index buffer allocated in driver-optimal memory. This technique prevents a redundant copy operation later. This technique does not work well if your application reads data back from an index buffer, because read operations done by the host from driver-optimal memory can be very slow. Therefore, if your application needs to read during processing or writes data to the buffer erratically, a system-memory index buffer is a better choice.

Note Always use D3DPOOL_DEFAULT, except when you don't want to expend video memory or expand large amounts of page-locked RAM when the driver is putting vertex or index buffers into AGP memory.


Using Index Buffers

The following topics discuss common tasks that an application performs when working with vertex buffers.

  • Creating an Index Buffer
  • Accessing the Contents of an Index Buffer
  • Rendering from an Index Buffer
  • Retrieving Index Buffer Descriptions


Creating an Index Buffer

Create an index buffer object by calling the IDirect3DDevice8::CreateIndexBuffer method, which accepts five parameters. The first parameter specifies the index buffer length, in bytes.

The second parameter is a set of usage controls. Among other things, its value determines whether the vertices being referred to by the indices are capable of containing clipping information. To improve performance, specify D3DUSAGE_DONOTCLIP when clipping is not required.

The third parameter is either the D3DFMT_INDEX16 or D3DFMT_INDEX32 member of the D3DFORMAT enumerated type that specifies the size of each index.

The fourth parameter is a member of the D3DPOOL enumerated type that tells the system where in memory to place the new index buffer.

The final parameter that CreateIndexBuffer accepts is the address of a variable that is filled with a pointer to the new IDirect3DIndexBuffer8 interface of the vertex buffer object, if the call succeeds.

The following C++ code example shows what creating a index buffer might look like in code.

/*
 * For the purposes of this example, the d3dDevice variable is the
 * address of an IDirect3DDevice8 interface exposed by a
 * Direct3DDevice object, g_IB is a variable of type
 * LPDIRECT3DINDEXBUFFER8.
 */

if( FAILED( d3dDevice->CreateIndexBuffer( 16384 *sizeof(WORD),
                                            D3DUSAGE_WRITEONLY, D3DFMT_INDEX16,
                                            D3DPOOL_DEFAULT, &g_IB ) ) )
    return E_FAIL;


Accessing the Contents of an Index Buffer

Index buffer objects enable applications to directly access the memory allocated for index data. You can retrieve a pointer to index buffer memory by calling the IDirect3DIndexBuffer8::Lock method, and then accessing the memory as needed to fill the buffer with new index data or to read any data it contains. The Lock method accepts four parameters. The first, OffsetToLock, is the offset into the index data. The second parameter is the size, measured in bytes, of the index data. The third parameter accepted by the Lock method, ppbData, is the address of a BYTE pointer filled with a pointer to the index data, if the call succeeds.

The last parameter, Flags, tells the system how the memory should be locked. You can use it to indicate how the application accesses the data in the buffer. Specify constants for the Flags parameter according to the way the index data will be accessed by your application. This allows the driver to lock the memory and provide the best performance given the requested access type. Use D3DLOCK_READONLY flag if your application will read only from the index buffer memory. Including this flag enables Microsoft® Direct3D® to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

After you fill or read the index data, call the IDirect3DIndexBuffer8::Unlock method, as shown in the following code example.

// This code example assumes the IB is a variable of type
// LPDIRECT3DINDEXBUFFER8 and that g_Indices has been properly
// initialized with indices.

// To fill the index buffer, you must lock the buffer to gain
// access to the indices. This mechanism is required because index
// buffers may be in device memory.

VOID* pIndices;

if( FAILED( IB->Lock( 0,                 // Fill from start of the buffer.
                      sizeof(g_Indices), // Size of the data to load.
                      (BYTE**)&pIndices, // Returned index data.
                      0 ) ) )            // Send default flags to the lock.
    return E_FAIL;

memcpy( pIndices, g_Indices, sizeof(g_Vertices) );
IB->Unlock();

Note If you create an index buffer with the D3DUSAGE_WRITEONLY flag, do not use the D3DLOCK_READONLY locking flag. Use the D3DLOCK_READONLY flag if your application will read only from the index buffer memory. Including this flag enables Direct3D to optimize its internal procedures to improve efficiency, given that access to the memory will be read-only.

See Using Dynamic Vertex and Index Buffers for information on using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the Lock method.

In C++, because you directly access the memory allocated for the index buffer, make sure your application properly accesses the allocated memory. Otherwise, you risk rendering that memory invalid. Use the stride of the index format your application uses to move from one index in the allocated buffer to another.


Rendering from an Index Buffer

Rendering index data from an index buffer requires a few steps. First, you need to set the stream source by calling the IDirect3DDevice8::SetStreamSource method.

d3dDevice->SetStreamSource( 0, VB, sizeof(CUSTOMVERTEX) );

The first parameter of SetStreamSource tells Microsoft® Direct3D® the source of the device data stream. The second parameter is the vertex buffer to bind to the data stream. The third parameter is the size of the component, in bytes. In the sample code above, the size of a CUSTOMVERTEX is used for the size of the component.

The next step is to call the IDirect3DDevice8::SetIndices method to set the source of the index data.

d3dDevice->SetIndices( IB, 0 );

The first parameter that SetIndices accepts is the address of the index buffer to set. The second parameter is the starting point in the vertex stream.

After setting the stream and indices source, use the IDirect3DDevice8::DrawIndexedPrimitive method to render vertices that use indices from the index buffer.

d3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, 0,
                                   dwVertices, 0, dwIndices / 3);

The second parameter that DrawPrimitive accepts is the minimum vertex index for vertices used during this call. The third parameter is the number of indices to use during this call starting from BaseVertexIndex + MinIndex. The fourth parameter is the location in the index array to start reading indices. The final parameter that DrawPrimitive accepts is the number of primitives to render. This parameter is a function of the primitive count and the primitive type. The code sample above uses triangles, so the number of primitives to render is the number of indices divided by three.


Retrieving Index Buffer Descriptions

Retrieve information about an index buffer by calling the IDirect3DIndexBuffer8::GetDesc method. This method fills the members of the D3DINDEXBUFFER_DESC structure with information about the vertex buffer.


Techniques and Special Effects

Microsoft® Direct3D® provides a powerful set of tools that you can use to increase the realistic appearance of a 3-D scene. This section presents information on common special effects that can be produced with Direct3D, but the range of possible effects is not limited to those presented here. The discussion in this section is organized into the following topics.

  • Alpha Blending
  • Antialiasing
  • Bump Mapping
  • Environment Mapping
  • Fog
  • Geometry Blending
  • Indexed Vertex Blending
  • Stencil Buffer Techniques
  • Vertex Tweening
  • Colored Lights


Alpha Blending

Alpha blending is used to display an image that has transparent or semi-transparent pixels. In addition to a red, green, and blue color channel, each pixel in an alpha bitmap has a transparency component known as its alpha channel. The alpha channel typically contains as many bits as a color channel. For example, an 8-bit alpha channel can represent 256 levels of transparency, from 0 (the entire pixel is transparent) to 255 (the entire pixel is opaque). The list below shows some special effects you can create using alpha blending.

  • Billboarding
  • Clouds, Smoke, and Vapor Trails
  • Fire, Flares, and Explosions


Billboarding

When creating 3-D scenes, an application can sometimes gain performance advantages by rendering 2-D objects in a way that makes them appear to be 3-D objects. This is the basic idea behind the technique of billboarding.

A billboard in the normal sense of the word is a sign along a roadway. Microsoft® Direct3D® applications can create and render this type of billboard by defining a rectangular solid and applying a texture to it. Billboarding in the more specialized sense of 3-D graphics is an extension of this. The goal is to make 2-D objects appear to be 3-D. The technique is to apply a texture that contains the object's image to a rectangular primitive. The primitive is rotated so that it always faces the user. It doesn't matter if the object's image is not rectangular. Portions of the billboard can be made transparent, so the parts of the billboard image that you don't want seen are not visible.

Many games employ billboarding for animated sprites. For instance, when the user is moving through a 3-D maze, he or she may see weapons or rewards that can be picked up. These are typically 2-D images textured on a rectangular primitive. Billboarding is often used in games to render images of trees, bushes, and clouds.

When an image is applied to a billboard, the rectangular primitive must first be rotated so that the resulting image faces the user. Your application must then translate it into position. The application can then apply a texture to the primitive.

Billboarding works best for symmetrical objects, especially objects that are symmetrical along the vertical axis. It also requires that the altitude of the viewpoint doesn't increase too much. If the user is allowed to view the billboarded from above, it becomes readily apparent that the object is 2-D rather than 3-D.


Clouds, Smoke, and Vapor Trails

Clouds, smoke, and vapor trails can all be created by an extension of the billboarding technique. See Billboarding. By rotating the billboard on two axes instead of one, your application can enable the user to look at a billboard from any angle. Typically, an application rotates the billboard on the horizontal and vertical axes.

To make a simple cloud, your application can rotate a rectangular primitive on one or two axes so that the primitive faces the user. A cloud-like texture can then be applied to the primitive with transparency. For details on applying transparent textures to primitives, see Texture Blending. You can animate the cloud by applying a series of textures over time.

An application can create more complex clouds by forming them from a group of primitives. Each part of the cloud is a rectangular primitive. The primitives can be moved independently over time to give the appearance of a dynamic mist. This concept is illustrated in the following figure.

The appearance of smoke is displayed in a manner similar to clouds. It typically requires multiple billboards, like complex clouds. Smoke usually billows and rises over time, so the billboards that make up the smoke plume need to move accordingly. You may need to add more billboards as the plume rises and disperses.

A vapor trail is a smoke plume that doesn't rise. However, like a smoke plume, it disperses over time. The following figure illustrates the technique of using billboards to simulate a vapor trail.


Fire, Flares, and Explosions

You can use Microsoft® Direct3D® to simulate natural phenomena involving energy releases. For instance, an application can generate the appearance of fire by applying flame-like textures to a set of billboards. This is especially effective if the application uses a sequence of fire textures to animate the flames on each billboard in the fire. Varying the speed of the animation playback from billboard to billboard increases the appearance of real flames. The semblance of intermingled 3-D flames can be achieved by layering the billboards and the textures on the billboards.

You can simulate flares and flashes by applying successively brighter light maps to all primitives in a scene. Although this is a computationally high-overhead technique, it allows your application to simulate a localized flare or flash. That is, the portion of the scene where the flare or flash originates can brighten first.

Another technique is to position a billboard in front of the scene so that the entire render target area is covered. The application applies successively whiter textures to the billboard and decreases the transparency over time. The entire scene fades to white as time passes. This is a low overhead method of creating a flare. However, using this technique, it can be difficult to generate the appearance of a bright flash from a single point light source.

Explosions can be displayed in a 3-D scene procedure similar to those used for fire, flashes, and flares. For instance, your application might use a billboard to display a shock wave and rising plume of smoke when the explosion occurs. At the same time, your application can use a set of billboards to simulate flames. In addition, it can position a single billboard in front of the scene to add a flare of light to the entire scene.

Energy beams can be simulated using billboards. Your application can also display them using primitives that are defined as line lists or line strips. For details, see Line Lists and Line Strips.

Your application can create force fields using billboards or primitives defined as triangle lists. To create a force field from triangle lists, define a set of disjoint triangles in a triangle list equally spaced over the region covered by the force field. The gaps between the triangles allow the user to see the scene behind the triangles, as you might expect when looking at a force field. Apply a texture to the triangle list that gives the triangles the appearance of glowing with energy. For further information, see Triangle Lists.


Antialiasing

Antialiasing is a technique you can use to reduce the appearance of stair-step pixels when drawing any line that is not exactly horizontal or vertical. In three-dimensional scenes, this artifact is most noticeable on the boundaries between polygons of different colors. Antialiasing effectively blends the pixels at these boundaries to produce a more natural look to the scene.

Microsoft® Direct3D® supports two antialiasing techniques: edge antialiasing and full-surface antialiasing. Which technique is best for your application depends on your requirements for performance and visual fidelity.

  • Edge Antialiasing
  • Full-Scene Antialiasing

The section below shows how to use special effects to simulate or use antialiasing.

  • Motion Blur


Edge Antialiasing

In edge antialiasing, you render a scene, then re-render the convex silhouettes of the objects to antialias with lines. The system redraws those edges, blurring them to reduce artifacts.

First, find out if the Microsoft® Direct3D® device supports antialiasing by calling the IDirect3DDevice8::GetDeviceCaps method. If a device supports edge antialiasing, GetDeviceCaps sets the D3DPRASTERCAPS_ANTIALIASEDGES capability flag in the D3DCAPS8 structure to TRUE.

If the device supports antialiasing, set the D3DRS_EDGEANTIALIAS render state to TRUE, as shown in the code example below.

d3dDevice->SetRenderState( D3DRS_EDGEANTIALIAS, TRUE );

Now, redraw only the edges in the scene, using IDirect3DDevice8::DrawPrimitive and either the D3DPT_LINESTRIP or D3DPT_LINELIST primitive type. The behavior of edge antialiasing is undefined for primitives other than lines, so make sure to disable the feature by setting D3DRS_EDGEANTIALIAS to FALSE when antialiasing is complete.

Redrawing every edge in your scene can work without introducing major artifacts, but it can be computationally expensive. In addition, it can be difficult to determine which edges should be antialiased. The most important edges to redraw are those between areas of very different colors, for example, silhouette edges, or boundaries between very different materials. Antialiasing the edge between two polygons of roughly the same color has no effect, yet is still computationally expensive. For these reasons, if current hardware supports full-scene antialiasing, it is often preferred. For more information, see Full-scene Antialiasing.


Full-Scene Antialiasing

Full-scene antialiasing refers to blurring the edges of each polygon in the scene as it is rasterized in a single pass—no second pass is required. Full-scene antialiasing, when supported, only affects triangles and groups of triangles; lines cannot be antialiased by using Microsoft® Direct3D® services. Full-scene antialiasing is done in Direct3D by using multisampling on each pixel. When multisampling is enabled all subsamples of a pixel are updated in one pass, but when used for other effects that involve multiple rendering passes, the application can specify that only some subsamples are to be affected by a given rendering pass. This latter approach enables simulation of motion blur, depth of field focus effects, reflection blur, and so on.

In both cases, the various samples recorded for each pixel are blended together and output to the screen. This enables the improved image quality of antialiasing or other effects.

Before creating a device with the IDirect3D8::CreateDevice method, you need to determine if full-scene antialiasing is supported. Do this by calling the IDirect3D8::CheckDeviceMultiSampleType method as shown in the code example below.

/*
 * The code below assumes that pD3D is a valid pointer
 * to a IDirect3D8 interface.
 */

if( SUCCEEDED(pD3D->CheckDeviceMultiSampleType( D3DADAPTER_DEFAULT,
                                                D3DDEVTYPE_HAL , D3DFMT_R8G8B8,
                                                FALSE, D3DMULTISAMPLE_2_SAMPLES ) ) )
    // Full-scene antialiasing is supported. Enable it here.

The first parameter that CheckDeviceMultiSampleType accepts is an ordinal number that denotes the display adapter to query. This sample uses D3DADAPTER_DEFAULT to specify the primary display adapter. The second parameter is a value from the D3DDEVTYPE enumerated type, specifying the device type. The third parameter specifies the format of the surface. The fourth parameter tells Direct3D whether to inquire about full-windowed multisampling (TRUE) or full-scene antialiasing (FALSE). This sample uses FALSE to tell Direct3D that it is inquiring about full-scene antialiasing. The last parameter specifies the multisampling technique that you want to test. Use a value from the D3DMULTISAMPLE_TYPE enumerated type. This sample tests to see if two levels of multisampling are supported.

If the device supports the level of multisampling that you want to use, the next step is to set the presentation parameters by filling in the appropriate members of the D3DPRESENT_PARAMETERS structure to create a multisample rendering surface. After that, you can create the device. The sample code below shows how to set up a device with a multisampling render surface.

/*
 * The example below assumes that pD3D is a valid pointer
 * to a IDirect3D8 interface, d3dDevice is a pointer to a
 * IDirect3DDevice8 interface, and hWnd is a valid handle
 * to a window.
 */

D3DPRESENT_PARAMETER d3dPP
ZeroMemory( &d3dPP, sizeof( d3dPP ) );
d3dPP.Windowed        = FALSE
d3dPP.SwapEffect      = D3DSWAPEFFECT_DISCARD;
d3dPP.MultiSampleType = D3DMULTISAMPLE_2_SAMPLES;
pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                   D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                   &d3dpp, &d3dDevice)

Note To use multisampling, the SwapEffect member of D3DPRESENT_PARAMETER must be set to D3DSWAPEFFECT_DISCARD.

The last step is to enable multisampling antialiasing by calling the IDirect3DDevice8::SetRenderState method and setting the D3DRS_MULTISAMPLEANTIALIAS to TRUE. After setting this value to TRUE, any rendering that you do will have multisampling applied to it. You might want to enable and disable multisampling, depending on what you are rendering.


Motion Blur

You can enhance the perceived speed of an object in a 3-D scene by blurring the object and leaving a blurred trail of object images behind the object. Microsoft® Direct3D® applications accomplish this by rendering the object multiple times per frame.

Recall that Direct3D applications typically render scenes into an off-screen buffer. The contents of the buffer are displayed on the screen when the application calls the IDirect3DDevice8::Present method. Your Direct3D application can render the object multiple times into a scene before it displays the frame on the screen.

Programmatically, your application makes multiple calls to a DrawPrimitive method, repeatedly passing the same 3-D object. Before each call, the position of the object is updated slightly, producing a series of blurred object images on the target rendering surface. If the object has one or more textures, your application can enhance the motion blur effect by rendering the first image of the object with all its textures nearly transparent. Each time the object renders, the transparency of the object's texture decreases. When your application renders the object in its final position, it should render the object's textures without transparency. The exception is if you're adding motion blur to another effect that requires texture transparency. In any case, the initial image of the object in the frame should be the most transparent. The final image should be the least transparent.

After your application renders the series of object images onto the target rendering surface and renders the rest of the scene, it should call the Present method to display the frame on the screen.

If your application is simulating the effect of the user moving through a scene at high speed, it can add motion blur to the entire scene. In this case, your application renders the entire scene multiple times per frame. Each time the scene renders, your application must move the viewpoint slightly. If the scene is highly complex, the user may see a visible performance degradation as acceleration is increased because of the increasing number of scene renderings per frame.


Bump Mapping

This section provides information about performing bump mapping with Microsoft® Direct3D®. The following topics introduce bump mapping, identify and define its key concepts, and provide details about how you can use bump-mapping in your applications.

  • What Is Bump Mapping?
  • Bump Map Pixel Formats
  • Bump Mapping Formulas
  • Using Bump Mapping


What Is Bump Mapping?

Bump mapping is a special form of specular or diffuse environment mapping that simulates the reflections of finely tessellated objects without requiring extremely high polygon counts. The following image, based on the BumpEarth Sample, demonstrates bump mapping effects.

The globe on the left is a sphere textured with an image of the Earth's surface, with a specular environment map applied. The globe on the right is exactly the same, but also has a bump map applied. The polygon count for the second globe is unchanged from that of the first globe.

Bump mapping in Microsoft® Direct3D® can be accurately described as per-pixel texture coordinate perturbation of specular or diffuse environment maps, because you provide information about the contour of the bump map in terms of delta-values, which the system applies to the u and v texture coordinates of an environment map in the next texture stage. The delta values are encoded in the pixel format of the bump map surface. For more information, see Bump Map Pixel Formats.

The BumpEarth sample uses a height-map to store contour data. When the sample starts, it processes the pixels in the height map to compute the appropriate u and v delta values, based on the relative height of each pixel to the four neighboring pixels.

Direct3D does not natively support height-maps; they are merely a convenient format in which to store and visualize contour data. The preceding image is based on the height map used by the BumpEarth sample to produce the bump map it supplies to Direct3D. and is included here for descriptive purposes. Your application can store contour information in any format, or even generate a procedural bump map, as the BumpWaves Sample does.

This is the height map image that the BumpEarth sample uses to compute the delta values encoded in the pixel format of the bump map texture.

Bump mapping relies completely on multiple texture blending services, and requires that the device support at least two blending stages—one for the bump map, and another for an environment map. A minimum of three texture blending stages are required to apply a base texture map, the most common case. The following figure shows the relationships between the base texture, the bump map, and the environment map in the texture blending cascade.

You must prepare the texture stages appropriately to enable bump mapping. This task is the topic of Configuring Bump Mapping Parameters.


Bump Map Pixel Formats

A bump map is a IDirect3DTexture8 object that uses a specialized pixel format. Rather than storing red, green, and blue color components, each pixel in a bump map stores the delta values for u and v (Du and Dv) and sometimes a luminance component, L. These values are applied by the system as described in the Bump Mapping Formulas topic.

You can specify a bump map pixel format by setting the D3DFORMAT enumerated type to one of the following bump map pixel formats.

Format | Description
D3DFMT_V8U8 | 16-bit bump-map format.
D3DFMT_L6V5U5 | 16-bit bump-map format with luminance.
D3DFMT_X8L8V8U8 | 32-bit bump-map format with luminance where 8 bits are reserved for each element.
D3DFMT_Q8W8V8U8 | 32-bit bump-map format.
D3DFMT_V16U16 | 32-bit bump-map format.
D3DFMT_W11V11U10 | 32-bit bump-map format.

The Du and Dv components of a pixel are signed values that range from –1.0 to +1.0. The luminance component, when used, is an unsigned integer value that ranges from 0 to 255.

Note Before picking a bump map pixel format, you should check if the particular format is supported. For more information, see Detecting Support for Bump Mapping.


Bump Mapping Formulas

Microsoft® Direct3D® applies the following formulas to the Du and Dv components in each bump map pixel.

In these formulas, the Du and Dv variables are taken directly from a bump map pixel and transformed by a 2×2 matrix to produce the output delta values Du' and Dv'. The system uses the output values to modify the texture coordinates that address the environment map in the next texture stage. The coefficients of the transformation matrix are set though the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT10, D3DTSS_BUMPENVMAT01, and D3DTSS_BUMPENVMAT11 texture stage states.

In addition to the u and v delta values, the system can compute a luminance value that it uses to modulate the color of the environment map in the next blending stage.

In this formula, L' is the output luminance being computed. The L variable is the luminance value taken from a bump map pixel, which is multiplied by the scaling factor, S, and offset by the value in the variable O. The D3DTSS_BUMPENVLSCALE and D3DTSS_BUMPENVLOFFSET texture stage states control the values for the S and O variables in the formula. This formula is only applied when the texture blending operation for the stage that contains the bump map is set to D3DTOP_BUMPENVMAPLUMINANCE. When using D3DTOP_BUMPENVMAP, the system uses a value of 1.0 for L'.

After computing the output delta values Du' and Dv', the system adds them to the texture coordinates in the next texture stage, and modulates the chosen color by the luminance to produce the color applied to the polygon.


Using Bump Mapping

The following topics provide details about the most common tasks an application must perform when using Microsoft® Direct3D® bump mapping.

  • Detecting Support for Bump Mapping
  • Creating a Bump Map Texture
  • Configuring Bump Mapping Parameters


Detecting Support for Bump Mapping

A Microsoft® Direct3D® device can perform bump mapping if it supports either the D3DTOP_BUMPENVMAP or D3DTOP_BUMPENVMAPLUMINANCE texture blending operation. Additionally, applications should check the device capabilities to make sure the device supports an appropriate number of blending stages, usually at least three, and exposes at least one bump-mapping pixel format.

The following code example checks device capabilities to detect support for bump mapping in the current device, using the given criteria.

BOOL SupportsBumpMapping()
{
    D3DCAPS8 d3dCaps;

    d3dDevice->GetDeviceCaps( &d3dCaps );

    // Does this device support the two bump mapping blend operations?
    if ( 0 == d3dCaps.TextureOpCaps & ( D3DTEXOPCAPS_BUMPENVMAP |
                                         D3DTEXOPCAPS_BUMPENVMAPLUMINANCE ))
        return FALSE;

    // Does this device support up to three blending stages?
    if( d3dCaps.MaxTextureBlendStages < 3 )
        return FALSE;
}


Creating a Bump Map Texture

You create a bump map texture like any other texture. Once your application verifies support for bump mapping and retrieves a valid pixel format, as discussed in Detecting Support For Bump Mapping, you can create a bump map texture surface. For information on creating textures, see Obtaining a Texture Surface Object.

After the surface is created, you can load each pixel with the appropriate delta values, and luminance, if the surface format includes luminance. The values for each pixel component are described in Bump Map Pixel Formats.


Configuring Bump Mapping Parameters

When your application has created a bump map and set the contents of each pixel, you can prepare for rendering by configuring bump mapping parameters. Bump mapping parameters include setting the required textures and their blending operations, as well as the transformation and luminance controls for the bump map itself.

To configure bump mapping parameters in C++

  1. Set the base texture map if used, bump map, and environment map textures into texture blending stages.
  2. Set the color and alpha blending operations for each texture stage.
  3. Set the bump map transformation matrix.
  4. Set the luminance scale and offset values as needed.

The following code example sets three textures—the base texture map, the bump map, and a specular environment map—to the appropriate texture blending stages.

    // Set the three textures.
    d3dDevice->SetTexture( 0, d3dBaseTexture );
    d3dDevice->SetTexture( 1, d3dBumpMap );
    d3dDevice->SetTexture( 2, d3dEnvMap );

After setting the textures to their blending stages, the following code example prepares the blending operations and arguments for each stage.

    // Set the color operations and arguments to prepare for
    // bump mapping.

    // Stage 0: the base texture.
    d3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
    d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    d3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
    d3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1 );
    d3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE );
    d3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, 1 );

    // Stage 1: the bump map - Use luminance for this example.
    d3dDevice->SetTextureStageState( 1, D3DTSS_TEXCOORDINDEX, 1 );
    d3dDevice->SetTextureStageState( 1, D3DTSS_COLOROP, D3DTOP_BUMPENVMAPLUMINANCE);
    d3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    d3dDevice->SetTextureStageState( 1, D3DTSS_COLORARG2, D3DTA_CURRENT );

    // Stage 2: a specular environment map.
    d3dDevice->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX, 0 );
    d3dDevice->SetTextureStageState( 2, D3DTSS_COLOROP, D3DTOP_ADD );
    d3dDevice->SetTextureStageState( 2, D3DTSS_COLORARG1, D3DTA_TEXTURE );
    d3dDevice->SetTextureStageState( 2, D3DTSS_COLORARG2, D3DTA_CURRENT );

Once the blending operations and arguments are set, the following code example sets the 2×2 bump mapping matrix to the identity matrix by setting the D3DTSS_BUMPENVMAT00 and D3DTSS_BUMPENVMAT11 texture stage states to 1.0. Setting the matrix to the identity causes the system to use the delta-values in the bump map unmodified, but this is not a requirement.

    // Set the bump mapping matrix.
    //
    // NOTE
    //    These calls rely on the following inline shortcut function:
    //       inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
    d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT00, F2DW(1.0f) );
    d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT01, F2DW(0.0f) );
    d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT10, F2DW(0.0f) );
    d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVMAT11, F2DW(1.0f) );

If you set the bump mapping operation to include luminance (D3DTOP_BUMPENVMAPLUMINANCE), you must set the luminance controls. The luminance controls configure how the system computes luminance before modulating the color from the texture in the next stage. For details, see Bump Mapping Formulas.

    // Set luminance controls. This is only needed when using
    // a bump map that contains luminance, and when the
    // D3DTOP_BUMPENVMAPLUMINANCE texture blending operation is
    // being used.
    //
    // NOTE
    //    These calls rely on the following inline shortcut function:
    //       inline DWORD F2DW( FLOAT f ) { return *((DWORD*)&f); }
    d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVLSCALE, F2DW(0.5f) );
    d3dDevice->SetTextureStageState( 1, D3DTSS_BUMPENVLOFFSET, F2DW(0.0f) );

After your application configures bump mapping parameters, it can render as normal, and the rendered polygons receive bump mapping effects.

Note The preceding example shows parameters set for specular environment mapping. When performing diffuse light mapping, applications set the texture blending operation for the last stage to D3DTOP_MODULATE. For more information, see Diffuse Light Maps.


Environment Mapping

This section provides information about performing two common types of environment mapping with Microsoft® Direct3D®. There are many types of environment mapping in use throughout the graphics industry, but the following topics target the two most common forms: cubic environment mapping and spherical environment mapping.

  • What Is Environment Mapping?
  • Cubic Environment Mapping
  • Spherical Environment Mapping


What Is Environment Mapping?

Environment mapping is a technique that simulates highly reflective surfaces without using ray-tracing. In practice, environment mapping applies a special texture map that contains an image of the scene surrounding an object to the object itself. The result approximates the appearance of a reflective surface, close enough to fool the eye, without incurring any of the expensive computations involved in ray-tracing.

The following image is taken from the SphereMap Sample, which, as its name implies, uses a type of environment mapping called spherical environment mapping. For details, see Spherical Environment Mapping.

The teapot in this image appears to reflect its surroundings; this is actually a texture being applied to the object. Because environment mapping uses a texture, combined with specially computed texture coordinates, it can be performed in real-time.


Cubic Environment Mapping

Cubic environment mapping textures an object with an image of the space or lighting effects surrounding the object, represented in the form of six internal faces of a cube. Information in this section is divided into the following topics.

  • What Are Cubic Environment Maps?
  • Creating Cubic Environment Map Surfaces
  • Accessing Cubic Environment Map Faces
  • Mipmapped Cubic Environment Maps
  • Rendering to Cubic Environment Maps
  • Texture Coordinates for Cubic Environment Maps


What Are Cubic Environment Maps?

Cubic environment maps—sometimes casually referred to as cube maps—are textures that contain image data representing the scene surrounding an object, as if the object were in the center of a cube. Each face of the cubic environment map covers a 90-degree field of view in the horizontal and vertical, and there are six faces per cube map. The orientation of the faces is given in the following illustration.

Each face of the cube is oriented perpendicular to the x/y, y/z, or x/z plane, in world space. The following figure shows how each plane corresponds to a face.

Cubic-environment maps are implemented as a series of texture objects. Applications can use static images for cubic-environment mapping, or they can render into the faces of the cube map to perform dynamic environment mapping. This technique requires that the cube-map surfaces be valid render-target surfaces, created with the D3DUSAGE_RENDERTARGET flag set.

The faces of a cube map don't need to contain extremely detailed renderings of the surrounding scene. In most cases, environment maps are applied to curved surfaces. Given the amount of curvature used by most applications, the resulting reflective distortion makes extreme detail in the environment map wasteful in terms of memory and rendering overhead.


Creating Cubic-Environment Map Surfaces

You create a cubic environment map texture by calling the IDirect3DDevice8::CreateCubeTexture method. Cubic-environment map textures must be square, with dimensions that are a power of two.

The following code example shows how your C++ application might create a simple cubic-environment map.

/*
 * For this example, m_d3dDevice is a valid
 * pointer to an IDirect3DDevice8 interface.
 */

LPDIRECT3DCUBETEXTURE8 m_pCubeMap;

m_d3dDevice->CreateCubeTexture( 256, 1, D3DUSAGE_RENDERTARGET, D3DFMT_R8G8B8,
                                D3DPOOL_MANAGED, &m_pCubeMap );


Accessing Cubic Environment Map Faces

You can navigate between faces of a cubic environment map by using the IDirect3DCubeTexture8::GetCubeMapSurface method.

The following code example uses GetCubeMapSurface to retrieve the cube-map surface used for the positive-y face (face 2).

/*
 * For this example, m_pCubeMap is a valid
 * pointer to a IDirect3DCubeTexture8 interface.
 */
LPDIRECT3DSURFACE8 pFace2;

m_pCubeMap->GetCubeMapSurface( D3DCUBEMAP_FACE_POSITIVE_Y, 0, &pFace2);

The first parameter that GetAttachedSurface accepts is a D3DCUBEMAP_FACES enumerated value that describes the attached surface that the method should retrieve. The second parameter tells Microsoft® Direct3D® which level of a mipmapped cube texture to retrieve. The third parameter accepted is the address of the IDirect3DSurface8 interface, representing the returned cube texture surface. Because this cube-map is not mipmapped, 0 is used here.

Note After calling this method, the internal reference count on the IDirect3DSurface8 interface is increased. When you are done using this surface, be sure to call the IUnknown::Release method on this IDirect3DSurface8 interface or you will have a memory leak.


Mipmapped Cubic Environment Maps

Cube maps can be mipmapped. If you include the DDSCAPS_MIPMAP capability, the system creates each face with attached mipmap surfaces. You can envision the topography of these surfaces as shown in the following graphic.

Applications that create mipmapped cubic-environment maps can access each face by calling the IDirect3DCubeTexture8::GetCubeMapSurface method. Start by setting the appropriate value from the D3DCUBEMAP_FACES enumerated type, as discussed in Accessing Cubic Environment Map Faces. Next, select the level to retrieve by setting the Level parameter to the mipmap level that you want. Remember that 0 corresponds with the top-level image.


Rendering to Cubic Environment Maps

You can copy images to the individual faces of the cube map just like you would any other texture or surface object. The most important thing to do before rendering to a face is set the transformation matrices so that the camera is positioned properly and points in the proper direction for that face: forward (+z), backward (-z), left (-x), right (+x), up (+y), or down (-y).

The following C++ code example prepares and sets a view matrix according to the face being rendered.

/*
 * For this example, pCubeMap is a valid pointer to a
 * IDirect3DCubeTexture8 interface and d3dDevice is a
 * valid pointer to a IDirect3DDevice8 interface.
 */
void RenderFaces()
{
    // Save transformation matrices of the device.
    D3DXMATRIX matProjSave, matViewSave;
    d3dDevice->GetTransform( D3DTS_VIEW,       &matViewSave );
    d3dDevice->GetTransform( D3DTS_PROJECTION, &matProjSave );

    // Store the current back buffer and z-buffer.
    LPDIRECT3DSURFACE8 pBackBuffer, pZBuffer;
    d3dDevice->GetRenderTarget( &pBackBuffer );
    d3dDevice->GetDepthStencilSurface( &pZBuffer );

Remember, each face of a cubic-environment map represents a 90-degree field of view. Unless your application requires a different field of view angle—for special effects, for example—take care to set the projection matrix accordingly.

This code example creates and sets a projection matrix for the most common case.

    // Use 90-degree field of view in the projection.
    D3DMATRIX matProj;
    D3DXMatrixPerspectiveFovLH( matProj, D3DX_PI/2, 1.0f, 0.5f, 1000.0f );
    d3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );

    // Loop through the six faces of the cube map.
    for( DWORD i=0; i<6; i++ )
    {
        // Standard view that will be overridden below.
        D3DVECTOR vEnvEyePt = D3DVECTOR( 0.0f, 0.0f, 0.0f );
        D3DVECTOR vLookatPt, vUpVec;

        switch( i )
        {
            case D3DCUBEMAP_FACE_POSITIVE_X:
                vLookatPt = D3DVECTOR( 1.0f, 0.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_X:
                vLookatPt = D3DVECTOR(-1.0f, 0.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
            case D3DCUBEMAP_FACE_POSITIVE_Y:
                vLookatPt = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 0.0f,-1.0f );
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_Y:
                vLookatPt = D3DVECTOR( 0.0f,-1.0f, 0.0f );
                vUpVec    = D3DVECTOR( 0.0f, 0.0f, 1.0f );
                break;
            case D3DCUBEMAP_FACE_POSITIVE_Z:
                vLookatPt = D3DVECTOR( 0.0f, 0.0f, 1.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
            case D3DCUBEMAP_FACE_NEGATIVE_Z:
                vLookatPt = D3DVECTOR( 0.0f, 0.0f,-1.0f );
                vUpVec    = D3DVECTOR( 0.0f, 1.0f, 0.0f );
                break;
        }

        D3DMATRIX matView;
        D3DXMatrixLookAtLH( matView, vEnvEyePt, vLookatPt, vUpVec );
        d3dDevice->SetTransform( D3DTS_VIEW, &matView );

Once the camera is in position and the projection matrix set, you can render the scene. Each object in the scene should be positioned as you would normally position them. The following code example, provided for completeness, outlines this task.

        //Get pointer to surface in order to render to it.
        LPDIRECT3DSURFACE8 pFace;
        pCubeMap->GetCubeMapSurface( (D3DCUBEMAP_FACES)i, 0, &pFace );
        d3dDevice->SetRenderTarget ( pFace , pZBuffer );
        pFace->Release();

        d3dDevice->BeginScene();
        // Render scene here.
        d3dDevice->EndScene();
    }

    // Change the render target back to the main back buffer.
    d3dDevice->SetRenderTarget( pBackBuffer, pZBuffer );
    pBackBuffer->Release();
    pZBuffer->Release();

    // Restore the original transformation matrices.
    d3dDevice->SetTransform( D3DTS_VIEW,       &matViewSave );
    d3dDevice->SetTransform( D3DTS_PROJECTION, &matProjSave );
}

Note the call to the IDirect3DDevice8::SetRenderTarget method. When rendering to the cube map faces, you must assign the face as the current render-target surface. Applications that use depth buffers can explicitly create a depth-buffer for the render-target, or reassign an existing depth-buffer to the render-target surface. The code sample above uses the latter approach.


Texture Coordinates for Cubic Environment Maps

Texture coordinates that index a cubic-environment map aren't simple u, v style coordinates, as used when standard textures are applied. In fact, cubic environment maps don't use texture coordinates at all. In place of a set of texture coordinates, cubic environment maps require a 3-D vector. You must take care to specify a proper vertex format. In addition to telling the system how many sets of texture coordinates your application uses, you must provide information about how many elements are in each set. Microsoft® Direct3D® offers the D3DFVF_TEXCOORDSIZEn set of macros for this purpose. These macros accept a single parameter, identifying the index of the texture coordinate set for which the size is being described. In the case of a 3-D vector, you include the bit pattern created by the D3DFVF_TEXCOORDSIZE3 macro. The following code example shows how this macro is used.

/*
 * Create a flexible vertex format descriptor for a vertex that
 * contains a position, normal, and one set of 3-D texture
 * coordinates.
 */
DWORD dwFVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX1 | D3DFVF_TEXCOORDSIZE3(0);

In some cases, such as diffuse light mapping, you use the camera-space vertex normal for the vector. In other cases, like specular environment mapping, you use a reflection vector. Because transformed vertex normals are widely understood, the information here concentrates on computing a reflection vector.

Computing a reflection vector on your own requires understanding of the position of each vertex, and of a vector from the viewpoint to that vertex. Direct3D can automatically compute the reflection vectors for your geometry. Using this feature saves memory because you don't need to include texture coordinates for the environment map. It also reduces bandwidth and, in the case of a TnLHAL Device, it can be significantly faster than the computations that your application can make on its own. To use this feature, in the texture stage that contains the cubic-environment map, set the D3DTSS_TEXCOORDINDEX texture stage state to a combination of the D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR flag and the index of a texture coordinate set. In some situations, like diffuse light mapping, you might use the D3DTSS_TCI_CAMERASPACENORMAL flag, which causes the system to use the transformed, camera-space, vertex normal as the addressing vector for the texture. The index is only used by the system to determine the wrapping mode for the texture.

The following code example shows how this value is used.

/*
 * The m_d3dDevice variable is a valid pointer
 * to an IDirect3DDevice8 interface.
 *
 * Automatically generate texture coordinates for stage 2.
 * This assumes that stage 2 is assigned a cube map.
 * Use the wrap mode from the texture coordinate set at index 1.
 */
m_d3dDevice->SetTextureStageState( 2, D3DTSS_TEXCOORDINDEX,
                                   D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR | 1);

When you enable automatic texture coordinate generation, the system uses one of two formulas to compute the reflection vector for each vertex. When the D3DRS_LOCALVIEWER render state is set to TRUE, the formula used is the following:

In the preceding formula, R is the reflection vector being computed, E is the normalized position-to-eye vector, and N is the camera-space vertex normal.

When the D3DRS_LOCALVIEWER render state is set to FALSE, the system uses the following formula.

The R and N elements in this formula are identical to the previous formula. The Nz element is the world-space z of the vertex normal, and I is the vector (0,0,1) of an infinitely distant viewpoint. The system uses the reflection vector from either formula to select and address the appropriate face of the cube map.

Note In most cases, applications should enable automatic normalization of vertex normals. To do this, set D3DRS_NORMALIZENORMALS to TRUE. If you do not enable this render state, the appearance of the environment map will be drastically different than you might expect.


Spherical Environment Mapping

Spherical environment mapping—often called sphere mapping—textures an object with an image or lighting effects of the space surrounding the object, where that space is encoded in a specially formatted texture map. The following topics introduce the concept of sphere mapping and provide information about how you can use it in your Microsoft® Direct3D® applications.

  • What Are Spherical Environment Maps?
  • Texture Coordinates for Spherical Environment Maps
  • Applying Spherical Environment Maps


What Are Spherical Environment Maps?

Spherical environment maps, or sphere maps, are special textures that contain an image of the scene surrounding an object, or the lighting effects around the object. Unlike cubic environment maps, sphere maps don't directly represent an object's surroundings. The teapot image in the What Is Environment Mapping? topic shows the reflection effects you can achieve with sphere mapping.

A sphere map is a 2-D representation of the full 360-degree view of the scene surrounding of an object, as if taken through a fish-eye lens. The following illustration is the sphere map used by the SphereMap Sample.


Texture Coordinates for Spherical Environment Maps

The texture coordinates that you specify for each vertex receiving an environment mapping should address the texture as a function of the reflective distortion created by the curvature of the surface. Applications must compute these texture coordinates for each vertex to achieve the desired effect. One simple and effective way to generate texture coordinates uses the vertex normal as input. Although several methods exist, the following formula is common among applications that perform environment mapping with sphere maps.

In these formulas, u and v are the texture coordinates being computed, and Nx and Ny are the x and y components of the camera-space vertex normal. The formula is simple but effective. If the normal has a positive x component, the normal points to the right, and the u coordinate is adjusted to address the texture appropriately. Likewise for the v coordinate: positive y indicates that the normal points up. The opposite is true for negative values in each component.

If the normal points directly at the camera, the resulting coordinates should receive no distortion. The +0.5 bias to both coordinates places the point of zero-distortion at the center of the sphere map, and a vertex normal of (0, 0, z) addresses this point. This formula doesn't account for the z component of the normal, but applications that use the formula can optimize computations by skipping vertices with a normal that has a positive z element. This works because, in camera space, if the normal points away from the camera (positive z), the vertex is culled when the object is rendered.


Applying Spherical Environment Maps

You apply an environment map to objects in the same manner as for any other texture, by setting the texture to the appropriate texture stage with the IDirect3DDevice8::SetTexture method. Set the first parameter to the index for the desired texture stage, and set the second parameter to the address of the IDirect3DCubeTexture8 interface returned when you created the cube-map texture for the environment map. You can set the color and alpha blending operations and arguments as needed to achieve the desired texture blending effects.


Fog

The following topics introduce fog and present information about using various fog features in Microsoft® Direct3D® applications.

  • Introduction to Fog
  • Fog Formulas
  • Fog Parameters
  • Fog Blending
  • Fog Color
  • Pixel Fog
  • Vertex Fog

Fog blending is controlled by render states; it is not part of the programmable pixel pipeline.


Introduction to Fog

Adding fog to a 3-D scene can enhance realism, provide ambiance or set a mood, and obscure artifacts sometimes caused when distant geometry comes into view. Microsoft® Direct3D® supports two fog models—pixel fog and vertex fog—each with its own features and programming interface.

Essentially, fog is implemented by blending the color of objects in a scene with a chosen fog color based on the depth of an object in a scene or its distance from the viewpoint. As objects grow more distant, their original color blends more and more with the chosen fog color, creating the illusion that the object is being increasingly obscured by tiny particles floating in the scene. The following illustration shows a scene rendered without fog, and a similar scene rendered with fog enabled.

In this illustration, the scene on the left has a clear horizon, beyond which no scenery is visible, even though it would be visible in the real world. The scene on the right obscures the horizon by using a fog color identical to the background color, making polygons appear to fade into the distance. By combining discrete fog effects with creative scene design you can add mood and soften the color of objects in a scene.

Direct3D provides two ways to add fog to a scene, pixel fog and vertex fog, named for how the fog effects are applied. For details, see Pixel Fog and Vertex Fog. In short, pixel fog—also called table fog—is implemented in the device driver, and vertex fog is implemented in the Direct3D lighting engine.

Note Regardless of which type of fog—pixel or vertex—you use, your application must provide a compliant projection matrix to ensure that fog effects are properly applied. This restriction applies even to applications that do not use the Direct3D transformation and lighting engine. For additional details about how you can provide an appropriate matrix, see A W-Friendly Projection Matrix.


Fog Formulas

C++ applications can control how fog affects the color of objects in a scene by changing how Microsoft® Direct3D® computes fog effects over distance. The D3DFOGMODE enumerated type contains members that identify the three fog formulas. All formulas calculate a fog factor as a function of distance, given parameters that your application sets. How distance is computed depends on the projection matrix or whether range-based fog is enabled. For more information, see Eye-Relative vs. Z-Based Depth and Range-Based Fog.

D3DFOG_LINEAR

In this linear formula, start is the distance at which fog effects begin, end is the distance at which fog effects no longer increase, and d represents depth, or distance from the viewpoint, in a scene. Values for d increase as objects become more distant. Linear and exponential formulas are supported for both pixel fog and vertex fog.

D3DFOG_EXP

D3DFOG_EXP2

In these two exponential formulas, e is the base of natural logarithms (approximately 2.71828), density is an arbitrary fog density that can range from 0.0 to 1.0, and d is depth, or distance from the viewpoint, in a scene.

Note The system stores the fog factor in the alpha component of the specular color for a vertex. If your application performs its own transformation and lighting, you can insert fog factor values manually, to be applied by the system during rendering.

The following illustration graphs these formulas, using common values as in the formula parameters.

When Direct3D calculates fog effects, it uses the fog factor from one of the preceding equations in a blending formula, shown here.

This formula effectively scales the color of the current polygon Ci by the fog factor f, and adds the product to the fog color Cf, scaled by the bitwise inverse of the fog factor. The resulting color value is a blend of the fog color and the original color, as a factor of distance. The formula applies to all devices supported in Microsoft DirectX® 7.0 and later. For the legacy ramp device, the fog factor scales the diffuse and specular color components, clamped to the range of 0.0 and 1.0, inclusive. The fog factor typically starts at 1.0 for the near plane and decreases to 0.0 at the far plane.


Fog Parameters

Fog parameters are controlled through device render states. Both pixel and vertex fog types support all the fog formulas introduced in Fog Formulas. The D3DFOGMODE enumerated type defines constants that you can use to identify the fog formula you want Microsoft® Direct3D® to use. The D3DRS_FOGTABLEMODE render state controls the fog mode that Direct3D uses for pixel fog, and the D3DRS_FOGVERTEXMODE render state controls the mode for vertex fog.

When using the linear fog formula, you set the starting and ending distances through the D3DRS_FOGSTART and D3DRS_FOGEND render states. How the system interprets these values depends on the type of fog your application uses—pixel or vertex fog—and, when using pixel fog, if z-based or w-based depth is being used. For information z- and w-based pixel fog, see Eye-Relative vs. Z-Based Depth. The following table summarizes fog types and their start and end units.

Fog type | Fog start/end units
Pixel (Z) | Device space [0.0,1.0]
Pixel (W) | Camera space
Vertex | Camera space

The D3DRS_FOGDENSITY render state controls the fog density applied when an exponential fog formula is enabled. Fog density is essentially a weighting factor, ranging from 0.0 to 1.0 (inclusive), that scales the distance value in the exponent.

The color that the system uses for fog blending is controlled through the D3DRS_FOGCOLOR device render state. For more information, see Fog Color and Fog Blending.


Fog Blending

Fog blending refers to the application of the fog factor to the fog and object colors to produce the final color that appears in a scene, as discussed in Fog Formulas. The D3DRS_FOGENABLE render state controls fog blending. Set this render state to TRUE to enable fog blending as shown in the following example code. The default is FALSE.

//
// For this example, g_pDevice is a valid pointer
// to an IDirect3DDevice8 interface.
HRESULT hr;
hr = g_pDevice->SetRenderState(
                     D3DRS_FOGENABLE,
                     TRUE);
if FAILED(hr)
    return hr;

You must enable fog blending for both pixel fog and vertex fog. For information about using these types of fog, see Pixel Fog and Vertex Fog.


Fog Color

Fog color for both pixel and vertex fog is set through the D3DRS_FOGCOLOR render state. The render state values can be any RGB color, specified as an RGBA color; the alpha component is ignored.

The following C++ example sets the fog color to white.

/* For this example, the d3dDevice variable is
 * a valid pointer to an IDirect3DDevice8 interface.
 */
HRESULT hr;

hr = d3dDevice->SetRenderState(
                    D3DRS_FOGCOLOR,
                    0x00FFFFFF); // Highest 8 bits are not used.

if(FAILED(hr))
    return hr;


Pixel Fog

This section introduces the concept of pixel fog and provides information about using it in Microsoft® Direct3D® applications. Information is divided into the following topics.

  • About Pixel Fog
  • Eye-Relative vs. Z-Based Depth
  • Using Pixel Fog


About Pixel Fog

Pixel fog gets its name from the fact that it is calculated on a per-pixel basis in the device driver, unlike vertex fog, in which Microsoft® Direct3D® computes fog effects when it performs transformation and lighting. Pixel fog is sometimes called table fog because some drivers use a precalculated look-up table to determine the fog factor, using the depth of each pixel, to apply in blending computations.

Pixel fog can be applied using any fog formula identified by members of the D3DFOGMODE enumerated type. Pixel-fog formula implementations are driver-specific, and if a driver doesn't support a complex fog formula, it should degrade to a less complex formula.

Note As discussed in Range-Based Fog, pixel fog does not support range-based fog calculations.


Eye-Relative vs. Z-Based Depth

To alleviate fog-related graphic artifacts caused by uneven distribution of z-values in a depth buffer, most hardware devices use eye-relative depth instead of z-based depth values for pixel fog. Eye-relative depth is essentially the w element from a homogeneous coordinate set. Microsoft® Direct3D® takes the reciprocal of the RHW element from a device space coordinate set to reproduce true w. If a device supports eye-relative fog, it sets the D3DPRASTERCAPS_WFOG flag in the RasterCaps member of the D3DCAPS8 structure when you call the IDirect3DDevice8::GetDeviceCaps method.

Note With the exception of the reference rasterizer, software devices always use z to calculate pixel fog effects.

When eye-relative fog is supported, the system automatically uses eye-relative depth rather than z-based depth if the provided projection matrix produces z-values in world space that are equivalent to w-values in device space. You set the projection matrix by calling the IDirect3DDevice8::SetTransform method, using the D3DTS_PROJECTION value and passing a D3DMATRIX structure that represents the desired matrix. If the projection matrix isn't compliant with this requirement, fog effects are not applied properly. For details about producing a compliant matrix, see A W-Friendly Projection Matrix. The perspective projection matrix provided in What Is the Projection Transformation? produces a compliant projection matrix.

Direct3D uses the currently set projection matrix in its w-based depth calculations. As a result, an application must set a compliant projection matrix to receive the desired w-based features, even if it does not use the Direct3D transformation pipeline.

Direct3D checks the fourth column of the projection matrix. If the coefficients are [0,0,0,1] (for an affine projection) the system will use z-based depth values for fog. In this case, you must also specify the start and end distances for linear fog effects in device space, which ranges from 0.0 at the nearest point to the user, and 1.0 at the farthest point.


Using Pixel Fog

Use the following steps to enable pixel fog in your application.

To enable pixel fog in a C++ application

  1. Enable fog blending by setting the D3DRS_FOGENABLE render state to TRUE.
  2. Set the desired fog color in the D3DRS_FOGCOLOR render state.
  3. Choose the fog formula to use by setting the D3DRS_FOGTABLEMODE render state to the corresponding member of the D3DFOGMODE enumerated type.
  4. Set the fog parameters as desired for the selected fog mode in the associated render states. This includes the start and end distances for linear fog, and fog density for exponential fog mode.

The following example shows what these steps might look like in code.

// For brevity, error values in this example are not checked
// after each call. A real-world application should check
// these values appropriately.
//
// For the purposes of this example, g_pDevice is a valid
// pointer to an IDirect3DDevice8 interface.
void SetupPixelFog(DWORD Color, DWORD Mode)
{
    float Start = 0.5f,    // For linear mode
          End   = 0.8f,
          Density = 0.66;  // For exponential modes

    // Enable fog blending.
    g_pDevice->SetRenderState(D3DRS_FOGENABLE, TRUE);

    // Set the fog color.
    g_pDevice->SetRenderState(D3DRS_FOGCOLOR, Color);

    // Set fog parameters.
    if(D3DFOG_LINEAR == Mode)
    {
        g_pDevice->SetRenderState(D3DRS_FOGTABLEMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGSTART, *(DWORD *)(&Start));
        g_pDevice->SetRenderState(D3DRS_FOGEND,   *(DWORD *)(&End));
    }
    else
    {
        g_pDevice->SetRenderState(D3DRS_FOGTABLEMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)(&Density));
    }

}

Note Some fog parameters are required as floating-point values, even though the IDirect3DDevice8::SetRenderState method only accepts DWORD values in the second parameter. The preceding example provides the floating-point values to SetRenderState without data translation by casting the addresses of the floating-point variables as DWORD pointers, and then dereferencing them.


Vertex Fog

This section introduces vertex fog and provides details about using it in Microsoft® Direct3D® applications. Information is divided into the following topics.

  • About Vertex Fog
  • Range-Based Fog
  • Using Vertex Fog


About Vertex Fog

When the system performs vertex fogging, it applies fog calculations at each vertex in a polygon, and then interpolates the results across the face of the polygon during rasterization. Vertex fog effects are computed by the Microsoft® Direct3D® lighting and transformation engine. For more information, see Fog Parameters.

If your application does not use Direct3D for transformation and lighting, it must perform fog calculations on its own. In this case, your application can place the fog factor that it computes in the alpha component of the specular color for each vertex. You are free to use whatever formulas you want—range-based, volumetric, or otherwise. Direct3D uses the supplied fog factor to interpolate across the face of each polygon. Applications that do not use Direct3D transformation and lighting need not set vertex fog parameters, but must still enable fog and set the fog color through the associated render states. For more information, see Fog Parameters.

Note Applications that perform their own transformation and lighting must also perform their own vertex fog calculations. As a result, such an application need only enable fog blending and set the fog color through the associated render states, as described in Fog Blending and Fog Color.


Range-Based Fog

Note Microsoft® Direct3D® uses range-based fog calculations only when using vertex fog with the Direct3D transformation and lighting engine. This is because pixel fog is implemented in the device driver, and no hardware currently exists to support per-pixel range-based fog. If your application performs its own transformation and lighting, it must perform its own fog calculations, range-based or otherwise.

Sometimes, using fog can introduce graphic artifacts that cause objects to be blended with the fog color in nonintuitive ways. For example, imagine a scene in which there are two visible objects: one distant enough to be affected by fog, and the other near enough to be unaffected. If the viewing area rotates in place, the apparent fog effects can change, even if the objects are stationary. The following illustration shows a top-down view of such a situation.

Range-based fog is another, more accurate, way to determine the fog effects. In range-based fog, Direct3D uses the actual distance from the viewpoint to a vertex for its fog calculations. Direct3D increases the effect of fog as the distance between the two points increases, rather than the depth of the vertex within in the scene, thereby avoiding rotational artifacts.

If the current device supports range-based fog, it will set the D3DPRASTERCAPS_FOGRANGE capability flag in the RasterCaps member of the D3DCAPS8 structure when you call the IDirect3DDevice8::GetDeviceCaps method. To enable range-based fog, set the D3DRS_RANGEFOGENABLE render state to TRUE.

Range-based fog is computed by Direct3D during transformation and lighting. As discussed in About Vertex Fog, applications that don't use the Direct3D transformation and lighting engine must also perform their own vertex fog calculations. In this case, provide the range-based fog factor in the alpha component of the specular component for each vertex.


Using Vertex Fog

Use the following steps to enable vertex fog in your application.

To enable vertex fog in a C++ application

  1. Enable fog blending by setting D3DRS_FOGENABLE to TRUE.
  2. Set the fog color in the D3DRS_FOGCOLOR render state.
  3. Choose the desired fog formula by setting the D3DRS_FOGVERTEXMODE render state to a member of the D3DFOGMODE enumerated type.
  4. Set the fog parameters as desired for the selected fog formula in the render states.

The following example, written in C++, shows what these steps might look like in code.

// For brevity, error values in this example are not checked
// after each call. A real-world application should check
// these values appropriately.
//
// For the purposes of this example, g_pDevice is a valid
// pointer to an IDirect3DDevice8 interface.
void SetupVertexFog(DWORD Color, DWORD Mode, BOOL UseRange, FLOAT Density)
{
    float Start = 0.5f,    // Linear fog distances
          End   = 0.8f;

    // Enable fog blending.
    g_pDevice->SetRenderState(D3DRS_FOGENABLE, TRUE);

    // Set the fog color.
    g_pDevice->SetRenderState(D3DRS_FOGCOLOR, Color);

    // Set fog parameters.
    if(D3DFOG_LINEAR == Mode)
    {
        g_pDevice->SetRenderState(D3DRS_FOGVERTEXMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGSTART, *(DWORD *)(&Start));
        g_pDevice->SetRenderState(D3DRS_FOGEND,   *(DWORD *)(&End));
    }
    else
    {
        g_pDevice->SetRenderState(D3DRS_FOGVERTEXMODE, Mode);
        g_pDevice->SetRenderState(D3DRS_FOGDENSITY, *(DWORD *)(&Density));
    }

    // Enable range-based fog if desired (only supported for
    // vertex fog). For this example, it is assumed that UseRange
    // is set to a nonzero value only if the driver exposes the
    // D3DPRASTERCAPS_FOGRANGE capability.
    // Note: This is slightly more performance intensive
    //       than non-range-based fog.
    if(UseRange)
        g_pDevice->SetRenderState(
                       D3DRS_RANGEFOGENABLE,
                       TRUE);
}

Some fog parameters are required as floating-point values, even though the IDirect3DDevice8::SetRenderState method only accepts DWORD values in the second parameter. This example successfully provides the floating-point values to these methods without data translation by casting the addresses of the floating-point variables as DWORD pointers, and then dereferencing them.


Geometry Blending

This section contains information about geometry blending. The following topics are discussed.

  • About Geometry Blending
  • Blending Transform and Render States
  • Blending Weights
  • Using Geometry Blending


About Geometry Blending

Microsoft® Direct3D® enables an application to increase the realism of its scenes by rendering segmented polygonal objects—especially characters—that have smoothly blended joints. These effects are often referred to as skinning. The system achieves this effect by applying additional world transformation matrices to a single set of vertices to create multiple results, and then performing a linear blend between the resultant vertices to create a single set of geometry for rendering. The following image of a banana illustrates this.

This image shows how you might imagine the geometry-blending process. In a single rendering call, the system takes the vertices for the banana, transforms them twice—once without modification, and once with a simple rotation—and blends the results to create a bent banana. The system blends the vertex position, as well as the vertex normal when lighting is enabled. Applications are not limited to two blending paths; Direct3D can blend geometry between as many as four world matrices, including the standard world matrix, D3DTS_WORLD.

Note When lighting is enabled, vertex normals are transformed by a corresponding inverse world-view matrix, weighted in the same way as the vertex position computations. The system normalizes the resulting normal vector if the D3DRS_NORMALIZENORMALS render state is set to TRUE.

Without geometry blending, dynamic articulated models are often rendered in segments. For instance, consider a 3-D model of the human arm. In the simplest view, an arm has two parts: the upper arm which connects to the body, and the lower arm, which connects to the hand. The two are connected at the elbow, and the lower arm rotates at that point. An application that renders an arm might retain vertex data for the upper and lower arm, each with a separate world transformation matrix. The following code example illustrates this.

typedef struct _Arm {
    VERTEX upper_arm_verts[200];
    D3DMATRIX matWorld_Upper;

    VERTEX lower_arm_verts[200];
    D3DMATRIX matWorld_Lower;
} ARM, *LPARM;

ARM MyArm; // This needs to be initialized.

To render the arm, two rendering calls are made, as shown in the following code.

// Render the upper arm.
d3dDevice->SetTransform( D3DTS_WORLD, &MyArm.matWorld_Upper );
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, numFaces );

// Render the lower arm, updating its world matrix to articulate
// the arm by pi/4 radians (45 degrees) at the elbow.
MyArm.matWorld_Lower = RotateMyArm(MyArm.matWorld, pi/4);
d3dDevice->SetTransform( D3DTS_WORLD, &MyArm.matWorld_Lower );
d3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, numFaces );

The following image is a banana, modified to use this technique.

The differences between the blended geometry and the nonblended geometry are obvious. This example is somewhat extreme. In a real-world application, the joints of segmented models are designed so that seams are not as obvious. However, seams are visible at times, which presents constant challenges for model designers.

Geometry blending in Direct3D presents an alternative to the classic segmented-modeling scenario. However, the improved visual quality of segmented objects comes at the cost of the blending computations during rendering. To minimize the impact of these additional operations, the Direct3D geometry pipeline is optimized to blend geometry with the least possible overhead. Applications that intelligently use the geometry blending services offered by Direct3D can improve the realism of their characters while avoiding serious performance repercussions.


Blending Transform and Render States

The IDirect3DDevice8::SetTransform method recognizes the D3DTS_WORLD and D3DTS_WORLDn macros, which correspond to values that can be defined by the D3DTS_WORLDMATRIX macro. These macros are used to identify the matrices between which geometry will be blended.

The D3DRENDERSTATETYPE enumerated type includes the D3DRS_VERTEXBLEND render state to enable and control geometry blending. Valid values for this render state are defined by the D3DVERTEXBLENDFLAGS enumerated type. If geometry blending is enabled, the vertex format must include the appropriate number of blending weights.

See Also

Setting Blending Matrices, Enabling Geometry Blending, Blending Weights


Blending Weights

A blending weight, sometimes called a beta weight, controls the extent to which a given world matrix affects a vertex. Blending weights are floating-point values that range from 0.0 to 1.0, encoded in the vertex format, where a value of 0.0 means the vertex is not blended with that matrix, and 1.0 means that the vertex is affected in full by the matrix.

Geometry blending weights are encoded in the vertex format, appearing immediately after the position for each vertex, as described in About Vertex Formats. You communicate the number of blending weights in the vertex format by including one of the D3DFVF_XYZB1 through D3DFVF_XYZB5 flexible vertex format flags in the vertex description that you provide to the Microsoft® Direct3D® rendering methods.

The system performs a linear blend between the weighted results of the blend matrices. The following is the complete blending formula.

In the preceding formula, vBlend is the output vertex, the v-elements are the vertices produced by the applied world matrix (D3DTS_WORLDn). The W elements are the corresponding weight values within the vertex format. A vertex blended between n matrices can have n–1 blending weight values, one for each blending matrix, except the last. The system automatically generates the weight for the last world matrix so that the sum of all weights is 1.0, expressed in sigma notation here. This formula can be simplified for each of the cases supported by Direct3D.

These are the simplified forms of the complete blending formula for the two, three, and four blend matrix cases.

Note Although Direct3D includes flexible vertex format descriptors to define vertices that contain up to five blending weights, only three can be used in this release of Microsoft DirectX®.


Using Geometry Blending

This section illustrates how you use geometry blending in your application. The following topics are discussed.

  • Defining Vertices for Blending
  • Setting Blending Matrices
  • Enabling Geometry Blending


Defining Vertices for Blending

The following user-defined structure can be used for vertices that will be blended between two matrices.

//
// The flexible vertex format descriptor for this vertex would be:
//
//     FVF = D3DFVF_XYZB1 | D3DFVF_NORMAL | D3DFVF_TEX1;
//
struct D3DBLENDVERTEX {
    D3DVECTOR v;
    FLOAT     blend;
    D3DVECTOR n;
    FLOAT     tu, tv;
};

As described in Blending Weights, the blend weight must appear after the position and RHW data in the flexible vertex format, and before the vertex normal.

Notice that the preceding vertex format contains only one blending weight value. This is because there will be two world matrices, defined in the D3DTS_WORLDMATRIX(0) and D3DTS_WORLDMATRIX(1) transform states. The system blends each vertex between these two matrices using the single weight value. For three matrices, only two weights are required, and so on.

Note Defining skin weights is easy. Using a linear function of the distance between joints is good start, but a smoother sigmoid function looks better. Choosing a skin-weight distribution function can result in sharp creases at joints, if desired, by using a large variation in skin weight over a short distance.

See Also

About Vertex Formats, Flexible Vertex Format Flags


Setting Blending Matrices

You set the transformation matrices between which the system blends by calling the IDirect3DDevice8::SetTransform method. Set the first parameter to a value defined by the D3DTS_WORLDMATRIX macro, and set the second parameter to the address of the matrix to be set.

The following C++ code example sets two world matrices, between which geometry is blended to create the illusion of a jointed arm.

// For this example, the d3dDevice variable is assumed to be a
// valid pointer to an IDirect3DDevice8 interface for an initialized
// 3-D scene.
float     BendAngle = 3.1415926f / 4.0f; // 45 degrees
D3DMATRIX matUpperArm, matLowerArm;

// The upper arm is immobile. Use the identity matrix.
D3DXMatrixIdentity( matUpperArm );
d3dDevice->SetTransform( D3DTS_WORLDMATRIX(0), &matUpperArm );

// The lower arm rotates about the x-axis, attached to the upper arm.
D3DXMatrixRotationX( matLowerArm, -BendAngle );
d3dDevice->SetTransform( D3DTS_WORLDMATRIX(1), &matLowerArm );

Setting a blending matrix merely causes the system to cache the matrix for later use; it doesn't instruct the system to begin blending vertices. For more information, see Enabling Geometry Blending.


Enabling Geometry Blending

Geometry blending is disabled by default. To enable geometry blending, call the IDirect3DDevice8::SetRenderState method to set the D3DRS_VERTEXBLEND render state to a value from the D3DVERTEXBLENDFLAGS enumerated type. The following code example shows what this call might look like when setting the render state for a blend between two world matrices.

d3dDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_1WEIGHTS );

When D3DRS_VERTEXBLEND is set to any value other than D3DVBF_DISABLE, the system assumes that the appropriate number of blending weights will be included in the vertex format. It is your responsibility to provide a compliant vertex format, and to provide a proper description of that format to the Microsoft® Direct3D® rendering methods. For more information, see Defining Vertices for Blending.

When enabled, the system performs geometry blending for all objects rendered by the DrawPrimitive rendering methods.


Indexed Vertex Blending

This section contains information about indexed vertex blending for the Microsoft® Direct3D® fixed function vertex pipeline. The following topics are discussed.

  • About Indexed Vertex Blending
  • Indexed Vertex Blending Transform and Render States
  • Using Indexed Vertex Blending


About Indexed Vertex Blending

Indexed vertex blending extends the vertex blending support in Microsoft® Direct3D® to allow matrices to be used for blending. These matrices are referred to by using a matrix index. These indices are supplied on a per-vertex basis and refer to a palette of up to 256 matrices. Each index is 8 bits and each vertex can have up to four indices, which allows four matrices to be blended per vertex. The indices are packed into a DWORD. Because indices are specified on a per-vertex basis, up to 12 matrices can affect a single triangle, and any matrix in the palette can affect the vertices of one draw call. This approach has the following advantages.

  • It enables more matrices to affect a single triangle.
  • It enables more blended triangles to be passed in the same draw call.
  • It makes vertex blending independent of triangle indices. This enables progressive meshes to work in conjunction with vertex blending.

One disadvantage of this approach is that it does not work with curved-surface primitives when tessellation occurs before vertex processing.

The following illustration demonstrates how four matrices can affect a vertex. Each vertex has up to four indices, so four matrices can be blended per vertex. The illustration below uses the matrices indexed at 0, 2, 5, and 6.

The illustration below demonstrates how up to 12 matrices can affect a triangle. Using indices specified on a per-vertex basis, up to 12 matrices can affect the triangle.

The following formula determines the general case for how matrices effect a vertex.

‹ [image] ›

Vmodel is the input model space vertex position. Index0..Index3 are the per-vertex matrix indices packed into a DWORD. M[] is the array of world matrices that get indexed into. b0..b2 are the blend weights. Vworld is the output world space vertex position.


Indexed Vertex Blending Transform and Render States

Transform states 256-511 are reserved to store up to 256 matrices that can be indexed using 8-bit indices. Use the macro D3DTS_WORLDMATRIX to map indices 0-255 to the corresponding transform states. The following code example shows how to use the IDirect3DDevice8::SetTransform method to set the matrix at transform state number 256 to an identity matrix.

D3DMATRIX matBlend1;

D3DXMatrixIdentity( &matBlend1 );
d3dDevice->SetTransform( D3DTS_WORLDMATRIX(0), &matBlend );

To enable or disable indexed vertex blending, set the D3DRS_INDEXEDVERTEXBLENDENABLE render state to TRUE. When the render state is enabled ,you must pass matrix indices as packed DWORDs with every vertex. When this render state is disabled and vertex blending is enabled, it is equivalent to having the matrix indices 0, 1, 2, and 3 in every vertex. The code example below uses the IDirect3DDevice8::SetRenderState method to enable indexed vertex blending.

d3dDevice->SetRenderState( D3DRS_INDEXEDVERTEXBLENDENABLE, TRUE );

To enable or disable vertex blending, set the D3DRS_VERTEXBLEND render state to a value other than D3DRS_DISABLE from the D3DVERTEXBLENDFLAGS enumerated type. If this render state is not set to D3DRS_DISABLE, then you must pass the required number of weights for each vertex. The following code example uses SetRenderState to enable vertex blending with three weights for each vertex.

d3dDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_3WEIGHTS );


Using Indexed Vertex Blending

The following topics are discussed in this section.

  • Determining Support for Indexed Vertex Blending
  • Passing Matrix Indices to Direct3D


Determining Support for Indexed Vertex Blending

To determine the maximum size for the indexed vertex blending matrix, check the MaxVertexBlendMatrix member of the D3DCAPS8 structure. The code example below uses the IDirect3DDevice8::GetDeviceCaps method to retrieve this size.

D3DCAPS8 d3dCaps;

d3dDevice->GetDeviceCaps( &d3dCaps );
IndexedMatrixMaxSize = d3dCaps.MaxVertexBlendMatrixIndex;

If the value set in MaxVertexBlendMatrix is 0, then the device does not support indexed matrices.

Note When software vertex processing is used, 256 matrices can be used for indexed vertex blending, with or without normal blending.


Passing Matrix Indices to Direct3D

World matrix indices can be passed to Microsoft® Direct3D® by using legacy vertex shaders (FVF) or declarations.

The code example below shows how to use legacy vertex shaders.

struct VERTEX
{
    float x,y,z;
    float weight;
    DWORD matrixIndices;
    float normal[3];
};

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZB2 | D3DFVF_LASTBETA_UBYTE4 |
                             D3DFVF_NORMAL);

When a legacy vertex shader is used, matrix indices are passed together with vertex positions using D3DFVF_XYZBn flags. Matrix indices are passed as bytes inside a DWORD and must be present immediately after the last vertex weight. Vertex weights are also passed using D3DFVF_XYZBn. A packed DWORD contains index3, index2, index1, and index0, where index0 is located in the lowest byte of the DWORD. The number of used world-matrix indices is equal to the number passed to the number of matrices used for blending as defined by D3DRS_VERTEXBLEND.

When a declaration is used, D3DVSDE_BLENDINDICES defines the input vertex register to get matrix indices from. Matrix indices must be passed as D3DVSDT_PACKEDBYTE.

The code example below shows how to use declarations. Note that the order of the components is no longer important unless using a fixed-function vertex shader.

struct VERTEX
{
    float x,y,z;
    float weight;
    DWORD matrixIndices;
    float normal[3];
}

DWORD decl[] =
{
    D3DVSD_STREAM(0),
    D3DVSD_REG(D3DVSDE_POSITION, D3DVSDT_FLOAT3),
    D3DVSD_REG(D3DVSDE_BLENDWEIGHT, D3DVSDT_FLOAT1),
    D3DVSD_REG(D3DVSDE_BLENDINDICES, D3DVSDT_UBYTE),
    D3DVSD_REG(D3DVSDE_NORMAL, D3DVSDT_FLOAT3),
    D3DVSD_END()
};


Stencil Buffer Techniques

Applications use the stencil buffer to mask pixels in an image. The mask controls whether the pixel is drawn. For more information on the stencil buffer, see Stencil Buffers.

Microsoft® Direct3D® applications can achieve a wide range of special effects with the stencil buffer. Some of the more common effects are discussed in this section.

  • Dissolves, Fades, and Swipes
  • Decaling
  • Compositing
  • Outlines and Silhouettes


Dissolves, Fades, and Swipes

Increasingly, applications employ special effects that are commonly used in movies and video, such as dissolves, swipes, and fades.

In a dissolve, one image is gradually replaced by another in a smooth sequence of frames. Although Microsoft® Direct3D® provides methods of using multiple texture blending to achieve the same effect, applications that use the stencil buffer for dissolves can use texture-blending capabilities for other effects while they do a dissolve.

When your application performs a dissolve, it must render two different images. It uses the stencil buffer to control which pixels from each image are drawn to the rendering target surface. You can define a series of stencil masks and copy them into the stencil buffer on successive frames. Alternately, you can define a base stencil mask for the first frame and alter it incrementally.

At the beginning of the dissolve, your application sets the stencil function and stencil mask so that most of the pixels from the starting image pass the stencil test. Most of the pixels from the ending image should fail the stencil test. On successive frames, the stencil mask is updated so that fewer and fewer of the pixels in the starting image pass the test. As the frames progress, fewer and fewer of the pixels in the ending image fail the test. In this manner, your application can perform a dissolve using any arbitrary dissolve pattern.

Fading in or fading out is a special case of dissolving. When fading in, the stencil buffer is used to dissolve from a black or white image to a rendering of a 3-D scene. Fading out is the opposite, your application starts with a rendering of a 3-D scene and dissolves to black or white. The fade can be done using any arbitrary pattern you want to employ.

Direct3D applications use a similar technique for swipes. For example, when an application performs a left-to-right swipe, the ending image appears to slide gradually on top of the starting image from left to right. As in a dissolve, you must define a series of stencil masks that are loaded into the stencil buffer on successive frames, or successively modify the starting stencil mask. The stencil masks are used to disable the writing of pixels from the starting image and to enable the writing of pixels from the ending image.

A swipe is somewhat more complex than a dissolve in that your application must read pixels from the ending image in the reverse order of the swipe. That is, if the swipe is moving from left to right, your application must read pixels from the ending image from right to left.


Decaling

Microsoft® Direct3D® applications use decaling to control which pixels from a particular primitive image are drawn to the rendering target surface. Applications apply decals to the images of primitives to enable coplanar polygons to render correctly.

For instance, when applying tire marks and yellow lines to a roadway, the markings should appear directly on top of the road. However, the z values of the markings and the road are the same. Therefore, the depth buffer might not produce a clean separation between the two. Some pixels in the back primitive may be rendered on top of the front primitive and vice versa. The resulting image appears to shimmer from frame to frame. This effect is called Z Fighting or flimmering.

To solve this problem, use a stencil to mask the section of the back primitive where the decal will appear. Turn off z-buffering and render the image of the front primitive into the masked-off area of the render-target surface.

Although multiple texture blending can be used to solve this problem, doing so limits the number of other special effects that your application can produce. Using the stencil buffer to apply decals frees up texture blending stages for other effects.


Compositing

Your application can use the stencil buffer to composite 2-D or 3-D images onto a 3-D scene. A mask in the stencil buffer is used to occlude an area of the rendering target surface. Stored 2-D information, such as text or bitmaps, can then be written to the occluded area. Alternately, your application can render additional 3-D primitives to the stencil-masked region of the rendering target surface. It can even render an entire scene.

Games often composite multiple 3-D scenes together. For instance, driving games typically display a rear-view mirror. The mirror contains the view of the 3-D scene behind the driver. It is essentially a second 3-D scene composited with the driver's forward view.


Outlines and Silhouettes

You can use the stencil buffer for more abstract effects, such as outlining and silhouetting.

If your application applies a stencil mask to the image of a primitive that is the same shape but slightly smaller, the resulting image contains only the primitive's outline. The application can then fill the stencil-masked area of the image with a solid color, giving the primitive an embossed look.

If the stencil mask is the same size and shape as the primitive you are rendering, the resulting image contains a hole where the primitive should be. Your application can then fill the hole with black to produce a silhouette of the primitive.


Vertex Tweening

This section contains information about vertex tweening using multiple streams. The following topics are discussed.

  • About Vertex Tweening
  • Vertex Tweening Algorithm
  • Using Vertex Tweening


About Vertex Tweening

Vertex tweening is used to blend two user-provided positions or normal streams. It can be used only with declarations. Tweening is enabled by setting D3DRS_VERTEXBLEND to D3DVBF_TWEENING. Vertex blending using weights and vertex blending tweening are mutually exclusive.

The C++ DolphinVS Sample uses vertex tweening to animate a dolphin so that it appears to move through the water. The images below show the dolphin at two different points. Notice that the dolphin's tail has gone from an up position to a down position and its nose points downward more in the right image.

‹ [image] ›


Vertex Tweening Algorithm

Tweening is performed before lighting and clipping. The resulting vertex position (normal) is computed as follows:

POSITION = POSITION1 * (1.0 - TWEENFACTOR) + POSITION2 * TWEENFACTOR, and likewise for normals.


Using Vertex Tweening

The following topics are discussed.

  • Determining Support for Vertex Tweening
  • Setting Vertex Declaration
  • Fixed-Function Tweening
  • Vertex Shader Tweening


Determining Support for Vertex Tweening

To determine if Microsoft® Direct3D® supports vertex tweening, check for the D3DVTXPCAPS_TWEENING flag in the VertexProcessingCaps member of the D3DCAPS8 structure. The following code example uses the IDirect3DDevice8::GetDeviceCaps method to determine if tweening is supported.

//
// This example assumes that m_d3dDevice is
// a valid pointer to a IDirect3DDevice8 interface.
//

D3DCAPS8 d3dCaps;

m_d3dDevice->GetDeviceCaps( &d3dCaps );
if( 0 != d3dCaps.VertexProcessingCaps & D3DVTXPCAPS_TWEENING )
    //Vertex tweening is supported.


Setting Vertex Declaration

To use vector tweening, you must first set up a custom vertex type that uses a second normal or a second position. The following code example shows a sample declaration that includes both a second point and a second position.

struct TEX_VERTEX
{
    D3DVECTOR position;
    D3DVECTOR normal;
    D3DVECTOR position2;
    D3DVECTOR normal2;
};

//Create a vertex buffer with the type TEX_VERTEX.

The next step is to set the current declaration. The code example below shows how to do this.

DWORD decl[]
{
    D3DVSD_STREAM(0),
    D3DVSD_REG( D3DVSDE_POSITION, D3DVSDT_FLOAT3 ) // Position 1
    D3DVSD_REG( D3DVSDE_NORMAL, D3DVSDT_FLOAT3 )   // Normal 1
    D3DVSD_REG( D3DVSDE_POSITION2, D3DVSDT_FLOAT3) // Position 2
    D3DVSD_REG( D3DVSDE_NORMAL2, D3DVSDT_FLOAT3 )  // Normal 2
    D3DVSD_END()
};

For more information on creating a custom vertex type and a vertex buffer, see Creating a Vertex Buffer.

For more information on creating a vertex shader declaration, see Vertex Shader Declaration.

Notes When vertex tweening is enabled, a second position or a second normal must be present in the current declaration.


Fixed-Function Tweening

The code example below shows how to implement fixed-function vertex tweening after a vertex type and declaration are set.

//Variables used for this example
DWORD handle;
float TweenFactor = 0.3f;

The first step is to use the IDirect3DDevice8::CreateVertexShader method to create a vertex shader, as shown in the code example below.

m_d3dDevice->CreateVertexShader( decl, NULL, &handle, 0 );

The first parameter accepted by CreateVertexShader is a pointer to a vector shader declaration. This example uses the declaration declared in the topic Setting Vertex Declaration. The second parameter accepts a pointer to a vertex shader function array. This example does not use a vertex shader function, so this parameter is set to NULL. The third parameter accepts a pointer to a vertex shader handle representing the returned vertex. The fourth parameter specifies the usage controls for the vertex shader. You can use the D3DUSAGE_SOFTWAREPROCESSING flag to indicate that the vertex shader should use software vertex processing. This example sets this parameter to zero to indicate that vertex processing should be done in hardware.

The next step is to set the current vertex shader by calling the IDirect3DDevice8::SetVertexShader method as shown in the code example below.

m_d3dDevice->SetVertexShader( handle );

SetVertexShader accepts a handle to a vertex shader. The value for this parameter can be a handle returned by CreateVertexShader or an FVF code. This example uses the handle returned from CreateVertexShader called in the last step.

The next step is to set the current render state to enable vertex tweening, set the tween factor, and set the stream source. The code example below uses IDirect3DDevice8::SetRenderState and IDirect3DDevice8::SetStreamSource to accomplish this.

m_d3dDevice->SetRenderState( D3DRS_VERTEXBLEND, D3DVBF_TWEENING );
m_d3dDevice->SetRenderState( D3DRS_TWEENFACTOR, *(DWORD*) &TweenFactor );
m_d3dDevice->SetStreamSource( 0 ,vb, 12*sizeof(float));

If you have more than one stream specified for the current vertex shader, you need to call SetStreamSource for each stream that will be used for the tweening effect. At this point, vertex tweening is enabled. A call to any rendering function automatically has vertex tweening applied to it.


Vertex Shader Tweening

The code for using vertex shader tweening is similar to the code for Fixed-Function Tweening. The only difference is the call to IDirect3DDevice8::CreateVertexShader as shown below.

m_d3dDevice->CreateVertexShader( decl, &vsFunction, &handle, 0 );

The second parameter for CreateVertexShader takes a pointer to a vertex shader function token array. This function can be created by calling any of the following functions.

  • D3DXAssembleShader
  • D3DXAssembleShaderFromFileA
  • D3DXAssembleShaderFromFileW

The code example below assembles a vertex shader from the file AppTween.vsh.

D3DXAssembleShaderFromFile( "AppTween.vsh", 0, NULL, &vsFunction, NULL );

For more information on creating a vertex shader function, see Vertex Shader Function.


Colored Lights

The color-related members of the D3DLIGHT8 structure (Diffuse, Specular, and Ambient) are D3DCOLORVALUE structures. The colors defined by these structures are RGBA values that generally range from 0.0 to 1.0, with 0.0 being black. Although you will usually want the light color to fall within this range, you can use values outside the range for special effects. For example, you can create a strong light that washes out a scene by setting the color to large values. You can also set the color to negative values to create a dark light, which actually removes light from a scene. Dark lights are useful for forcing dramatic shadows in scenes and other special effects.


Advanced Topics in DirectX Graphics

This section is a guide to using the advanced features of the Microsoft® Direct3D® and Direct3DX APIs. It goes beyond the information covered in Using DirectX Graphics.

Information is presented in the following topics.

  • Effects and Techniques
  • Higher-Order Primitives
  • Matrix Stack
  • Pixel Shaders
  • Point Sprites
  • Vertex Shaders
  • X Files


Effects and Techniques

This section introduces effects and techniques and discusses how they can be used in your applications. Information is divided into the following sections.

  • Introduction to Effects and Techniques
  • Effect File Components
  • Using Effects and Techniques


Introduction to Effects and Techniques

Using an effect in Microsoft® Direct3D® allows an application to define many different techniques for a single effect. Each effect contains one or more techniques that controls the rendering of the effect. Each technique can be validated to see if the current device can support it. If the current device does not support a technique, then a different technique can be used.

You can use different techniques to control the complexity of a rendered effect. For example, say you want a pond of water that has rippled waves that reflect light. One technique might render the entire scene with multiple textures and lighting in one pass, while other techniques might use multiple-pass rendering. This can be done so that video cards that don't support single-pass rendering can still render an effect.

You can also adjust effects based on the level of detail needed. An effect that appears in the distance might use a simpler technique to decrease the computational overhead that is incurred when rendering a complex technique.

Another advantage to using effects is that you can modify the effect file without recompiling the source application. This enables you to release a product that makes optimum use of modern video cards. It also enables you to update the effect file to take advantage of video cards of the future.


Effect File Components

An effect file defines the techniques that will be used. The basic layout of an effect file starts with one or more declarations and then defines each technique for that effect. The sample below shows a basic effect file that contains two textures and two techniques.

The effect file starts by declaring two textures that will be used for the effect.

texture tex0; //First texture
texture tex1; //Second texture

The first technique uses one pass to render the scene.

technique t0
{
    pass p0
    {
        Texture[0] = <tex0>;
        Texture[1] = <tex1>;

        ColorOp[0] = SelectArg1;
        ColorArg1[0] = Texture;

        ColorOp[1] = Add;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Current;

        ColorOp[2] = Disable;
    }
}

The second technique uses multiple passes to render the scene. This technique would be used if the current device did not support single-pass rendering for multiple textures.

technique t1
{
    pass p0
    {
        Texture[0] = <tex0>;

        ColorOp[0] = SelectArg1;
        ColorArg1[0] = Texture;
        ColorOp[1] = Disable;
    }

    pass p1
    {
        AlphaBlendEnable = True;
        SrcBlend = One;
        DestBlend = One;

        Texture[0] = <tex1>;

        ColorOp[0] = SelectArg1;
        ColorArg1[0] = Texture;
        ColorOp[1] = Disable;
    }
}

This effect file enables a device that doesn't support single-pass rendering for two textures to use multiple passes to render the textures. For more information on the layout of an effect file, see Effect File Format.


Using Effects and Techniques

This section shows how to create and use effects and techniques in an application.

  • Creating an Effect
  • Validating a Technique
  • Rendering with a Technique
  • Retrieving Effect and Technique Descriptions
  • Sample Effect File


Creating an Effect

The first step to creating an effect is to compile the effect. The following functions can be used to compile an effect.

  • D3DXCompileEffect
  • D3DXCompileEffectFromFileA
  • D3DXCompileEffectFromFileW

The code example below uses the D3DXCompileEffectFromFileA function to load and compile the effect described in the file Water.sha.

LPD3DXBUFFER pCompiledEffect;
D3DXCompileEffectFromFile( "Water.sha", &pCompiledEffect, NULL );

The first parameter that D3DXCompileEffectFromFileA accepts is a pointer to an ANSI string that specifies the file from which to create the effect. The second parameter accepts the address of a pointer to an ID3DXBuffer interface. This buffer will contain the compiled effect. The final parameter that D3DXCompileEffectFromFileA accepts is the address of a pointer to an ID3DXBuffer interface. This buffer will contain returned ASCII error message. This example ignores the errors and sets this parameter to NULL.

After compiling an effect, use the D3DXCreateEffect function to obtain a pointer to an ID3DXEffect interface as shown in the code sample below.

ID3DXEffect * pEffect;
D3DXCreateEffect( g_d3dDevice, pCompiledEffect->GetBufferPointer(),
                  pCompiledEffect->GetBufferSize(), 0, &pEffect);
pCompiledEffect->Release();

If this function succeeds, then pEffect contains a valid pointer to ID3DXEffect interface. When finished with the ID3DXBuffer that stored the compiled effect, be sure to call the IUnknown::Release method to avoid a memory leak.


Validating a Technique

Before using a technique, it is good to verify that the device can support it. To validate a technique, use the ID3DXTechnique::Validate method as show in the code sample below.

LPD3DXTECHNIQUE pTechnique;
pEffect->GetTechnique(0, &pTechnique);
if ( pTechnique->Validate() != D3D_OK)
    //Technique is not valid on current device.

Note It is strongly recommended that you validate a technique before using it. Using invalid techniques has unknown effects.


Rendering with a Technique

The following sample shows how an application would render a technique. After finding a valid technique the application can call the ID3DXTechnique::Begin method to start the application of the technique as shown in the code example below.

UINT uPasses;
pTechnique->Begin(&uPasses);

The only parameter that Begin accepts is the address of a unsigned integer. After Begin is called, this integer will contain the number of passes used for the technique.

The next step is to render each pass individually. To render a pass, call the ID3DXTechnique::Pass method. The code example below uses a loop to render all the passes required for a technique.

for(UINT uPass = 0; uPass < uPasses; uPass++)
{
    pTechnique->Pass(uPass);
    g_d3dDevice->SetStreamSource( 0, pvbVertices, sizeof(WATER_VERTEX) );
    g_d3dDevice->SetIndices( pIB, 0 );
    g_d3dDevice->DrawIndexedPrimitive( D3DPT_TRIANGLESTRIP, 0,
                                       uVertices, 0, uIndices -2 );
}

The call to Pass sets up the necessary states to render the scene.

Note The call to ID3DXTechnique::Begin must be inside a IDirect3DDevice8::BeginScene / IDirect3DDevice8::EndScene block.


Retrieving Effect and Technique Descriptions

To retrieve information about an effect, use the ID3DXEffect::GetDesc method and pass a D3DXEFFECT_DESC structure for the parameter. The D3DXEFFECT_DESC structure contains members that describe an effect.

To retrieve information about a technique, use the ID3DXTechnique::GetDesc method and pass a D3DXTECHNIQUE_DESC structure for the parameter. The D3DXTECHNIQUE_DESC structure contains members that describe the technique.


Sample Effect File

The following effect file is used for the Water Sample.

The file starts by declaring two matrices, three textures, and a vertex shader that will be used for this effect.

matrix mID;     // Identity transform
matrix mENV;    // Environment map transform

texture tFLR;   // Floor texture
texture tCAU;   // Caustic texture
texture tENV;   // Cubic environment map

vertexshader vs =  decl { fvf xyz | normal | diffuse | tex1; };

The first technique renders the water scene using both the floor texture and caustic texture. Both the water and the floor reflect light. This technique uses a single pass and four texture stage states.

technique T0
{
    vertexshader = <vs>;

    pass P0
    {
        Lighting       = True;
        SpecularEnable = True;

        // Stage0
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Texture;
        AlphaOp[0]   = SelectArg2;
        AlphaArg2[0] = Current;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = Point;

        Texture[0] = <tFLR>;
        TextureTransform[0] = <mID>;
        TextureTransformFlags[0] = Count2;

        // Stage1
        ColorOp[1]   = Add;
        ColorArg1[1] = Texture;
        ColorArg2[1] = Current;
        AlphaOp[1]   = SelectArg2;
        AlphaArg2[1] = Current;

        MinFilter[1] = Linear;
        MagFilter[1] = Linear;
        MipFilter[1] = Point;

        Texture[1] = <tCAU>;
        TextureTransform[1] = <mID>;
        TextureTransformFlags[1] = Count2;

        // Stage2
        ColorOp[2]   = BlendCurrentAlpha;
        ColorArg1[2] = Texture;
        ColorArg2[2] = Current;
        AlphaOp[2]   = Disable;

        MinFilter[2] = Linear;
        MagFilter[2] = Linear;
        MipFilter[2] = Point;

        Texture[2] = <tENV>;
        TextureTransform[2] = <mENV>;
        TextureTransformFlags[2] = Count3;
        TexCoordIndex[2] = CameraSpaceReflectionVector;

        // Stage3
        ColorOp[3] = Disable;
        AlphaOp[3] = Disable;
    }
}

The second technique renders the water scene using both the floor texture and caustic texture. Both the floor and water reflect light. This technique uses two passes to render the scene.

technique T1
{
    vertexshader = <vs>;

    pass P0
    {
        // Stage0
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Texture;
        AlphaOp[0]   = Disable;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = Point;

        Texture[0] = <tFLR>;
        TextureTransform[0] = <mID>;
        TextureTransformFlags[0] = Count2;

        // Stage1
        ColorOp[1]   = Add;
        ColorArg1[1] = Texture;
        ColorArg2[1] = Current;
        AlphaOp[1]   = Disable;

        MinFilter[1] = Linear;
        MagFilter[1] = Linear;
        MipFilter[1] = Point;

        Texture[1] = <tCAU>;
        TextureTransform[1] = <mID>;
        TextureTransformFlags[1] = Count2;

        // Stage2
        ColorOp[2] = Disable;
        AlphaOp[2] = Disable;
    }

    pass P1
    {
        SrcBlend  = One;
        DestBlend = InvSrcAlpha;

        Lighting         = True;
        SpecularEnable   = True;
        AlphaBlendEnable = True;

        // Stage0
        ColorOp[0]   = BlendDiffuseAlpha;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Diffuse;
        AlphaOp[0]   = SelectArg2;
        AlphaArg2[0] = Diffuse;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = Point;

        Texture[0] = <tENV>;
        TextureTransform[0] = <mENV>;
        TextureTransformFlags[0] = Count3;
        TexCoordIndex[0] = CameraSpaceReflectionVector;

        // Stage1
        ColorOp[1] = Disable;
        AlphaOp[1] = Disable;
    }
}

The third technique renders the water scene using both the floor texture and caustic texture. The water surface reflects light. This effect uses three passes to render the scene.

technique T2
{
    vertexshader = <vs>;

    pass P0
    {
        // Stage0
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Texture;
        AlphaOp[0]   = Disable;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = Point;

        Texture[0] = <tFLR>;
        TextureTransform[0] = <mID>;
        TextureTransformFlags[0] = Count2;

        // Stage1
        ColorOp[1] = Disable;
        AlphaOp[1] = Disable;
    }

    pass P1
    {
        SrcBlend  = One;
        DestBlend = One;

        Lighting         = False;
        SpecularEnable   = True;
        AlphaBlendEnable = True;

        // Stage0
        ColorOp[0]   = Add;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Current;
        AlphaOp[0]   = Disable;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = Point;

        Texture[0] = <tCAU>;
        TextureTransform[0] = <mID>;
        TextureTransformFlags[0] = Count2;

        // Stage1
        ColorOp[1] = Disable;
        AlphaOp[1] = Disable;
    }

    pass P2
    {
        SrcBlend  = One;
        DestBlend = InvSrcAlpha;

        Lighting         = True;
        SpecularEnable   = True;
        AlphaBlendEnable = True;

        // Stage0
        ColorOp[0]   = BlendDiffuseAlpha;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Diffuse;
        AlphaOp[0]   = SelectArg2;
        AlphaArg2[0] = Diffuse;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = Point;

        Texture[0] = <tENV>;
        TextureTransform[0] = <mENV>;
        TextureTransformFlags[0] = Count3;
        TexCoordIndex[0] = CameraSpaceReflectionVector;

        // Stage1
        ColorOp[1] = Disable;
        AlphaOp[1] = Disable;
    }
}

The fourth technique renders the water scene using both the floor texture and caustic texture. This effect uses a single pass to render the scene.

technique T3
{
    vertexshader = <vs>;

    pass P0
    {
        Lighting       = True;
        SpecularEnable = True;

        // Stage0
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Texture;
        AlphaOp[0]   = Disable;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = Point;

        Texture[0]   = <tFLR>;

        // Stage1
        ColorOp[1]   = Add;
        ColorArg1[1] = Texture;
        ColorArg2[1] = Current;
        AlphaOp[1]   = Disable;

        MinFilter[1] = Linear;
        MagFilter[1] = Linear;
        MipFilter[1] = Point;

        Texture[1]   = <tCAU>;

        // Stage2
        ColorOp[2]   = Disable;
        AlphaOp[2]   = Disable;
    }
}

The fifth technique renders the water scene using both the floor and caustic textures. There is no reflection in this technique. This effect uses two passes to render the scene.

technique T4
{
    vertexshader = <vs>;

    pass P0
    {
        // Stage 0
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Diffuse;

        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Texture;
        AlphaArg2[0] = Diffuse;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = Point;

        Texture[0]   = <tFLR>;

        // Stage 1
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;
    }

    pass P1
    {
        SrcBlend  = One;
        DestBlend = One;

        Lighting         = True;
        SpecularEnable   = True;
        AlphaBlendEnable = True;

        // Stage 0
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Current;

        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Texture;
        AlphaArg2[0] = Current;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = Point;

        Texture[0]   = <tCAU>;

        // Stage 1
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;
    }
}

The sixth and final technique renders the water scene with just the floor texture. There is no reflection in this technique. This effect uses a single pass to render the scene.

technique T5
{
    vertexshader = <vs>;

    pass P0
    {
        Lighting       = True;
        SpecularEnable = True;

        // Stage 0
        ColorOp[0]   = SelectArg1;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Current;

        AlphaOp[0]   = SelectArg1;
        AlphaArg1[0] = Texture;
        AlphaArg2[0] = Current;

        MinFilter[0] = Linear;
        MagFilter[0] = Linear;
        MipFilter[0] = None;

        Texture[0]   = <tFLR>;

        // Stage 1
        ColorOp[1]   = Disable;
        AlphaOp[1]   = Disable;
    }
}


Higher-Order Primitives

This section introduces higher-order primitives and discusses how they can be used in your applications. Information is divided into the following sections.

  • What are Higher-Order Primitives?
  • Improved Quality through Resolution Enhancement
  • Direct Mapping from Spline-Based Tools
  • Using Higher-Order Primitives


What are Higher-Order Primitives?

Microsoft® Direct3D® for Microsoft DirectX® 8.0 supports points, lines, triangles, and grid primitives. These have been extended to support higher-order interpolation beyond linear. While triangles and lines have spatial extent, until now they were both rendered using linear interpolation. In DirectX 8.0, Direct3D supports rendering of these primitive types using higher order, up to quintic, interpolation. Furthermore, a new quad primitive type is now supported. This new type can also be rendered with higher-order interpolation. This feature is primarily driven by requirements for animation and rendering of characters. It can also be used for other surfaces such as terrain or water.

Higher-order primitives support higher-order interpolation when transmitted to the application programming interface (API) as lists, strips, fans, or indexed meshes. This is achieved by using additional information encoded in the vertices themselves. For example, normal vectors can be used to define tangent planes at the vertices to enable cubic interpolation. Most implementations support higher-order interpolation by tessellation into planar triangles. The tessellation step is applied logically before the vertex shader stage. Because the vertex shader API does not impose semantics on its input data, a special mechanism is provided to identify the vertex stream component that represents the position, and optionally the normal vector. All other components are interpolated accordingly.


Improved Quality through Resolution Enhancement

Current primitives are not ideal for representing smooth surfaces. Higher-order interpolation methods, such as cubic polynomials, allow more accurate calculations in rendering curved shapes. This provides increased realism by reducing or eliminating faceting artifacts visible on silhouette edges or on specular surface lighting. Furthermore, when tessellation occurs on the chip, the tessellated triangles do not impact the bus bandwidth. In many cases, a small amount of tessellation can provide improvements in image quality with minimal performance impact.

Microsoft® Direct3D® for Microsoft DirectX® 8.0 provides a simple way to apply resolution enhancement to content created by existing polygon-oriented tools and art pipelines. The application need only provide a desired level of tessellation, and transmit the data using standard triangle syntax that includes normal vectors.


Direct Mapping from Spline-Based Tools

Many current authoring tools support higher-order primitives to enable more powerful modeling operations than are commonly provided for with planar triangle meshes. When used efficiently, so that the number of patches generated is reasonable, such tools can produce content that can be rendered directly by the application programming interface (API). To meet this requirement, a new entry point has been added that interprets the incoming vertex data stream as a 2-D array of control points and tessellates it to the desired resolution.


Using Higher-Order Primitives

This section shows you how to use higher-order primitives in your application.

  • Determining Higher-Order Primitive Support
  • Drawing Patches


Determining Higher-Order Primitive Support

The DevCaps member of D3DCAPS8 can be queried to determine the level of support for operations involving higher-order primitives. The following table lists the device capabilities related to higher-order primitives in Microsoft® DirectX® 8.0.

Device capability | Description
D3DDEVCAPS_NPATCHES | Device supports N-patches.
D3DDEVCAPS_QUINTICRTPATCHES | Device supports quintic béziers and B-splines.
D3DDEVCAPS_RTPATCHES | Device supports rectangular and triangular (RT) patches.
D3DDEVCAPS_RTPATCHHANDLEZERO | RT-patches might be drawn efficiently using handle zero.


Drawing Patches

Microsoft® DirectX® 8.0 supports two types of higher order primitives, or patches. These are referred to as N-Patches and Rect/Tri patches. N-Patches can be rendered using any triangle rendering call by enabling D3DRS_PATCHSEGMENTS to a value greater than 1.0. Rect/Tri patches must be rendered using the following explicit entry points.

You can use the following methods to draw patches in Microsoft Direct3D® for DirectX.

  • IDirect3DDevice8::DrawRectPatch
  • IDirect3DDevice8::DrawTriPatch

DrawRectPatch draws a rectangular high-order patch specified by the pRectPatchInfo parameter using the currently set streams. The Handle parameter is used to associate the patch with a handle, so that the next time the patch is drawn, there is no need to respecify pRectPatchInfo. This makes it possible to precompute and cache forward difference coefficients or other information, which in turn enables subsequent calls to DrawRectPatch using the same handle to execute efficiently.

It is intended that for static patches, an application would set the vertex shader and appropriate streams, supply patch information in the pRectPatchInfo parameter, and specify a handle so that Direct3D can capture and cache information. The application can then call DrawRectPatch subsequently with pRectPatchInfo set to NULL to efficiently draw the patch. When drawing a cached patch, the currently set streams are ignored. However, it is possible to override the cached pNumSegs by specifying new values for pNumSegs. Also, it is required to set the same vertex shader when rendering a cached patch as was set when it was captured.

For dynamic patches, the patch data changes for every rendering of the patch, so it is not efficient to cache information. The application can convey this to Direct3D by setting Handle to 0. In this case, Direct3D draws the patch using the currently set streams and the pNumSegs values and does not cache any information. It is not valid to simultaneously set Handle to 0 and pPatch to NULL.

By respecifying pRectPatchInfo for the same handle, the application can overwrite the previously cached information.

If pNumSegs is set to NULL, then the tessellator uses D3DRS_PATCHSEGMENTS to control the amount of tessellation. In this case, obviously, the same tessellation is used for all sides. There are no special methods for N-patches. Tessellation is simply controlled by D3DRS_PATCHSEGMENTS. It is necessary to supply normals.

DrawTriPatch is similar to DrawRectPatch except that it draws a triangular high-order patch.


Matrix Stack

The Direct3DX utility library provides a matrix stack through a COM object.

This section provides information on the following topics.

  • What Is a Matrix Stack?
  • Implementing a Scene Hierarchy


What Is a Matrix Stack?

The Direct3DX utility library provides the ID3DXMatrixStack interface. It supplies a mechanism to enable matrices to be pushed onto and popped off of a matrix stack. Implementing a matrix stack is an efficient way to track matrices while traversing a transform hierarchy.

The Direct3DX utility library uses a matrix stack to store transformations as matrices. The various methods of the ID3DXMatrixStack interface deal with the current matrix, or the matrix located on top of the stack. You can clear the current matrix with the ID3DXMatrixStack::LoadIdentity method. To explicitly specify a certain matrix to load as the current transformation matrix, use the ID3DXMatrixStack::LoadMatrix method. Then you can call either the ID3DXMatrixStack::MultMatrix method or the ID3DXMatrixStack::MultMatrixLocal method to multiply the current matrix by the specified matrix.

The ID3DXMatrixStack::Pop method enables you to return to the previous transformation matrix and the ID3DXMatrixStack::Push method adds a transformation matrix to the stack.

The individual matrices on the matrix stack are represented as 4×4 homogeneous matrices, defined by the Direct3DX utility library D3DXMATRIX structure.


Implementing a Scene Hierarchy

A matrix stack simplifies the construction of hierarchical models, in which complicated objects are constructed from a series of simpler objects.

A scene, or transform, hierarchy is usually represented by a tree data structure. Each node in the tree data structure contains a matrix. A particular matrix represents the change in coordinate systems from the node's parent to the node. For example, if you are modeling a human arm, you might implement the following hierarchy.

In this hierarchy, the Body matrix places the body in the world. The UpperArm matrix contains the rotation of the shoulder, the LowerArm matrix contains the rotation of the elbow, and the Hand matrix contains the rotation of the wrist. To determine where the hand is relative to the world, you simply multiply all the matrices from Body down through Hand together.

The previous hierarchy is overly simplistic, because each node has only one child. If you begin to model the hand in more detail, you will probably add fingers and a thumb. Each digit can be added to the hierarchy as children of Hand.

If you traverse the complete graph of the arm in depth-first order—traversing as far down one path as possible before moving on to the next path—to draw the scene, you perform a sequence of segmented rendering. For example, to render the hand and fingers, you implement the following pattern.

  1. Push the Hand matrix onto the matrix stack.
  2. Draw the hand.
  3. Push the Thumb matrix onto the matrix stack.
  4. Draw the thumb.
  5. Pop the Thumb matrix off the stack.
  6. Push the Finger 1 matrix onto the matrix stack.
  7. Draw the first finger.
  8. Pop the Finger 1 matrix off the stack.
  9. Push the Finger 2 matrix onto the matrix stack. You continue in this manner until all the fingers and thumb are rendered.

After you have completed rendering the fingers, you would pop the Hand matrix off the stack.

You can follow this basic process in code with the following examples. When you encounter a node during the depth-first search of the tree data structure, push the matrix onto the top of the matrix stack.

MatrixStack->Push();
MatrixStack->MultMatrix(pNode->matrix);

When you are finished with a node, pop the matrix off the top of the matrix stack.

MatrixStack->Pop();

In this way, the matrix on the top of the stack always represents the world-transform of the current node. Therefore, before drawing each node, you should set the Microsoft® Direct3D® matrix.

pD3DDevice->SetTransform(D3DTS_WORLDMATRIX(0), *MatrixStack->GetTop());

For more information on the specific methods that you can perform on a Direct3DX matrix stack, see the ID3DXMatrixStack reference topic.


Pixel Shaders

This section describes pixel shaders, the update to the pixel processing operations supported by Microsoft® DirectX® 8.0, and how they are used in Microsoft Direct3D® applications. The following topics are discussed.

  • Introduction to Pixel Shaders
  • Pixel Shader Basics
  • Pixel Shader Scope
  • Pixel Shader Data Flow
  • Using Pixel Shaders
  • Pixel Shader Examples

All pixel shader code and syntax used in this documentation is based on and compatible with the Direct3DX pixel shader assembler. Before reading this section, ensure that you are familiar with the pixel shader assembler by studying the Pixel Shader Assembler Reference.


Introduction to Pixel Shaders

The following example illustrates a way to introduce pixel shaders and their syntax as understood by the Direct3DX pixel shader assembler.

ps.1.0          // DirectX8 version.
tex t0          // Declare the texture.
tex t1          // Declare the light map.

mov r0, t0
mul r0, r0, t1  // Modulate the light map.
mul r0, r0, v0  // Modulate the diffuse.
add r0, r0, v1  // Add the specular.

This pixel shader declares a base texture with a light map, diffuse color, and specular add.

Pixel shaders control the color and alpha blending operations and the texture addressing operations. Microsoft® Direct3D® for Microsoft DirectX® 8.0 defines a procedural paradigm for defining pixel and texture blending operations. This model includes a definition of a virtual machine architecture and a set of instructions and modifiers that define its behavior. This paradigm does not necessarily imply a processor-based implementation.

The pixel shaders extend and generalize the multitexture capabilities of DirectX 6.0 and 7.0 in the following ways.

  • A set of general read/write registers is added to enable more flexible expression than can be supported by the serial cascade using only D3DTA_CURRENT. This would require the specification of a separate result register argument for each stage.
  • The D3DTOP_MODULATE2X and D3DTOP_MODULATE4X texture operations are broken into separate modifiers applicable to any instruction orthogonally. This eliminates the need for separate D3DTOP_MODULATE and D3DTOP_MODULATE2X operations.
  • The bias and unbias texture operation modifiers are orthogonal. This eliminates the need for separate add and add bias operations.
  • An optional third argument is added to modulate add, so the procedural pixel shader can do arg1 * arg2 + arg0. This eliminates the D3DTOP_MODULATEALPHA_ADDCOLOR and D3DTOP_MODULATECOLOR_ADDALPHA texture operations. In addition, an optional third argument is added to the blend operation, so the procedural pixel shader can use arg0 as the blend proportion between arg1 and arg2. This eliminates the D3DTOP_BLENDDIFFUSEALPHA, D3DTOP_BLENDTEXTUREALPHA, D3DTOP_BLENDFACTORALPHA, D3DTOP_BLENDTEXTUREALPHAPM, and D3DTOP_BLENDCURRENTALPHA texture operations.
  • Texture address modifying operations, such as D3DTOP_BUMPENVMAP, are broken out from the color and alpha operations and defined as a third operation type specifically for operating on texture addresses.

To support this increased flexibility more efficiently , the application programming interface (API) syntax is changed from DWORD pairs to an ASCII assemble code syntax. This exposes the functionality offered by procedural pixel shaders.

Note When you use pixel shaders, specular add is no longer specifically controlled by a render state, and it is up to the pixel shader to implement if needed. However, fog blending is still applied by the fixed-function syntax.

For further details and information on how to use the Direct3DX pixel shader assembler, see Pixel Shader Assembler Reference.


Pixel Shader Basics

This section provides basic information that you need to know when working with pixel shaders.

  • Pixel Shader Arithmetic Logic Unit
  • Pixel Shader Instruction Pairing
  • Pixel Shader Order of Operations
  • Pixel Shader Texture Declarations
  • Pixel Shader Texture Addressing
  • Pixel Shader Lighting


Pixel Shader Arithmetic Logic Unit

The following diagram illustrates the pixel shader arithmetic logic unit (ALU).


Pixel Shader Instruction Pairing

The processor that executes the pixel shader has two parallel pipelines, one for vector processing (RGB), and one for scalar processing (alpha). Using these pipelines in parallel results in substantially better processor utilization and performance by reducing the total number of clock cycles required. In essence, this affects the pixel fill rate performance.

The output masks can affect how the two pipelines are allocated, but there can be ambiguities in the order of operations unless explicit pairing syntax is used. The following table illustrates the output masks and their associated pipe.

Output mask | Pipe
.a | The operation is in the scalar pipe.
.rgb | The operation is in the vector pipe.
.rgba | The operation is in both the scalar and vector pipes. It already counts as a pair.

Pairing is indicated by a plus sign (+) preceding the second instruction of the pair.

  mul r0.rgb, t0, v0    // Component-wise multiply the colors,
+ add r0.a,   t0, v0    // but add the alpha components.

The dot product instructions are a special case. They are vector operations and always executed in the vector pipeline. Therefore, you can specify a different instruction in the scalar pipe and still get pairing, as shown in the following pixel shader example code.

dp3 r0.rgb, t0, v0
mul r0.a,   t0, v0

You cannot specify a dot product operation as a scalar instruction without a dot product operations as a vector instruction.


Pixel Shader Order of Operations

The order of operations for processing pixel instructions and modifiers is defined as follows: the input or argument modifier is applied, the core instruction is executed, the output or instruction modifier is applied, and then the result is written with respect to the output write mask.

For the input or argument modifiers, the ordering is as follows: bias is applied, scaling is applied, and then the negate or complement step is performed. Alpha replication is also performed at this stage. For the output or instruction modifiers, the scale/shift operations have higher precedence than the saturation step.

The net ordering of operations is defined by the following list.

  1. The Argument Modifiers are applied.
  2. The core instruction is executed.
  3. The Instruction Modifiers are applied.
  4. The Output Write Masks are applied.


Pixel Shader Texture Declarations

Texture declarations (texture addressing instructions) are a separate set of pixel shader instructions, as distinguished from the color and alpha blending instructions. These instructions must appear at the top of the pixel shader and can use only previously defined values. Texture addressing instructions can also perform operations. For example, you can use them to modify texture coordinates used as addresses by sampling stages or to enable perturbations effects.

For more information, see Texture Addressing Instructions.


Pixel Shader Texture Addressing

The following diagram illustrates the mechanics of pixel shader texture addressing.

Texture registers t0, t1, t2, and t3 result from sampling the four input textures using the texture coordinates in conjunction with the texture operations. The mapping of texture coordinates set to texture registers is controlled by the D3DTSS_TEXCOORDINDEX texture stage state. By default, all texture stages receive texture coordinates from coordinate set 0. The positions of the instructions are required to be in order because they can use results only from previous texture registers.

When you use dependent textures, any texture can be used to perturb the coordinates of a higher-numbered texture; for example, t1 can be used to perturb the coordinates of t2.

The Direct3DX pixel shader assembler provides both texture address operators and modifiers. For details, see Pixel Shader Assembler Reference.

The following pixel shader code shows a texture address shader by programming a bump environment map on a lit base texture.

ps.1.0              // DirectX8 Version.
tex t0              // Declare the texture.
tex t1              // Declare the bump map.
texbem t3, t1       // Perturb and then sample
                    // the environment map.
mul r0, v0, t0      // Modulate the diffuse.
add r0, r0, t3      // Add bumped specular environment map.


Pixel Shader Lighting

The following diagram illustrates the mechanics behind pixel shader lighting.

For example, in the case of a 3-D bump environment map, you sample the normal map and iterate a 3×3 matrix across the polygon using texture coordinates as rows. Then, you can transform and index into a diffuse radiance cube map, or reflect and index into a specular environment cube map. You apply to the base from a previous pass.


Pixel Shader Scope

The pixel shader completely replaces the pixel blending functionality specified by the Microsoft® DirectX® 6.0 and 7.0 multitexturing application programming interfaces (APIs), specifically those operations defined by the D3DTSS_COLOROP, D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHAOP, D3DTSS_ALPHAARG1, and D3DTSS_ALPHAARG2 texture stage states, and associated arguments and modifiers. When a procedural pixel shader is set, these states are ignored.

Information on pixel shader scope is divided into the following topics.

  • Pixel Shaders and Texture Stage States
  • Pixel Shaders and Texture Sampling
  • Post-Shader Pixel Processing


Pixel Shaders and Texture Stage States

When pixel shaders are in operation, the following texture stage states are still observed.

  • D3DTSS_ADDRESSU
  • D3DTSS_ADDRESSV
  • D3DTSS_ADDRESSW
  • D3DTSS_BUMPENVMAT00
  • D3DTSS_BUMPENVMAT01
  • D3DTSS_BUMPENVMAT10
  • D3DTSS_BUMPENVMAT11
  • D3DTSS_BORDERCOLOR
  • D3DTSS_MAGFILTER
  • D3DTSS_MINFILTER
  • D3DTSS_MIPFILTER
  • D3DTSS_MIPMAPLODBIAS
  • D3DTSS_MAXMIPLEVEL
  • D3DTSS_MAXANISOTROPY
  • D3DTSS_BUMPENVLSCALE
  • D3DTSS_BUMPENVLOFFSET
  • D3DTSS_TEXCOORDINDEX
  • D3DTSS_TEXTURETRANSFORMFLAGS

Because these texture stage states are not part of the pixel shader, they are not available at shader compile time so the driver can make no assumptions about them. For example, the driver cannot differentiate between bilinear and trilinear filtering at that time. The application is free to change these states without requiring the regeneration of the currently bound shader.

Furthermore, calls to the IDirect3DDevice8::SetTexture method to change the image data used cannot cause the pixel shader to become invalid, so texture format, in terms of bit depth, is free to change. Calling SetTexture with a two-channel texture format such as D3DFMT_A8L8 or D3DFMT_V8U8 must continue to work as though the third channel was set to 0.


Pixel Shaders and Texture Sampling

Texture sampling and filtering operations are controlled by the standard texture stage states for minification, magnification, mip filtering, and the wrap addressing modes. For more information, see Texture Stage States.

This information is not available to the driver at shader compile time, so shaders must be able to continue operation when this state changes. The texture type—texture, cube texture, or volume texture—is specified explicitly in the shader syntax. The application is responsible for setting only textures of the correct type during shader execution. Setting a texture of the incorrect type during shader execution will produce unexpected results.


Post-Shader Pixel Processing

In Microsoft® DirectX® 8.0, pixel processing such as fog blending, stencil operations, and render target blending occur after execution of the shader. Render target blending syntax is updated to support new features as described in this topic.

Pixel Shader Inputs

In DirectX 8.0, all colors—diffuse and specular—declared in the texture registers are assumed saturated (clamped) to the range 0 through 1 before use by the shader because this is the range of valid inputs to the shader. Position is assumed to be clipped before the execution of the pixel shader.

All iterated values are assumed by the pixel shader to be iterated-perspective correct, but this is not guaranteed in all hardware. Colors generated as texture coordinates by the address shader are always iterated in a perspective correct manner. However, they are also clamped to the range 0 to 1 during iteration.

Pixel Shader Outputs

The result emitted by the pixel shader is the contents of register r0. Whatever it contains when the shader completes processing is sent to the fog stage and render target blender.


Pixel Shader Data Flow

The section explains the data flow as it is routed to and from the pixel shader virtual machine. The following topics are intended to provide a high-level understanding of developing pixel shaders and the underlying virtual machine.

  • Understanding the Pixel Shader Virtual Machine
  • Processing Pixel Data


Understanding the Pixel Shader Virtual Machine

The following diagram illustrates the logical flow of data through the pixel shader virtual machine.

The data that is interpolated per triangle is routed to the virtual machine as shown in the above diagram. The texture coordinates and color values are interpolated for each pixel. Note that the mapping of texture coordinates is controlled by setting the D3DTSS_TEXCOORDINDEX texture stage state. For example, the oD0 data output by the vertex shader would be iterated across a triangle, with the results at each individual pixel being set into the v0 register of the pixel shader.


Processing Pixel Data

For the purpose of understanding how pixel data is processed by the virtual machine, imagine an orange sphere that you want to bump map and place into an environment where lights will shine on its surface. For this simple scenario, assume that the orange color is interpolated using the triangles that form the sphere. The orange color is interpolated from the data passed down the oD0 channel of the vertex shader, and as such, each pixel is presented to the pixel shader through the v0 register.

The following topics trace the steps needed to render the final image of the orange sphere with the bump and environment map data.

  • Preparing Data for the Pixel Shader Virtual Machine
  • Sending Data Through the Pixel Shader Virtual Machine
  • Pixel Shader Pipeline Order of Operations

Although this section uses a specific example to illustrate how the pixel shader virtual machine processes data, the principles and steps demonstrated are valid for developing a variety of pixel shaders.


Preparing Data for the Pixel Shader Virtual Machine

Before rendering the orange sphere with the bump and environment map data, you must load the bump and environment maps. Then set the relevant texture stage states for each of the texture operation units. This includes setting the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, D3DTSS_BUMPENVMAT11, and D3DTSS_TEXCOORDINDEX texture stage states. However, the color operations—defined by D3DTSS_COLOROP—do not need to be set. This is because the pixel shader code is used to define the operations performed on a per-pixel basis. In general, the texture stage states that remain constant while rendering a triangle, object, or frame are set before invoking the pixel shader virtual machine. This includes the 2×2 bump-mapping matrix values. However, the data that is used to shade each pixel is specified through the pixel shader language.

For this example, the front end processing that occurs in the vertex shader is not addressed. Instead, assume that the front end sets up the texture interpolation so that the bump data is passed through the oT0 channel of the vertex shader. For the orange sphere example, this means that the bump map address used to access the bump data is set to the first texture coordinate register of the pixel shader (t0). In a similar fashion, the light map address—before the modification done in the texture operation unit—is passed from the vertex shader oT1 channel to the pixel shader through t1.


Sending Data Through the Pixel Shader Virtual Machine

The address used for the texture operation for stage 0 is the bump map addresses presented through the first texture coordinate register (t0). The operation is a simple look-up of the bump data, as illustrated by the following pixel shader code.

tex t0

The texture operation for stage 1 is more complicated. In this case, you must set the texture stage state so that the 2×2 matrix is loaded. Note that there is a 2×2 matrix that can be loaded to simulate the change between the eye-point and the light source. This enables the bump and environment map to be reused as the eye-point is moved around a scene. Therefore, the address into the environment map is a base address, presented through the second texture coordinate, t1, modulated by the eye-point adjustment and local bump value. More precisely, the u coordinate into the environment map is u = t1.r + mat00 * t0.r + mat01 * t0.g, and the v coordinate into the environment map is v = t1.g + mat10 * t0.r + mat11 * t0.g. The values in the t0.r and t0.g register components are actually the du and dv values that represent the bump data looked-up in stage 0 and stored in register t0.

Note The u and v address calculations can require two slots in the actual pixel shader code. This is because most hardware reuses the logic for the u and then the v address calculation. Current hardware does not provide for the addresses to be computed in parallel.

The following example shows how this is done in pixel shader code.

ps.1.0         // DirectX8 Version.
tex t0         // Declare the texture (the bump data).
texbem t1, t0  // Declare the environment map and get data from t0.
mov r0, v0     // Note the assumption that the diffuse orange color
               // is fed into the pixel shader through register v0 for
               // each pixel.
add r0, r0, t1 // Add the specular environment data.

However, this simple example is not the most common case. Typically, there is a base texture applied to the object before performing the bump environment mapping. For example, you might send a white sphere that is used as a base for applying the texture data. This is the diffuse light that is brighter on part of the surface and less bright on other parts. In this case, you move the bump environment mapping operations out a stage and modulate the base texture by the diffuse light. The following example shows how this is done in pixel shader code.

ps.1.0         // DirectX8 Version.
tex t0         // Declare the base texture. It could be something
               // like marble or wood or any other surface material.
tex t1         // Declare the texture (the bump data).
texbem t2, t1  // Declare the environment map.
mul r0, v0, t0 // Modulate the base texture by the diffuse light.
add r0, r0, t2 // Add the specular environment data.

You can use traditional texture mapping (one stage), interpolate the specular, and have it available through register v1 of the pixel shader virtual machine. Other complex pixel shaders can be constructed using a set of fixed constants stored in the constant registers (c0-c7). Also, the texture registers are often used with texture stages but are read/write to the pixel arithmetic logic unit (ALU). Thus the pixel shader can use a texture register as a temporary register. Note also that r0 and r1 are read/write to the ALU, but the results stored in r0 are the only results that are sent to the depth and stencil logic. In fact, the only way that results can be passed downstream is through the r0 register.


Pixel Shader Pipeline Order of Operations

You can control the states of the pixel shader pipeline throughout its execution by setting render states and texture stage states, and by calling the IDirect3DDevice8::SetTexture, IDirect3DDevice8::SetTextureStageState, IDirect3DDevice8::SetPixelShader, and IDirect3Ddevice8::SetPixelShaderConstant methods. These states and functions specify the flow of control in the pixel shader and the states of the steps in the pixel shader pipeline. The following diagram illustrates the order of these steps and the settings that most directly control them.

Depending on the value of the handle passed to SetPixelShader, either the fixed function or pixel shader pipeline is used in any one instance, but not both. The depth stencil test may occur prior to the time indicated by the figure, but this does not affect the results of the color pipeline. When stepping through a shading algorithm, keep in mind the various pipeline operations that can clamp values.


Using Pixel Shaders

This section shows you how to use pixel shaders in your application.

  • Determining Pixel Shader Support
  • Setting Pixel Shader Texture Inputs
  • Setting the Pixel Shader Constant Registers
  • Compiling a Pixel Shader
  • Creating a Pixel Shader


Determining Pixel Shader Support

You can query members of D3DCAPS8 to determine the level of support for operations involving pixel shaders. The following table lists the device capabilities related to programmable pixel processing in Microsoft® DirectX® 8.0.

Device capability | Description
MaxPixelShaderValue | Maximum value of pixel shader arithmetic component.
MaxSimultaneousTextures | Number of texture declaration instructions supported.
MaxTextureBlendStages | Number of instructions supported.
PixelShaderVersion | Level of support for pixel shaders.

The MaxSimultaneousTextures and MaxTextureBlendStages capabilities only apply to fixed-function pixel blending(using multi-texture).

The PixelShaderVersion capability indicates the level of pixel shader supported. Only pixel shaders with version numbers equal to or less than this value will be successfully created when calling the method IDirect3DDevice8::CreatePixelShader. The major version number is encoded in the second byte of PixelShaderVersion. The low byte contains a minor version number. The pixel shader version is indicated by the first token in each shader.

Pixel shader applications do not need to check the MaxSimultaneousTextures and MaxTextureBlendStages device capabilities.

Each implementation sets the PixelShaderVersion member to indicate the maximum pixel shader version that it can fully support. This implies that implementations should never fail the creation of a valid shader of the version less than or equal to the version reported by PixelShaderVersion.

The following table summarizes the supported pixel shader versions and the associated level of functionality and register counts.

Version | Functionality | tn | rn | cn | vn
1.0 | DirectX 8.0 | 4 | 2 | 8 | 2
1.1 | DirectX 8.0 | 4 | 2 | 8 | 2

Version 1.0 supports all the operations documented in the Instructions reference topic for pixel shaders. A maximum of four texture address operations and a total of eight instructions are supported. In this version the texture registers tn are read-only, and only one can be used in a given instruction.

Version 1.1 supports instructions, with limits of four address operations and eight blending operations. In this version the texture registers are read/write, and two can be used as inputs in a single instruction.


Setting Pixel Shader Texture Inputs

There is a direct mapping between the input register colors and the texture stages. The temporary registers of the Direct3DX pixel shader assembler are preloaded with the texture colors from the corresponding texture stages. Conversely, the textures are bound directly to the temporary registers by calling the IDirect3DDevice8::SetTexture method.

In addition, texture coordinates are mapped directly and defined by texture declarations.


Setting the Pixel Shader Constant Registers

You can use the following methods to set and retrieve the values in the pixel shader constant registers.

  • IDirect3DDevice8::GetPixelShaderConstant
  • IDirect3DDevice8::SetPixelShaderConstant

In addition, you can use the def Direct3DX assembler instruction to set the constant registers of a pixel shader.


Compiling a Pixel Shader

The Direct3DX utility library provides a set of functions to compile pixel shaders. The following functions are provided.

  • D3DXAssembleShader
  • D3DXAssembleShaderFromFileA
  • D3DXAssembleShaderFromFileW


Creating a Pixel Shader

The IDirect3DDevice8::CreatePixelShader method is used to create a pixel shader in Microsoft® DirectX® 8.0. You pass a declaration that defines the blending operations. Microsoft Direct3D® returns a shader handle. The shader validation is done when CreatePixelShader is called.

Note that a given shader may fail creation due to the restraints of the DirectX 8.0 hardware model.


Pixel Shader Examples

This section provides a list of common effects implemented with pixel shader code. Information is divided into the following topics.

  • Diffuse Lighting
  • Specular Mapping
  • Diffuse Lighting and Specular Mapping
  • Dot Product Lighting
  • Pixel Shader Sample


Diffuse Lighting

The following shader performs per-pixel diffuse lighting. Use the dp3 instruction to compute diffuse intensity.

ps.1.0                      // DirectX8 Version.
tex t0                      // Declare the n-map.
texm3x3pad t1, t0_bx2       // First row of transform.
texm3x3pad t2, t0_bx2       // Second row of transform.
texm3x3tex t3, t0_bx2       // Third row of transform.
dp3_sat r0, t3_bx2, v0_bx2


Specular Mapping

The following shader performs per-pixel specular mapping.

ps.1.0                   // DirectX8 Version.
tex t0                   // Declare the n-map.
texm3x3pad   t1, t0      // First row of transform.
texm3x3pad   t2, t0      // Second row of transform.
texm3x3spec  t3, t0, c0  // Third row of transform. Then reflect
                         // infinite and sample the cube map.

mov r0, t3               // Emit to the frame buffer blender.
                         // This adds to the frame buffer contents.


Diffuse Lighting and Specular Mapping

The following combination shader performs per-pixel diffuse lighting and specular mapping.

ps.1.0                // DirectX8 Version.
tex t0                // Declare the n-map.
texm3x3pad  t1, t0    // First row of transform.
texm3x3pad  t2, t0    // Second row of transform.
texm3x3spec t3, t0    // Third row of transform. Sample diffuse cube
                      // map to t2 and specular cube map into t3.
mov r0, t3            // Output the specular color.


Dot Product Lighting

Dot products require signed data, so you need to convert the inputs using the _bx2 argument modifier. Lighting clamps negative values using the _sat instruction modifier.

// Diffuse is the light direction.

ps.1.0      // DirectX8 Version
tex t0      // The normal map
dp3_sat r0, t0_bx2, v0_bx2


Pixel Shader Sample

The MFCPixelShader Sample shows the effect that different pixel shaders have on a rendered scene. This sample has six predefined shaders to select from, it and enables the user to modify the predefined pixel shaders to get different results.


Point Sprites

This section discusses point sprites. Information is divided into the following topics.

  • What Are Point Sprites?
  • Point Primitive Rendering Controls
  • Point Size Computations
  • Point Rendering


What Are Point Sprites?

Support for point sprites in Microsoft® Direct3D® for Microsoft DirectX® 8.0 enables the high-performance rendering of points (particle systems). Point sprites are generalizations of generic points that enable arbitrary shapes to be rendered as defined by textures.

Point sprites are not supported in the fixed-function geometry pipeline. To use point sprites, programmable vertex processing must be used.


Point Primitive Rendering Controls

Microsoft® Direct3D® for Microsoft DirectX® 8.0 supports additional parameters to control the rendering of point sprites (point primitives). These parameters enable points to be of variable size and have a full texture map applied. The size of each point is determined by an application-specified size combined with a distance-based function computed by Direct3D. The application can specify point size either as per-vertex or by setting D3DRS_POINTSIZE, which applies to points without a per-vertex size. The point size is expressed in camera space units, with the exception of when the application is passing post-transformed flexible vertex format (FVF) vertices. In this case, the distance-based function is not applied and the point size is expressed in units of pixels on the render target.

The texture coordinates computed and used when rendering points depends on the setting of D3DRS_POINTSPRITEENABLE. When this value is set to TRUE, the texture coordinates are set so that each point displays the full-texture. In general, this is only useful when points are significantly larger than one pixel. When D3DRS_POINTSPRITEENABLE is set to FALSE, each point's vertex texture coordinate is used for the entire point.


Point Size Computations

Point size is determined by D3DRS_POINTSCALEENABLE. If this value is set to FALSE, the application-specified point size is used as the screen-space (post-transformed) size. Vertices that are passed to Microsoft® Direct3D® in screen space do not have point sizes computed; the specified point size is interpreted as screen-space size.

If D3DRS_POINTSCALEENABLE is TRUE, Direct3D computes the screen-space point size according to the following formula. The application-specified point size is expressed in camera space units.

Ss = Vh * Si * sqrt(1/(A + B*De + C*(De2)))

In this formula, the input point size, Si, is either per-vertex or the value of the D3DRS_POINTSIZE render state. The point scale factors, D3DRS_POINTSCALE_A, D3DRS_POINTSCALE_B, and D3DRS_POINTSCALE_C, are represented by the points A, B, and C. The height of the viewport, Vh, is the Height member of the D3DVIEWPORT8 structure representing the viewport. De, the distance from the eye to the position (the eye at the origin), is computed by taking the eye space position of the point (Xe, Ye, Ze) and performing the following operation.

De = sqrt (Xe2 + Ye2 + Ze2)

The maximum point size, Pmax, is determined by taking the smaller of either the MaxPointSize member of D3DCAPS8 or the D3DRS_POINTSIZE_MAX render state. The minimum point size, Pmin, is determined by querying the value of D3DRS_POINTSIZE_MIN. Thus the final screen-space point size, S, is determined in the following manner.

  • If Ss > Pmax , then S = Pmax
  • if Ss < Pmin, then S = Pmin
  • Otherwise, S = Ss


Point Rendering

A screen-space point,

P = (X, Y, Z, W)

of screen-space size S is rasterized as a quadrilateral of the following four vertices.

((X+S/2, Y+S/2, Z, W), (X+S/2, Y-S/2, Z, W), (X-S/2, Y-S/2, Z, W), (X-S/2, Y+S/2, Z, W))

The vertex color attributes are duplicated at each vertex; thus each point is always rendered with constant colors.

The assignment of texture indices is controlled by the D3DRS_POINTSPRITEENABLE render state setting. If D3DRS_POINTSPRITEENABLE is set to FALSE, then the vertex texture coordinates are duplicated at each vertex. If D3DRS_POINTSPRITEENABLE is set to TRUE, then the texture coordinates at the four vertices are set to the following values.

(0.F, 0.F), (0.F, 1.F), (1.F, 0.F), (1.F, 1.F)

This is shown in the following diagram.

When clipping is enabled, points are clipped in the following manner. If the vertex exceeds the range of depth values—MinZ and MaxZ of the D3DVIEWPORT8 structure—into which a scene is to be rendered, the point exists outside of the view frustum and is not rendered. If the point, taking into account the point size, is completely outside the viewport in X and Y, then the point is not rendered; the remaining points are rendered. It is possible for the point position to be outside the viewport in X or Y and still be partially visible.

Points may or may not be correctly clipped to user-defined clip planes. If D3DPMISCCAPS_CLIPPLANESCALEDPOINTS is not set in the PrimitiveMiscCaps member of D3DCAPS8, then points are clipped to user-defined clip planes based only on the vertex position, ignoring the point size. In this case, scaled points are fully rendered when the vertex position is inside the clip planes, and discarded when the vertex position is outside a clip plane. Applications can prevent potential artifacts by adding a border geometry to clip planes that is as large as the maximum point size.

If the D3DPMISCCAPS_CLIPPLANESCALEDPOINTS bit is set, then the scaled points are correctly clipped to user-defined clip planes.

Hardware vertex processing may or may not support point size. For example, if a device is created with D3DCREATE_HARDWARE_VERTEXPROCESSING on a HAL Device (D3DDEVTYPE_HAL) that has the MaxPointSize member of its D3DCAPS8 structure set to 1.0 or 0.0, then all points are a single pixel. To render pixel point sprites less than 1.0, you must use either flexible vertex format (FVF) TL (transformed and lit) vertices or software vertex processing (D3DCREATE_SOFTWARE_VERTEXPROCESSING), in which case the Microsoft® Direct3D® run time emulates the point sprite rendering. For details on FVF TL vertices, see Transformed and Lit Vertex Functionality.

A hardware device that does vertex processing and supports point sprites—MaxPointSize set to greater than 1.0f—is required to perform the size computation for nontransformed sprites and is required to properly set the per-vertex or D3DRS_POINTSIZE for TL vertices.


Vertex Shaders

This section describes vertex shaders and how they are used in Microsoft® Direct3D® applications. The following topics are discussed.

  • Introduction to Vertex Shaders
  • Vertex Shader Components
  • Using Vertex Shaders
  • Vertex Shader Techniques and Applications
  • Vertex Shader Examples

All vertex shader code and syntax used in this documentation is based on and compatible with the Direct3DX vertex shader assembler. Before reading this section, ensure that you are familiar with the vertex shader assembler by studying the Vertex Shader Assembler Reference.


Introduction to Vertex Shaders

Vertex shaders control the loading and processing of vertices. Microsoft® Direct3D® for Microsoft DirectX® 8.0 supports two types of vertex processing: programmable vertex processing and fixed-function vertex processing. In DirectX 8.0 documentation, the term vertex shader most often applies to the programmable mode, although the vertex shader API mechanism encompasses both types of functionality. Vertex shaders are defined at creation as using programmable vertex processing or fixed-function vertex processing. Once created, a vertex shader is referred to by its handle. Vertex shaders are not editable. To change a vertex shader, it must be destroyed and recreated.

Each vertex shader includes a function, which defines the operations to apply to each vertex, and a declaration, which defines the inputs to the shader, including how vertex elements in the input data streams are used by the shader.

Vertex processing performed by vertex shaders encompasses only operations applied to single vertices. The output of the vertex processing step is defined as individual vertices, each of which consists of a clip-space position (x, y, z, and w) plus color, texture coordinate, fog intensity, and point size information. The projection and mapping of these positions to the viewport, the assembling of multiple vertices into primitives, and the clipping of primitives is done by a subsequent processing stage and is not under the control of the vertex shader.

Fixed function vertex processing provides the same functionality as in Direct3D for DirectX 7.0, including transformation and lighting, vertex blending, and texture coordinate generation. Unlike programmed vertex shaders, where the operations applied to vertices are defined within the shader, fixed-function vertex processing is controlled by a device state set by methods on IDirect3DDevice8, which set lights, transforms, and so on. It is still useful to have multiple fixed-function vertex shaders, because even though the function is fixed and shared, the declarations can vary. This enables feeding the fixed-function shader with differing layouts of multistream inputs.

The input vertex elements for fixed-function vertex processing have fixed semantics. Thus the declaration tags specify input vertex elements as coordinate, normal, color, and so on. The vertex outputs for fixed-function vertex shaders always include coordinates, diffuse and specular colors, and multiple texture coordinates, as required by the current device state settings for pixel processing.

Programmed vertex shaders have a function defined by an array of instructions to apply to each vertex. The mapping of the input vertex elements to the vertex input registers for programmed vertex shaders is defined in the shader declaration, but the input vertex elements do not have specific semantics about their use. The interpretation of the input vertex elements is up to the shader instructions. The vertex outputs for programmed vertex shaders are explicitly written to by instructions in the shader function.

For more information on the Direct3DX vertex shader assembler, see Vertex Shader Assembler Reference.


Vertex Shader Components

This section describes the components of a vertex shader. This information is divided into the following topics.

  • Vertex Shader Declaration
  • Vertex Shader Function


Vertex Shader Declaration

The declaration portion of a vertex shader defines the static external interface of the shader. A vertex shader declaration includes the following information.

  • Binding stream data to vertex shader input registers. This information defines the type and vertex input register assignment of each element in each data stream. The type specifies the arithmetic data type and the dimensionality—one, two, three, or four values. Stream data elements that are less than four values are always expanded to four values with zero or more 0.F values and one 1.F value.
  • Binding vertex shader input registers to implicit data from the primitive tessellator. This controls the loading of vertex data that is not loaded from a stream but rather is generated during primitive tessellation prior to the vertex shader.
  • Loading data in the constant memory at the time that a shader is set as the current shader. Each token specifies values for one or more contiguous 4-DWORD constant registers. This enables the shader to update an arbitrary subset of the constant memory, overwriting the device state, which contains the current values of the constant memory. These values can be overwritten, between DrawPrimitive calls, during the time that a shader is bound to a device through the IDirect3DDevice8::SetVertexShaderConstant method.

Declaration arrays are single-dimensional arrays of DWORDs composed of multiple tokens, each of which is one or more DWORDs. The single-DWORD token value 0xFFFFFFFF is a special token used to indicate the end of the declaration array. The single DWORD token value 0x00000000 is a padding token that is ignored during the declaration parsing. This pad token enables more complex in-place editing of declarations. Note that 0x00000000 is a valid value for DWORDs following the first DWORD for multiple word tokens.

The following code example is an example of writing declarators. It shows how to define a vertex using a simple structure.

struct Vertex
{
    D3DXVECTOR3 Position;
    D3DXVECTOR3 Normal;
    D3DCOLOR    Diffuse;
    D3DXVECTOR2 TexCoord0;
};

Now consider the following code example, which shows how to define the same vertex structure above as a declarator.

DWORD dwDecl[] =
{
    D3DVSD_STREAM( 0 ),
    D3DVSD_REG( D3DVSDE_POSITION,  D3DVSDT_FLOAT3 ),
    D3DVSD_REG( D3DVSDE_NORMAL,    D3DVSDT_FLOAT3 ),
    D3DVSD_REG( D3DVSDE_DIFFUSE,   D3DVSDT_D3DCOLOR ),
    D3DVSD_REG( D3DVSDE_TEXCOORD0, D3DVSDT_FLOAT2 ),
    D3DVSD_END()
};

DWORD dwFvf = D3DFVF_POSITION | D3DFVF_NORMAL | D3DFVF_DIFFUSE |
              D3DFVF_TEX0 | D3DFVF_TEXCOORDSIZE2(0);

The declarator sets data stream 0, defines a position and normal vector composed of three float values, defines a diffuse component composed of a four component unsigned byte, and defines a pair of texture coordinates composed of two float values.

When you use the fixed-function vertex shader, the mapping of the vertex input registers is fixed so that specific vertex elements, such as position or normal, must be placed in specific register locations in the vertex input memory. These assignments are made automatically when passing an FVF code to IDirect3DDevice8::SetVertexShader. When you use an explicit shader declaration, the D3DVSDE preprocessor macros define the vertex input location into which specific elements must be loaded. See D3d8types.h for a definition of the macros used to generate the declaration token array.

For information on the shader declaration token types and bit definitions, see Vertex Shader Declarator Macros.

Notes When you use fixed-function vertex shaders, the vertex stride set in IDirect3DDevice8::SetStreamSource and vertex size must be the same size. For vertex shaders that use declarations, the stream stride can be greater than the declaration stride.


Vertex Shader Function

The function portion of a vertex shader defines the operations applied to each vertex. Only programmed vertex shaders have shader functions. Like declarations, shader functions are single dimensional arrays of DWORDs that form an ordered list of instructions to execute for each vertex. Each instruction is composed of multiple DWORDs.

The Direct3DX utility library supplies a set of functions to generate the standard DWORD tokens transmitted to the driver. For details, see Compiling a Vertex Shader.


Using Vertex Shaders

This section shows you how to define and use vertex shaders in your application and introduces some effects that can be achieved with vertex shaders.

  • Determining Vertex Shader Support
  • Setting the Vertex Shader Constant Registers
  • Compiling a Vertex Shader
  • Creating a Vertex Shader


Determining Vertex Shader Support

You can query members of D3DCAPS8 to determine the level of support for operations involving vertex shaders. The following table lists the device capabilities related to programmable vertex processing in Microsoft® DirectX® 8.0.

Device capability | Description
MaxPrimitiveCount | Maximum number of primitives for each DrawPrimitive call.
MaxVertexIndex | Maximum size of indices supported for hardware vertex processing.
MaxStreams | Maximum number of concurrent data streams.
MaxStreamStride | Maximum data stream for a stride.
MaxVertexShaderConst | Number of vertex shader constant registers.
VertexShaderVersion | Level of support for vertex shaders.

The VertexShaderVersion capability indicates the level of vertex shader supported. Only vertex shaders with version numbers equal to or less than this value will be successfully created when calling the method IDirect3DDevice8::CreateVertexShader. The level of vertex shader is specified to CreateVertexShader as the first token in the shader token stream.

The following table summarizes the supported vertex shader versions.

Version | Functionality
0.0 | DirectX 7.0
1.0 | DirectX 8.0 without address register A0.
1.1 | DirectX 8.0 with address register A0.

The only difference between support levels 1.0 and 1.1 is support for the A0 register.


Setting the Vertex Shader Constant Registers

You can use the following methods to set and retrieve the values in the vertex shader constant registers.

  • IDirect3DDevice8::GetVertexShaderConstant
  • IDirect3DDevice8::SetVertexShaderConstant

In addition, you can use the def Direct3DX assembler instruction to set the constant registers of a vertex shader.


Compiling a Vertex Shader

The Direct3DX utility library includes a set of functions to compile vertex shaders. The following functions are provided.

  • D3DXAssembleShader
  • D3DXAssembleShaderFromFileA
  • D3DXAssembleShaderFromFileW


Creating a Vertex Shader

A vertex shader is defined by two token arrays that specify the declaration and function of the shader. The token arrays are composed of single or multiple DWORD tokens terminated by an 0xFFFFFFFF token value.

The shader declaration defines the static external interface of the shader, including binding of stream data to vertex register inputs and values loaded into the shader constant memory. The shader function defines the operation of the shader as an array of instructions. These instructions are executed in order for each vertex that is processed during the time that the shader is bound to a device. Shaders created without a function array apply the fixed-function vertex processing when that shader is current.

The IDirect3DDevice8::CreateVertexShader method is used to create a vertex shader in Microsoft® DirectX® 8.0. You pass a declaration that defines the parallel DMA streams used and the function that defines the blending operations. Direct3D returns a shader handle. The shader validation is done when CreateVertexShader is called.


Vertex Shader Techniques and Applications

This section provides a list of common techniques implemented with vertex shaders. Information is divided into the following topics.

  • Matrix Palette Skinning
  • Procedural Geometry
  • Wave Modeling


Matrix Palette Skinning

A set of eight to ten matrices can be loaded into the constant registers as a palette. Then each processed vertex can be transformed by a subset of these matrices and blended into a final result using a vertex-level weight. One convenient implementation is to use a packed 4-byte integer array to store the matrix palette addresses of four matrices influencing the vertex. A standard 4-D component, such as a Microsoft® DirectX® 7.0 texture coordinate set, can contain the four weights used to blend those matrices.


Procedural Geometry

You can simulate a muscle moving under skin by an ellipsoid computed from a sphere with scaling along three axes. This can be evaluated and used to perturb the position of incoming mesh vertices. The muscle ellipsoid can be scaled and translated by updating the constant registers containing its relative position and scale factors.


Wave Modeling

A shape such as a quadratic hyperboloid can be generated in the unit square and mapped repeatedly onto incoming geometry. To do this, take input vertex (x, y) values, map them into unit square using the frc macro, compute local hyperboloid elevation, and add to input vertex z value. This can be used to simulate waves on an ocean, and so on.


Vertex Shader Examples

This section provides a list of common effects implemented with vertex shader code. Information is divided into the following topics.

  • Transformation and Constant Shading
  • Directional Light
  • Other Vertex Shader Samples


Transformation and Constant Shading

The following shader performs a one-matrix transform with constant color. The input vertex register v0 is the position, which is assumed to be homogeneous. The transform matrix is in the constant registers (c[0] through c[3]). Diffuse color is loaded into c[4].

dp4 r0.x, v0, c[0]
dp4 r0.y, v0, c[1]
dp4 r0.z, v0, c[2]
dp4 r0.w, v0, c[3]
mov oD0, c[4]         ; The constant color.
mov oPos, r0          ; Emit the output.

This shader executes in six clock cycles.


Directional Light

The following shader builds on the Transformation and Constant Shading vertex shader example by adding a directional light source.

; The directional light source.
dp3 r1.x, v1, c[8]   ; N dot L
max r1, r1.x, c[0000]   ; clamp greater than 0

; diffuse = dot*diffuse + ambient
mad oD0, r1.x, c[5], c[6]


Other Vertex Shader Samples

Several samples in the SDK use vertex shader files. Look for files with the .vsh extension in the \Samples\Multimedia\Media directory.


X Files

This section discusses the structure of Microsoft® DirectX® (.x) files and how to use them in your applications.

Information is divided into the following topics.

  • About X Files
  • X File Interface Hierarchy
  • X File Architecture
  • Using X Files


About X Files

The .x file format was introduced with Microsoft® DirectX® 2.0. A binary version of this format was subsequently released with DirectX 3.0, which is also detailed in this reference. Then DirectX version 6.0 introduced interfaces and methods that enable reading from and writing to DirectX (.x) files.

The .x file format provides a rich, template-driven format that enables the storage of meshes, textures, animations, and user-definable objects. Support for animation sets enables you to store predefined paths for playback in real time. Instancing and hierarchies are also supported. Instancing enables multiple references to an object, such as a mesh, while storing its data only once per file. Hierarchies are used to express relationships between data records.

The .x file format provides low-level data primitives on which applications define higher-level primitives through templates.


X File Interface Hierarchy

The following diagram illustrates the relationship between the .x file interfaces.


X File Architecture

The Microsoft® DirectX® (.x) file format is architecture-free and context-free. It is template-driven and free of any usage knowledge. The file format can be used by any client application.

This following sections deal with the content and syntax of the file format. The file format uses the extension .x when used with the DirectX Software Development Kit (SDK).

  • Reserved Words, Header, and Comments
  • Templates
  • Data
  • Use of Commas and Semicolons


Reserved Words, Header, and Comments

The table below shows which words are reserved and must not be used.

  • ARRAY
  • DWORD
  • UCHAR
  • BINARY
  • FLOAT
  • ULONGLONG
  • BINARY_RESOURCE
  • SDWORD
  • UNICODE
  • CHAR
  • STRING
  • WORD
  • CSTRING
  • SWORD
  • DOUBLE
  • TEMPLATE

The variable-length header is compulsory and must be at the beginning of the data stream. The header contains the following data.

Type | Size | Contents | Content meaning
Magic Number (required) | 4 bytes | "xof" |
Version Number (required) | 2 bytes | 03 | Major Version 3
 | 2 bytes | 02 | Major Version 2
Format Type (required) | 4 bytes | "txt" | Text File
 |  | "bin" | Binary File
 |  | "tzip" | MSZip Compressed Text File
 |  | "bzip" | MSZip Compressed Binary File
Float Size (required) | 4 bytes | 0064 | 64-bit floats
 |  | 0032 | 32-bit floats

The following example shows a valid header.

xof 0302txt 0064

Comments are applicable only in text files. Comments can occur anywhere in the data stream. A comment begins with either C++ style double-slashes (//), or a number sign (#). The comment runs to the next new line. The following example shows valid comments.

#  This is a comment.
// This is another comment.


Templates

Templates define how the data stream is interpreted—the data is modulated by the template definition. This section discusses the following aspects of a template and provides an example template.

  • Template Form, Name, and UUID
  • Template Members
  • Template Restrictions
  • Template Example

There is one special template—the header template. It is recommended that each application define a header template and use it to define application-specific information, such as version information. If present, this header is read by the .x file format API. If a flags member is available, it is used to determine how the following data is interpreted. The flags member, if defined, should be a DWORD. One bit is currently defined—bit 0. If this bit is clear, the following data in the file is binary. If set, the following data is text. You can use multiple header data objects to switch between binary and text within the file.


Template Form, Name, and UUID

A template has the following form.

template <template-name> {
<UUID>
<member 1>;
...
<member n>;
[restrictions]
}

The template name is an alphanumeric name that can include the underscore character (_). It must not begin with a digit. The UUID is a universally unique identifier formatted to the Open Software Foundation's Distributed Computing Environment standard and enclosed by angle brackets (< >). For example: <3D82AB43-62DA-11cf-AB39-0020AF71E433>.


Template Members

Template members consist of a named data type followed by an optional name or an array of a named data type. Valid primitive data types are defined in the following table.

Type | Size
WORD | 16 bits
DWORD | 32 bits
FLOAT | IEEE float
DOUBLE | 64 bits
CHAR | 8 bits
UCHAR | 8 bits
BYTE | 8 bits
STRING | NULL terminated string
CSTRING | Formatted C string (not supported)
UNICODE | Unicode™ string (not supported)

Additional data types defined by templates encountered earlier in the data stream can also be referenced within a template definition. No forward references are allowed.

Any valid data type can be expressed as an array in the template definition. The basic syntax is shown in the following example.

array <data-type> <name>[<dimension-size>];

<dimension-size> can either be an integer or a named reference to another template member whose value is then substituted. Arrays can be n-dimensional, where n is determined by the number of paired square brackets trailing the statement, as in the following example.

array DWORD FixedHerd[24];
array DWORD Herd[nCows];
array FLOAT Matrix4x4[4][4];


Template Restrictions

Templates can be open, closed, or restricted. These restrictions determine which data types can appear in the immediate hierarchy of a data object defined by the template. An open template has no restrictions, a closed template rejects all data types, and a restricted template allows a named list of data types.

The syntax for indicating an open template is three periods enclosed by square brackets.

[ ... ]

A comma-separated list of named data types followed optionally by their universally unique identifiers (UUIDs) enclosed by square brackets indicates a restricted template.

[ { data-type [ UUID ] , } ... ]

The absence of either of the above indicates a closed template.


Template Example

The following shows an example template.

template Mesh {
<3D82AB44-62DA-11cf-AB39-0020AF71E433>
DWORD nVertices;
array Vector vertices[nVertices];
DWORD nFaces;
array MeshFace faces[nFaces];
 [ ... ]                // An open template
}
template Vector {
<3D82AB5E-62DA-11cf-AB39-0020AF71E433>
FLOAT x;
FLOAT y;
FLOAT z;
}                        // A closed template
template FileSystem {
<UUID>
STRING name;
[ Directory <UUID>, File <UUID> ]    // A restricted template
}


Data

Data objects contain the actual data or a reference to that data. Each data object has a corresponding template that specifies the data type. The following sections discuss the form and parts of data objects.

  • Form, Identifier, and Name
  • Data Members


Form, Identifier, and Name

Data objects have the following form.

<Identifier> [name] { [<UUID>]
<member 1>;
...
<member n>;
}

The identifier is compulsory and must match a previously defined data type or primitive. However, the name is optional. For details on the member part, see Data Members.


Data Members

Data members can be one of the following: data object, data reference, integer list, float list, or string list.

A data object is a nested data object. This enables the hierarchical nature of the file format to be expressed. The types of nested data objects allowed in the hierarchy may be restricted. See Templates for more information.

A data reference is a reference to a previously encountered data object as shown in the following example.

{
  name |
  UUID |
  name UUID
}

An integer list is a semicolon-separated list of integers, as shown in the following example.

1; 2; 3;

A float list is a semicolon-separated list of floats, as shown in the following example.

1.0; 2.0; 3.0;

A string list is a semicolon-separated list of strings, as shown in the following example.

"Moose"; "Goats"; "Sheep";


Use of Commas and Semicolons

Using commas and semicolons can be the most complex syntax issue in the file format, and this usage is very strict. Commas are used to separate array members; semicolons terminate each data item.

For example, if a template is defined in the following manner:

template mytemp {
DWORD myvar;
}

Then an instance of this template looks like the following:

mytemp dataTemp {
1;
}

If a template containing another template is defined in the following manner;

template mytemp {
DWORD myvar;
DWORD myvar2;
}
template container {
FLOAT aFloat;
mytemp aTemp;
}

Then an instance of this template looks like the following:

container dataContainer {
1.1;
2; 3;;
}

Note that the second line that represents the mytemp inside container has two semicolons at the end of the line. The first semicolon indicates the end of the data item, aTemp (inside container), and the second semicolon indicates the end of the container.

If an array is defined in the following manner:

Template mytemp {
array DWORD myvar[3];
}

Then an instance of this looks like the following:

mytemp aTemp {
1, 2, 3;
}

In the array example, there is no need for the data items to be separated by semicolons because they are delineated by commas. The semicolon at the end marks the end of the array.

Consider a template that contains an array of data items defined by a template.

template mytemp {
DWORD myvar;
DWORD myvar2;
}
template container {
DWORD count;
array mytemp tempArray[count];
}

An instance of this would look like the following example.

container aContainer {
3;
1;2;,3;4;,5;6;;
}


Using X Files

This section contains information about using .x files in a Microsoft® Direct3D® application. Information is divided into the following topics.

  • Loading an X File
  • Saving to an X File
  • Creating a Cube
  • Converting and Exporting 3-D Models to X Files


Loading an X File

Use the following procedure to load an .x file.

  1. Use the DirectXFileCreate function to create an IDirectXFile object.
  2. If templates are present in the Microsoft® DirectX® file that you will load, use the IDirectXFile::RegisterTemplates method to register those templates.
  3. Use the IDirectXFile::CreateEnumObject method to create an IDirectXFileEnumObject enumerator object.
  4. Loop through the objects in the file. For each object, perform the following steps.
    1. Use the IDirectXFileEnumObject::GetNextDataObject method to retrieve each IDirectXFileData object.
    2. Use the IDirectXFileData::GetType method to retrieve the data's type.
    3. Load the data using the IDirectXFileData::GetData method.
    4. If the object has optional members, retrieve the optional members by calling the IDirectXFileData::GetNextObject method.
    5. Release the IDirectXFileData object.
  5. Release the IDirectXFileEnumObject object.
  6. Release the IDirectXFile object.


Saving to an X File

Use the following procedure to save .x file templates and data to an .x file.

  1. Use the DirectXFileCreate function to create an IDirectXFile object.
  2. Use the IDirectXFile::RegisterTemplates method to inform the Microsoft® DirectX® file system about any templates that you will use.
  3. Use the IDirectXFile::CreateSaveObject method to create an IDirectXFileSaveObject object.
  4. Use the IDirectXFileSaveObject::SaveTemplates method to save templates, if desired.
  5. Loop through the objects to save. For each top-level object, perform the following steps.
    1. Use the IDirectXFileSaveObject::CreateDataObject method to create an IDirectXFileData object as a top-level object in the file. If the top-level data object has optional child objects, add them to the object by using the appropriate method from the next step.
    2. Each IDirectXFileData object can have optional child objects if its template allows it. The child objects can be any of the three types of objects: IDirectXFileData, IDirectXFileDataReference, or IDirectXFileBinary. Loop through the objects you need to save, adding each optional child member to the object list in the manner appropriate to its type, as illustrated in the following steps. Then, if the object type is Data, call the IDirectXFileSaveObject::CreateDataObject method to create an IDirectXFileData object, and then call the IDirectXFileData::AddDataObject method to add it as a child of the object. If the object type is Data Reference, call the IDirectXFileData::AddDataReference method to create and add the data reference object as a child of the object. Or, if the object type is Binary, call the IDirectXFileData::AddBinaryObject method to create and add the binary object as a child of the object.
    3. Call the IDirectXFileSaveObject::SaveData method to save the data object and its children.
    4. Release the IDirectXFileData object.
  6. Release the IDirectXFileSaveObject object.
  7. Release the IDirectXFile object.


Creating a Cube

This section describes a simple cube and shows how to add textures, frames, and animations.

  • Defining a Simple Cube
  • Adding Textures
  • Adding Frames and Animations


Defining a Simple Cube

The following file defines a simple cube that has four red sides and two green sides. In this file, optional information is used to add information to the data object defined by the Mesh template.

Material RedMaterial {
1.000000;0.000000;0.000000;1.000000;;    // R = 1.0, G = 0.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
}
Material GreenMaterial {
0.000000;1.000000;0.000000;1.000000;;     // R = 0.0, G = 1.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
}
// Define a mesh with 8 vertices and 12 faces (triangles). Use
// optional data objects in the mesh to specify materials, normals,
// and texture coordinates.
Mesh CubeMesh {
8;                                // 8 vertices.
1.000000;1.000000;-1.000000;,     // Vertex 0.
-1.000000;1.000000;-1.000000;,    // Vertex 1.
-1.000000;1.000000;1.000000;,     // And so on.
1.000000;1.000000;1.000000;,
1.000000;-1.000000;-1.000000;,
-1.000000;-1.000000;-1.000000;,
-1.000000;-1.000000;1.000000;,
1.000000;-1.000000;1.000000;;

12;                      // 12 faces.
3;0,1,2;,                // Face 0 has three vertices.
3;0,2,3;,                // And so on.
3;0,4,5;,
3;0,5,1;,
3;1,5,6;,
3;1,6,2;,
3;2,6,7;,
3;2,7,3;,
3;3,7,4;,
3;3,4,0;,
3;4,7,6;,
3;4,6,5;;

// All required data has been defined. Now define optional data
// using the hierarchical nature of the file format.
MeshMaterialList {
2;                    // Number of materials used.
12;                   // A material for each face.
0,                    // Face 0 uses the first material.
0,
0,
0,
0,
0,
0,
0,
1,                    // Face 8 uses the second material.
1,
1,
1;;
{RedMaterial}         // References to the definitions
{GreenMaterial}       // of material 0 and 1.
}
MeshNormals {
8;                    // Define 8 normals.
0.333333;0.666667;-0.666667;,
-0.816497;0.408248;-0.408248;,
-0.333333;0.666667;0.666667;,
0.816497;0.408248;0.408248;,
0.666667;-0.666667;-0.333333;,
-0.408248;-0.408248;-0.816497;,
-0.666667;-0.666667;0.333333;,
0.408248;-0.408248;0.816497;;
12;                   // For the 12 faces, define the normals.
3;0,1,2;,
3;0,2,3;,
3;0,4,5;,
3;0,5,1;,
3;1,5,6;,
3;1,6,2;,
3;2,6,7;,
3;2,7,3;,
3;3,7,4;,
3;3,4,0;,
3;4,7,6;,
3;4,6,5;;
}
MeshTextureCoords {
8;                        // Define texture coords for each vertex.
0.000000;1.000000;
1.000000;1.000000;
0.000000;1.000000;
1.000000;1.000000;
0.000000;0.000000;
1.000000;0.000000;
0.000000;0.000000;
1.000000;0.000000;;
}
}


Adding Textures

To add textures, use the hierarchical nature of the file format and add an optional TextureFilename data object to the Material data objects. The Material objects now read as follows:

Material RedMaterial {
1.000000;0.000000;0.000000;1.000000;;    // R = 1.0, G = 0.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
TextureFilename {
"tex1.ppm";
}
}
Material GreenMaterial {
0.000000;1.000000;0.000000;1.000000;;     // R = 0.0, G = 1.0, B = 0.0
0.000000;
0.000000;0.000000;0.000000;;
0.000000;0.000000;0.000000;;
TextureFilename {
"win95.ppm";
}
}


Adding Frames and Animations

This section shows how to add frames and animations to a simple cube.

  • Working with Frames
  • Working with AnimationSets and Animations


Working with Frames

A frame is expected to take the following structure.

Frame Aframe {        // The frame name is chosen for convenience.
FrameTransformMatrix {
...transform data...
}
[ Meshes ] and/or [ More frames]
}

Place the defined cube mesh inside a frame with an identity transform. Then apply an animation to this frame.

Frame CubeFrame {
FrameTransformMatrix {
1.000000, 0.000000, 0.000000, 0.000000,
0.000000, 1.000000, 0.000000, 0.000000,
0.000000, 0.000000, 1.000000, 0.000000,
0.000000, 0.000000, 0.000000, 1.000000;;
}
{CubeMesh}        // You could have the mesh inline, but this
                  // uses an object reference instead.
}


Working with AnimationSets and Animations

An animation is defined by a set of keys. A key is a time value associated with a scaling operation, an orientation, or a position.

Animation Animation0 {        // The name is chosen for convenience.
{ Frame that it applies to&em;normally a reference }
AnimationKey {
...animation key data...
}
{ ...more animation keys... }
}

Animations are then grouped into AnimationSets:

AnimationSet AnimationSet0 { // The name is chosen for convenience.
{ an animation—could be inline or a reference }
{ ... more animations ... }
}

Now take the cube through an animation.

AnimationSet AnimationSet0 {
Animation Animation0 {
{CubeFrame}    // Use the frame containing the cube.
AnimationKey {
2;             // Position keys
9;             // 9 keys
10; 3; -100.000000, 0.000000, 0.000000;;,
20; 3; -75.000000, 0.000000, 0.000000;;,
30; 3; -50.000000, 0.000000, 0.000000;;,
40; 3; -25.500000, 0.000000, 0.000000;;,
50; 3; 0.000000, 0.000000, 0.000000;;,
60; 3; 25.500000, 0.000000, 0.000000;;,
70; 3; 50.000000, 0.000000, 0.000000;;,
80; 3; 75.500000, 0.000000, 0.000000;;,
90; 3; 100.000000, 0.000000, 0.000000;;;
}
}
}

For more information, see the Animation and AnimationSet templates.


Converting and Exporting 3-D Models to X Files

Microsoft® Direct3D® supplies the following tools to convert and export 3-D models to the .x file format.

  • Conv3ds.exe
  • XSkinExp.dle


Conv3ds.exe

The Conv3ds.exe utility converts three-dimensional (3-D) models produced by Autodesk 3-D Studio and other modeling packages to the Microsoft® DirectX® file format. By default, the utility produces binary .x files with no templates.

Information is divided into the following sections.

  • Running Conv3ds.exe
  • Specifying Optional Arguments for Conv3ds.exe
  • Producing 3DS Files from Lightwave Objects
  • Hints and Tips


Running Conv3ds.exe

You can run Conv3ds.exe with no options, and it will produce an .x file containing a hierarchy of frames. For example, the following command produces an .x file called File.x from the .3ds file.

conv3ds File.3ds

To run Conv3ds.exe with options, see Specifying Optional Arguments for Conv3ds.exe.


Specifying Optional Arguments for Conv3ds.exe

If the .3ds file contains key frame data, you can use the -A option to produce an .x file that contains an animation set. The following command would do this.

conv3ds -A File.3ds

The File.3ds parameter is the name of the file to be converted.

Use the -m option to make an .x file that contains a single mesh made from all the objects in the .3ds file.

conv3ds -m File.3ds

Use the -T option to wrap all the objects and frame hierarchies in a single top-level frame. Using this option, all the frames and objects in the .3ds file can be loaded with a single call. The first top-level frame hierarchy in the .x file will be loaded. The frame containing all the other frames and meshes is called x3ds_filename, without the .3ds extension. The -T option will have no effect if it is used with the -m option.

The -s option enables you to specify a scale factor for all the objects converted in the .3ds file. For example, the following command makes all objects ten times bigger.

conv3ds -s10 File.3ds

The following command makes all objects ten times smaller:

conv3ds -s0.1 File.3ds

The -r option reverses the winding order of the faces when the .3ds file is converted. If, after converting the .3ds file and viewing it in Microsoft® Direct3D®, the object appears inside-out, try converting it with the -r option. All Lightwave models exported as .3ds files need this option. For details, see Producing 3DS Files from Lightwave Objects.

The -v option turns on verbose output mode. Specify an integer with it. The following table shows the currently supported integers.

Option | Meaning
-v0 | Default. Verbose mode off.
-v1 | Prints warnings about bad objects, and prints general information about what the converter is doing.
-v2 | Prints basic key frame information, the objects being included in the conversion process, and information about the objects being saved.
-v3 | Very verbose. Most useful for debugging information.

The -e option enables you to change the extension for texture map files, as shown in the following example.

conv3ds -e"ppm" File.3ds

If File.3ds contains objects that reference the texture map file Brick.gif, the .x file will reference the texture map file Brick.ppm. The converter does not convert the texture map file. The texture map files must be in the D3DPATH when the resulting .x file is loaded. The D3DPath is an environment variable that sets the default search path.

The -x option forces the Conv3ds.exe utility to produce a text .x file, instead of a binary .x file. Text files are larger but can be easily edited by hand.

The -X option forces the Conv3ds.exe utility to include the .x file templates in the file. By default, the templates are not included.

The -t option specifies that the .x file produced will not contain texture information.

The -N option specifies that the .x file produced will not contain normal vector information. All the load calls will generate normal vectors for objects with no normal vectors in the .x file.

The -c option specifies that the .x file produced should not contain texture coordinates. By default, if you use the -m option, the mesh that is output will contain (0,0) uv texture coordinates if the .3ds object had no texture coordinates.

The -f option specifies that the .x file produced should not contain a frame transformation matrix.

The -z and -Z options enable you to adjust the alpha face color value of all the materials referenced by objects in the .x file. For example, the following command causes Conv3ds.exe to add 0.1 to all alpha values under 0.2.

conv3ds -z0.1 -Z0.2 File.3ds

The following command causes Conv3ds.exe to subtract 0.2 from the alpha values for all alphas.

conv3ds-z"-0.2" -z1 File.3ds

The -o option enables you to specify the file name for the .x file produced.

The -h option tells the converter not to try to resolve any hierarchy information in the .3ds file, usually produced by the key framer. Instead, all the objects are output in top-level frames if the -m option is not used.


Producing 3DS Files from Lightwave Objects

There are several issues with .3ds files exported by the Trans3d plug-in for Lightwave. These are best handled using the following Conv3ds.exe command.

conv3ds -r -N -f -h -T|m trans3dfile.3ds

All the .3ds objects produced by Trans3d and the Lightwave object editor need their winding order reversed. Otherwise, they appear inside-out when displayed. They contain no surface normal vector information.


Hints and Tips

If you cannot see objects produced by Conv3ds.exe after loading them, use the scale option -s with a scale factor of approximately 100. This increases the scale of the objects in the .x file.

If, after loading the object into the viewer and switching from flat shading into Gouraud shading, the object turns dark gray, try converting with the -N option.

If the textures are not loaded after the object is converted, check whether the object is referencing either .ppm or .bmp files by using the -e option. Also check whether the texture widths and heights are a power of 2. Make sure the textures are stored in a directory in your D3DPATH.

Currently, Conv3ds.exe cannot handle dummy frames used in .3ds animations. It ignores them. However, it converts any child objects.


XSkinExp.dle

XSkinExp.dle is located in the extras directory and is used as an exporter for 3dsmax. To find out how to use it, read the readme file provided with XSkinExp.dle.


Programming Tips and Tools

This section contains information to help you develop Microsoft® DirectX® Graphics applications efficiently. The following topics are covered.

  • Troubleshooting
  • Performance Optimizations
  • Multithreading Issues
  • Working with Device Windows
  • Working with Earlier Drivers
  • Working with Multiple Monitor Systems
  • Presenting Multiple Views in Windowed Mode


Troubleshooting

This section lists common categories of problems that you might encounter when writing Microsoft® Direct3D® applications, and how to prevent them.

  • Device Creation
  • Using Lit Vertices
  • Nothing Visible
  • Debugging
  • Borland Floating-Point Initialization
  • Parameter Validation


Device Creation

If your application fails during device creation, check for the following common errors.

  • Make sure you check the device capabilities, particularly the render depths.
  • Examine the error code. D3DERR_OUTOFVIDEOMEMORY is always possible.
  • Use the debug DirectX DLLs and review output messages under the debugger.


Using Lit Vertices

Applications that use lit vertices should disable the Microsoft® Direct3D® lighting engine by setting the D3DRS_LIGHTING render state to FALSE. By default, when lighting is enabled, the system sets the color for any vertex that doesn't contain a normal vector to 0 (black), even if the input vertex contained a nonzero color value. Because lit-vertices don't, by their nature, contain a vertex normal, any color information passed to Direct3D is lost during rendering if the lighting engine is enabled.

Obviously, vertex color is important to any application that performs its own lighting. To prevent the system from imposing the default values, make sure you set D3DRS_LIGHTING to FALSE.


Nothing Visible

If your application runs but nothing is visible, check for the following common errors.

  • Ensure that your triangles are not degenerate.
  • Ensure that your triangles are not being culled.
  • Make sure that your transformations are internally consistent.
  • Check the viewport settings to be sure they allow your triangles to be seen.


Debugging

Debugging a Microsoft® Direct3D® application can be challenging. Try the following techniques, in addition to checking all the return values—a particularly important piece of advice in Direct3D programming, which is dependent on very different hardware implementations.

  • Switch to debug DLLs.
  • Force a software-only device, turning off hardware acceleration even when it is available.
  • Force surfaces into system memory.
  • Create an option to run in a window, so that you can use an integrated debugger.

The second and third options in this list can help you avoid the Win16 lock which can otherwise cause your debugger to hang.

Also, try adding the following entries to Win.ini.

[Direct3D]
debug=3
[DirectDraw]
debug=3


Borland Floating-Point Initialization

Compilers from Borland report floating-point exceptions in a manner that is incompatible with Microsoft® Direct3D®. To solve this problem, include a _matherr exception handler like the following:

// Borland floating point initialization
#include <math.h>
#include <float.h>

void initfp(void)
{
    // Disable floating point exceptions.
    _control87(MCW_EM,MCW_EM);
}

int _matherr(struct _exception  *e)
{
    e;               // Dummy reference to catch the warning.
    return 1;        // Error has been handled.
}


Parameter Validation

For performance reasons, the debug version of the Microsoft® Direct3D® Immediate Mode run time performs more parameter validation than the retail version, which sometimes performs no validation at all. This enables applications to perform robust debugging with the slower debug run-time component before using the faster retail version for performance tuning and final release.

Although several Direct3D Immediate Mode methods impose limits on the values that they can accept, these limits are often only checked and enforced by the debug version of the Direct3D Immediate Mode run time. Applications must conform to these limits, or unpredictable and undesirable results can occur when running on the retail version of Direct3D. For example, the IDirect3Ddevice8::DrawPrimitive method accepts a parameter (PrimitiveCount) that indicates the number of primitives that the method will render. The method can only accept values between 0 and D3DMAXNUMPRIMITIVES. In the debug version of Direct3D, if you pass more than D3DMAXNUMPRIMITIVES primitives, the method fails gracefully, printing an error message to the error log, and returning an error value to your application. Conversely, if your application makes the same error when it is running with the retail version of the run time, behavior is undefined. For performance reasons, the method does not validate the parameters, resulting in unpredictable and completely situational behavior when they are not valid. In some cases the call might work, and in other cases it might cause a memory fault in Direct3D. If an invalid call consistently works with a particular hardware configuration and DirectX version, there is no guarantee that it will continue to function on other hardware or with future releases of DirectX.

If your application encounters unexplained failures when running with the retail Direct3D Immediate Mode run-time file, test against the debug version and look closely for cases where your application passes invalid parameters.


Performance Optimizations

Every developer who creates real-time applications that use 3-D graphics is concerned about performance optimization. This section provides you with guidelines about getting the best performance from your code.

You can use the guidelines in the following sections for any Microsoft® Direct3D® application.

  • General Performance Tips
  • Databases and Culling
  • Batching Primitives
  • Lighting Tips
  • Texture Size
  • Using Dynamic Vertex and Index Buffers
  • Using Meshes
  • Z-buffer Performance


General Performance Tips

You can follow a few general guidelines to increase the performance of your application.

  • Only clear when you must.
  • Minimize state changes.
  • Use perspective correction only if you must.
  • Use smaller textures, if you can do so.
  • Gracefully degrade special effects that require a disproportionate share of system resources.
  • Constantly test your application's performance.
  • Ensure that your application runs well with both hardware acceleration and software emulation.


Databases and Culling

Building a reliable database of the objects in your world is key to excellent performance in Microsoft® Direct3D®. It is more important than improvements to rasterization or hardware.

You should maintain the lowest polygon count you can possibly manage. Design for a low polygon count by building low-poly models from the start. Add polygons if you can do so without sacrificing performance later in the development process. Remember, the fastest polygons are the ones you don't draw.


Batching Primitives

To get the best rendering performance during execution, try to work with primitives in batches and keep the number of render-state changes as low as possible. For example, if you have an object with two textures, group the triangles that use the first texture and follow them with the necessary render state to change the texture. Then group all the triangles that use the second texture. The simplest hardware support for Microsoft® Direct3D® is called with batches of render states and batches of primitives through the hardware abstraction layer (HAL). The more effectively the instructions are batched, the fewer HAL calls are performed during execution.


Lighting Tips

Because lights add a per-vertex cost to each rendered frame, you can achieve significant performance improvements by being careful about how you use them in your application. Most of the following tips derive from the maxim, the fastest code is code that is never called.

  • Use as few light sources as possible. If you only need to increase the overall lighting level, use the ambient light instead of adding a new light source. It's much cheaper.
  • Directional lights are cheaper than point lights or spotlights. For directional lights, the direction to the light is fixed and doesn't need to be calculated on a per-vertex basis.
  • Spotlights can be cheaper than point lights, because the area outside the cone of light is calculated quickly. Whether spotlights are cheaper depends on how much of your scene is lit by the spotlight.
  • Use the range parameter to limit your lights to only the parts of the scene you need to illuminate. All the light types exit fairly early when they are out of range.
  • Specular highlights almost double the cost of a light—use them only when you must. Set the D3DRS_SPECULARENABLE render state to 0, the default value, whenever possible. When defining materials you must set the specular power value to zero to turn off specular highlights for that material—simply setting the specular color to 0,0,0 is not enough.


Texture Size

Texture-mapping performance is heavily dependent on the speed of memory. There are a number of ways to maximize the cache performance of your application's textures.

  • Keep the textures small; the smaller the textures are, the better chance they have of being maintained in the main CPU's secondary cache.
  • Do not change the textures on a per-primitive basis. Try to keep polygons grouped in order of the textures they use.
  • Use square textures whenever possible. Textures whose dimensions are 256×256 are the fastest. If your application uses four 128×128 textures, for example, try to ensure that they use the same palette and place them all into one 256×256 texture. This technique also reduces the amount of texture swapping. Of course, you should not use 256×256 textures unless your application requires that much texturing because, as mentioned, textures should be kept as small as possible.


Using Dynamic Vertex and Index Buffers

Dynamic vertex and index buffers have a difference in performance based the size and usage. The usage styles below help to determine whether to use D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the Lock method.

Usage Style 1:

for loop()
{
    pBuffer->Lock(...D3DLOCK_DISCARD...); //Ensures that hardware
                                          //doesn't stall by returning
                                          //a new pointer.
    Fill data (optimally 1000s of vertices/indices, no fewer) in pBuffer.
    pBuffer->Unlock()
    Change state(s).
    DrawPrimitive() or DrawIndexedPrimitive()
}

Usage Style 2:

for loop()
{
    pVB->Lock(...D3DLOCK_DISCARD...); //Ensures that hardware doesn't
                                      //stall by returning a new
                                      //pointer.
    Fill data (optimally 1000s of vertices/indices, no fewer) in pBuffer.
    for loop( 100s of times )
    {
        Change State
        DrawPrimitive() or DrawIndexPrimitives() //Tens of primitives
    }
}

Usage Style 3:

for loop()
{
    If there is space in the Buffer
    {
        //Append vertices/indices.
        pBuffer->Lock(…D3DLOCK_NOOVERWRITE…);
    }
    Else
    {
        //Reset to beginning.
        pBuffer->Lock(…D3DLOCK_DISCARD…);
    }
    Fill few 10s of vertices/indices in pBuffer
    pBuffer->Unlock
    Change State
    DrawPrimitive() or DrawIndexedPrimitive() //A few primitives

}

Style 1 is faster than either style 2 or 3, but is generally not very practical. Style 2 is usually faster than style 3, provided that the application fills at least a couple thousand vertices/indices for every Lock, on average. If the application fills fewer than that on average, then style 3 is faster. There is no guaranteed answer as to which lock method is faster and the best way to find out is to experiment.


Using Meshes

You can optimize meshes by using Microsoft® Direct3D® indexed triangles instead of indexed triangle strips. The hardware will discover that 95% of successive triangles actually form strips and adjust accordingly. Many drivers do this for legacy hardware also.

The following topics describes the different attributes of a mesh.

Attribute ID

An attribute ID is a value that associates a group of faces with an attribute group. This ID describes which subset of faces DrawSubset should draw. Attribute IDs are specified for the faces in the attribute buffer. The actual values of the attribute IDs can be anything that fits in 32bits, but it is common to use 0 to n where n is the number of attributes.

Attribute Buffer

The attribute buffer is an array of DWORDs (one per face) that specifies which attribute group each face belongs in. This buffer is initialized to zero on creation of a mesh, but is either filled by the load routines or must be filled by the user if more than one attribute with ID 0 is desired. This buffer contains the information that is used to sort the mesh based on attributes in Optimize. If no attribute table is present, DrawSubset scans this buffer to select the faces of the given attribute to draw.

Attribute Table

The attribute table is a structure owned and maintained by the mesh. The only way for one to be generated is by calling Optimize with attribute sorting or stronger optimization enabled. The attribute table is used to quickly initiate a single draw primitive call to DrawSubset. The only other use is that progressing meshes also maintain this structure, so it is possible to see what faces and vertices are active at the current level of detail(LOD).


Z-Buffer Performance

Applications can increase performance when using z-buffering and texturing by ensuring that scenes are rendered from front to back. Textured z-buffered primitives are pretested against the z-buffer on a scan line basis. If a scan line is hidden by a previously rendered polygon, the system rejects it quickly and efficiently. Z-buffering can improve performance, but the technique is most useful when a scene includes a great deal of overdraw. Overdraw is the average number of times that a screen pixel is written to. Overdraw is difficult to calculate exactly, but you can often make a close approximation. If the overdraw averages less than 2, you can achieve the best performance by turning z-buffering off and rendering the scene from back-to-front.

On faster personal computers, software rendering to system memory is often faster than rendering to video memory, although it has the disadvantage of not being able to use double buffering or hardware-accelerated clear operations. If your application can render to either system or video memory, and if you include a routine that tests which is faster, you can take advantage of the best approach on the current system. The Microsoft® Direct3D® sample code in this SDK demonstrates this strategy. It is necessary to implement both methods because there is no other way to test the speed. Speeds can vary enormously from computer to computer, depending on the main-memory architecture and the type of graphics adapter being used.


Multithreading Issues

Full-screen Microsoft® Direct3D® applications provide a window handle to the Direct3D run time. The window is hooked by the run time. This means that all messages passed to the application's window message procedure have first been examined by the Direct3D run time's own message-handling procedure.

Display mode changes are affected by support routines built into the underlying operating system. When mode changes occur, the system broadcasts several messages to all applications. In Direct3D applications, the messages are received on the window procedure thread, which is not necessarily the same thread that called IDirect3DDevice8::Reset or IDirect3D8::CreateDevice (or the final IUnknown::Release of IDirect3DDevice8, which can cause a display mode change). The Direct3D run time maintains several critical sections internally. Because at least one of these critical sections is held across the mode switch caused by Reset or CreateDevice, these critical sections are still held when the application receives the mode-change related window messages.

This design has some implications for multithreaded applications. In particular, an application must be sure to strongly segregate its window message handling threads from its Direct3D threads. An application that causes a mode change on one thread but makes Direct3D calls on a different thread in its window procedure is in danger of deadlock.

For these reasons, Direct3D is designed so that the methods Reset, CreateDevice, TestCoorperativeLevel, or the final Release of IDirect3DDevice8 can only be called from the same thread that handles window messages.


Working with Device Windows

This section lists issues that you might encounter when working with device windows in Microsoft® Direct3D® applications.

  • Direct3D only hooks up the focus windows instead of the device window with the Direct3D message processing function, and only processes the focus window messages. So, the focus window should be the parent of any device window.
  • For any application, multiple monitor or single monitor, at least one device window must be the focus window. In practical terms, this means that you cannot use a child window of your focus window as the device window in single monitor systems. You must use the parent focus window as both the focus and device windows. For a multiple monitor system, at least one monitor must use the focus window as its device window.


Working with Earlier Drivers

This section lists issues that may be encountered when working with Microsoft® DirectX® 8.0 on drivers written for versions of DirectX earlier than DirectX 8.0.

  • When working with a TnLHAL device, the fog intensity is computed but the absolute value operation is not applied to this value. Rather, the value is left negative if that is what is computed. The best way to avoid this situation is to set up transforms appropriately. A less-preferred method is to make the fog-start and fog-end values negative to match.

You can detect a driver not written for DirectX 8.0 by querying the MaxStream member of D3DCAPS8. If this value is 0, then it is not a DirectX 8.0 driver.


Working with Multiple Monitor Systems

The concept of exclusive full-screen mode is retained in Microsoft® DirectX® 8.0, but it is kept entirely implicit in the IDirect3D8::CreateDevice and IDirect3DDevice8::Reset method calls. Whenever a device is successfully reset or created in full-screen operation, the Microsoft® Direct3D® object that created the device is marked as owning all adapters on that system. This state is known as exclusive mode, and at this point the Direct3D object owns exclusive mode. Exclusive mode means that devices created by any other Direct3D8 object can neither assume full-screen operation nor allocate video memory. In addition, when a Direct3D8 object assumes exclusive mode, all devices other than the device that went full-screen are placed into the lost state. For information on how to handle lost devices, see Lost Devices.

Along with exclusive mode, the Direct3D8 object is informed of the focus window to be used by the device. Exclusive mode is released when the last full-screen device owned by that Direct3D8 object is either reset to windowed mode or destroyed.

Devices can be divided into two categories when a Direct3D8 object owns exclusive mode. The first category of devices are those that were created by the same Direct3D8 object that created the device that is already full-screen, have the same focus window as the device that is already full-screen, and represent a different adapter from any full-screen device. Devices in this category have no restrictions concerning their ability to be reset or created and are not placed into the lost state. Devices in this category can even be placed into full-screen mode.

Devices not in this category, which would be those created by a different Direct3D8 object, or with a different focus window, or for some adapter with a device already full-screen cannot be reset and remain in the lost state until exclusive mode is lost.

The practical implication is that a multiple monitor application can place several devices in full-screen mode, but only if all these devices are for different adapters, were created by the same Direct3D8 object, and all share the same focus window.


Presenting Multiple Views in Windowed Mode

In addition to the swap chain that is owned and manipulated through the IDirect3DDevice8 interface, an application can create additional swap chains in order to present multiple views from the same device. The application typically creates one swap chain per view by using the IDirect3DDevice8::CreateAdditionalSwapChain method, and associates each swap chain with a particular window. The application renders images into the back buffers of each swap chain, and then presents them individually.

Only one swap chain at a time can be full-screen on each adapter.


DirectX Graphics C/C++ Tutorials

The tutorials in this section show how to use Microsoft® Direct3D® and Direct3DX in a C/C++ application for common tasks. The tasks are divided into required steps. In some cases, steps are organized into substeps for clarity.

The following tutorials are provided.

  • Tutorial 1: Creating a Device
  • Tutorial 2: Rendering Vertices
  • Tutorial 3: Using Matrices
  • Tutorial 4: Creating and Using Lights
  • Tutorial 5: Using Texture Maps
  • Tutorial 6: Using Meshes

Note The sample code in these tutorials is from source projects whose location is provided in each tutorial.

The sample files in these tutorials are written in C++. If you are using a C compiler, you must make the appropriate changes to the files for them to successfully compile. At the very least, you need to add the vtable and this pointers to the interface methods.

Some comments in the included sample code might differ from the source files in the Microsoft Platform Software Development Kit (SDK). Changes are made for brevity only and are limited to comments to avoid changing the behavior of the sample code.

See Also

DirectX Graphics C/C++ Samples


Tutorial 1: Creating a Device

To use Microsoft® Direct3D®, you first create an application window, then you create and initialize Direct3D objects. You use the COM interfaces that these objects implement to manipulate them and to create other objects required to render a scene. The CreateDevice sample project on which this tutorial is based illustrates these tasks by creating a Direct3D device and rendering a blue screen.

This tutorial uses the following steps to initialize Direct3D, render a scene, and eventually shut down.

  • Step 1: Creating a Window
  • Step 2: Initializing Direct3D
  • Step 3: Handling System Messages
  • Step 4: Rendering and Displaying a Scene
  • Step 5: Shutting Down

Note The path of the CreateDevice sample project is:

(SDK Root)\Samples\Multimedia\Direct3D\Tutorials\Tut01_CreateDevice.


Step 1: Creating a Window

The first thing any Microsoft® Windows® application must do when it is executed is create an application window to display to the user. To do this, the CreateDevice sample project begins execution at its WinMain function. The following sample code performs window initialization.

INT WINAPI WinMain( HINSTANCE hInst, HINSTANCE, LPSTR, INT )
{
    // Register the window class.
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L,
                      GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
                      "D3D Tutorial", NULL };
    RegisterClassEx( &wc );

    // Create the application's window.
    HWND hWnd = CreateWindow( "D3D Tutorial", "D3D Tutorial 01: CreateDevice",
                              WS_OVERLAPPEDWINDOW, 100, 100, 300, 300,
                              GetDesktopWindow(), NULL, wc.hInstance, NULL );

The preceding code sample is standard Windows programming. The sample starts by defining and registering a window class called "D3D Tutorial." After the class is registered, the sample code creates a basic top-level window that uses the registered class, with a client area of 300 pixels wide by 300 pixels tall. This window has no menu or child windows. The sample uses the WS_OVERLAPPEDWINDOW window style to create a window that includes Minimize, Maximize, and Close buttons common to windowed applications. (If the sample were to run in full-screen mode, the preferred window style is WS_EX_TOPMOST, which specifies that the created window should be placed above all non-topmost windows and should stay above them, even when the window is deactivated). Once the window is created, the code sample calls standard Microsoft Win32® functions to display and update the window.

With the application window ready, you can begin setting up the essential Microsoft Direct3D® objects, as described in Step 2: Initializing Direct3D.


Step 2: Initializing Direct3D

The CreateDevice sample project performs Microsoft® Direct3D® initialization in the InitD3D application-defined function called from WinMain after the window is created. After you create an application window, you are ready to initialize the Direct3D object that you will use to render the scene. This process includes creating a Direct3D object, setting the presentation parameters, and finally creating the Direct3D device.

After creating a Direct3D object, you can use the IDirect3D8::CreateDevice method to create a Direct3D device. You can also use the Direct3D object to enumerate devices, types, modes, and so on. The code fragment below creates a Direct3D object with the Direct3DCreate8 function.

if( NULL == ( g_pD3D = Direct3DCreate8( D3D_SDK_VERSION ) ) )
    return E_FAIL;

The only parameter passed to Direct3DCreate8 should always be D3D_SDK_VERSION. This informs Direct3D that the correct header files are being used. This value is incremented whenever a header or other change would require applications to be rebuilt. If the version does not match, Direct3DCreate8 will fail.

The next step is to retrieve the current display mode by using the IDirect3D8::GetAdapterDisplayMode method as shown in the code fragment below.

D3DDISPLAYMODE d3ddm;
if( FAILED( g_pD3D->GetAdapterDisplayMode( D3DADAPTER_DEFAULT, &d3ddm ) ) )
    return E_FAIL;

The Format member of the D3DDISPLAYMODE structure will be used when creating the Direct3D device. To run in windowed mode, the Format member is used to create a back buffer that matches the adapter's current mode.

By filling in the fields of the D3DPRESENT_PARAMETERS you can specify how you want your 3-D application to behave. The CreateDevice sample project sets its Windowed member to TRUE, its SwapEffect member to D3DSWAPEFFECT_DISCARD, and its BackBufferFormat member to d3ddm.Format.

D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed   = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = d3ddm.Format;

The final step is to use the IDirect3D8::CreateDevice method to create the Direct3D device, as illustrated in the following code example.

if( FAILED( g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                  D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                  &d3dpp, &g_pd3dDevice ) ) )

The preceding code sample creates the device with the default adapter by using the D3DADAPTER_DEFAULT flag. In most cases, the system will have only a single adapter, unless it has multiple graphics hardware cards installed. Indicate that you prefer a hardware device over a software device by specifying D3DDEVTYPE_HAL for the DeviceType parameter. This code sample uses D3DCREATE_SOFTWARE_VERTEXPROCESSING to tell the system to use software vertex processing. Note that if you tell the system to use hardware vertex processing by specifying D3DCREATE_HARDWARE_VERTEXPROCESSING, you will see a significant performance gain on video cards that support hardware vertex processing.

Now that the Direct3D has been initialized, the next step is to ensure that you have a mechanism to process system messages, as described in Step 3: Handling System Messages.


Step 3: Handling System Messages

After you have created the application window and initialized Microsoft® Direct3D®, you are ready to render the scene. In most cases, Microsoft Windows® applications monitor system messages in their message loop, and they render frames whenever no messages are in the queue. However, the CreateDevice sample project waits until a WM_PAINT message is in the queue, telling the application that it needs to redraw all or part of its window.

// The message loop.
MSG msg;
while( GetMessage( &msg, NULL, 0, 0 ) )
{
    TranslateMessage( &msg );
    DispatchMessage( &msg );
}

Each time the loop runs, DispatchMessage calls MsgProc, which handles messages in the queue. When WM_PAINT is queued, the application calls Render, the application-defined function that will redraw the window. Then the Microsoft Win32® function ValidateRect is called to validate the entire client area.

The sample code for the message-handling function is shown below.

LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch( msg )
    {
        case WM_DESTROY:
            PostQuitMessage( 0 );
            return 0;

        case WM_PAINT:
            Render();
            ValidateRect( hWnd, NULL );
            return 0;
    }

    return DefWindowProc( hWnd, msg, wParam, lParam );
}

Now that the application handles system messages, the next step is to render the display, as described in Step 4: Rendering and Displaying a Scene.


Step 4: Rendering and Displaying a Scene

To render and display the scene, the sample code in this step clears the back buffer to a blue color, transfers the contents of the back buffer to the front buffer, and presents the front buffer to the screen.

To clear a scene, call the IDirect3DDevice8::Clear method.

// Clear the back buffer to a blue color
g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0 );

The first two parameters accepted by Clear inform Microsoft® Direct3D® of the size and address of the array of rectangles to be cleared. The array of rectangles describes the areas on the render target surface to be cleared.

In most cases, you use a single rectangle that covers the entire rendering target. You do this by setting the first parameter to 0 and the second parameter to NULL. The third parameter determines the method's behavior. You can specify a flag to clear a render-target surface, an associated depth buffer, the stencil buffer, or any combination of the three. This tutorial does not use a depth buffer, so D3DCLEAR_TARGET is the only flag used. The last three parameters are set to reflect clearing values for the render target, depth buffer, and stencil buffer. The CreateDevice sample project sets the clear color for the render target surface to blue (D3DCOLOR_XRGB(0,0,255)). The final two parameters are ignored by the Clear method because the corresponding flags are not present.

After clearing the viewport, the CreateDevice sample project informs Direct3D that rendering will begin, then it signals that rendering is complete, as shown in the following code fragment.

// Begin the scene.
g_pd3dDevice->BeginScene();

// Rendering of scene objects happens here.

// End the scene.
g_pd3dDevice->EndScene();

The IDirect3DDevice8::BeginScene and IDirect3DDevice8::EndScene methods signal to the system when rendering is beginning or is complete. You can call rendering methods only between calls to these methods. Even if rendering methods fail, you should call EndScene before calling BeginScene again.

After rendering the scene, you display it by using the IDirect3DDevice8::Present method.

g_pd3dDevice->Present( NULL, NULL, NULL, NULL );

The first two parameters accepted by Present are a source rectangle and destination rectangle. The sample code in this step presents the entire back buffer to the front buffer by setting these two parameters to NULL. The third parameter sets the destination window for this presentation. Because this parameter is set to NULL, the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is used. The fourth parameter is the DirtyRegion parameter and in most cases should be set to NULL.

The final step for this tutorial is shutting down the application, as described in Step 5: Shutting Down


Step 5: Shutting Down

At some point during execution, your application must shut down. Shutting down a Microsoft® DirectX® application not only means that you destroy the application window, but you also deallocate any DirectX objects your application uses, and you invalidate the pointers to them. The CreateDevice sample project calls Cleanup, an application-defined function to handle this when it receives a WM_DESTROY message.

VOID Cleanup()
{
    if( g_pd3dDevice != NULL)
        g_pd3dDevice->Release();
    if( g_pD3D != NULL)
        g_pD3D->Release();
}

The preceding function deallocates the DirectX objects it uses by calling the IUnknown::Release methods for each object. Because this tutorial follows COM rules, the reference count for most objects should become zero and should be automatically removed from memory.

In addition to shutdown, there are times during normal execution—such as when the user changes the desktop resolution or color depth—when you might need to destroy and re-create the Microsoft Direct3D® objects in use. Therefore it is a good idea to keep your application's cleanup code in one place, which can be called when the need arises.

This tutorial has shown you how to create a device. Tutorial 2: Rendering Vertices shows you how to use vertices to draw geometric shapes.


Tutorial 2: Rendering Vertices

Applications written in Microsoft® Direct3D® use vertices to draw geometric shapes. Each 3-D scene includes one or more of these geometric shapes. The Vertices sample project creates the simplest shape, a triangle, and renders it to the display.

This tutorial shows how to use vertices to create a triangle with the following steps:

  • Step 1: Defining a Custom Vertex Type
  • Step 2: Setting Up the Vertex Buffer
  • Step 3: Rendering the Display

Note The path of the Vertices sample project is:

(SDK Root)\Samples\Multimedia\Direct3D\Tutorials\Tut02_Vertices.

The sample code in the Vertices project is nearly identical to the sample code in the CreateDevice project. The Rendering Vertices tutorial focuses only on the code unique to vertices, and does not cover initializing Direct3D, handling Microsoft Windows® messages, rendering, or shutting down. For information on these tasks, see Tutorial 1: Creating a Device.


Step 1: Defining a Custom Vertex Type

The Vertices sample project renders a 2-D triangle by using three vertices. This introduces the concept of the vertex buffer, which is a Microsoft® Direct3D® object that is used to store and render vertices. Vertices can be defined in many ways by specifying a custom vertex structure and corresponding custom flexible vector format (FVF). The format of the vertices in the Vertices sample project is shown in the following code fragment.

struct CUSTOMVERTEX
{
    FLOAT x, y, z, rhw; // The transformed position for the vertex.
    DWORD color;        // The vertex color.
};

The structure above specifies the format of the custom vertex type. The next step is to define the FVF that describes the contents of the vertices in the vertex buffer. The following code fragment defines a FVF that corresponds with the custom vertex type created above.

#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW|D3DFVF_DIFFUSE)

Flexible vertex format flags describe what type of custom vertex is being used. The sample code above uses the D3DFVF_XYZRHW and D3DFVF_DIFFUSE flags, which tell the vertex buffer that the custom vertex type has a transformed point followed by a color component.

Now that the custom vector format and FVF are specified, the next step is to fill the vertex buffer with vertices, as described in Step 2: Setting Up the Vertex Buffer.

Note The vertices in the Vertices sample project are transformed. In other words, they are already in 2-D window coordinates. This means that the point (0,0) is at the top-left corner and the positive x-axis is right and the positive y-axis is down. These vertices are also lit, meaning that they are not using Direct3D lighting but are supplying their own color.


Step 2: Setting Up the Vertex Buffer

Now that the custom vertex format is defined, it is time to initialize the vertices. The Vertices sample project does this by calling the application-defined function InitVB after creating the required Microsoft® Direct3D® objects. The following code fragment initializes the values for three custom vertices.

CUSTOMVERTEX g_Vertices[] =
{
    { 150.0f,  50.0f, 0.5f, 1.0f, 0xffff0000, }, // x, y, z, rhw, color
    { 250.0f, 250.0f, 0.5f, 1.0f, 0xff00ff00, },
    {  50.0f, 250.0f, 0.5f, 1.0f, 0xff00ffff, },
};

The preceding code fragment fills three vertices with the points of a triangle and specifies which color each vertex will emit. The first point is at (150, 50) and emits the color red (0xffff0000). The second point is at (250, 250) and emits the color green (0xff00ff00). The third point is at (50, 250) and emits the color blue-green (0xff00ffff). Each of these points has a depth value of 0.5 and an RHW of 1.0. For more information on this vector format see Transformed and Lit Vertices

The next step is to call IDirect3DDevice8::CreateVertexBuffer to create a vertex buffer as shown in the following code fragment.

if( FAILED( g_pd3dDevice->CreateVertexBuffer( 3*sizeof(CUSTOMVERTEX),
                                              0 /* Usage */, D3DFVF_CUSTOMVERTEX,
                                              D3DPOOL_DEFAULT, &g_pVB ) ) )
    return E_FAIL;

The first two parameters of CreateVertexBuffer tell Direct3D the desired size and usage for the new vertex buffer. The next two parameters specify the vector format and memory location for the new buffer. The vector format here is D3DFVF_CUSTOMVERTEX, which is the FVF that the sample code specified earlier. The D3DPOOL_DEFAULT flag tells Direct3D to create the vertex buffer in the memory allocation that is most appropriate for this buffer. The final parameter is the address of the vertex buffer to create.

After creating a vertex buffer, it is filled with data from the custom vertices as shown in the following code fragment.

VOID* pVertices;
if( FAILED( g_pVB->Lock( 0, sizeof(g_Vertices), (BYTE**)&pVertices, 0 ) ) )
    return E_FAIL;
memcpy( pVertices, g_Vertices, sizeof(g_Vertices) );
g_pVB->Unlock();

The vertex buffer is first locked by calling IDirect3DVertexBuffer8::Lock. The first parameter is the offset into the vertex data to lock, in bytes. The second parameter is the size of the vertex data to lock, in bytes. The third parameter is the address of a BYTE pointer, filled with a pointer to vertex data. The fourth parameter tells the vertex buffer how to lock the data.

The vertices are then copied into the vertex buffer using memcpy. After the vertices are in the vertex buffer, a call is made to IDirect3DVertexBuffer8::Unlock to unlock the vertex buffer. This mechanism of locking and unlocking is required because the vertex buffer may be in device memory.

Now that the vertex buffer is filled with the vertices, it is time to render the display, as described in Step 3: Rendering the Display.


Step 3: Rendering the Display

Now that the vertex buffer is filled with vertices, it is time to render the display. Rendering the display starts by clearing the back buffer to a blue color and then calling BeginScene.

g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0L );
g_pd3dDevice->BeginScene();

Rendering vertex data from a vertex buffer requires a few steps. First, you need to set the stream source; in this case, use stream 0. The source of the stream is specified by calling IDirect3DDevice8::SetStreamSource.

g_pd3dDevice->SetStreamSource( 0, g_pVB, sizeof(CUSTOMVERTEX) );

The first parameter of SetStreamSource tells Microsoft® Direct3D® the source of the device data stream. The second parameter is the vertex buffer to bind to the data stream. The third parameter is the size of the component, in bytes. In the sample code above, the size of a CUSTOMVERTEX is used for the size of the component.

The next step is to let Direct3D know what vertex shader to use by calling IDirect3DDevice8::SetVertexShader. Full, custom vertex shaders are an advanced topic, but in most cases the vertex shader is only the FVF code. This lets Direct3D know what types of vertices it is dealing with. The following code fragment sets the vertex shader.

g_pd3dDevice->SetVertexShader( D3DFVF_CUSTOMVERTEX );

The only parameter for SetVertexShader is a handle to the vertex shader to use. The value for this parameter can be a handle returned by IDirect3DDevice8::CreateVertexShader, or an FVF code. Here, the FVF code defined by D3DFVF_CUSTOMVERTEX is used.

For more information on vertex shaders, see Vertex shaders.

The next step is to use IDirect3DDevice8::DrawPrimitive to render the vertices in the vertex buffer as shown in the following code fragment.

g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 1 );

The first parameter accepted by DrawPrimitive is a flag that tells Direct3D what type of primitives to draw. This sample uses the flag D3DPT_TRIANGLELIST to specify a list of triangles. The second parameter is the index of the first vertex to load. The third parameter tells the number of primitives to draw. Because this sample draws only one triangle, this value is set to 1.

For more information on different kinds of primitives, see 3-D Primitives.

The last steps are to end the scene and then present the back buffer to the front buffer. This is shown in the following code fragment.

g_pd3dDevice->EndScene();
g_pd3dDevice->Present( NULL, NULL, NULL, NULL );

After the back buffer is presented to the front buffer, the client window shows a triangle with three different colored points.

This tutorial has shown you how to use vertices to render geometric shapes. Tutorial 3: Using Matrices introduces the concept of matrices and how to use them.


Tutorial 3: Using Matrices

This tutorial introduces the concept of matrices and shows how to use them. The Vertices sample project rendered 2-D vertices to draw a triangle. However, in this tutorial you will be working with transformations of vertices in 3-D. Matrices are also used to set up cameras and viewports. For more information on working with transformation matrices, see 3-D Transformations.

Before the Matrices sample project renders geometry, it calls the SetupMatrices application-defined function to create and set the matrix transformations that are used to render the 3-D triangle. Typically, three types of transformation are set for a 3-D scene. Steps for creating each one of these typical transformations are listed below.

  • Step 1: Defining the World Transformation Matrix
  • Step 2: Defining the View Transformation Matrix
  • Step 3: Defining the Projection Transformation Matrix

For more information on matrices and transformations, see Matrices.

For more information on 3-D Transformations, see 3-D Transformations.

Note The path of the Matrices sample project is:

(SDK Root)\Samples\Multimedia\Direct3D\Tutorials\Tut03_Matrices.

The order in which these transformation matrices are created does not affect the layout of the objects in a scene. However, Direct3D applies the matrices to the scene in the following order: (1) World ,(2) View, (3) Projection.

The sample code in the Matrices project is nearly identical to the sample code in the Vertices project. The Using Matrices tutorial focuses only on the code unique to matrices and does not cover initializing Direct3D, handling Microsoft Windows® messages, rendering, or shutting down. For information on these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information on selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.


Step 1: Defining the World Transformation Matrix

The world transformation matrix defines how to translate, scale, and rotate the geometry in the 3-D model space.

The following code fragment rotates the triangle on the y-axis and then sets the current world transformation for the Microsoft® Direct3D® device.

D3DXMATRIX matWorld;
D3DXMatrixRotationY( &matWorld, timeGetTime()/150.0f );
g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld );

The first step is to rotate the triangle around the Y-axis by calling the D3DXMatrixRotationY method. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second parameter is the angle of rotation in radians.

The next step is to call IDirect3DDevice8::SetTransform to set the world transformation for the Direct3D device. The first parameter accepted by SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_WORLD macro to specify that the world transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information on world transformations, see The World Transformation.

After defining the world transformation for the scene, you can prepare the view transformation matrix. Again, note that the order in which transformations are defined is not critical. However, Direct3D applies the matrices to the scene in the following order: (1) World ,(2) View, (3) Projection.

Defining the view transformation matrix is described in Step 2: Defining the View Transformation Matrix.


Step 2: Defining the View Transformation Matrix

The view transformation matrix defines the position and rotation of the view. The view matrix is the camera for the scene.

The following code fragment creates the view transformation matrix and then sets the current view transformation for the Microsoft® Direct3D® device.

D3DXMATRIX matView;
D3DXMatrixLookAtLH( &matView, &D3DXVECTOR3( 0.0f, 3.0f,-5.0f ),
                              &D3DXVECTOR3( 0.0f, 0.0f, 0.0f ),
                              &D3DXVECTOR3( 0.0f, 1.0f, 0.0f ) );
g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );

The first step is to define the view matrix by calling D3DXMatrixLookAtLH. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second, third, and fourth parameters define the eye point, look-at point, and "up" direction. Here the eye is set back along the z-axis by five units and up three units, the look-at point is set at the origin, and "up" is defined as the y-direction.

The next step is to call IDirect3DDevice8::SetTransform to set the view transformation for the Direct3D device. The first parameter accepted by SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_VIEW flag to specify that the view transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information on view transformations, see The View Transformation.

After defining the world transformation for the scene, you can prepare the projection transformation matrix. Again, note that the order in which transformations are defined is not critical. However, Direct3D applies the matrices to the scene in the following order: (1) World ,(2) View, (3) Projection.

Defining the projection transformation matrix is described in Step 3: Defining the Projection Transformation Matrix


Step 3: Defining the Projection Transformation Matrix

The projection transformation matrix defines how geometry is transformed from 3-D view space to 2-D viewport space.

The following code fragment creates the projection transformation matrix and then sets the current projection transformation for the Microsoft® Direct3D® device.

D3DXMATRIX matProj;
D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, 1.0f, 1.0f, 100.0f );
g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );

The first step is to call D3DXMatrixPerspectiveFovLH to set up the projection matrix. The first parameter is a pointer to a D3DXMATRIX structure that is the result of the operation. The second parameter defines the field of view, which tells how objects in the distance get smaller. A typical field of view is 1/4 pi, which is what the sample uses. The third parameter defines the aspect ratio. The sample uses the typical aspect ratio of 1. The fourth and fifth parameters define the near and far clipping plane. This determines the distance at which geometry should no longer be rendered. The Matrices sample project has its near clipping plane set at 1 and its far clipping plane set at 100.

The next step is to call IDirect3DDevice8::SetTransform to apply the transformation to the Direct3D device. The first parameter accepted by SetTransform tells Direct3D which transformation to set. This sample uses the D3DTS_PROJECTION flag to specify that the projection transformation should be set. The second parameter is a pointer to a matrix that is set as the current transformation.

For more information on projection transformations, see The Projection Transformation.

This tutorial has shown you how to use matrices. Tutorial 4: Creating and Using Lights shows how to add lights to your scene for more realism.


Tutorial 4: Creating and Using Lights

Microsoft® Direct3D® lights add more realism to 3-D objects. When used, each geometric object in the scene will be lit based on the location and type of lights that are used. The sample code in this tutorial introduces the topics of lights and materials.

This tutorial has the following steps to create a material and a light.

  • Step 1: Initializing Scene Geometry
  • Step 2: Setting up Material and Light

Note The path of the Lights sample project is:

(SDK Root)\Samples\Multimedia\Direct3D\Tutorials\Tut04_Lights.

The sample code in the Lights project is nearly identical to the sample code in the Matrices project. The Creating and Using Lights tutorial focuses only on the code unique to creating and using lights and does not cover setting up Direct3D, handling Microsoft Windows messages, rendering, or shutting down. For information on these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information on selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial makes use of matrices to transform geometry. For more information on matrices and transformations, see Tutorial 3: Using Matrices.


Step 1: Initializing Scene Geometry

One of the requirements of using lights is that each surface has a normal. To do this, the Lights sample project uses a different custom vertex type. The new custom vertex format has a 3-D position and a surface normal. The surface normal is used internally by Microsoft® Direct3D® for lighting calculations.

struct CUSTOMVERTEX
{
    D3DXVECTOR3 position; // The 3-D position for the vertex.
    D3DXVECTOR3 normal;   // The surface normal for the vertex.
};

// Custom FVF.
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_NORMAL)

Now that the correct vector format is defined, the Lights sample project calls InitGeometry, an application-defined function that creates a cylinder. The first step is to create a vertex buffer that stores the points of the cylinder as shown in the following sample code.

// Create the vertex buffer.
if( FAILED( g_pd3dDevice->CreateVertexBuffer( 50*2*sizeof(CUSTOMVERTEX),
                                              0 /* Usage */, D3DFVF_CUSTOMVERTEX,
                                              D3DPOOL_DEFAULT, &g_pVB ) ) )
    return E_FAIL;

The next step is to fill the vertex buffer with the points of the cylinder. Note that in the following sample code, each point is defined by a position and a normal.

for( DWORD i=0; i<50; i++ )
{
    FLOAT theta = (2*D3DX_PI*i)/(50-1);
    pVertices[2*i+0].position = D3DXVECTOR3( sinf(theta),-1.0f, cosf(theta) );
    pVertices[2*i+0].normal   = D3DXVECTOR3( sinf(theta), 0.0f, cosf(theta) );
    pVertices[2*i+1].position = D3DXVECTOR3( sinf(theta), 1.0f, cosf(theta) );
    pVertices[2*i+1].normal   = D3DXVECTOR3( sinf(theta), 0.0f, cosf(theta) );
}

After the preceding sample code fills the vertex buffer with the vertices for a cylinder, the vertex buffer is ready for rendering. But first, the material and light for this scene must be set up before rendering the cylinder. This is described in Step 2: Setting up Material and Light.


Step 2: Setting up Material and Light

To use lighting in Microsoft® Direct3D®, you must create one or more lights. To determine which color a geometric object reflects, a material is created that is used to render geometric objects. Before rendering the scene, the Lights sample project calls SetupLights, an application-defined function that sets up one material and one directional light. This function takes the following steps to create a material and a light.

  • Step 2.1: Creating a Material
  • Step 2.2: Creating a Light


Step 2.1: Creating a Material

A material defines the color that is reflected off the surface of a geometric object when a light hits it. The following code fragment uses the D3DMATERIAL8 structure to create a material that is yellow.

D3DMATERIAL8 mtrl;
ZeroMemory( &mtrl, sizeof(D3DMATERIAL8) );
mtrl.Diffuse.r = mtrl.Ambient.r = 1.0f;
mtrl.Diffuse.g = mtrl.Ambient.g = 1.0f;
mtrl.Diffuse.b = mtrl.Ambient.b = 0.0f;
mtrl.Diffuse.a = mtrl.Ambient.a = 1.0f;
g_pd3dDevice->SetMaterial( &mtrl );

The diffuse color and ambient color for the material are set to yellow. The call to the IDirect3DDevice8::SetMaterial method applies the material to the Microsoft® Direct3D® device used to render the scene. The only parameter that SetMaterial accepts is the address of the material to set. After this call is made, every primitive will be rendered with this material until another call is made to SetMaterial that specifies a different material.

Now that material has been applied to the scene, the next step is to create a light. This is described in Step 2.2: Creating a Light.


Step 2.2: Creating a Light

There are three types of lights available in Microsoft® Direct3D®: point lights, directional lights, and spotlights. The sample code creates a directional light, which is a light that goes in one direction, and it oscillates the direction of the light.

The following code fragment uses the D3DLIGHT8 structure to create a directional light.

D3DXVECTOR3 vecDir;
D3DLIGHT8 light;
ZeroMemory( &light, sizeof(D3DLIGHT8) );
light.Type       = D3DLIGHT_DIRECTIONAL;

The following code fragment sets the diffuse color for this light to white.

light.Diffuse.r  = 1.0f;
light.Diffuse.g  = 1.0f;
light.Diffuse.b  = 1.0f;

The following code fragment rotates the direction of the light around in a circle.

vecDir = D3DXVECTOR3(cosf(timeGetTime()/360.0f),
                     0.0f,
                     sinf(timeGetTime()/360.0f) );
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction, &vecDir );

The call to D3DXVec3Normalize normalizes the direction vector used to determine the direction of the light.

A range can be specified to tell Direct3D how far the light will have an effect. This member does not affect directional lights. The following code fragment assigns a range of 1000 units to this light.

light.Range       = 1000.0f;

The following code fragment assigns the light to the Direct3D device by calling IDirect3DDevice8::SetLight.

g_pd3dDevice->SetLight( 0, &light );

The first parameter that SetLight accepts is the index that this light will be assigned to. Note that if a light already exists at that location, it will be overwritten by the new light. The second parameter is a pointer to the light structure that defines the light. The Lights sample project places this light at index 0.

The following code fragment enables the light by calling IDirect3DDevice8::LightEnable.

g_pd3dDevice->LightEnable( 0, TRUE);

The first parameter that LightEnable accepts is the index of the light to enable. The second parameter is a Boolean value that tells whether to turn the light on (TRUE) or off (FALSE). In the sample code above, the light at index 0 is turned on.

The following code fragment tells Direct3D to render lights by calling IDirect3DDevice8::SetRenderState.

g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, TRUE );

The first two parameters that SetRenderState accepts is which device state variable to modify and what value to set it to. This code sample sets the D3DRS_LIGHTING device variable to TRUE, which has the effect of enabling the rendering of lights.

The final step in this code sample is to turn on ambient lighting by again calling SetRenderState.

g_pd3dDevice->SetRenderState( D3DRS_AMBIENT, 0x00202020 );

The preceding code fragment sets the D3DRS_AMBIENT device variable to a light gray color (0x00202020). Ambient lighting will light up all objects by the given color.

For more information on lighting, see Mathematics of Direct3D Lighting.

This tutorial has shown you how to use lights and materials. Tutorial 5: Using Texture Maps shows you how to add texture to surfaces.


Tutorial 5: Using Texture Maps

While lights and materials add a great deal of realism to a scene, nothing adds more realism than adding textures to surfaces. Textures can be thought of as wallpaper that is shrink-wrapped onto a surface. You could place a wood texture on a cube to make it look like the cube is actually made of wood. The Texture sample project adds a banana peel texture to the cylinder created in Tutorial 4: Creating and Using Lights. This tutorial covers how to load textures, set up vertices, and display objects with texture.

This tutorial implements textures using the following steps:

  • Step 1: Defining a Custom Vector Format
  • Step 2: Initializing Screen Geometry
  • Step 3: Rendering the Scene

Note The path of the Texture sample project is:

(SDK Root)\Samples\Multimedia\Direct3D\Tutorials\Tut05_Textures.

The sample code in the Texture project is nearly identical to the sample code in the Lights project, except that the Texture sample project does not create a material or a light. The Using Texture Maps tutorial focuses only on the code unique to textures and does not cover initializing Microsoft® Direct3D®, handling Microsoft Windows® messages, rendering, or shutting down. For information on these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information on selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial makes use of matrices to transform geometry. For more information on matrices and transformations, see Tutorial 3: Using Matrices.


Step 1: Defining a Custom Vector Format

Before using textures, a custom vertex format that includes texture coordinates must be used. Texture coordinates tell Microsoft® Direct3D® where to place a texture for each vector in a primitive. Texture coordinates range from 0.0 to 1.0, where (0.0, 0.0) represents the top-left side of the texture and (1.0, 1.0) represents the bottom-right side of the texture.

The following sample code shows how the Texture sample project sets up its custom vertex format to include texture coordinates.

struct CUSTOMVERTEX
{
    D3DXVECTOR3 position; // The position.
    D3DCOLOR    color;    // The color.
    FLOAT       tu, tv;   // The texture coordinates.
};

// The custom FVF, which describes the custom vertex structure.
#define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1)

For more information on texture coordinates, see Texture Coordinates.

Now that a custom vertex type has been defined, the next step is to load a texture and create a cylinder, as described in Step 2: Initializing Screen Geometry.


Step 2: Initializing Screen Geometry

Before rendering, the Texture sample project calls InitGeometry, an application-defined function that creates a texture and initializes the geometry for a cylinder.

Textures are created from file-based images. The following code fragment uses D3DXCreateTextureFromFile to create a texture from Banana.bmp that will be used to cover the surface of the cylinder.

if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice, "Banana.bmp",
                                       &g_pTexture ) ) )
    return E_FAIL;

The first parameter that D3DXCreateTextureFromFile accepts is a pointer to the Microsoft® Direct3D® device that will be used to render the texture. The second parameter is a pointer to an ANSI string that specifies the filename from which to create the texture. This sample specifies Banana.bmp to load the image from that file. The third parameter is the address of a pointer to a texture object.

When the banana texture is loaded and ready to use, the next step is to create the cylinder. The following code sample fills the vertex buffer with a cylinder. Note that each point has the texture coordinates (tu, tv).

for( DWORD i=0; i<50; i++ )
{
    FLOAT theta = (2*D3DX_PI*i)/(50-1);

    pVertices[2*i+0].position = D3DXVECTOR3( sinf(theta),-1.0, cosf(theta) );
    pVertices[2*i+0].color    = 0xffffffff;
    pVertices[2*i+0].tu       = ((FLOAT)i)/(50-1);
    pVertices[2*i+0].tv       = 1.0f;

    pVertices[2*i+1].position = D3DXVECTOR3( sinf(theta), 1.0, cosf(theta) );
    pVertices[2*i+1].color    = 0xff808080;
    pVertices[2*i+1].tu       = ((FLOAT)i)/(50-1);
    pVertices[2*i+1].tv       = 0.0f;
}

Each vertex includes position, color, and texture coordinates. The code sample above sets the texture coordinates for each point so that the texture will wrap smoothly around the cylinder.

Now that the texture is loaded and the vertex buffer is ready for rendering, it is time to render the display, as described in Step 3: Rendering the Scene.


Step 3: Rendering the Scene

After scene geometry has been initialized, it is time to render the scene. In order to render an object with texture, the texture must be set as one of the current textures. The next step is to set the texture stage states values. Texture stage states enable you to define the behavior of how a texture or textures are to be rendered. For example, you could blend multiple textures together.

The Texture sample project starts by setting the texture to use. The following code fragment sets the texture that the Microsoft® Direct3D® device will use to render with IDirect3DDevice8::SetTexture.

g_pd3dDevice->SetTexture( 0, g_pTexture );

The first parameter that SetTexture accepts is a stage identifier to set the texture to. A device can have up to eight set textures, so the maximum value here is 7. The Texture sample project has only one texture and places it at stage 0. The second parameter is a pointer to a texture object. The Texture sample project uses the texture object that it created in its InitGeometry application-defined function.

The following code sample sets the texture stage state values by calling the IDirect3DDevice8::SetTextureStageState method.

g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLOROP,   D3DTOP_MODULATE );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_ALPHAOP,   D3DTOP_DISABLE );

The first parameter that SetTextureState accepts is the stage index for the state variable to be set. This code sample is changing the values for the texture at stage 0, so it puts a 0 here. The next parameter is the texture state to set. For a list of all valid texture states and their meaning, see D3DTEXTURESTAGESTATETYPE. The next parameter is the value to set the texture state to. The value that you place here is based on the texture stage state value that you are modifying.

After setting up the desired values for each texture stage state, the cylinder can be rendered and texture will be added to the surface.

Another way to use texture coordinates is to have them automatically generated. This is done by using a texture coordinate index (TCI). The TCI uses a texture matrix to transform the (x,y,z) TCI coordinates into (tu, tv) texture coordinates. In the Texture sample project, the position of the vertex in camera space is used to generate texture coordinates.

The first step is to create the matrix that will be used for the transformation, as demonstrated in the following code fragment.

D3DXMATRIX mat;
mat._11 = 0.25f; mat._12 = 0.00f; mat._13 = 0.00f; mat._14 = 0.00f;
mat._21 = 0.00f; mat._22 =-0.25f; mat._23 = 0.00f; mat._24 = 0.00f;
mat._31 = 0.00f; mat._32 = 0.00f; mat._33 = 1.00f; mat._34 = 0.00f;
mat._41 = 0.50f; mat._42 = 0.50f; mat._43 = 0.00f; mat._44 = 1.00f;

After the matrix is created, it must be set by calling IDirect3DDevice8::SetTransform, as shown in the following code fragment.

g_pd3dDevice->SetTransform( D3DTS_TEXTURE0, &mat );

The D3DTS_TEXTURE0 flag tells Direct3D to apply the transformation to the texture located at texture stage 0. The next step that this sample takes is to set more texture stage state values to get the desired effect. That is done in the following code fragment.

g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXTURETRANSFORMFLAGS, D3DTTFF_COUNT2 );
g_pd3dDevice->SetTextureStageState( 0, D3DTSS_TEXCOORDINDEX, D3DTSS_TCI_CAMERASPACEPOSITION );

The texture coordinates are set up, and now the scene is ready to be rendered. Notice that the coordinates are automatically created for the cylinder. This particular setup gives the effect of the texture being laid over the rendering screen after the geometric shapes have been rendered.

For more information on textures, see Textures.

This tutorial has shown you how to use textures for surfaces. Tutorial 6: Using Meshes shows you how to use complex geometric shapes with meshes.


Tutorial 6: Using Meshes

Complicated geometry is usually modeled using 3-D modeling software and saved to a file. An example of this is the .x file format. Microsoft® Direct3D® uses meshes to load the objects from these files. Meshes are somewhat complicated, but D3DX contains functions that make using meshes easier. The Meshes sample project introduces the topic of meshes and shows how to load, render, and unload a mesh.

This tutorial shows how to load, render, and unload a mesh using the following steps.

  • Step 1: Loading a Mesh Object
  • Step 2: Rendering a Mesh Object
  • Step 3: Unloading a Mesh Object

Notes The path of the Meshes sample project is:

(SDK Root)\Samples\Multimedia\Direct3D\Tutorials\Tut06_Meshes.

The sample code in the Meshes project is nearly identical to the sample code in the Lights project, except that the code in the Meshes project does not create a material or a light. The Using Meshes tutorial focuses only on the code unique to meshes and does not cover setting up Direct3D, handling Microsoft Windows® messages, rendering, or shutting down. For information on these tasks, see Tutorial 1: Creating a Device.

This tutorial uses custom vertices and a vertex buffer to display geometry. For more information on selecting a custom vertex type and implementing a vertex buffer, see Tutorial 2: Rendering Vertices.

This tutorial makes use of matrices to transform geometry. For more information on matrices and transformations, see Tutorial 3: Using Matrices.

This tutorial uses textures to cover the surface of the mesh. For more information on loading and using textures, see Tutorial 5: Using Texture Maps.


Step 1: Loading a Mesh Object

A Microsoft® Direct3D® application must first load a mesh before using it. The Meshes sample project loads the tiger mesh by calling InitGeometry, an application-defined function, after loading the required Direct3D objects.

A mesh needs a material buffer that will store all the materials and textures that will be used. The function starts by declaring a material buffer as shown in the following code fragment.

LPD3DXBUFFER pD3DXMtrlBuffer;

The following code fragment uses the D3DXLoadMeshFromX method to load the mesh.

// Load the mesh from the specified file.
if( FAILED( D3DXLoadMeshFromX( "tiger.x", D3DXMESH_SYSTEMMEM,
                               g_pd3dDevice, NULL,
                               &pD3DXMtrlBuffer, &g_dwNumMaterials,
                               &g_pMesh ) ) )
    return E_FAIL;

The first parameter that D3DXLoadMeshFromX accepts is a pointer to a string that tells the name of the Microsoft DirectX® file to load. This sample loads the tiger mesh from Tiger.x.

The second parameter tells Direct3D how to create the mesh. The sample uses the D3DXMESH_SYSTEMMEM flag, which is equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM. Both of these flags tell Direct3D to put the index buffer and vertex buffer for the mesh in system memory.

The third parameter is a pointer to a Direct3D device that will be used to render the mesh.

The fourth parameter is a pointer to an ID3DXBuffer object. This object will be filled with information about neighbors for each face. This information is not required for this sample, so this parameter is set to NULL.

The fifth parameter also takes a pointer to a ID3DXBuffer object. After this method is finished, this object will be filled with D3DXMATERIAL structures for the mesh.

The sixth parameter is a pointer to the number of D3DXMATERIAL structures placed into the ppMaterials array after the method returns.

The seventh parameter is the address of a pointer to a mesh object, representing the loaded mesh.

After loading the mesh object and material information, you need to extract the material properties and texture names from the material buffer.

The Meshes sample project does this by first getting the pointer to the material buffer. The following code fragment uses the ID3DXBuffer::GetBufferPointer method to get this pointer.

D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer();

The following code fragment creates new mesh and texture objects based on the total number of materials for the mesh.

g_pMeshMaterials = new D3DMATERIAL8[g_dwNumMaterials];
g_pMeshTextures  = new LPDIRECT3DTEXTURE8[g_dwNumMaterials];

For each material in the mesh the following steps occur.

The first step is to copy the material, as shown in the following code fragment.

g_pMeshMaterials[i] = d3dxMaterials[i].MatD3D;

The second step is to set the ambient color for the material, as shown in the following code fragment.

g_pMeshMaterials[i].Ambient = g_pMeshMaterials[i].Diffuse;

The final step is to create the texture for the material, as shown in the following code fragment.

// Create the texture.
if( FAILED( D3DXCreateTextureFromFile( g_pd3dDevice,
                                       d3dxMaterials[i].pTextureFilename,
                                       &g_pMeshTextures[i] ) ) )
    g_pMeshTextures[i] = NULL;
}

After loading each material, you are finished with the material buffer and need to release it by calling IUnknown::Release.

pD3DXMtrlBuffer->Release();

The mesh, along with the corresponding materials and textures are loaded. The mesh is ready to be rendered to the display, as described in Step 2: Rendering a Mesh Object.


Step 2: Rendering a Mesh Object

In step 1 the mesh was loaded and is now ready to be rendered. It is divided into a subset for each material that was loaded for the mesh. To render each subset, the mesh is rendered in a loop. The first step in the loop is to set the material for the subset, as shown in the following code fragment.

g_pd3dDevice->SetMaterial( &g_pMeshMaterials[i] );

The second step in the loop is to set the texture for the subset, as shown in the following code fragment.

g_pd3dDevice->SetTexture( 0, g_pMeshTextures[i] );

After setting the material and texture, the subset is drawn with the ID3DXBaseMesh::DrawSubset method, as shown in the following code fragment.

g_pMesh->DrawSubset( i );

The DrawSubset method takes a DWORD that specifies which subset of the mesh to draw. This sample uses a value that is incremented each time the loop runs.

After using a mesh, it is important to properly remove the mesh from memory, as described in Step 3: Unloading a Mesh Object.


Step 3: Unloading a Mesh Object

After any Microsoft® DirectX® program finishes, it needs to deallocate any DirectX objects that it used and invalidate the pointers to them. The mesh objects used in this sample also need to be deallocated. When it receives a WM_DESTROY message, the Meshes sample project calls Cleanup, an application-defined function, to handle this.

The following code fragment deletes the material list.

if( g_pMeshMaterials )
    delete[] g_pMeshMaterials;

The following code fragment deallocates each individual texture that was loaded and then deletes the texture list.

if( g_pMeshTextures )
{
    for( DWORD i = 0; i < g_dwNumMaterials; i++ )
    {
        if( g_pMeshTextures[i] )
            g_pMeshTextures[i]->Release();
    }
delete[] g_pMeshTextures;

The following code fragment deallocates the mesh object.

Delete the mesh object
if( g_pMesh )
    g_pMesh->Release();

This tutorial has shown you how to load and render meshes. This is the last tutorial in this section. To see how a typical Direct3D application is written, see DirectX Graphics C/C++ Samples.


DirectX Graphics C/C++ Samples

The following sample applications demonstrate the use and capabilities of the Microsoft® Direct3D® and Direct3DX application programming interfaces.

  • Billboard Sample
  • BumpEarth Sample
  • BumpLens Sample
  • BumpUnderwater Sample
  • BumpWaves Sample
  • DotProduct3 Sample
  • Emboss Sample
  • ClipMirror Sample
  • DolphinVS Sample
  • DXTex Tool
  • EnhancedMesh Sample
  • CubeMap Sample
  • FishEye Sample
  • SphereMap Sample
  • MFCFog Sample
  • MFCPixelShader Sample
  • MFCTex Sample
  • OptimizedMesh Sample
  • Pick Sample
  • PointSprites Sample
  • ProgressiveMesh Sample
  • RTPatch Sample
  • SkinnedMesh Sample
  • ShadowVolume Sample
  • StencilDepth Sample
  • StencilMirror Sample
  • Text3D Sample
  • VertexBlend Sample
  • VertexShader Sample
  • VolumeTexture Sample
  • Water Sample

Although Microsoft DirectX® samples include Microsoft Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.

See Also

DirectX Graphics C/C++ Tutorials


Billboard Sample

Description

The Billboard sample illustrates the billboarding technique. Rather than rendering complex 3-D models, such as a high-polygon tree model, billboarding renders a 2-D image of the model and rotates it to always face the eyepoint. This technique is commonly used to render trees, clouds, smoke, explosions, and more. For more information, see Billboarding.

In this sample, a camera flies around a 3-D scene with a tree-covered hill. The trees look like 3-D objects, but they are actually 2-D billboarded images that are rotated towards the eyepoint. The hilly terrain and the skybox, a six-sided cube containing sky textures, are objects loaded from .x files. They are used for visual effect and are unrelated to the billboarding technique.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\Billboard

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The billboarding technique is the focus of this sample. The camera is moved in each frame, so the viewpoint changes accordingly. As the viewpoint changes, a rotation matrix is generated to rotate the billboards about the y-axis so that they face the new viewpoint. The computation of the billboard matrix occurs in the FrameMove function. The trees are also sorted in this function, as required for proper alpha blending, because billboards typically have some transparent pixels. The trees are rendered from a vertex buffer in the DrawTrees function.

The billboards in this sample are constrained to rotate about the y-axis only. Otherwise, the tree trunks would appear to not be fixed to the ground. For effects such as explosions in a 3-D flight simulator or space shooter, billboards are typically not constrained to one axis.

This sample uses common Microsoft® DirectX® code that consists of programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the source code in (SDK Root)\Samples\Multimedia\VBSamples.


BumpEarth Sample

Description

The BumpEarth sample demonstrates the bump mapping capabilities of Microsoft® Direct3D®. Bump mapping is a texture-blending technique that renders the appearance of rough, bumpy surfaces. This sample renders a rotating, bump-mapped planet Earth.

Not all cards support all features for bump mapping techniques. Some hardware has no, or limited, bump mapping support. For more information on bump mapping, see Bump Mapping.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\BumpMapping\BumpEarth

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

A bump map is a texture that stores the perturbation data. Bump mapping requires two textures. One is an environment map, which contains the lights that you see in the scene. The other is the actual bump mapping, which contain values—stored as du and dv—used to bump the environment map's texture coordinates. Some bump maps also contain luminance values to control the shininess of a particular texel.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


BumpLens Sample

Description

The BumpLens sample demonstrates a lens effect that can be achieved using bump mapping. Bump mapping is a multitexture-blending technique that renders the appearance of rough, bumpy surfaces, but can also be used for other effects, as shown here.

Not all cards support all features for bump mapping techniques. Some hardware has no, or limited, bump mapping support. For more information on bump mapping, see Bump Mapping.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\BumpMapping\BumpLens

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

A bump map is a texture that stores the perturbation data. Bump mapping requires two textures. One is an environment map, which contains the lights that you see in the scene. The other is the actual bump mapping, which contain values—stored as du and dv—used to bump the environment map's texture coordinates. Some bump maps also contain luminance values to control the shininess of a particular texel.

This sample uses bump mapping in a nontraditional fashion. Because bump mapping only perturbs an environment map, it can be used for other effects. In this case, it is used to perturb a background image, which can be rendered on the fly, to make a lens effect.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in the following directory: (SDK Root)\Samples\Multimedia\Common


BumpUnderwater Sample

Description

The BumpUnderwater sample demonstrates an underwater effect that can be achieved using bump mapping. Bump mapping is a multitexture-blending technique that renders the appearance of rough, bumpy surfaces, but can also be used for other effects as shown here.

Not all cards support all features for bump mapping techniques. Some hardware has no, or limited, bump mapping support. For more information on bump mapping, see Bump Mapping.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\BumpMapping\BumpUnderWater

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

A bump map is a texture that stores the perturbation data. Bump mapping requires two textures. One is an environment map, which contains the lights that you see in the scene. The other is the actual bump mapping, which contain values—stored as du and dv—used to bump the environment map's texture coordinates. Some bump maps also contain luminance values to control the shininess of a particular texel.

This sample uses bump mapping in a nontraditional fashion. Because bump mapping only perturbs an environment map, it can be used for other effects. In this case, it is used to perturb a background image, which can be rendered on the fly, to make an underwater effect.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


BumpWaves Sample

Description

The BumpWaves sample demonstrates the bump mapping capabilities of Microsoft® Direct3D®. Bump mapping is a multitexture-blending technique that renders the appearance of rough, bumpy surfaces. This sample renders a waterfront scene with only four triangles. The waves in the scene are completely fabricated with a bump map.

Not all cards support all features for bump mapping techniques. Some hardware has no, or limited, bump mapping support. For more information on bump mapping, refer to the Microsoft DirectX® SDK documentation.

This sample also uses a technique called projected textures, which is a texture-coordinate generation technique and is not the focal point of the sample. For more information on texture-coordinate generation, see Bump Mapping.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\BumpMapping\BumpWaves

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

A bump map is a texture that stores the perturbation data. Bump mapping requires two textures. One is an environment map, which contains the lights that you see in the scene. The other is the actual bump mapping, which contain values—stored as du and dv—used to bump the environment map's texture coordinates. Some bump maps also contain luminance values to control the shininess of a particular texel.

In this sample, bump mapping is used to generate waves in a scene. The backdrop is used as a projective texture for the environment map, so it reflects in the waves. The waves themselves appear to be generated with many polygons. However, it is one large quad.

This sample uses common Microsoft DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


DotProduct3 Sample

Description

The DotProduct3 sample demonstrates an alternative approach to Microsoft® Direct3D® bump mapping. This technique is named after the mathematical operation that combines a light vector with a surface normal. The normals for a surface are traditional (x,y,z) vectors stored in RGBA format in a texture map—called a normal map for this technique.

Not all cards support DotProduct3 blending texture stages, and not all cards support Direct3D bump mapping.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\BumpMapping\DotProduct3

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The lighting equation for simulating bump mapping involves using the dot product of the surface normal and the lighting vector. The lighting vector is passed into the texture factor, and the normals are encoded in a texture map. The blend stages look like this:

SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_DOTPRODUCT3 );
SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_TFACTOR );

The next step is to store the normals in the texture. To do this, the components of a vector (XYZW) are each turned from a 32-bit floating value into a signed 8-bit integer and packed into a texture color (RGBA). The code shows how to do this using a custom-generated normal map, as well as one built from a bump mapping texture image.

Not all cards support all features for bump mapping techniques. Some hardware has no, or limited, bump mapping support. For more information on bump mapping, refer to the Microsoft® DirectX® SDK documentation.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


Emboss Sample

Description

The Emboss sample demonstrates an alternative approach to Microsoft® Direct3D® bump mapping. Embossing is done by subtracting the height map from itself and having texture coordinates that are slightly changed.

Not all cards support Direct3D bump mapping. Refer to the Microsoft DirectX® SDK documentation for more information.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\Emboss

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.
CTRL-E | Turns emboss effect on/off.

Programming Notes

A bump map is a texture that stores the perturbation data. Bump mapping requires two textures. One is an environment map, which contains the lights that you see in the scene. The other is the actual bump mapping, which contain values—stored as du and dv—used to bump the environment map's texture coordinates. Some bump maps also contain luminance values to control the shininess of a particular texel.

In this sample, bump mapping is used to emboss the surface of the tiger.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


ClipMirror Sample

Description

The ClipMirror sample demonstrates the use of custom-defined clip planes. A 3-D scene is rendered normally, and then in a second pass as if reflected in a planar mirror. Clip planes are used to clip the reflected scene to the edges of the mirror.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\ClipMirror

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

The mouse is also used in this sample to control the viewing position.

Programming Notes

The main feature of this sample is the use of clip planes. The rectangular mirror has four edges, so four clip planes are used. Each plane is defined by the eyepoint and two vertices of one edge of the mirror. With the clip planes in place, the view matrix is reflected in the mirror's plane, and then the scene geometry (the teapot object) can be rendered as normal. Afterward, a semi-transparent rectangle is drawn to represent the mirror itself.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


DolphinVS Sample

Description

The DolphinVS sample shows an underwater scene of a dolphin swimming, with caustic effects on the dolphin and sea floor. The dolphin is animated using a technique called tweening. The underwater effect simply uses fog, and the water caustics use an animated set of textures. These effects are achieved using vertex shaders.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\DolphinVS

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Several things are happening in this sample.

  • Two vertex shaders are used: one for the dolphin and one for the sea floor. The vertex shaders are assembly instructions which are assembled from two files, DolphinTween.vsh and SeaFloor.vsh.
  • The dolphin is tweened—a form of morphing—by passing three versions of the dolphin down in multiple vertex streams. The vertex shader takes the weighted positions of each mesh and produces an output position. The vertex is then lit, texture coordinates are computed, and fog is added.
  • The sea floor is handled similarly, just with no need for tweening. The caustic effects are added in a separate alpha-blended pass, using an animated set of 32 textures. The texture coordinates for the caustics are generated in the vertex shaders, stored as TEXCOORDINDEX stage 1.

This sample uses common Microsoft® DirectX® code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


DXTex Tool

Description

The DXTex tool enables DirectX SDK users to create texture maps that use the new DXTn compression formats. Creating a DXTn-compressed texture is not difficult. However, Direct3D can do the conversion for you when using the IDirect3DTexture8 interface Advanced developers will probably want to write their own tools that meet their specific needs, but the DXTex tool provides useful basic functionality.

Functionality

  • Opens .bmp and DirectDrawSurface (DDS) files. For more information, see DDS File Format, below.
  • Opens .bmp files as alpha channel, either explicitly or implicitly, using a <filename>_a.bmp naming convention.
  • Saves textures in DDS format.
  • Supports conversion to all five DXTn compression formats.
  • Supports generation of mipmaps, using a box filter.
  • Supports visualization of alpha channel as a grayscale image or through a user-selectable background color.
  • Supports easy visual comparison of image quality between formats.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\DXTex

Executable: (SDK Root)\bin\dxutils

User Interface

DxTex uses a fairly traditional user interface (UI) in that each texture map is a document, and several documents can be open at a time. However, each document can hold the texture in either one or two formats at once while the document is open in DxTex. For example, you can import a .bmp file, which automatically creates a 32-bit ARGB texture. You can then choose to convert the texture to DXT1 format. The document now has the image open in both formats, and you can switch between the formats by clicking the window or. You can also switch by clicking Original View or New View on the View menu. This makes it easy for the you to observe any artifacts introduced by image compression, and to try different compression formats without progressive degradation of the image. For example, if this technique is not used and you convert an image from ARGB to DXT1, all but one bit of alpha is lost.

If the you then decide to convert to DXT2, there is still only two alpha levels. Using the DxTex system, the second conversion is done from the original ARGB format, and the DXT2 image will contain all 16 levels of alpha supported by DXT2. When the image is saved, the original format is discarded, and only the new format is stored.

Keep in mind the following when using the DxTex interface.

  • If no format conversion has been requested since the document was opened, the one format is the original format—that is, the format in which the image will be written when the document is saved.
  • If format conversion has been requested since the document was opened, the converted format is the new format—that is, the format in which the image will be written when the document is saved.
  • If a second format conversion is requested, the new format from the first conversion is replaced with the second format. The original format will be unchanged.
  • Generating mipmaps applies to both formats simultaneously.
  • If the original format has multiple mipmaps, and conversion to a new format is requested, the new format will automatically have multiple mipmaps as well.

Performance

DxTex uses the Microsoft Direct3D® Reference Rasterizer to draw the textures, regardless of what 3-D hardware is available. So with larger textures (greater than 256x256 pixels), the application may be somewhat slow, depending on your CPU speed.

DSS File Format

The DxTex native file format is called the DDS file format because it encapsulates the information in a DirectDrawSurface. It has the following format:

DWORD dwMagic (0x20534444, or "DDS")
DDSURFACEDESC2 ddsd (provides information about the surface format)
BYTE bData1[] (surface data for the main surface)
[BYTE bData2[]...] (surface data for attached surfaces follows)

This format is easy to read and write to, and it supports features such as alpha and multiple mip levels, as well as DXTn compression. The Compress sample application in the DirectX SDK demonstrates how to properly import a DDS file.

It is not necessary to use the DDS format in order to use DXTn-compressed textures, or vice-versa, but the two work well together.

Mipmaps

Mipmapping is a technique that improves image quality and reduces texture memory bandwidth by providing prefiltered versions of the texture image at multiple resolutions.

To generate mipmaps in DxTex, the width and height of the source image must both be powers of 2. To do this, go to the Format menu, click Generate Mip Maps. Filtering is done through a simple box filter. That is, the four nearest pixels are averaged to produce each destination pixel.

Alpha

Many texture formats include an alpha channel, which provides opacity information at each pixel. DxTex fully supports alpha in textures. When you import a .bmp file, if there is a file of the same size with a name that ends in _a—for example, Sample.bmp and Sample_a.bmp—the second file is loaded as an alpha channel. The blue channel of the second .bmp is stored in the alpha channel. Once a document is open, you can explicitly load a .bmp file as the alpha channel by clicking Open As Alpha Channel on the File menu.

To view the alpha channel directly without the RGB channels, on the View menu, click Alpha Channel Only. The alpha channel appears as a grayscale image. If no alpha channel has been loaded, every pixel has a full alpha channel and the image appears solid white when viewing "Alpha Channel Only". To turn off alpha channel viewing, click the Alpha Channel Only command a second time.

In the usual view, the effect of the alpha channel is visible because the window has a solid background color that shows through the texture where the alpha channel is less than 100 percent. You can change this background color by clicking Change Background Color on the View menu. This choice does not affect the texture itself or the data that is written when the file is saved.

The DXT2 and DXT4 formats use premultiplied alpha. This means that the red, green, and blue values stored in the surface are already multiplied by the corresponding alpha value. Direct3D cannot copy from a surface that contains premultiplied alpha to one that contains non-premultiplied alpha, so some DxTex operations (Open as Alpha Channel, conversion to DXT3, and conversion to DXT5) are not possible on DXT2 and DXT4 formats. Supporting textures using these formats is difficult on Direct3D devices that do not support DXTn textures. This is because Direct3D cannot copy them to a traditional ARGB surface either, unless that ARGB surface uses premultiplied alpha as well, which is rare. For this reason, you might find it easier to use DXT3 rather than DXT2, and DXT5 rather than DXT4 when possible.

Command Line Options

You can use command-line options to pass input files, an output file name, and processing options to DxTex. If an output file name is specified, the application exits automatically after writing the output file, and no user interface is presented.

dxtex [infilename] [-a alphaname] [-m] [DXT1|DXT2|DXT3|DXT4|DXT5] [outfilename]

infilename:               Name of the file to load.  This can be a
                          .bmp or DDS file.

-a alphaname:             The next parameter is the name of a .bmp
                          file to load as the alpha channel. If no
                          alpha filename is specified, DxTex still
                          looks for a file named Infilename_a.bmp. If
                          it exists, use that file as the alpha
                          channel.

-m:                       Mipmaps are generated.

DXT1|DXT2|DXT3|DXT4|DXT5: Compression format. If no format is
                          specified, the image will be in ARGB-8888.

outfilename:              Name of the destination file.  If this
                          option is not specified, the user interface
                          shows the current file and all requested
                          operations.  If an outfilename is specified,
                          the application exits after saving the
                          processed file without presenting a user
                          interface.


EnhancedMesh Sample

Description

The EnhancedMesh sample shows how to use D3DX to load and enhance a mesh. The mesh is enhanced by increasing the vertex count.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\EnhancedMesh

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

This sample uses common Microsoft® DirectX® code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


CubeMap Sample

Description

The CubeMap sample demonstrates an environment mapping technique called cube mapping. Environment mapping is a technique in which the environment surrounding a 3-D object, such as the lights, is put into a texture map, so that the object can have complex lighting effects without expensive lighting calculations.

Not all cards support all features for environment mapping techniques, such as cube mapping and projected textures. For more information on environment mapping, cube mapping, and projected textures, refer to the Microsoft® DirectX® SDK documentation.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\EnvMapping\CubeMap

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Cube mapping is a technique that employs a six-sided texture. To visualize the effects of this technique, imagine a wall-papered room in which the wallpaper has been shrink-wrapped around an object. Cube mapping is superior to sphere-mapping because the latter is inherently view-dependent; sphere maps are constructed for one particular viewpoint in mind. Cube maps also have no geometry distortions, so they can be generated on the fly using IDirect3DDevice8::SetRenderTarget for all six cube map faces.

Cube mapping works with Microsoft Direct3D® texture coordinate generation. By setting D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR, Direct3D generates cube map texture coordinates from the reflection vector for a vertex, thereby making this technique easy for environment mapping effects where the environment is reflected in the object.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


FishEye Sample

Description

The FishEye sample shows a fish-eye lens effect that can be achieved using cube maps.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\EnvMapping\FishEye

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The FishEye sample scene is rendered into the surfaces of a cube map, rather than the back buffer. Then the cube map is used as an environment map to reflect the scene in some distorted geometry—in this case, some geometry approximating a fish eye lens. See the CubeMap sample for more information about cube mapping.

This sample uses common Microsoft DirectX® code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


SphereMap Sample

Description

The SphereMap sample demonstrates an environment mapping technique called sphere mapping. Environment mapping is a technique in which the environment surrounding a 3-D object, such as the lights, are put into a texture map, so that the object can have complex lighting effects without expensive lighting calculations.

Not all cards support all features for environment mapping techniques, such as cube mapping and projected textures. For more information on environment mapping, cube mapping, and projected textures, refer to the Microsoft® DirectX® SDK documentation.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\EnvMapping\SphereMap

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Sphere-mapping uses a precomputed (at model time) texture map that contains the entire environment as reflected by a chrome sphere. The idea is to consider each vertex, compute its normal, find where the normal matches on the chrome sphere, and then assign that texture coordinate to the vertex.

Although the math is not complicated, this involves computations for each vertex for every frame. Direct3D has a texture-coordinate generation feature that you can use to do this. The relevant render state operation is D3DTSS_TCI_CAMERASPACENORMAL, which takes the normal of the vertex in camera space and puts it through a texture transform to generate texture coordinates. Then you set up the texture matrix to do the rest. In this simple case, the matrix only has to scale and translate the texture coordinates to get from camera space (-1, +1) to texture space (0,1).

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


MFCFog Sample

Description

The MFCFog sample illustrates how to use Microsoft® Direct3D® with Microsoft Foundation Classes (MFC), using a CFormView. Various controls are used to control fog parameters for the 3-D scene.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\MFCFog

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

All user interaction for this sample is implemented through the visible MFC controls—sliders, radio buttons, and so on. You are encouraged to play with the controls and observe the various effects they have on the rendered 3-D scene.

Programming Notes

All the MFC code is contained with the CFormView class's derived member functions. You can find the MFC code and D3D initialization code in the D3dapp.cpp source file. This file can be ported to work with another application by stripping out the fog-related code.

The Direct3D fog code is contained in Fog.cpp. It includes functions to initialize, animate, render, and clean up the scene.

This sample uses common Microsoft DirectX® code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


MFCPixelShader Sample

Description

The MFCFog sample illustrates how to use Microsoft® Direct3D® with Microsoft Foundation Classes (MFC), using a CFormView. Various controls are used to the control the pixel shader used for the 3-D scene.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\MFCPixelShader

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

All user interaction for this sample is implemented through the visible MFC controls—sliders, radio buttons, and so on. You are encouraged to play with controls and observe the various effects they have on the rendered 3-D scene.

Programming Notes

All the MFC code is contained with the CFormView class's derived member functions. You can find the MFC code and D3D initialization code in the D3dapp.cpp source file. This file can be ported to work with another application by stripping out the fog-related code.

The Direct3D fog code is contained in Fog.cpp. It includes functions to initialize, animate, render, and clean up the scene.

This sample uses common Microsoft DirectX® code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


MFCTex Sample

Description

The MFCTex sample illustrates how to use Microsoft® Direct3D® with Microsoft Foundation Classes (MFC), using a CFormView. Various controls are used to the control the texture appearance.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\MFCTex

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

All user interaction for this sample is implemented through the visible MFC controls—sliders, radio buttons, and so on. You are encouraged to play with controls and observe the various effects they have on the rendered 3-D scene.

Programming Notes

All the MFC code is contained with the CFormView class's derived member functions. You can find the MFC code and D3D initialization code in the D3dapp.cpp source file. This file can be ported to work with another application by stripping out the fog-related code.

The Direct3D fog code is contained in Fog.cpp. It includes functions to initialize, animate, render, and clean up the scene.

This sample uses common Microsoft DirectX® code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


OptimizedMesh Sample

Description

The OptimizedMesh sample illustrates how to load and optimize a file-based mesh using the D3DX mesh utility functions.

For more information on D3DX, refer to the Microsoft® DirectX® SDK documentation.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\OptimizedMesh

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.
CTRL-O | Opens mesh file.
CTRL-M | Toggles optimized mesh.

Programming Notes

Many Microsoft Direct3D® samples in the DirectX SDK use file-based meshes. However, the OptimizedMesh sample is a good example of the basic code necessary for loading a mesh. The D3DX mesh loading functionality collapses the frame hierarchy of an .x file into one mesh.

For other samples, the bare bones D3DX mesh functionality is wrapped in a common class CD3DMesh. If you want to keep the frame hierarchy, you can use the common class CD3DFile.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


Pick Sample

Description

The Pick sample shows how to implement picking; that is, finding which triangle in a mesh is intersected by a ray. In this case, the ray comes from mouse coordinates.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\Pick

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Use the mouse to pick any spot in the mesh to see that triangle.

Programming Notes

When you click the mouse, the code reads the screen coordinates of the cursor. These coordinates are converted, through the projection and view matrices, into a ray that goes from the eyepoint through the point clicked on the screen and into the scene. This ray is passed to IntersectTriangle along with each triangle of the loaded model to determine which triangles, if any, are intersected by the ray. The texture coordinates of the intersected triangle is also determined.

This sample uses common Microsoft® DirectX® code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


PointSprites Sample

Description

The PointSprites sample shows how to use the new Microsoft® Direct3D® point sprites feature. A point sprite is simply a forward-facing, textured quad that is referenced only by (x,y,z) position coordinates. Point sprites are most often used for particle systems and related effects.

Not all cards support all features for point sprites. For more information on point sprites, refer to the Microsoft DirectX® SDK documentation.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\PointSprites

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
W, S | Moves forward and back.
E, Q | Turns left and right.
A, Z | Rotates up and down.
ARROW KEYS | Slides left, right, up, and down.
F1 | Shows Help or available commands.
F2 | Prompts the user to select a new rendering device or display mode.
F3 | Animates the emitter.
F4 | Changes color.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Without Direct3D support, point sprites can be implemented with four vertices that are oriented each frame towards the eyepoint, much like a billboard. With Direct3D, though, you can refer to each point sprite just by its center position and a radius. This saves processor computation time and bandwidth when uploading vertex information to the graphics card.

In this sample, each particle is implemented using multiple alpha-blended point sprites, giving the particle a motion-blur effect.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


ProgressiveMesh Sample

Description

The ProgressiveMesh sample illustrates how to load and optimize a file-based mesh using the D3DX mesh utility functions. A progressive mesh is one in which the vertex information is stored internally in a special tree that can be accessed to render the mesh with any number of vertices. This procedure is fast, so progressive meshes are ideal for level-of-detail scenarios, where objects in the distance are rendered with fewer polygons.

For more information on D3DX, refer to the Microsoft® DirectX® SDK documentation.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\ProgressiveMesh

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F1 | Shows Help or available commands.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.
UP ARROW | Adds one vertex to the progressive mesh.
DOWN ARROW | Subtracts one vertex from the progressive mesh.
PAGE UP | Adds 100 vertices to the progressive mesh.
PAGE DOWN | Subtracts 100 vertices from the progressive mesh.
HOME | Displays all available vertices for the progressive mesh.
END | Displays the minimum vertices for the progressive mesh.

Programming Notes

Many Microsoft Direct3D® samples in the DirectX SDK use file-based meshes. However, the ProgressiveMesh sample is a good example of the basic code necessary for loading a mesh. The D3DX mesh loading functionality collapses the frame hierarchy of an .x file into one mesh.

The primary reason to use progressive meshes is the call to ID3DXPMesh::SetNumVertices for the mesh.

For other samples, the basic D3DX mesh functionality is wrapped in a common class CD3DMesh. To keep the frame hierarchy, you can use the common class CD3DFile.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


RTPatch Sample

Description

The RTPatch sample shows how uses patches in Direct3D.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\RTPatch

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F1 | Shows Help or available commands.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.
UP ARROW | Increase number of patches per segment.
DOWN ARROW | Decrease number of patches per segment.
W | Toggles the wireframe.

Programming Notes

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


SkinnedMesh Sample

Description

The SkinnedMesh sample shows how to load and render a skinned mesh.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\SkinnedMesh

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


ShadowVolume Sample

Description

The ShadowVolume sample uses stencil buffers to implement real-time shadows. In the sample, a complex object is rendered and used as a shadow caster to cast real-time shadows on itself and on the terrain below.

Stencil buffers are a depth-buffer technique that can be updated as geometry is rendered, and used again as a mask for drawing more geometry. Common effects include mirrors, shadows (an advanced technique), dissolves, and so on.

Not all cards support all features for stencil-buffer techniques. Some hardware has no, or limited, stencil-buffer support. For more information on stencil buffers, refer to the Microsoft® DirectX® SDK documentation.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\StencilBuffer\ShadowVolume

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Creating real-time shadows is a fairly advanced technique. In each frame, or as the geometry or lights in the scene are moved, an object called a shadow volume is computed. A shadow volume is a 3-D object that is the silhouette of the shadowcasting object, as protruded away from the light source.

In this sample, the 3-D object that casts shadows is a bi-plane. The silhouette of the plane is computed in each frame. This technique uses an edge-detection algorithm in which silhouette edges are found. This can be done because the normals of adjacent polygons will have opposing normals with respect to the light vector. The resulting edge list (the silhouette) is protruded into a 3-D object away from the light source. This 3-D object is known as the shadow volume, as every point inside the volume is inside a shadow.

Next, the shadow volume is rendered into the stencil buffer twice. First, only forward-facing polygons are rendered, and the stencil-buffer values are incremented each time. Then the back-facing polygons of the shadow volume are drawn, decrementing values in the stencil buffer. Normally, all incremented and decremented values cancel each other out. However, because the scene was already rendered with normal geometry, in this case the plane and the terrain, some pixels fail the zbuffer test as the shadow volume is rendered. Any values left in the stencil buffer correspond to pixels that are in the shadow.

Finally, these remaining stencil-buffer contents are used as a mask, as a large all-encompassing black quad is alpha-blended into the scene. With the stencil buffer as a mask, only pixels in shadow are darkened

This sample uses common Microsoft DirectX® code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


StencilDepth Sample

Description

The StencilDepth sample uses stencil buffers to display the depth complexity of a scene. The depth complexity of a scene is defined as the average number of times each pixel is rendered.

Stencil buffers are a depth-buffer technique that can be updated as geometry is rendered, and used again as a mask for drawing more geometry. Common effects include mirrors, shadows (an advanced technique), dissolves, and so on.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\StencilBuffer\StencilDepth

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Displaying depth complexity is a valuable tool to analyze the performance of a scene. Scenes with high amounts of overdraw can benefit from some scene optimization such as sorting the geometry in a front-to-back order.

Not all cards support all features for stencil-buffer techniques. Some hardware has no, or limited, stencil buffer-support. For more information on stencil buffers, refer to the Microsoft® DirectX® SDK documentation.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


StencilMirror Sample

Description

The StencilMirror sample uses stencil buffers to implement a mirror effect. In the sample, a watery terrain scene is rendered with the water reflecting a helicopter that flies above.

Stencil buffers are a depth-buffer technique that can be updated as geometry is rendered, and used again as a mask for drawing more geometry. Common effects include mirrors, shadows (an advanced technique), dissolves, and so on.

Not all cards support all features for stencil buffer-techniques. Some hardware has no, or limited, stencil buffer-support. For more information on stencil buffers, refer to the Microsoft® DirectX® SDK documentation.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\StencilBuffer\StencilMirror

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

In this sample, a stencil buffer is used to create the effect of a reflection coming off the water. The geometry of the water is rendered into the stencil buffer. Then the stencil buffer is used as a mask to render the scene again, this time with the geometry translated and rendered upside down, to appear as if it were reflected in the mirror.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


Text3D Sample

Description

The Text3D sample shows how to draw 2-D text in a 3-D scene. This is useful for displaying statistics or game menus, and so on.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\Text3D

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

This sample uses the common class, CD3DFont, to display 2-D text in a 3-D scene. The source code for the class is of most interest to this sample. The class uses GDI to load a font and output each letter to a bitmap. That bitmap, in turn, is used to create a texture.

When the CD3DFont class's DrawText function is called, a vertex buffer is filled with polygons that are textured using the font texture created as mentioned above. The polygons may be drawn as a 2-D overlay—useful, for example, for printing statistics—or truly integrated in the 3-D scene.

This sample uses common Microsoft® DirectX® code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


VertexBlend Sample

Description

The VertexBlend sample demonstrates a technique called vertex blending, also known as surface skinning. It displays a file-based object that is made to bend in various spots.

Vertex blending is used for creating effects such as smooth joints and bulging muscles in character animations.

Not all cards support all features for vertex blending. For more information on vertex blending, refer to the Microsoft® DirectX® SDK documentation.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\VertexBlend

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.
CTRL-V | Switches between a custom vertex shader and Direct3D vertex blending.

Programming Notes

Vertex blending requires each vertex to have an associated blend weight. Multiple world transforms are set up using SetTransformState and the blend weights determine how much contribution each world matrix has when positioning each vertex.

In this sample, a mesh is loaded using the common helper code. Note how a custom vertex and a custom FVF is declared and used to build the mesh; see the SetFVF call for the mesh object. Without using the mesh helper code, the technique is the same. Create a vertex buffer full of vertices that have a blend weight, and use the appropriate FVF.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


VertexShader Sample

Description

The VertexShader sample shows some effects that can be achieved using vertex shaders. Vertex shaders use a set of instructions, executed by the 3-D device on a per-vertex basis, that can affect the properties of the vertex—positions, normal, color, texture coordinates, and so on—in interesting ways.

Not all cards support all features for vertex shaders. For more information on vertex shaders, refer to the Microsoft® DirectX® SDK documentation.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\VertexShader

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
W, S | Moves forward and back.
E, Q | Turns left and right.
A, Z | Rotates up and down.
ARROW KEYS | Slides left, right, up, and down.
F1 | Shows Help or available commands.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Programming vertex shaders is not a trivial task. Refer to the Microsoft DirectX® SDK documentation for more information.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


VolumeTexture Sample

Description

The VolumeTexture sample illustrates how to use the new volume textures in Microsoft® Direct3D®. Normally, a texture is thought of as a 2-D image, which has a width and a height and whose texels are addressed with two coordinate, tu and tv. Volume textures are the 3-D counterparts, with a width, height, and depth, are addressed with three coordinates, tu, tv, and tw.

You can use volume textures for interesting effects such as patchy fog, explosions, and so on.

Not all cards support all features for volume textures. For more information on volume textures, refer to the Microsoft DirectX® SDK documentation.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\VolumeTexture

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

Volume textures are no more difficult to use than 3-D textures. In this sample source code, note the vertex declaration, which has a third texture coordinate; texture creation, which also takes a depth dimension; and texture locking, again with the third dimension. The 3-D rasterizer interpolates texel values much as for 2-D textures.

This sample uses common DirectX code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


Water Sample

Description

The Water sample illustrates using D3DX techniques stored in shader files.

The sample shows a square pond inside a building, with rippling water effects including water caustics.

Path

Source: (SDK Root)\Samples\Multimedia\Direct3D\Water

Executable: (SDK Root)\Samples\Multimedia\Direct3D\Bin

User's Guide

The following table lists the keys that are implemented. You can use menu commands for the same controls.

Key | Action
ENTER | Starts and stops the scene.
SPACEBAR | Advances the scene by a small increment.
W, S | Moves forward and back.
E, Q | Turns left and right.
A, Z | Rotates up and down.
ARROW KEYS | Slides left, right, up, and down.
D | Starts a water drop.
PAGE DOWN | Displays next technique.
PAGE UP | Displays previous technique.
SHIFT+PAGE DOWN | Displays next technique with no validation.
SHIFT+PAGE UP | Displays previous technique with no validation.
F1 | Shows Help or available commands.
F2 | Prompts the user to select a new rendering device or display mode.
ALT+ENTER | Toggles between full-screen and windowed modes.
ESC | Exits the application.

Programming Notes

The D3DX shaders technique is the focus of this sample.

This sample uses common Microsoft® DirectX® code that consists programming elements such as helper functions. This code is shared with other samples in the DirectX SDK. You can find the common headers and source code in (SDK Root)\Samples\Multimedia\Common.


Direct3D C/C++ Reference

This section contains reference information for the API elements provided by Microsoft® Direct3D®. Reference material is divided into the following categories.

  • Interfaces
  • Functions
  • Macros
  • Vertex Shader Declarator Macros
  • Structures
  • Enumerated Types
  • Other Types
  • Texture Argument Flags
  • Flexible Vertex Format Flags
  • Four-Character Codes (FOURCC)
  • Return Values


Interfaces

This section contains reference information for the COM interfaces provided by Microsoft® Direct3D®. The following interfaces are used with Direct3D.

  • IDirect3D8
  • IDirect3DBaseTexture8
  • IDirect3DCubeTexture8
  • IDirect3DDevice8
  • IDirect3DIndexBuffer8
  • IDirect3DResource8
  • IDirect3DSurface8
  • IDirect3DSwapChain8
  • IDirect3DTexture8
  • IDirect3DVertexBuffer8
  • IDirect3DVolume8
  • IDirect3DVolumeTexture8


IDirect3D8

Applications use the methods of the IDirect3D8 interface to create Microsoft® Direct3D® objects and set up the environment. This interface includes methods for enumerating and retrieving capabilities of the device.

The IDirect3D8 interface is obtained by calling the Direct3DCreate8 function.

The methods of the IDirect3D8 interface can be organized into the following groups.

Creation | CreateDevice
Enumeration | EnumAdapterModes
Information | GetAdapterCount
 | GetAdapterDisplayMode
 | GetAdapterIdentifier
 | GetAdapterModeCount
 | GetAdapterMonitor
 | GetDeviceCaps
Registration | RegisterSoftwareDevice
Verification | CheckDepthStencilMatch
 | CheckDeviceFormat
 | CheckDeviceMultiSampleType
 | CheckDeviceType

The IDirect3D8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3D8 and PDIRECT3D8 types are defined as pointers to the IDirect3D8 interface.

typedef struct IDirect3D8 *LPDIRECT3D8, *PDIRECT3D8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

Direct3DCreate8


IDirect3D8::CheckDepthStencilMatch

Determines whether or not a depth-stencil format is compatible with a render target format in a particular display mode.

HRESULT CheckDepthStencilMatch(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  D3DFORMAT AdapterFormat,
  D3DFORMAT RenderTargetFormat,
  D3DFORMAT DepthStencilFormat
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
AdapterFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the display mode into which the adapter will be placed.
RenderTargetFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the render target surface to be tested.
DepthStencilFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the depth-stencil surface to be tested.

Return Values

If the depth-stencil format is compatible with the render target format in the display mode, this method returns D3D_OK.

D3DERR_INVALIDCALL can be returned if one or more of the parameters is invalid. If a depth-stencil format is not compatible with the render target in the display mode, then this method returns D3DERR_NOTAVAILABLE.

Remarks

This method is provided to enable applications to work with hardware requiring that certain depth formats can only work with certain render target formats.

The following code fragment shows how you could use CheckDeviceFormat to validate a depth stencil format.

BOOL IsDepthFormatOk( D3DFORMAT DepthFormat, D3DFORMAT AdapterFormat,
                      D3DFORMAT BackBufferFormat ) {
    // Verify that the depth format exists.
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          D3DUSAGE_DEPTHSTENCIL,
                                          D3DRTYPE_SURFACE,
                                          DepthFormat);

    if( FAILED( hr ) ) return FALSE;

    // Verify that the depth format is compatible.
    hr = pD3D->CheckDepthStencilMatch( D3DADAPTER_DEFAULT,
                                       D3DDEVTYPE_HAL,
                                       AdapterFormat,
                                       BackBufferFormat,
                                       DepthFormat);
    return SUCCEEDED( hr );
}

The preceding call will return FALSE if DepthFormat cannot be used in conjunction with AdapterFormat and BackBufferFormat.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3D8::CheckDeviceFormat

Determines whether a surface format is available as a specified resource type and can be used as a texture, depth-stencil buffer, or render target, or any combination of the three, on a device representing this adapter.

HRESULT CheckDeviceFormat(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  D3DFORMAT AdapterFormat,
  DWORD Usage,
  D3DRESOURCETYPE RType,
  D3DFORMAT CheckFormat
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
AdapterFormat
[in] Member of the D3DFORMAT enumerated type, identifying the format of the display mode into which the adapter will be placed.
Usage
[in] Requested usage for a surface of the CheckFormat. One or more of the following flags can be specified.
D3DUSAGE_DEPTHSTENCIL
Set to indicate that the surface can be used as a depth-stencil surface.
D3DUSAGE_RENDERTARGET
Set to indicate that the surface can be used as a render target. In cases where the RType parameter value unambiguously implies a specific usage, the application can leave the Usage parameter as 0.
RType
[in] A member of the D3DRESOURCETYPE enumerated type, specifying the resource type requested for use with the queried format.
CheckFormat
[in] Member of the D3DFORMAT enumerated type. Indicates the format of the surfaces which may be used, as defined by Usage.

Return Values

If the format is compatible with the specified device for the requested usage, this method returns D3D_OK.

D3DERR_INVALIDCALL is returned if Adapter equals or exceeds the number of display adapters in the system, or if DeviceType is unsupported. This method returns D3DERR_NOTAVAILABLE if the format is not acceptable to the device for this usage.

Remarks

A typical use of CheckDeviceFormat is to verify the existence of a particular depth-stencil surface format. See Selecting a Device for more detail on the enumeration process. The following code fragment shows how you could use CheckDeviceFormat to verify the existence of a depth-stencil format.

BOOL IsDepthFormatExisting( D3DFORMAT DepthFormat, D3DFORMAT AdapterFormat ) {
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          D3DUSAGE_DEPTHSTENCIL,
                                          D3DRTYPE_SURFACE,
                                          DepthFormat);

    return SUCCEEDED( hr );
}

The preceding call will return FALSE if DepthFormat does not exist on the system.

Another typical use of CheckDeviceFormat would be to verify if textures existing in particular surface formats can be rendered, given the current display mode. The following code fragment shows how you could use CheckDeviceFormat to verify that texture formats are compatible with specific back buffer formats.

BOOL IsTextureFormatOk( D3DFORMAT TextureFormat, D3DFORMAT AdapterFormat ) {
    HRESULT hr = pD3D->CheckDeviceFormat( D3DADAPTER_DEFAULT,
                                          D3DDEVTYPE_HAL,
                                          AdapterFormat,
                                          0,
                                          D3DRTYPE_TEXTURE,
                                          TextureFormat);

    return SUCCEEDED( hr );
}

The preceding call will return FALSE if TextureFormat cannot be used to render textures while the adapter surface format is AdapterFormat.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3D8::CheckDeviceMultiSampleType

Determines if a multisampling technique is available on this device.

HRESULT CheckDeviceMultiSampleType(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  D3DFORMAT SurfaceFormat,
  BOOL Windowed,
  D3DMULTISAMPLE_TYPE MultiSampleType
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns FALSE when this value equals or exceeds the number of display adapters in the system. See Remarks.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type, identifying the device type.
SurfaceFormat
[in] Member of the D3DFORMAT enumerated type that specifies the set of multisampling types requested for the surface. See Remarks.
Windowed
[in] Boolean value. Specify TRUE to inquire about windowed multisampling, and specify FALSE to inquire about full-screen multisampling.
MultiSampleType
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, identifying the multisampling technique to test.

Return Values

If the device can perform the specified multisampling method, this method returns D3D_OK.

D3DERR_INVALIDCALL is returned if the Adapter or MultiSampleType parameters are invalid. This method returns D3DERR_NOTAVAILABLE if the queried multisampling technique is not supported by this device. D3DERR_INVALIDDEVICE is returned if DeviceType does not apply to this adapter.

Remarks

This method is intended for use with both render-target and depth-stencil surfaces because you must create both surfaces multisampled if you want to use them together.

The following code fragment shows how you could use CheckDeviceMultiSampleType to test for devices that support a specific multisampling method.

if( SUCCEEDED(pDevice->CheckDeviceMultiSampleType( pCaps->AdapterOrdinal,
                                pCaps->DeviceType, pMode->Format,
                                FALSE, D3DMULTISAMPLE_3_SAMPLES ) ) )
    return S_OK;

The preceding code will return S_OK if the device supports the full-screen D3DMULTISAMPLE_3_SAMPLES multisampling method with the surface format.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3D8::CheckDeviceType

Verifies whether or not a certain device type can be used on this adapter and expect hardware acceleration using the given formats.

HRESULT CheckDeviceType(
  UINT Adapter,
  D3DDEVTYPE CheckType,
  D3DFORMAT DisplayFormat,
  D3DFORMAT BackBufferFormat,
  BOOL Windowed
);

Parameters

Adapter
[in] Ordinal number denoting the display adapter to enumerate. D3DADAPTER_DEFAULT is always the primary display adapter. This method returns D3DERR_INVALIDCALL when this value equals or exceeds the number of display adapters in the system.
CheckType
[in] Member of the D3DDEVTYPE enumerated type, indicating the device type to check.
DisplayFormat
[in] Member of the D3DFORMAT enumerated type, indicating the format of the adapter display mode for which the device type is to be checked. For example, some devices will operate only in 16-bits-per-pixel modes.
BackBufferFormat
[in] Member of the D3DFORMAT enumerated type, indicating the format of the back buffer to be tested
Windowed
[in] Value indicating whether the device type will be used in full-screen or windowed mode. If set to TRUE, the query is performed for windowed applications; otherwise, this value should be set FALSE.

Return Values

If the device can be used on this adapter, D3D_OK is returned.

D3DERR_INVALIDCALL is returned if Adapter equals or exceeds the number of display adapters in the system. This method returns D3DERR_INVALIDDEVICE if CheckType specified a device that does not exist. D3DERR_NOTAVAILABLE is returned if either surface format is not supported, or if hardware acceleration is not available for the specified formats.

Remarks

The most important device type that may not be present is D3DDEVTYPE_HAL. D3DDEVTYPE_HAL requires hardware acceleration. Applications should use CheckDeviceType to determine if the needed hardware and drivers are present on the system. The other device that may not be present is D3DDEVTYPE_SW. This device type represents a pluggable software device that was registered using IDirect3D8::RegisterSoftwareDevice.

Applications should not specify a DisplayFormat that contains an alpha channel. This will result in a failed call. Note that an alpha channel may be present in the back buffer, but the two display formats must be identical in all other respects. For example, if DisplayFormat is D3DFMT_X1R5G5B5, valid values for BackBufferFormat include D3DFMT_X1R5G5B5 and D3DFMT_A1R5G5B5, but exclude D3DFMT_R5G6B5.

The following code fragment shows how you could use CheckDeviceType to test whether or not a certain device type can be used on this adapter.

if(SUCCEEDED(pD3Device->CheckDeviceType(D3DADAPTER_DEFAULT,
                                        D3DDEVTYPE_HAL,
                                        DisplayFormat,
                                        BackBufferFormat,
                                        bIsWindowed)))
     return S_OK;

// There is no HAL on this adapter using this render target format.
// Try again, using another format.

The preceding code will return S_OK if the device can be used on the default adapter, with the specified surface format.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3D8::CreateDevice

Creates a device to represent the display adapter.

HRESULT CreateDevice(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  HWND  hFocusWindow,
  DWORD BehaviorFlags,
  D3DPRESENT_PARAMETERS* pPresentationParameters,
  IDirect3DDevice8** ppReturnedDeviceInterface
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type. Denotes the desired device type. If the desired device type is not available, the method will fail.
hFocusWindow
[in] Window handle to which focus belongs for this Microsoft® Direct3D® device. The window specified must be a top-level window for full-screen.
BehaviorFlags
[in] A combination of one or more flags that control global behaviors of the Direct3D device.
D3DCREATE_FPU_PRESERVE
Indicates that the application needs either double precision FPU or FPU exceptions enabled. Direct3D sets the FPU state each time it is called. Setting the flag will reduce Direct3D performance.
D3DCREATE_HARDWARE_VERTEXPROCESSING
Specifies hardware vertex processing. See Remarks.
D3DCREATE_MIXED_VERTEXPROCESSING
Specifies mixed (both software and hardware) vertex processing. See Remarks.
D3DCREATE_MULTITHREADED
Indicates that the application requests Direct3D to be multithread safe. This makes Direct3D take its global critical section more frequently, which can degrade performance.
D3DCREATE_PUREDEVICE
Specifies that Direct3D does not support Get* calls for anything that can be stored in state blocks. It also tells Direct3D not to provide any emulation services for vertex processing. This means that if the device does not support vertex processing, then the application can use only post-transformed vertices.
D3DCREATE_SOFTWARE_VERTEXPROCESSING
Specifies software vertex processing. See Remarks.
pPresentationParameters
[in, out] Pointer to a D3DPRESENT_PARAMETERS structure, describing the presentation parameters for the device to be created. Calling CreateDevice can change the value of the BackBufferCount member of D3DPRESENT_PARAMETERS; the back buffer count is changed to reflect a corrected number of back buffers.
ppReturnedDeviceInterface
[out, retval] Address of a pointer to the returned IDirect3DDevice8 interface, representing the created device.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY

Remarks

This method returns a fully working device interface, set to the required display mode (or windowed), and allocated with the appropriate back buffers. The application only needs to create and set a depth buffer, if desired, to begin rendering.

This method should not be executed during the handling of WM_CREATE. Therefore, the application should never pass a window handle to Direct3D while handling WM_CREATE. DirectX 8.0 applications can expect messages to be sent to them during this call—that is, before this call is returned. Applications should take precautions not to call into Direct3D at this time. In addition, note that a call to create, release, or reset the device can only happen on the same thread as the window procedure of the focus window.

Note that D3DCREATE_HARDWARE_VERTEXPROCESSING, D3DCREATE_MIXED_VERTEXPROCESSING, and D3DCREATE_SOFTWARE_VERTEXPROCESSING are mutually exclusive flags, and that at least one of these vertex processing flags must be specified when calling CreateDevice.

Back buffers created as part of the device are only lockable if D3DPRESENTFLAG_LOCKABLE_BACKBUFFER is specified in the presentation parameters. (Multisampled back buffers and depth-surfaces are never lockable.)

The methods IDirect3DDevice8::Reset, Release, and IDirect3DDevice8::TestCooperativeLevel must be called from the same thread that used CreateDevice to create a device.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

Direct3DCreate8, IDirect3DDevice8::Reset, D3DDEVICE_CREATION_PARAMETERS


IDirect3D8::EnumAdapterModes

Enumerates the display modes of an adapter.

HRESULT EnumAdapterModes(
  UINT Adapter,
  UINT Mode,
  D3DDISPLAYMODE* pMode
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
Mode
[in] Ordinal number that denotes the mode to enumerate. D3DCURRENT_DISPLAY_MODE is a special value denoting the current desktop display mode on this adapter and cannot be specified for this method. See Remarks.
pMode
[in, out] Pointer to a D3DDISPLAYMODE structure, to be filled with information describing this mode. On error conditions, this value is zeroed.

Return Values

If the method succeeds, the return value is D3D_OK.

If Adapter or Mode is out of range, or pMode is invalid, this method returns D3DERR_INVALIDCALL.

Remarks

Some display drivers include refresh rate information that will greatly increase the number of modes. On older drivers, refresh rates of D3DADAPTER_DEFAULT are the only ones enumerated. Direct3D attempts to limit display modes and refresh rates based on the monitor capabilities, however there is still some risk that an enumerated mode will not be supported by the system's monitor. You may want to implement a display mode testing facility similar to that used by the Microsoft® Windows® Display Control Panel utility.

Use IDirect3D8::GetAdapterModeCount to determine the total number of modes supported by the system. Valid values for the Mode parameter range from 0 to the total number of modes minus 1.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3D8::GetAdapterModeCount


IDirect3D8::GetAdapterCount

Returns the number of adapters on the system.

UINT GetAdapterCount();

Parameters

None.

Return Values

A UINT value that denotes the number of adapters on the system at the time this IDirect3D8 interface was instantiated.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3D8::GetAdapterIdentifier


IDirect3D8::GetAdapterDisplayMode

Retrieves the current display mode of the adapter.

HRESULT GetAdapterDisplayMode(
  UINT Adapter,
  D3DDISPLAYMODE* pMode
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter to query. D3DADAPTER_DEFAULT is always the primary display adapter.
pMode
[in, out] Pointer to a D3DDISPLAYMODE structure, to be filled with information describing the current adapter's mode.

Return Values

If the method succeeds, the return value is D3D_OK.

If Adapter is out of range or pMode is invalid, this method returns D3DERR_INVALIDCALL.

Remarks

Note that a device that represents an adapter may have been reset into a particular mode, but this may not be the actual mode of the adapter. A device reset to a particular mode may be lost, and therefore it can not determine the current mode of the adapter. This function returns the adapter mode, not any particular device's desired mode.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3D8::GetAdapterIdentifier

Describes the physical display adapters present in the system when the IDirect3D8 interface was instantiated.

HRESULT GetAdapterIdentifier(
  UINT Adapter,
  DWORD Flags,
  D3DADAPTER_IDENTIFIER8* pIdentifier
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter. The minimum value for this parameter is 0, and the maximum value for this parameter is one less than the value returned by IDirect3D8::GetAdapterCount.
Flags
[in] Parameter that is typically set to zero. However, you can specify the following value.
D3DENUM_NO_WHQL_LEVEL
Forces the WHQLLevel member of the D3DADAPTER_IDENTIFIER8 structure to be zero, meaning that no information is returned for the WHQL certification date. Setting this flag will avoid the one- or two-second time penalty incurred to determine the WHQL certification date.
pIdentifier
[in, out] Pointer to a D3DADAPTER_IDENTIFIER8 structure to be filled with information describing this adapter. If Adapter is greater than or equal to the number of adapters in the system, this structure will be zeroed.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if Adapter is out of range, if Flags contains unrecognized parameters, or if pIdentifier is NULL or points to unwriteable memory.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3D8::GetAdapterCount


IDirect3D8::GetAdapterModeCount

Returns the number of display modes available on this adapter.

UINT GetAdapterModeCount(
  UINT Adapter
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.

Return Values

This method returns the number of display modes on this adapter, or zero if Adapter is greater than or equal to the number of adapters on the system.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3D8::EnumAdapterModes


IDirect3D8::GetAdapterMonitor

Returns the handle of the monitor associated with the Microsoft® Direct3D® object.

HMONITOR GetAdapterMonitor(
  UINT Adapter
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.

Return Values

Handle of the monitor associated with the Direct3D object.

Remarks

As shown in the following code fragment, which illustrates how to obtain a handle to the monitor associated with a given device, use IDirect3DDevice8::GetDirect3D to return the Direct3D enumerator from the device and use IDirect3DDevice8::GetCreationParameters to retrieve the value for Adapter.

    if( FAILED( pDevice->GetCreationParameters(  &Parameters ) ) )
        return E_INVALIDCALL;

    if( FAILED( pDevice->GetDirect3D(&pD3D) ) )
        return E_INVALIDCALL;

    hMonitor = pD3D->GetAdapterMonitor(Parameters.AdapterOrdinal);

    pD3D->Release();

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetCreationParameters, IDirect3DDevice8::GetDirect3D


IDirect3D8::GetDeviceCaps

Retrieves device-specific information about a device.

HRESULT GetDeviceCaps(
  UINT Adapter,
  D3DDEVTYPE DeviceType,
  D3DCAPS8* pCaps
);

Parameters

Adapter
[in] Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.
DeviceType
[in] Member of the D3DDEVTYPE enumerated type. Denotes the device type.
pCaps
[out] Pointer to a D3DCAPS8 structure to be filled with information describing the capabilities of the device.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_INVALIDDEVICE
D3DERR_OUTOFVIDEOMEMORY

Remarks

The application should not assume the persistence of vertex processing capabilities across Microsoft® Direct3D® device objects. The particular capabilities that a physical device exposes may depend on parameters supplied to IDirect3D8::CreateDevice. For example, the capabilities may yield different vertex processing capabilities before and after creating a Direct3D Device Object with hardware vertex processing enabled. For more information see the description of D3DCAPS8.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3D8::RegisterSoftwareDevice

Registers a pluggable software device with Microsoft® Direct3D®.

HRESULT RegisterSoftwareDevice(
  void* pInitializeFunction
);

Parameters

pInitializeFunction
[in] Pointer to the initialization function for the software device to be registered.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

Remarks

Software rasterization for Direct3D is provided by pluggable software devices, enabling applications to access a variety of software rasterizers through the Direct3D interfaces. Software devices are loaded by the application and registered with the Direct3D object, at which point a Direct3DDevice object can be created that will perform rendering with the software device.

Direct3D software devices communicate with Direct3D through an interface similar to the hardware device driver interface (DDI).

The Direct3D DDK provides the documentation and headers for developing pluggable software devices.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DBaseTexture8

Applications use the methods of the IDirect3DBaseTexture8 interface to manipulate texture resources including cube and volume textures.

The IDirect3DBaseTexture8 interface assigned to a particular stage for a device is obtained by calling the IDirect3DDevice8::GetTexture method.

The IDirect3DBaseTexture8 interface inherits the following IDirect3DResource8 methods, which can be organized into these groups.

Devices | GetDevice
Information | GetType
Private Surface Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData
Resource Management | GetPriority
 | PreLoad
 | SetPriority

The methods of the IDirect3DBaseTexture8 interface can be organized into the following groups.

Detail | GetLOD
 | SetLOD
Information | GetLevelCount

The IDirect3DBaseTexture8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DBASETEXTURE8 and PDIRECT3DBASETEXTURE8 types are defined as pointers to the IDirect3DBaseTexture8 interface.

typedef struct IDirect3DBaseTexture8 *LPDIRECT3DBASETEXTURE8, *PDIRECT3DBASETEXTURE8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DBaseTexture8::GetLevelCount

Returns the number of texture levels in a multilevel texture.

DWORD GetLevelCount();

Parameters

None.

Return Values

A DWORD value indicating the number of texture levels in a multilevel texture.

Applies To

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture8.

  • IDirect3DCubeTexture8
  • IDirect3DTexture8
  • IDirect3DVolumeTexture8

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DBaseTexture8::GetLOD

Returns a value clamped to the maximum level of detail (LOD) set for a managed texture.

DWORD GetLOD();

Parameters

None.

Return Values

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels).

Applies To

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture8.

  • IDirect3DCubeTexture8
  • IDirect3DTexture8
  • IDirect3DVolumeTexture8

Remarks

GetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DBaseTexture8::SetLOD


IDirect3DBaseTexture8::SetLOD

Sets the most detailed level of detail (LOD) for a managed texture.

DWORD SetLOD(
  DWORD LODNew
);

Parameters

LODNew
[in] Most detailed LOD value to set for the mipmap chain.

Return Values

A DWORD value, clamped to the maximum LOD value (one less than the total number of levels). Subsequent calls to this method will return the clamped value, not the LOD value that was previously set.

Applies To

This method applies to the following interfaces, which inherit from IDirect3DBaseTexture8.

  • IDirect3DCubeTexture8
  • IDirect3DTexture8
  • IDirect3DVolumeTexture8

Remarks

SetLOD is used for LOD control of managed textures. This method returns 0 on nonmanaged textures.

SetLOD communicates to the Microsoft® Direct3D® texture manager the most detailed mipmap in the chain that should be loaded into local video memory. For example, in a five-level mipmap chain, setting LODNew to 2 indicates that the texture manager should load only mipmap levels 2 through 4 into local video memory at any given time.

More specifically, if the texture was created with the dimensions of 256×256, setting the most detailed level to 0 indicates that 256×256 is the largest mipmap available, setting the most detailed level to 1 indicates that 128×128 is the largest mipmap available, and so on, up to the most detailed mip level (the smallest texture size) for the chain.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DBaseTexture8::GetLOD


IDirect3DCubeTexture8

Applications use the methods of the IDirect3DCubeTexture8 interface to manipulate a cube texture resource.

The IDirect3DCubeTexture8 interface is obtained by calling the IDirect3DDevice8::CreateCubeTexture method.

The IDirect3DCubeTexture8 interface inherits the following IDirect3DResource8 methods, which can be organized into the following groups.

Devices | GetDevice
Information | GetType
Private Surface Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData
Resource Management | GetPriority
 | PreLoad
 | SetPriority

The IDirect3DCubeTexture8 interface inherits the following IDirect3DBaseTexture8 methods, which can be organized into the following groups.

Detail | GetLOD
 | SetLOD
Information | GetLevelCount

The methods of the IDirect3DCubeTexture8 interface can be organized into the following groups.

Information | GetLevelDesc
Locking Surfaces | LockRect
 | UnlockRect
Miscellaneous | AddDirtyRect
 | GetCubeMapSurface

The IDirect3DCubeTexture8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DCUBETEXTURE8 and PDIRECT3DCUBETEXTURE8 types are defined as pointers to the IDirect3DCubeTexture8 interface.

typedef struct IDirect3DCubeTexture8 *LPDIRECT3DCUBETEXTURE8, *PDIRECT3DCUBETEXTURE8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::CreateCubeTexture


IDirect3DCubeTexture8::AddDirtyRect

Adds a dirty region to a cube texture resource.

HRESULT AddDirtyRect(
  D3DCUBEMAP_FACES FaceType,
  CONST RECT* pDirtyRect
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying the cube map face.
pDirtyRect
[in] Pointer to a RECT structure, specifying the dirty region. Specifying NULL expands the dirty region to cover the entire cube texture.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DCubeTexture8::GetLevelDesc, IDirect3DCubeTexture8::LockRect, IDirect3DCubeTexture8::UnlockRect


IDirect3DCubeTexture8::GetCubeMapSurface

Retrieves a cube texture map surface.

HRESULT GetCubeMapSurface(
  D3DCUBEMAP_FACES FaceType,
  UINT Level,
  IDirect3DSurface8** ppCubeMapSurface
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.
ppCubeMapSurface
[out, retval] Address of a pointer to an IDirect3DSurface8 interface, representing the returned cube texture map surface.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DCubeTexture8::GetLevelDesc

Retrieves a description of the specified cube texture level

HRESULT GetLevelDesc(
  UINT Level,
  D3DSURFACE_DESC* pDesc
);

Parameters

Level
[in] Specifies a level of a mipmapped cube texture.
pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing the specified cube texture level.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments are invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DCubeTexture8::AddDirtyRect, IDirect3DCubeTexture8::LockRect, IDirect3DCubeTexture8::UnlockRect


IDirect3DCubeTexture8::LockRect

Locks a rectangle on a cube texture resource.

HRESULT LockRect(
  D3DCUBEMAP_FACES FaceType,
  UINT Level,
  D3DLOCKED_RECT* pLockedRect,
  CONST RECT* pRect,
  DWORD Flags
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.
pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure, describing the region to lock.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT structure. Specifying NULL for this parameter expands the dirty region to cover the entire cube texture.
Flags
[in] A combination of zero or more locking flags, describing the type of lock to perform.
D3DLOCK_NO_DIRTY_UPDATE
By default, a lock on a resource adds a dirty region to that resource. This flag prevents any changes to the dirty state of the resource. Applications should use this flag when they have additional information about the actual set of regions changed during the lock operation and can then pass this information to IDirect3DCubeTexture8::AddDirtyRect.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation uses slightly more memory, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long-duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments are invalid.

Remarks

Cube Textures created with POOL_DEFAULT are not-lockable.

The only lockable format for a depth-stencil surface is D3DFMT_D16_LOCKABLE.

A multisample backbuffer cannot be locked.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DCubeTexture8::AddDirtyRect, IDirect3DCubeTexture8::GetLevelDesc, IDirect3DCubeTexture8::UnlockRect


IDirect3DCubeTexture8::UnlockRect

Unlocks a rectangle on a cube texture resource.

HRESULT UnlockRect(
  D3DCUBEMAP_FACES FaceType,
  UINT Level
);

Parameters

FaceType
[in] Member of the D3DCUBEMAP_FACES enumerated type, identifying a cube map face.
Level
[in] Specifies a level of a mipmapped cube texture.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments are invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DCubeTexture8::AddDirtyRect, IDirect3DCubeTexture8::LockRect


IDirect3DDevice8

Applications use the methods of the IDirect3DDevice8 interface to perform DrawPrimitive-based rendering, create resources, work with system-level variables, adjust gamma ramp levels, work with palettes, and create shaders.

The IDirect3DDevice8 interface is obtained by calling the IDirect3D8::CreateDevice method.

The methods of the IDirect3DDevice8 interface can be organized into the following groups.

Cursors | SetCursorPosition
 | SetCursorProperties
 | ShowCursor
Creation | CreateAdditionalSwapChain
 | CreateCubeTexture
 | CreateDepthStencilSurface
 | CreateImageSurface
 | CreateIndexBuffer
 | CreateRenderTarget
 | CreateTexture
 | CreateVertexBuffer
 | CreateVolumeTexture
Device States | ApplyStateBlock
 | BeginStateBlock
 | CaptureStateBlock
 | CreateStateBlock
 | DeleteStateBlock
 | EndStateBlock
 | GetClipStatus
 | GetDisplayMode
 | GetRenderState
 | GetRenderTarget
 | GetTransform
 | SetClipStatus
 | SetRenderState
 | SetRenderTarget
 | SetTransform
Gamma Ramps | GetGammaRamp
 | SetGammaRamp
High-Order Primitives | DeletePatch
 | DrawRectPatch
 | DrawTriPatch
Index Data | GetIndices
 | SetIndices
Information | GetAvailableTextureMem
 | GetCreationParameters
 | GetDeviceCaps
 | GetDirect3D
 | GetInfo
 | GetRasterStatus
Lighting and Materials | GetLight
 | GetLightEnable
 | GetMaterial
 | LightEnable
 | SetLight
 | SetMaterial
Miscellaneous | CopyRects
 | GetFrontBuffer
 | MultiplyTransform
 | ProcessVertices
 | ResourceManagerDiscardBytes
 | TestCooperativeLevel
Palettes | GetCurrentTexturePalette
 | GetPaletteEntries
 | SetCurrentTexturePalette
 | SetPaletteEntries
Pixel Shaders | CreatePixelShader
 | DeletePixelShader
 | GetPixelShader
 | GetPixelShaderConstant
 | GetPixelShaderFunction
 | SetPixelShader
 | SetPixelShaderConstant
Presentation | Present
 | Reset
Rendering | DrawIndexedPrimitive
 | DrawIndexedPrimitiveUP
 | DrawPrimitive
 | DrawPrimitiveUP
 | DrawRectPatch
 | DrawTriPatch
Scenes | BeginScene
 | EndScene
Stream Data | GetStreamSource
 | SetStreamSource
Surfaces | GetBackBuffer
 | GetDepthStencilSurface
Textures | GetTexture
 | GetTextureStageState
 | SetTexture
 | SetTextureStageState
 | UpdateTexture
 | ValidateDevice
User-Defined Clip Planes | GetClipPlane
 | SetClipPlane
Viewports | Clear
 | GetViewport
 | SetViewport
Vertex Shaders | CreateVertexShader
 | DeleteVertexShader
 | GetVertexShader
 | GetVertexShaderConstant
 | GetVertexShaderDeclaration
 | GetVertexShaderFunction
 | SetVertexShader
 | SetVertexShaderConstant

The IDirect3DDevice8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DDEVICE8 and PDIRECT3DDEVICE8 types are defined as pointers to the IDirect3DDevice8 interface.

typedef struct IDirect3DDevice8 *LPDIRECT3DDEVICE8, *PDIRECT3DDEVICE8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3D8::CreateDevice


IDirect3DDevice8::ApplyStateBlock

Applies an existing device-state block to the rendering device.

HRESULT ApplyStateBlock(
  DWORD Token
);

Parameters

Token
[in] Handle to the device-state block to execute, as returned by a previous call to the IDirect3DDevice8::EndStateBlock method.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The value 0xFFFFFFFF is an invalid state block handle.

Applications cannot apply a device-state block while recording another block.

As with all operations that affect the state of the rendering device, it is recommended that you apply state blocks during scene rendering—that is, after calling the IDirect3DDevice8::BeginScene method and before calling IDirect3DDevice8::EndScene.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::BeginStateBlock, IDirect3DDevice8::EndStateBlock, IDirect3DDevice8::CaptureStateBlock, IDirect3DDevice8::CreateStateBlock, IDirect3DDevice8::DeleteStateBlock


IDirect3DDevice8::BeginScene

Begins a scene.

HRESULT BeginScene();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Applications must call this method before performing any rendering and must call IDirect3DDevice8::EndScene when rendering is complete and before calling BeginScene again.

If the BeginScene method fails, the device was unable to begin the scene, and there is no need to call the IDirect3DDevice8::EndScene method. In fact, calls to EndScene will fail if the previous call to BeginScene failed.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::EndScene


IDirect3DDevice8::BeginStateBlock

Signals Microsoft® Direct3D® to begin recording a device-state block.

HRESULT BeginStateBlock();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

Applications can ensure that all recorded states are valid by calling the IDirect3DDevice8::ValidateDevice method prior to calling this method.

The following methods can be recorded in a state block, after calling BeginStateBlock and before IDirect3DDevice8::EndStateBlock.

  • IDirect3DDevice8::LightEnable
  • IDirect3DDevice8::SetClipPlane
  • IDirect3DDevice8::SetIndices
  • IDirect3DDevice8::SetLight
  • IDirect3DDevice8::SetMaterial
  • IDirect3DDevice8::SetPixelShader
  • IDirect3DDevice8::SetPixelShaderConstant
  • IDirect3DDevice8::SetRenderState
  • IDirect3DDevice8::SetStreamSource
  • IDirect3DDevice8::SetTexture
  • IDirect3DDevice8::SetTextureStageState
  • IDirect3DDevice8::SetTransform
  • IDirect3DDevice8::SetViewport
  • IDirect3DDevice8::SetVertexShader
  • IDirect3DDevice8::SetVertexShaderConstant

The ordering of state changes in a state block is not guaranteed. If the same state is specified multiple times in a state block, only the last value is used.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::ApplyStateBlock, IDirect3DDevice8::EndStateBlock, IDirect3DDevice8::CaptureStateBlock, IDirect3DDevice8::CreateStateBlock, IDirect3DDevice8::DeleteStateBlock


IDirect3DDevice8::CaptureStateBlock

Updates the values within an existing state block to the values set for the device.

HRESULT CaptureStateBlock(
  DWORD Token
);

Parameters

Token
[in] Handle to the state block into which the device state is captured.

Return Values

If the method succeeds, the return value is D3D_OK.

If a state block is currently being recorded the method fails and the return value can be D3DERR_INVALIDCALL.

Remarks

The value 0xFFFFFFFF is an invalid state block handle.

This method captures updated values for states within an existing state block. It does not capture the entire state of the device.

CaptureStateBlock will not capture information for lights that are explicitly or implicitly created after the stateblock is created. For example, capturing the current state into a stateblock of type D3DSBT_ALL will not store information for lights that are created post-capture.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::ApplyStateBlock, IDirect3DDevice8::BeginStateBlock, IDirect3DDevice8::CreateStateBlock, IDirect3DDevice8::EndStateBlock, IDirect3DDevice8::DeleteStateBlock


IDirect3DDevice8::Clear

Clears the viewport, or a set of rectangles in the viewport, to a specified RGBA color, clears the depth buffer, and erases the stencil buffer.

HRESULT Clear(
  DWORD Count,
  CONST D3DRECT* pRects,
  DWORD Flags,
  D3DCOLOR Color,
  float Z,
  DWORD Stencil
);

Parameters

Count
[in] Number of rectangles in the array at pRects. If you set pRects to NULL, this parameter must be set to 0.
pRects
[in] Pointer to an array of D3DRECT structures that describe the rectangles to clear. Set a rectangle to the dimensions of the rendering target to clear the entire surface. Each rectangle uses screen coordinates that correspond to points on the render target surface. Coordinates are clipped to the bounds of the viewport rectangle. This parameter can be set to NULL to indicate that the entire viewport rectangle is to be cleared.
Flags
[in] Flags that indicate which surfaces should be cleared. This parameter can be any combination of the following flags, but at least one flag must be used.
D3DCLEAR_STENCIL
Clear the stencil buffer to the value in the Stencil parameter.
D3DCLEAR_TARGET
Clear the render target to the color in the Color parameter.
D3DCLEAR_ZBUFFER
Clear the depth buffer to the value in the Z parameter.
Color
[in] A 32-bit ARGB color value to which the render target surface is cleared.
Z
[in] New z value that this method stores in the depth buffer. This parameter can be in the range from 0.0 through 1.0 (for z-based or w-based depth buffers). A value of 0.0 represents the nearest distance to the viewer, and 1.0 the farthest distance.
Stencil
[in] Integer value to store in each stencil-buffer entry. This parameter can be in the range from 0 through 2n–1, where n is the bit depth of the stencil buffer.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method fails if you specify the D3DCLEAR_ZBUFFER or D3DCLEAR_STENCIL flags when the render target does not have an attached depth buffer. Similarly, if you specify the D3DCLEAR_STENCIL flag when the depth-buffer format does not contain stencil buffer information, this method fails.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::CopyRects

Copies rectangular subsets of pixels from one surface to another.

HRESULT CopyRects(
  IDirect3DSurface8* pSourceSurface,
  CONST RECT* pSourceRectsArray,
  UINT cRects,
  IDirect3DSurface8* pDestinationSurface,
  CONST POINT* pDestPointsArray
);

Parameters

pSourceSurface
[in] Pointer to an IDirect3DSurface8 interface, representing the source surface. This parameter must point to a different surface than pDestinationSurface.
pSourceRectsArray
[in] Pointer to an array of RECT structures, representing the rectangles to be transferred. Each rectangle will be transferred to the destination surface, with its top-left pixel at the position identified by the corresponding element of pDestPointsArray. Specifying NULL for this parameter causes the entire surface to be copied.
cRects
[in] Number of RECT structures contained in pSourceRectsArray.
pDestinationSurface
[in] Pointer to an IDirect3DSurface8 interface, representing the destination surface. This parameter must point to a different surface than pSourceSurface.
pDestPointsArray
[in] Pointer to an array of POINT structures, identifying the top-left pixel position of each rectangle contained in pSourceRectsArray. If this parameter is NULL, the RECTs are copied to the same offset (same top/left location) as the source rectangle.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method does not support stretch, color key, alpha blend, format conversion, or clipping of either source or destination rectangles. Note that this method will fail unless all the source rectangles and their corresponding destination rectangles are completely contained within the source and destination surfaces respectively. The format of the two surfaces must match, but they can have different dimensions.

This method cannot be applied to surfaces whose formats are classified as depth stencil formats.

A POINT structure defines the x- and y- coordinates of a point. For more information on POINT, see the Microsoft® Platform Software Development Kit (SDK).

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::CreateAdditionalSwapChain

Creates an additional swap chain for rendering multiple views.

HRESULT CreateAdditionalSwapChain(
  D3DPRESENT_PARAMETERS* pPresentationParameters,
  IDirect3DSwapChain8** ppSwapChain
);

Parameters

pPresentationParameters
[in] Pointer to a D3DPRESENT_PARAMETERS structure, representing the presentation parameters for the new swap chain. This value cannot be NULL.
ppSwapChain
[out, retval] Address of a pointer to an IDirect3DSwapChain8 interface, representing the additional swap chain.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Remarks

There is always at least one swap chain (the implicit swap chain) for each device, because Microsoft® Direct3D® for Microsoft DirectX® 8.0 has one swap chain as a property of the device.

Note that any given device can support only one full-screen swap chain.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

Presenting Multiple Views in Windowed Mode


IDirect3DDevice8::CreateCubeTexture

Creates a cube texture resource.

HRESULT CreateCubeTexture(
  UINT EdgeLength,
  UINT Levels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  IDirect3DCubeTexture8** ppCubeTexture
);

Parameters

EdgeLength
[in] Size of the edges of all the top-level faces of the cube texture. The pixel dimensions of subsequent levels of each face will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead.
Levels
[in] The number of levels in each face of the cube texture. If this is zero, Microsoft® Direct3D® will generate all cube texture sub-levels down to 1×1 pixels for each face for hardware that supports mipmapped cube textures. Otherwise, it will create one level. Call IDirect3DBaseTexture8::GetLevelCount to see the number of levels generated.
Usage
[in] A combination of one or more of the following flags, describing the usage for this resource.
D3DUSAGE_DEPTHSTENCIL
Set to indicate that the surface is to be used as a depth-stencil surface. The resource can be passed to the pNewDepthStencil parameter of the IDirect3DDevice8::SetRenderTarget method. See Remarks.
D3DUSAGE_RENDERTARGET
Set to indicate that the surface is to be used as a render target. The resource can be passed to the pRenderTarget parameter of the SetRenderTarget method. See Remarks.

If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DEPTHSTENCIL is specified, the application should check that the device supports these operations by calling IDirect3D8::CheckDeviceFormat.

Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in all faces of the cube texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
ppCubeTexture
[out, retval] Address of a pointer to an IDirect3DCubeTexture8 interface, representing the created cube texture resource.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces. In order to call SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture8::GetCubeMapSurface and pass the resulting surface to SetRenderTarget.

A texture (mipmap) is a collection of successively downsampled (mipmapped) surfaces. On the other hand, a cube texture (created by CreateCubeTexture) is a collection of six textures (mipmaps), one for each face. All faces must be present in the cube texture. Also, a cube map surface must be the same pixel size in all three dimensions (x, y, and z).

In DirectX® 8.0, resource usage is enforced. An application that wants to use a resource in a certain operation must specify that operation at resource creation time.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::CreateDepthStencilSurface

Creates a depth-stencil resource.

HRESULT CreateDepthStencilSurface(
  UINT Width,
  UINT Height,
  D3DFORMAT Format,
  D3DMULTISAMPLE_TYPE MultiSample,
  IDirect3DSurface8** ppSurface
);

Parameters

Width
[in] Width of the depth-stencil surface, in pixels.
Height
[in] Height of the depth-stencil surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the depth-stencil surface. This value must be one of the enumerated depth-stencil formats for this device.
MultiSample
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, describing the multisampling buffer type. This value must be one of the allowed multisample types. When this surface is passed to SetRenderTarget, its multisample type must be the same as that of the render target.
ppSurface
[out, retval] Address of a pointer to an IDirect3DSurface8 interface, representing the created depth-stencil surface resource.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY

Remarks

The memory class of the depth-stencil buffer is always D3DPOOL_DEFAULT.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::CopyRects, IDirect3DDevice8::SetRenderTarget


IDirect3DDevice8::CreateImageSurface

Creates an image surface.

HRESULT CreateImageSurface(
  UINT Width,
  UINT Height,
  D3DFORMAT Format,
  IDirect3DSurface8** ppSurface
);

Parameters

Width
[in] Width of the image surface, in pixels.
Height
[in] Height of the image surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the image surface.
ppSurface
[out, retval] Address of a pointer to an IDirect3DSurface8 interface, representing the created image surface.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Remarks

Image surfaces are place holders, they are surfaces that cannot be used in any Microsoft® Direct3D® operations except locking and IDirect3DDevice8::CopyRects.

Image surfaces are placed in the D3DPOOL_SYSTEMMEM memory class.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::CreateIndexBuffer

Creates an index buffer.

HRESULT CreateIndexBuffer(
  UINT Length,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  IDirect3DIndexBuffer8** ppIndexBuffer
);

Parameters

Length
[in] Size of the index buffer, in bytes.
Usage
[in] A combination of one or more of the following flags, describing the usage controls for this resource.
D3DUSAGE_DONOTCLIP
Set to indicate that the index buffer content will never require clipping.
D3DUSAGE_DYNAMIC
Set to indicate when the vertex or index buffer requires dynamic memory usage. This usage is useful for drivers because it enables them to decide where to place the driver. In general, static vertex buffers will be placed in video memory and dynamic vertex buffers will be placed in AGP memory. Note that there is no separate static usage; if you do not specify D3DUSAGE_DYNAMIC the vertex buffer is made static. D3DUSAGE_DYNAMIC is strictly enforced through the D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE locking flags. As a result, D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE are only valid on vertex and index buffers created with D3DUSAGE_DYNAMIC; they are not valid flags on static vertex buffers.

Note that D3DUSAGE_DYNAMIC cannot be specified on managed vertex and index buffers. For more information, see Managing Resources.

D3DUSAGE_RTPATCHES
Set to indicate when the index buffer is to be used for drawing high-order primitives.
D3DUSAGE_NPATCHES
Set to indicate when the index buffer is to be used for drawing N patches.
D3DUSAGE_POINTS
Set to indicate when the index buffer is to be used for drawing point sprites or indexed point lists.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the buffer is to be used with software processing.
D3DUSAGE_WRITEONLY
Informs the system that the application writes only to the index buffer. Using this flag enables the driver to select the best memory location for efficient write operations and rendering. Attempts to read from an index buffer that is created with this capability can result in degraded performance.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the index buffer. The valid settings are the following:
D3DFMT_INDEX16
Indices are 16 bits each.
D3DFMT_INDEX32
Indices are 32 bits each.

See Remarks.

Pool
[in] Member of the D3DPOOL enumerated type, describing a valid memory class into which to place the resource.
ppIndexBuffer
[out, retval] Address of a pointer to an IDirect3DIndexBuffer8 interface, representing the created index buffer resource.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Index buffers are memory resources used to hold indices, they are similar to both surfaces and vertex buffers. The use of index buffers enables Microsoft® Direct3D® to avoid unnecessary data copying and to place the buffer in the optimal memory type for the expected usage.

To use index buffers, create an index buffer, lock it, fill it with indices, unlock it, pass it to IDirect3DDevice8::SetIndices, set up the vertices, set up the vertex shader, and call IDirect3DDevice8::DrawIndexedPrimitive for rendering.

The MaxVertexIndex member of the D3DCAPS8 structure indicates the types of index buffers that are valid for rendering.

Requirements

Header: Declared in D3d8.h
Import Library: Use D3d8.lib.

See Also

IDirect3DIndexBuffer8::GetDesc


IDirect3DDevice8::CreatePixelShader

Creates a pixel shader.

HRESULT CreatePixelShader(
  CONST DWORD* pFunction,
  DWORD* pHandle
);

Parameters

pFunction
[in] Pointer to the pixel shader function token array, specifying the blending operations. This value cannot be NULL.
pHandle
[out, retval] Pointer to the returned pixel shader handle.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::DeletePixelShader, D3DXAssembleShader, D3DXAssembleShaderFromFileA, D3DXAssembleShaderFromFileW


IDirect3DDevice8::CreateRenderTarget

Creates a render target surface.

HRESULT CreateRenderTarget(
  UINT Width,
  UINT Height,
  D3DFORMAT Format,
  D3DMULTISAMPLE_TYPE MultiSample,
  BOOL Lockable,
  IDirect3DSurface8** ppSurface
);

Parameters

Width
[in] Width of the render target surface, in pixels.
Height
[in] Height of the render target surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of the render target.
MultiSample
[in] Member of the D3DMULTISAMPLE_TYPE enumerated type, describing the multisampling buffer type. This parameter specifies the antialiasing type for this render target. The type must be the same as that of the depth-stencil buffer when both surfaces are passed to SetRenderTarget.
Lockable
[in] Render targets are not lockable unless the application specifies TRUE for Lockable. Note that lockable render targets incur a performance cost on some graphics hardware.
ppSurface
[out, retval] Address of a pointer to a IDirect3DSurface8 interface.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Remarks

Render target surfaces are placed in the D3DPOOL_DEFAULT memory class.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::CreateStateBlock

Creates a new state block that contains the values for all device states, vertex-related states, or pixel-related states.

HRESULT CreateStateBlock(
  D3DSTATEBLOCKTYPE Type,
  DWORD* pToken
);

Parameters

Type
[in] Type of state data that the method should capture. This parameter can be set to a value defined in the D3DSTATEBLOCKTYPE enumerated type.
pToken
[out, retval] Pointer to a DWORD value to contain the state block handle if the method succeeds.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Remarks

The value 0xFFFFFFFF is an invalid state block handle.

Vertex-related device states typically refer to those states that affect how the system processes vertices. Pixel-related states generally refer to device states that affect how the system processes pixel or depth-buffer data during rasterization. Some states are contained in both groups.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::ApplyStateBlock, IDirect3DDevice8::BeginStateBlock, IDirect3DDevice8::CaptureStateBlock, IDirect3DDevice8::EndStateBlock, IDirect3DDevice8::DeleteStateBlock


IDirect3DDevice8::CreateTexture

Creates a texture resource.

HRESULT CreateTexture(
  UINT Width,
  UINT Height,
  UINT  Levels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  IDirect3DTexture8** ppTexture
);

Parameters

Width
[in] Width of the top-level of the texture, in pixels. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead.
Height
[in] Height of the top-level of the texture, in pixels. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead.
Levels
[in] The number of levels in the texture. If this is zero, Microsoft® Direct3D® will generate all texture sub-levels down to 1×1 pixels for hardware that supports MIP mapped textures. Otherwise, it will create one level. Call IDirect3DBaseTexture8::GetLevelCount to see the number of levels generated.
Usage
[in] A combination of one or more of the following flags, describing the usage for this resource.
D3DUSAGE_DEPTHSTENCIL
Set to indicate that the surface is to be used as a depth-stencil surface. The resource can be passed to the pNewZStencil parameter of the IDirect3DDevice8::SetRenderTarget method.
D3DUSAGE_RENDERTARGET
Set to indicate that the surface is to be used as a render target. The resource can be passed to the pRenderTarget parameter of SetRenderTarget.

If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DEPTHSTENCIL is specified, the application should check that the device supports these operations by calling IDirect3D8::CheckDeviceFormat.

Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in the texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
ppTexture
[out, retval] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture resource.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Remarks

In order to call IDirect3DDevice8::SetRenderTarget with a texture, you must select a level using IDirect3DTexture8::GetSurfaceLevel and pass the resulting surface to SetRenderTarget.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::CreateVertexBuffer

Creates a vertex buffer.

HRESULT CreateVertexBuffer(
  UINT Length,
  DWORD Usage,
  DWORD FVF,
  D3DPOOL Pool,
  IDirect3DVertexBuffer8** ppVertexBuffer
);

Parameters

Length
[in] Size of the vertex buffer, in bytes. For flexible vertex format (FVF) vertex buffers, Length must be large enough to contain at least one vertex, but it need not be a multiple of the vertex size. Length is not validated for nonFVF buffers. See Remarks.
Usage
[in] A combination of one or more of the following flags, describing the usage controls for this resource.
D3DUSAGE_DONOTCLIP
Set to indicate that the vertex buffer content will never require clipping. When rendering with buffers that have this flag set, the D3DRS_CLIPPING renderstate must be set to false.
D3DUSAGE_DYNAMIC
Set to indicate when the vertex or index buffer requires dynamic memory usage. This usage is useful for drivers because it enables them to decide where to place the driver. In general, static vertex buffers will be placed in video memory and dynamic vertex buffers will be placed in AGP memory. Note that there is no separate static usage; if you do not specify D3DUSAGE_DYNAMIC the vertex buffer is made static. D3DUSAGE_DYNAMIC is strictly enforced through the D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE locking flags. As a result, D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE are only valid on vertex and index buffers created with D3DUSAGE_DYNAMIC; they are not valid flags on static vertex buffers.

For more information about using dynamic vertex buffers, see Using Dynamic Vertex and Index Buffers.

Note that D3DUSAGE_DYNAMIC cannot be specified on managed vertex and index buffers. For more information, see Managing Resources.

D3DUSAGE_RTPATCHES
Set to indicate when the vertex buffer is to be used for drawing high-order primitives.
D3DUSAGE_NPATCHES
Set to indicate when the vertex buffer is to be used for drawing N patches.
D3DUSAGE_POINTS
Set to indicate when the vertex buffer is to be used for drawing point sprites or indexed point lists.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the vertex buffer is to be used with software vertex processing.
D3DUSAGE_WRITEONLY
Informs the system that the application writes only to the vertex buffer. Using this flag enables the driver to choose the best memory location for efficient write operations and rendering. Attempts to read from a vertex buffer that is created with this capability will fail.
FVF
[in] Combination of flexible vertex format flags, a usage specifier that describes the vertex format of the vertices in this buffer. When this parameter is set to a valid FVF code, the created vertex buffer is an FVF vertex buffer (see Remarks); otherwise, when this parameter is set to zero, the vertex buffer is a non-FVF vertex buffer.
Pool
[in] Member of the D3DPOOL enumerated type, describing a valid memory class into which to place the resource.
ppVertexBuffer
[out,retval] Address of a pointer to an IDirect3DVertexBuffer8 interface, representing the created vertex buffer resource.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Remarks

The IDirect3DDevice8 interface supports rendering of primitives using vertex data stored in vertex buffer objects. Vertex buffers are created from the IDirect3DDevice8 interface, and are usable only with the IDirect3DDevice8 object from which they are created.

When set to a non-zero value, which must be a valid FVF code, the FVF parameter indicates that the buffer content is to be characterized by an FVF code. A vertex buffer that is created with an FVF code is referred to as an FVF vertex buffer. For more information, see FVF Vertex Buffers.

The D3DUSAGE_SOFTWAREPROCESSING flag specifies that the vertex buffer is to be used with software vertex processing. For more information, see Device Types and Vertex Processing Requirements.

Non-FVF buffers can be used to interleave data during multipass rendering or multitexture rendering in a single pass. To do this, one buffer contains geometry data and the others contain texture coordinates for each texture to be rendered. When rendering, the buffer containing the geometry data is interleaved with each of the buffers containing the texture coordinates. If FVF buffers were used instead, each of them would need to contain identical geometry data in addition to the texture coordinate data specific to each texture rendered. This would result in either a speed or memory penalty, depending on the strategy used. For more information on texture coordinates, see Understanding Texture Coordinates.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DVertexBuffer8::GetDesc, IDirect3DDevice8::ProcessVertices


IDirect3DDevice8::CreateVertexShader

Creates a vertex shader and if created successfully sets that shader as the current shader.

HRESULT CreateVertexShader(
  CONST DWORD* pDeclaration,
  CONST DWORD* pFunction,
  DWORD* pHandle,
  DWORD Usage
);

Parameters

pDeclaration
[in, out] Pointer to the vertex shader declaration token array. This parameter defines the inputs to the shader, including how the vertex elements within the input data streams are used by the shader.
pFunction
[in, out] Pointer to the vertex shader function token array. This parameter defines the operations to apply to each vertex. If this parameter is set to NULL, a shader is created for the fixed-function pipeline and the parameter declaration indicated by pDeclaration is made current and available to be set in a subsequent call to IDirect3DDevice8::SetVertexShader as long as a handle pointer is provided.

If this parameter is not set to NULL, the shader is programmable.

pHandle
[in, out] Pointer to the returned vertex shader handle. This value cannot be set as NULL.
Usage
[in] Usage controls for the vertex shader. The following flag can be set.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the vertex shader is to be used with software vertex processing. The D3DUSAGE_SOFTWAREPROCESSING flag must be set for vertex shaders used when the D3DRS_SOFTWAREVERTEXPROCESSING member of the D3DRENDERSTATETYPE enumerated type is TRUE, and removed for vertex shaders used when D3DRS_SOFTWAREVERTEXPROCESSING is FALSE.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Remarks

A vertex shader is defined by two token arrays that specify the declaration and function of the shader. The token arrays are composed of single or multiple DWORD tokens terminated by a special 0xFFFFFFFF token value.

The shader declaration defines the static external interface of the shader, including binding of stream data to vertex register inputs and values loaded into the shader constant memory. The shader function defines the operation of the shader as an array of instructions that are executed in order for each vertex processed during the time the shader is bound to a device. Shaders created without a function array apply the fixed function vertex processing when that shader is current.

See d3d8types.h for a definition of the macros used to generate the declaration token array.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::DeleteVertexShader, D3DXAssembleShader, D3DXAssembleShaderFromFileA, D3DXAssembleShaderFromFileW, D3DXDeclaratorFromFVF


IDirect3DDevice8::CreateVolumeTexture

Creates a volume texture resource.

HRESULT CreateVolumeTexture(
  UINT Width,
  UINT Height,
  UINT Depth,
  UINT Levels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  IDirect3DVolumeTexture8** ppVolumeTexture
);

Parameters

Width
[in] Width of the top-level of the volume texture, in pixels. This value must be a power of two. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by two results in 0 (zero), 1 will be taken instead.
Height
[in] Height of the top-level of the volume texture, in pixels. This value must be a power of two. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead.
Depth
[in] Depth of the top-level of the volume texture, in pixels. This value must be a power of two. The pixel dimensions of subsequent levels will be the truncated value of half of the previous level's pixel dimension (independently). Each dimension clamps at a size of 1 pixel. Thus, if the division by 2 results in 0 (zero), 1 will be taken instead.
Levels
[in] The number of levels in the texture. If this is zero, Microsoft® Direct3D® will generate all texture sub-levels down to 1×1×1 pixels for hardware that supports mipmapped volume textures. Otherwise, it will create one level. Call IDirect3DBaseTexture8::GetLevelCount to see the number of levels generated.
Usage
[in] Currently not used, set to 0.
Format
[in] Member of the D3DFORMAT enumerated type, describing the format of all levels in the volume texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.
ppVolumeTexture
[out, retval] Address of a pointer to an IDirect3DVolumeTexture8 interface, representing the created volume texture resource.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::DeletePixelShader

Deletes the pixel shader referred to by the specified handle.

HRESULT DeletePixelShader(
  DWORD Handle
);

Parameters

Handle
[in] Pixel shader handle, identifying the pixel shader to be deleted from its internal entry.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::CreatePixelShader


IDirect3DDevice8::DeleteStateBlock

Deletes a previously recorded device-state block.

HRESULT DeleteStateBlock(
  DWORD Token
);

Parameters

Token
[in] Handle to the device-state block to delete, as returned by a previous call to the IDirect3DDevice8::EndStateBlock method.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The value 0xFFFFFFFF is an invalid state block handle.

Applications cannot delete a device-state block while another is being recorded

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::ApplyStateBlock, IDirect3DDevice8::BeginStateBlock, IDirect3DDevice8::CaptureStateBlock, IDirect3DDevice8::CreateStateBlock, IDirect3DDevice8::EndStateBlock


IDirect3DDevice8::DeletePatch

Frees a cached high-order patch.

HRESULT DeletePatch(
  UINT Handle
);

Parameters

Handle
[in] Handle of the cached high-order patch to delete.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::DrawRectPatch, IDirect3DDevice8::DrawTriPatch, Drawing Patches


IDirect3DDevice8::DeleteVertexShader

Deletes the vertex shader referred to by the specified handle and frees up the associated resources.

HRESULT DeleteVertexShader(
  DWORD Handle
);

Parameters

Handle
[in] Vertex shader handle, identifying the vertex shader to be deleted.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::CreateVertexShader


IDirect3DDevice8::DrawIndexedPrimitive

Renders the specified geometric primitive, based on indexing into an array of vertices.

HRESULT DrawIndexedPrimitive(
  D3DPRIMITIVETYPE Type,
  UINT MinIndex,
  UINT NumVertices,
  UINT StartIndex,
  UINT PrimitiveCount
);

Parameters

Type
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render. See Remarks.
MinIndex
[in] Minimum vertex index for vertices used during this call.
NumVertices
[in] The number of vertices used during this call starting from BaseVertexIndex + MinIndex
StartIndex
[in] Location in the index array to start reading vertices.
PrimitiveCount
[in] Number of primitives to render. The number of vertices used is a function of the primitive count and the primitive type. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS8 structure.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method draws indexed primitives from the current set of data input streams.

MinIndex and all the indices in the index stream are relative to the BaseVertexIndex, set during the IDirect3DDevice8::SetIndices call.

The minIndex and NumVertices parameters specify the range of vertex indices used for each DrawIndexedPrimitive call. These are used to optimize vertex processing of indexed primitives by processing a sequential range of vertices prior to indexing into these vertices. It is invalid for any indices used during this call to reference any vertices outside of this range.

DrawIndexedPrimitive fails if no index array is set.

The D3DPT_POINTLIST member of the D3DPRIMITIVETYPE enumerated type is not supported and should not be specified for Type.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::DrawPrimitive, IDirect3DDevice8::SetStreamSource, Rendering Primitives


IDirect3DDevice8::DrawIndexedPrimitiveUP

Renders the specified geometric primitive with data specified by a user memory pointer.

HRESULT DrawIndexedPrimitiveUP(
  D3DPRIMITIVETYPE PrimitiveType,
  UINT MinIndex,
  UINT NumVertices,
  UINT PrimitiveCount,
  CONST void* pIndexData,
  D3DFORMAT IndexDataFormat,
  CONST void* pVertexStreamZeroData,
  UINT VertexStreamZeroStride
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
MinIndex
[in] Minimum vertex index, relative to zero (the start of pIndexData), for vertices used during this call.
NumVertices
[in] Number of vertices used during this call; starting from MinIndex.
PrimitiveCount
[in] Number of primitives to render. The number of indices used is a function of the primitive count and the primitive type. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS8 structure.
pIndexData
[in] User memory pointer to the index data.
IndexDataFormat
[in] Member of the D3DFORMAT enumerated type, describing the format of the index data. The valid settings are the following:
D3DFMT_INDEX16
Indices are 16 bits each.
D3DFMT_INDEX32
Indices are 32 bits each.
pVertexStreamZeroData
[in] User memory pointer to vertex data to use for vertex stream zero.
VertexStreamZeroStride
[in] Stride between data for each vertex, in bytes.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method is intended for use in applications that are unable to store their vertex data in vertex buffers. This method supports only a single vertex stream. The effect of this call is to use the provided vertex data pointer and stride for vertex stream zero. It is invalid to have the declaration of the current vertex shader refer to vertex streams other than stream zero.

Following any DrawIndexedPrimitiveUP call, the stream zero settings, referenced by IDirect3DDevice8::GetStreamSource, are set to NULL. Also, the index buffer setting for IDirect3DDevice8::SetIndices is set to NULL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::DrawPrimitiveUP, IDirect3DDevice8::SetStreamSource, Rendering Primitives


IDirect3DDevice8::DrawPrimitive

Renders a sequence of nonindexed, geometric primitives of the specified type from the current set of data input streams.

HRESULT DrawPrimitive(
  D3DPRIMITIVETYPE PrimitiveType,
  UINT StartVertex,
  UINT PrimitiveCount
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
StartVertex
[in] Index of the first vertex to load. Beginning at StartVertex the correct number of vertices will be read out of the vertex buffer.
PrimitiveCount
[in] Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS8 structure. PrimitiveCount is the number of primitives as determined by the primitive type. If it is a line list, each primitive has two vertices. If it is a triangle list, each primitive has three vertices.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

DrawPrimitive should not be called with a single triangle at a time.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::DrawIndexedPrimitive, IDirect3DDevice8::SetStreamSource, Rendering Primitives


IDirect3DDevice8::DrawPrimitiveUP

Renders data specified by a user memory pointer as a sequence of geometric primitives of the specified type.

HRESULT DrawPrimitiveUP(
  D3DPRIMITIVETYPE PrimitiveType,
  UINT PrimitiveCount,
  CONST void* pVertexStreamZeroData,
  UINT VertexStreamZeroStride
);

Parameters

PrimitiveType
[in] Member of the D3DPRIMITIVETYPE enumerated type, describing the type of primitive to render.
PrimitiveCount
[in] Number of primitives to render. The maximum number of primitives allowed is determined by checking the MaxPrimitiveCount member of the D3DCAPS8 structure.
pVertexStreamZeroData
[in] User memory pointer to vertex data to use for vertex stream zero.
VertexStreamZeroStride
[in] Stride between data for each vertex, in bytes.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method is intended for use in applications that are unable to store their vertex data in vertex buffers. This method supports only a single vertex stream. The effect of this call is to use the provided vertex data pointer and stride for vertex stream zero. It is invalid to have the declaration of the current vertex shader refer to vertex streams other than stream zero.

Following any DrawPrimitiveUP call, the stream zero settings, referenced by IDirect3DDevice8::GetStreamSource, are set to NULL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::DrawIndexedPrimitiveUP, IDirect3DDevice8::SetStreamSource, Rendering Primitives


IDirect3DDevice8::DrawRectPatch

Draws a rectangular high-order patch using the currently set streams.

HRESULT DrawRectPatch(
  UINT Handle,
  CONST float* pNumSegs,
  CONST D3DRECTPATCH_INFO* pRectPatchInfo
);

Parameters

Handle
[in] Handle to the rectangular high-order patch to draw.
pNumSegs
[in, out] Pointer to a floating-point value identifying the number of segments that each edge of the high-order primitive should be divided into when tessellated.
pRectPatchInfo
[in, out] Pointer to a D3DRECTPATCH_INFO structure, describing the rectangular high-order patch to draw.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::DeletePatch, Drawing Patches


IDirect3DDevice8::DrawTriPatch

Draws a triangular high-order patch using the currently set streams.

HRESULT DrawTriPatch(
  UINT Handle,
  CONST float* pNumSegs,
  CONST D3DTRIPATCH_INFO* pTriPatchInfo
);

Parameters

Handle
[in] Handle to the triangular high-order patch to draw.
pNumSegs
[in, out] Pointer to a floating-point value identifying the number of segments that each edge of the high-order primitive should be divided into when tessellated.
pTriPatchInfo
[in, out] Pointer to a D3DTRIPATCH_INFO structure, describing the triangular high-order patch to draw.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::DeletePatch, Drawing Patches


IDirect3DDevice8::EndScene

Ends a scene that was begun by calling the IDirect3DDevice8::BeginScene method.

HRESULT EndScene();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When this method succeeds, the scene has been rendered and the device surface holds the rendered scene.

When scene rendering begins successfully, you must call this method before you can call the IDirect3DDevice8::BeginScene method to start rendering another scene. If a prior call to BeginScene method fails, the scene did not begin and this method should not be called.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::BeginScene


IDirect3DDevice8::EndStateBlock

Signals Microsoft® Direct3D® to stop recording a device-state block and retrieve a handle to the state block.

HRESULT EndStateBlock(
  DWORD* pToken
);

Parameters

pToken
[out, retval] Pointer to a variable to fill with the handle to the completed device-state block. This value is used with the IDirect3DDevice8::ApplyStateBlock and IDirect3DDevice8::DeleteStateBlock methods.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

Remarks

The value 0xFFFFFFFF is an invalid state block handle.

See Also

IDirect3DDevice8::ApplyStateBlock, IDirect3DDevice8::BeginStateBlock, IDirect3DDevice8::CaptureStateBlock, IDirect3DDevice8::CreateStateBlock, IDirect3DDevice8::DeleteStateBlock


IDirect3DDevice8::GetAvailableTextureMem

Returns an estimate of the amount of available texture memory.

UINT GetAvailableTextureMem();

Parameters

None.

Return Values

The function returns an estimate of the available texture memory.

Remarks

The returned value is rounded to the nearest MB. This is done to reflect the fact that video memory estimates are never precise due to alignment and other issues that affect consumption by certain resources. Applications can use this value to make gross estimates of memory availability to make large-scale resource decisions such as how many levels of a mipmap to attempt to allocate, but applications cannot use this value to make small-scale decisions such as if there is enough memory left to allocate another resource.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::GetBackBuffer

Retrieves a back buffer from the device's swap chain.

HRESULT GetBackBuffer(
  UINT BackBuffer,
  D3DBACKBUFFER_TYPE Type,
  IDirect3DSurface8** ppBackBuffer
);

Parameters

BackBuffer
[in] Index of the back buffer object to return. Back buffers are numbered from 0 to the total number of back buffers - 1. A value of 0 returns the first back buffer, not the front buffer. The front buffer is not accessible through this method.
Type
[in] Stereo view is not supported in DirectX 8.0, so the only valid value for this parameter is D3DBACKBUFFER_TYPE_MONO.
ppBackBuffer
[out, retval] Address of a pointer to an IDirect3DSurface8 interface, representing the returned back buffer surface.

Return Values

If the method succeeds, the return value is D3D_OK.

If BackBuffer exceeds or equals the total number of back buffers, then the function fails and returns D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DSurface8 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::GetClipPlane

Retrieves the coefficients of a user-defined clipping plane for the device.

HRESULT GetClipPlane(
  DWORD Index,
  float* pPlane
);

Parameters

Index
[in] Index of the clipping plane for which the plane equation coefficients are retrieved.
pPlane
[out] Pointer to a four-element array of values that represent the coefficients of the clipping plane in the form of the general plane equation. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is D3DERR_INVALIDCALL. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device, or that the array at pPlane is not large enough to contain four floating-point values.

Remarks

The coefficients that this method reports take the form of the general plane equation. If the values in the array at pPlane were labeled A, B, C, and D in the order that they appear in the array, they would fit into the general plane equation so that Ax + By + Cz + Dw = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist on or behind the clipping plane are clipped from the scene.

The plane equation used by this method exists in world space and is set by a previous call to the IDirect3DDevice8::SetClipPlane method.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetClipPlane


IDirect3DDevice8::GetClipStatus

Retrieves the clip status.

HRESULT GetClipStatus(
  D3DCLIPSTATUS8* pClipStatus
);

Parameters

pClipStatus
[out] Pointer to a D3DCLIPSTATUS8 structure that describes the clip status.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetClipStatus


IDirect3DDevice8::GetCreationParameters

Retrieves the creation parameters of the device.

HRESULT GetCreationParameters(
  D3DDEVICE_CREATION_PARAMETERS* pParameters
);

Parameters

pParameters
[out] Pointer to a D3DDEVICE_CREATION_PARAMETERS structure, describing the creation parameters of the device.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Remarks

You can query the AdapterOrdinal member of the returned D3DDEVICE_CREATION_PARAMETERS structure to retrieve the ordinal of the adapter represented by this device.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::GetCurrentTexturePalette

Retrieves the current texture palette.

HRESULT GetCurrentTexturePalette(
  UINT* pPaletteNumber
);

Parameters

pPaletteNumber
[out, retval] Pointer to a returned value that identifies the current texture palette.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetCurrentTexturePalette, Texture Palettes


IDirect3DDevice8::GetDepthStencilSurface

Retrieves the depth-stencil surface owned by the Direct3DDevice object.

HRESULT GetDepthStencilSurface(
  IDirect3DSurface8** ppZStencilSurface
);

Parameters

ppZStencilSurface
[out, retval] Address of a pointer to an IDirect3DSurface8 interface, representing the returned depth-stencil surface.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DSurface8 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetRenderTarget, IDirect3DDevice8::CopyRects


IDirect3DDevice8::GetDeviceCaps

Retrieves the capabilities of the rendering device.

HRESULT GetDeviceCaps(
  D3DCAPS8* pCaps
);

Parameters

pCaps
[out] Pointer to a D3DCAPS8 structure, describing the returned device.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

GetDeviceCaps retrieves the software vertex pipeline capabilities when the device is being used in software vertex processing mode. Software vertex processing mode is selected when a device has been created with D3DCREATE_SOFTWAREVERTEXPROCESSING, or when a device has been created with D3DCREATE_MIXEDVERTEXPROCESSING and D3DRS_SOFTWAREVERTEXPROCESSING is set to TRUE.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::GetDirect3D

Returns an interface to the instance of the Microsoft® Direct3D® object that created the device.

HRESULT GetDirect3D(
  IDirect3D8** ppD3D8
);

Parameters

ppD3D8
[out, retval] Address of a pointer to an IDirect3D8 interface, representing the interface of the Direct3D object that created the device.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Calling GetDirect3D increases the reference count on the interface, so applications should call IUnknown::Release through this pointer when finished with the interface.

Note Calling this method will increase the internal reference count on the IDirect3D8 interface. Failure to call IUnknown::Release when finished using this IDirect3D8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::GetDisplayMode

Retrieves the display mode's spatial resolution, color resolution, and refresh frequency.

HRESULT GetDisplayMode(
  D3DDISPLAYMODE* pMode
);

Parameters

pMode
[out] Pointer to a D3DDISPLAYMODE structure containing data about the display mode of the adapter. As opposed to the display mode of the device, which may not be active if the device does not own full-screen mode.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::GetFrontBuffer

Generates a copy of the device's front buffer and places that copy in a system memory buffer provided by the application.

HRESULT GetFrontBuffer(
  IDirect3DSurface8* pDestSurface
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface8 interface that will receive a copy of the contents of the front buffer. The data is returned in successive rows with no intervening space, starting from the vertically highest row on the device's output to the lowest.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

If the method fails, the return value can be one of the following values.

D3DERR_DEVICELOST
D3DERR_INVALIDCALL

Remarks

The buffer pointed to by pDestSurface will be filled with a representation of the front buffer, converted to the standard 32bpp format, D3DFMT_A8R8G8B8.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::GetGammaRamp

Retrieves the gamma correction ramp for the swap chain.

void GetGammaRamp(
  D3DGAMMARAMP* pRamp
);

Parameters

pRamp
[in, out] Pointer to an application-supplied D3DGAMMARAMP structure to fill with the gamma correction ramp.

Return Values

None.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DSwapChain8, IDirect3DDevice8::SetGammaRamp


IDirect3DDevice8::GetIndices

Retrieves index data.

HRESULT GetIndices(
  IDirect3DIndexBuffer8** ppIndexData,
  UINT* pBaseVertexIndex
);

Parameters

ppIndexData
[out] Address of a pointer to an IDirect3DIndexBuffer8 interface, representing the returned index data.
pBaseVertexIndex
[out] Pointer to a UINT value, holding the returned base value for vertex indices. This value is added to all indices prior to referencing vertex data, defining a starting position in the vertex streams.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The values in the index list are used to index into a vertex list when creating geometry to render.

The value returned in the pBaseVertexIndex parameter specifies the base value for indices. This base value is added to all indices prior to referencing into the vertex data streams, the result of which is to set a starting position in the vertex data streams. The base vertex index enables multiple indexed primitives to be packed into a single set of vertex data without requiring the indices to be recomputed based on where the corresponding primitive is placed in the vertex data.

Note Calling this method will increase the internal reference count on the IDirect3DIndexBuffer8 interface. Failure to call IUnknown::Release when finished using this IDirect3DIndexBuffer8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetIndices


IDirect3DDevice8::GetInfo

Retrieves information about the rendering device.

HRESULT GetInfo(
  DWORD DevInfoID,
  VOID* pDevInfoStruct,
  DWORD DevInfoStructSize
);

Parameters

DevInfoID
[in] Value used to identify what information will be returned in pDevInfoStruct.
pDevInfoStruct
[in, out] Pointer to a structure that receives the specified device information if the call succeeds.
DevInfoStructSize
[in] Size of the structure at pDevInfoStruct, in bytes.

Return Values

If the method succeeds, the return value is D3D_OK. This method returns S_FALSE on retail builds of Microsoft® DirectX® (see Remarks).

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Information returned by this method can pertains to the underlying device driver. This method makes it possible for drivers to declare specific information types, and corresponding structures, that are not documented in this SDK.

This method executes synchronously and can negatively impact an application's performance when it executes slowly. Do not call this method during scene rendering (between calls to IDirect3DDevice8::BeginScene and IDirect3DDevice8::EndScene).

This method is intended to be used for performance tracking and debugging during product development (on the debug version of DirectX). The method can succeed, returning S_FALSE, without retrieving device data. This occurs when the retail version of the DirectX runtime is installed on the host system.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::GetLight

Retrieves a set of lighting properties that this device uses.

HRESULT GetLight(
  DWORD Index,
  D3DLIGHT8* pLight
);

Parameters

Index
[in] Zero-based index of the lighting property set to retrieve.
pLight
[out] Pointer to a D3DLIGHT8 structure that is filled with the retrieved lighting-parameter set.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if the pLight parameter is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetLight, IDirect3DDevice8::GetLightEnable, IDirect3DDevice8::LightEnable


IDirect3DDevice8::GetLightEnable

Retrieves the activity status—enabled or disabled—for a set of lighting parameters within a device.

HRESULT GetLightEnable(
  DWORD Index,
  BOOL* pEnable
);

Parameters

Index
[in] Zero-based index of the set of lighting parameters that are the target of this method.
pEnable
[out, retval] Pointer to a variable to fill with the status of the specified lighting parameters. After the call, a nonzero value at this address indicates that the specified lighting parameters are enabled; a value of 0 indicates that they are disabled.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetLight, IDirect3DDevice8::LightEnable, IDirect3DDevice8::SetLight


IDirect3DDevice8::GetMaterial

Retrieves the current material properties for the device.

HRESULT GetMaterial(
  D3DMATERIAL8*pMaterial
);

Parameters

pMaterial
[out] Pointer to a D3DMATERIAL8 structure to fill with the currently set material properties.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if the pMaterial parameter is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetMaterial


IDirect3DDevice8::GetPaletteEntries

Retrieves palette entries.

HRESULT GetPaletteEntries(
  UINT PaletteNumber,
  PALETTEENTRY* pEntries
);

Parameters

PaletteNumber
[in] An ordinal value identifying the particular palette to retrieve.
pEntries
[in, out] Pointer to a PALETTEENTRY structure, representing the returned palette entries. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

For more information on PALETTEENTRY see the Microsoft® Platform Software Development Kit (SDK). Note that as of DirectX 8.0 the peFlags member of the PALETTEENTRY structure does not work the way it is documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetCurrentTexturePalette, IDirect3DDevice8::SetCurrentTexturePalette, IDirect3DDevice8::SetPaletteEntries, Texture Palettes


IDirect3DDevice8::GetPixelShader

Retrieves the currently set pixel shader.

HRESULT GetPixelShader(
   DWORD* pHandle
);

Parameters

pHandle
[out, retval] Pointer to a pixel shader handle, representing the returned the pixel shader.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetPixelShader


IDirect3DDevice8::GetPixelShaderConstant

Retrieves the values in the pixel constant array.

HRESULT GetPixelShaderConstant(
   DWORD Register,
   void* pConstantData,
   DWORD ConstantCount
);

Parameters

Register
[in] Register address at which to start retrieving data from the pixel constant array.
pConstantData
[in, out] Pointer to the data block to hold the retrieved values from the pixel constant array. The size of the data block is (ConstantCount * 4 * sizeof(float)).
ConstantCount
[in] Number of constants to retrieve from the pixel constant array. Each constant is comprised of four floating-point values.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This is the method used to retrieve the values in the constant registers of the pixel shader assembler.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetPixelShaderConstant


IDirect3DDevice8::GetPixelShaderFunction

Retrieves the pixel shader function.

HRESULT GetPixelShaderFunction(
   DWORD Handle,
   void* pData,
   DWORD* pSizeOfData
);

Parameters

Handle
[in] Handle to the referred to pixel shader.
pData
[out] Pointer to a previously allocated buffer to be filled with the code associated with the requested pixel shader handle, if the call succeeds. The application calling this method in responsible for allocating and releasing this buffer.
pSizeOfData
[in, out] Pointer to a DWORD value, indicating the size of the buffer at pData, in bytes. If this value is less than the actual size of the data (such as 0) the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA. If the buffer is NULL, then this parameter is filled with the required size and D3D_OK is returned.

Return Values

If the method succeeds, the return value is D3D_OK.

The return value can be D3DERR_INVALIDCALL if Handle is an invalid handle to a pixel shader.

Remarks

The pixel shader function specifies blending operations.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetPixelShader


IDirect3DDevice8::GetRasterStatus

Returns information describing the raster of the monitor on which the swap chain is presented.

HRESULT GetRasterStatus(
  D3DRASTER_STATUS* pRasterStatus
);

Parameters

pRasterStatus
[out] Pointer to a D3DRASTER_STATUS structure filled with information about the position or other status of the raster on the monitor driven by this adapter.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if pRasterStatus is invalid or if the device does not support reading the current scan line. To determine whether or not the device supports reading the scan line, check for the D3DCAPS_READ_SCANLINE flag in the Caps member of D3DCAPS8.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

D3DRASTER_STATUS


IDirect3DDevice8::GetRenderState

Retrieves a render-state value for a device.

HRESULT GetRenderState(
  D3DRENDERSTATETYPE State,
  DWORD* pValue
);

Parameters

State
[in] Device state variable that is being queried. This parameter can be any member of the D3DRENDERSTATETYPE enumerated type.
pValue
[out, retval] Pointer to a variable that receives the value of the queried render state variable when the method returns.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetRenderState


IDirect3DDevice8::GetRenderTarget

Retrieves a pointer to the Microsoft® Direct3D® surface that is being used as a render target.

HRESULT GetRenderTarget(
  IDirect3DSurface8** ppRenderTarget
);

Parameters

ppRenderTarget
[out, retval] Address of a pointer to an IDirect3DSurface8 interface, representing the returned render target surface for this device.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Note Calling this method will increase the internal reference count on the IDirect3DSurface8 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetRenderTarget


IDirect3DDevice8::GetStreamSource

Retrieves a vertex buffer bound to the specified data stream.

HRESULT GetStreamSource(
   UINT StreamNumber
   IDirect3DVertexBuffer8** ppStreamData,
   UINT* pStride
);

Parameters

StreamNumber
[in] Specifies the data stream, in the range from 0 to the maximum number of streams - 1.
ppStreamData
[in, out] Address of a pointer to an IDirect3DVertexBuffer8 interface, representing the returned vertex buffer bound to the specified data stream.
pStride
[in, out] Pointer to a returned stride of the component, in bytes. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A stream is defined as a uniform array of component data, where each component consists of one or more elements representing a single entity such as position, normal, color, and so on.

Note Calling this method will increase the internal reference count on the IDirect3DVertexBuffer8 interface. Failure to call IUnknown::Release when finished using this IDirect3DVertexBuffer8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetStreamSource


IDirect3DDevice8::GetTexture

Retrieves a texture assigned to a stage for a device.

HRESULT GetTexture(
  DWORD Stage,
  IDirect3DBaseTexture8** ppTexture
);

Parameters

Stage
[in] Stage identifier of the texture to retrieve. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum value allowed for Stage is 7.
ppTexture
[out, retval] Address of a pointer to an IDirect3DBaseTexture8 interface, representing the returned texture.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DTexture8 interface. Failure to call IUnknown::Release when finished using this IDirect3DTexture8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetTexture, IDirect3DDevice8::GetTextureStageState, IDirect3DDevice8::SetTextureStageState


IDirect3DDevice8::GetTextureStageState

Retrieves a state value for an assigned texture.

HRESULT GetTextureStageState(
  DWORD Stage,
  D3DTEXTURESTAGESTATETYPE Type,
  DWORD* pValue
);

Parameters

Stage
[in] Stage identifier of the texture for which the state is retrieved. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum value allowed for Stage is 7.
Type
[in] Texture state to retrieve. This parameter can be any member of the D3DTEXTURESTAGESTATETYPE enumerated type.
pValue
[out, retval] Pointer a variable to fill with the retrieved state value. The meaning of the retrieved value is determined by the Type parameter.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetTextureStageState, IDirect3DDevice8::GetTexture, IDirect3DDevice8::SetTexture


IDirect3DDevice8::GetTransform

Retrieves a matrix describing a transformation state.

HRESULT GetTransform(
  D3DTRANSFORMSTATETYPE State,
  D3DMATRIX* pMatrix
);

Parameters

State
[in] Device state variable that is being modified. This parameter can be any member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro.
pMatrix
[out] Pointer to a D3DMATRIX structure, describing the returned transformation state.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetTransform


IDirect3DDevice8::GetVertexShader

Retrieves the currently set vertex shader.

HRESULT GetVertexShader(
   DWORD* pHandle
);

Parameters

pHandle
[out, retval] Pointer to a vertex shader handle, representing the returned vertex shader.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if pHandle is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetVertexShader


IDirect3DDevice8::GetVertexShaderConstant

Retrieves the values in the vertex constant array.

HRESULT GetVertexShaderConstant(
   DWORD Register,
   void* pConstantData,
   DWORD ConstantCount
);

Parameters

Register
[in] Register address at which to start retrieving data from the vertex constant array.
pConstantData
[out] Pointer to the data block to hold the retrieved values from the vertex constant array. The size of the data block is (ConstantCount * 4 * sizeof(float)).
ConstantCount
[in] Number of constants to retrieve from the vertex constant array. Each constant is comprised of four floating-point values.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This is the method used to retrieve the values in the constant registers of the vertex shader assembler.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetVertexShaderConstant


IDirect3DDevice8::GetVertexShaderDeclaration

Retrieves the vertex shader declaration token array.

HRESULT GetVertexShaderDeclaration(
   DWORD Handle,
   void* pData,
   DWORD* pSizeOfData
);

Parameters

Handle
[in] Handle to the referred to vertex shader.
pData
[in] Pointer to a previously allocated buffer to be filled with the declaration associated with the requested vertex shader handle, if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer.
pSizeOfData
[in, out] Pointer to a DWORD value, indicating the size of the buffer at pData, in bytes. If this value is less than the actual size of the data (such as 0) the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA. If the buffer is NULL, then this parameter is filled with the required size and D3D_OK is returned.

Return Values

If the method succeeds, the return value is D3D_OK.

The return value can be D3DERR_INVALIDCALL if Handle is an invalid handle to a vertex shader.

Remarks

The vertex shader declaration token array defines the inputs to the shader, including how the vertex elements within the input data streams are used by the shader.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetVertexShader


IDirect3DDevice8::GetVertexShaderFunction

Retrieves the vertex shader function.

HRESULT GetVertexShaderFunction(
   DWORD Handle,
   void* pData,
   DWORD* pSizeOfData
);

Parameters

Handle
[in] Handle to the referred to vertex shader.
pData
[out] Pointer to a previously allocated buffer to be filled with the code associated with the requested vertex shader handle, if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer.
pSizeOfData
[in, out] Pointer to a DWORD value, indicating the size of the buffer at pData, in bytes. If this value is less than the actual size of the data (such as 0) the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA. If the buffer is NULL, then this parameter is filled with the required size and D3D_OK is returned.

Return Values

If the method succeeds, the return value is D3D_OK.

The return value can be D3DERR_INVALIDCALL if Handle is an invalid handle to a vertex shader.

Remarks

The vertex shader function defines the operation to apply to each vertex.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetVertexShader


IDirect3DDevice8::GetViewport

Retrieves the viewport parameters currently set for the device.

HRESULT GetViewport(
  D3DVIEWPORT8* pViewport
);

Parameters

pViewport
[out] Pointer to a D3DVIEWPORT8 structure, representing the returned viewport parameters.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the pViewport parameter is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetViewport


IDirect3DDevice8::LightEnable

Enables or disables a set of lighting parameters within a device.

HRESULT LightEnable(
  DWORD LightIndex,
  BOOL bEnable
);

Parameters

LightIndex
[in] Zero-based index of the set of lighting parameters that are the target of this method.
bEnable
[in] Value that indicates if the set of lighting parameters are being enabled or disabled. Set this parameter to TRUE to enable lighting with the parameters at the specified index, or FALSE to disable it.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If a value for LightIndex is outside the range of the light property sets assigned within the device, the LightEnable method creates a light source represented by a D3DLIGHT8 structure with the following properties and sets its enabled state to the value specified in bEnable.

Member | Default
Type | D3DLIGHT_DIRECTIONAL
Diffuse | (R:1, G:1, B:1, A:0)
Specular | (R:0, G:0, B:0, A:0)
Ambient | (R:0, G:0, B:0, A:0)
Position | (0, 0, 0)
Direction | (0, 0, 1)
Range | 0
Falloff | 0
Attenuation0 | 0
Attenuation1 | 0
Attenuation2 | 0
Theta | 0
Phi | 0

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetLight, IDirect3DDevice8::GetLightEnable, IDirect3DDevice8::SetLight


IDirect3DDevice8::MultiplyTransform

Multiplies a device's world, view, or projection matrices by a specified matrix.

HRESULT MultiplyTransform(
  D3DTRANSFORMSTATETYPE State,
  CONST D3DMATRIX* pMatrix
);

Parameters

State
[in] Member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro that identifies which device matrix is to be modified. The most common setting, D3DTS_WORLDMATRIX(0), modifies the world matrix, but you can specify that the method modify the view or projection matrices, if needed.
pMatrix
[in] Pointer to a D3DMATRIX structure that modifies the current transformation.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Remarks

The multiplication order is pMatrix times State.

An application might use the MultiplyTransform method to work with hierarchies of transformations. For example, the geometry and transformations describing an arm might be arranged in the following hierarchy.

shoulder_transformation
    upper_arm geometry
    elbow transformation
        lower_arm geometry
        wrist transformation
            hand geometry

An application might use the following series of calls to render this hierarchy. Not all the parameters are shown in this pseudocode.

IDirect3DDevice8::SetTransform(D3DTS_WORLDMATRIX(0),
    shoulder_transform)
IDirect3DDevice8::DrawPrimitive(upper_arm)
IDirect3DDevice8::MultiplyTransform(D3DTS_WORLDMATRIX(0),
    elbow_transform)
IDirect3DDevice8::DrawPrimitive(lower_arm)
IDirect3DDevice8::MultiplyTransform(D3DTS_WORLDMATRIX(0),
    wrist_transform)
IDirect3DDevice8::DrawPrimitive(hand)

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::DrawPrimitive, IDirect3DDevice8::SetTransform, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX


IDirect3DDevice8::Present

Presents the contents of the next in the sequence of back buffers owned by the device.

HRESULT Present(
  CONST RECT* pSourceRect,
  CONST RECT* pDestRect,
  HWND hDestWindowOverride,
  CONST RGNDATA* pDirtyRegion
);

Parameters

pSourceRect
[in] Pointer to a value that must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY or D3DSWAPEFFECT_COPY_VSYNC. pSourceRectis a pointer to a RECT structure containing the source rectangle. If NULL, the entire source surface is presented. If the rectangle exceeds the source surface, the rectangle is clipped to the source surface.
pDestRect
[in] Pointer to a value that must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY or D3DSWAPEFFECT_COPY_VSYNC. PDestRect is a pointer to a RECT structure containing the destination rectangle, in window client coordinates. If NULL, the entire client area is filled. If the rectangle exceeds the destination client area, the rectangle is clipped to the destination client area.
hDestWindowOverride
[in] Pointer to a destination window whose client area is taken as the target for this presentation. If this value is NULL, then the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is taken.
pDirtyRegion
[in] This parameter is not used and should be set to NULL.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_DEVICELOST

Remarks

If necessary, a stretch operation is applied to transfer the pixels within the source rectangle to the destination rectangle in the client area of the target window.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::Reset


IDirect3DDevice8::ProcessVertices

Applies the vertex processing defined by the vertex shader to the set of input data streams, generating a single stream of interleaved vertex data to the destination vertex buffer.

HRESULT ProcessVertices(
  UINT SrcStartIndex,
  UINT DestIndex,
  UINT VertexCount,
  IDirect3DVertexBuffer8* pDestBuffer,
  DWORD Flags
);

Parameters

SrcStartIndex
[in] Index of first vertex to be loaded.
DestIndex
[in] Index of first vertex in the destination vertex buffer into which the results are placed.
VertexCount
[in] Number of vertices to process.
pDestBuffer
[in] Pointer to an IDirect3DVertexBuffer8 interface, the destination vertex buffer representing the stream of interleaved vertex data.
Flags
[in] Processing options. Set this parameter to 0 for default processing. Set to D3DPV_DONOTCOPYDATA to prevent the system from copying vertex data not affected by the vertex operation into the destination buffer.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The destination vertex buffer, pDestBuffer, must be created with a nonzero FVF parameter. The FVF code specified during the call to the IDirect3DDevice8::CreateVertexBuffer method specifies the vertex elements present in the destination vertex buffer.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

Device Types and Vertex Processing Requirements


IDirect3DDevice8::Reset

Resets the type, size, and format of the swap chain.

HRESULT Reset(
  D3DPRESENT_PARAMETERS* pPresentationParameters
);

Parameters

pPresentationParameters
[in] Pointer to a D3DPRESENT_PARAMETERS structure, describing the new presentation parameters. This value cannot be NULL.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Remarks

If a call to Reset fails, the device will be placed in the "lost" state (as indicated by a return value of D3DERR_DEVICELOST from a call to IDirect3DDevice::TestCooperativeLevel) unless it is already in the "not reset" state (as indicated by a return value of D3DERR_DEVICENOTRESET from a call to IDirect3DDevice8::TestCooperativeLevel). Refer to IDirect3DDevice8::TestCooperativeLevel and Lost Devices for further information concerning the use of Reset in the context of lost devices.

Calling Reset causes all texture memory surfaces to be lost, managed textures to be flushed from video memory, and all state information to be lost. Before calling the Reset method for a device, an application should release any explicit render targets, depth stencil surfaces, additional swap chains and D3DPOOL_DEFAULT resources associated with the device.

The different types of swap chains are full-screen or windowed. If the new swap chain is full-screen, the adapter will be placed in the display mode that matches the new size.

DirectX 8.0 applications can expect messages to be sent to them during this call (for example, before this call is returned); applications should take precautions not to call into Direct3D at this time. In addition, when Reset fails, the only valid methods that can be called are Reset, IDirect3DDevice8::TestCooperativeLevel, and the various Release member functions. Calling any other method may result in an exception.

A call to Reset will fail if called on a different thread than that used to create the device being reset.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

D3DSWAPEFFECT, D3DPRESENT_PARAMETERS, IDirect3DDevice8::Present


IDirect3DDevice8::ResourceManagerDiscardBytes

Invokes the resource manager to free memory.

HRESULT ResourceManagerDiscardBytes(
  DWORD Bytes
);

Parameters

Bytes
[in] The number of target bytes to discard. If zero, then the resource manager should discard all bytes.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The resource manager frees up memory allocations until the number of target bytes is reached. The resource manager follows a least-recently-used (LRU) priority technique.

Note that the number of bytes freed are not guaranteed to be contiguous. Therefore you might not be able to create a resource that takes the number of bytes specified in Bytes after calling this method.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::SetClipPlane

Sets the coefficients of a user-defined clipping plane for the device.

HRESULT SetClipPlane(
  DWORD Index,
  CONST float* pPlane
);

Parameters

Index
[in] Index of the clipping plane for which the plane equation coefficients are to be set.
pPlane
[in] Pointer to an address of a four-element array of values that represent the clipping plane coefficients to be set, in the form of the general plane equation. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value is D3DERR_INVALIDCALL. This error indicates that the value in Index exceeds the maximum clipping plane index supported by the device or that the array at pPlane is not large enough to contain four floating-point values.

Remarks

The coefficients that this method sets take the form of the general plane equation. If the values in the array at pPlane were labeled A, B, C, and D in the order that they appear in the array, they would fit into the general plane equation so that Ax + By + Cz + Dw = 0. A point with homogeneous coordinates (x, y, z, w) is visible in the half space of the plane if Ax + By + Cz + Dw >= 0. Points that exist on or behind the clipping plane are clipped from the scene.

When the fixed function pipeline is used the plane equations are assumed to be in world space. When the programmable pipeline is used the plane equations are assumed to be in the clipping space (the same space as output vertices).

This method does not enable the clipping plane equation being set. To enable a clipping plane, set the corresponding bit in the DWORD value applied to the D3DRS_CLIPPLANEENABLE render state.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetClipPlane


IDirect3DDevice8::SetClipStatus

Sets the clip status.

HRESULT SetClipStatus(
  CONST D3DCLIPSTATUS8* pClipStatus
);

Parameters

pClipStatus
[in] Pointer to a D3DCLIPSTATUS8 structure, describing the clip status settings to be set.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if one of the arguments is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetClipStatus


IDirect3DDevice8::SetCurrentTexturePalette

Sets the current texture palette.

HRESULT SetCurrentTexturePalette(
  UINT PaletteNumber
);

Parameters

PaletteNumber
[in] Value that specifies the texture palette to set as the current texture palette.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A single logical palette is associated with the device, and is shared by all texture stages.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetCurrentTexturePalette, Texture Palettes


IDirect3DDevice8::SetCursorPosition

Sets the cursor position and update options.

void SetCursorPosition(
  UINT XScreenSpace,
  UINT YScreenSpace,
  DWORD Flags
);

Parameters

XScreenSpace
[in] The new X-position of the cursor in screen-space coordinates. See Remarks.
YScreenSpace
[in] The new Y-position of the cursor in screen-space coordinates. See Remarks.
Flags
[in] Specifies the update options for the cursor. Currently, only one flag is defined.
D3DCURSOR_IMMEDIATE_UPDATE
Update cursor at the refresh rate.

If this flag is specified, the system guarantees that the cursor will be updated at a minimum of half the display refresh rate, but never more frequently than the display refresh rate. Otherwise, the method delays cursor updates until the next IDirect3DDevice8::Present call. This default behavior usually results in better performance than if the flag had been set. However, applications should set this flag if the rate of calls to Present is high enough that users would notice a significant delay in cursor motion.

Return Values

None.

Remarks

When running in full-screen mode, screen-space coordinates are the back-buffer coordinates appropriately scaled to the current display mode. When running in windowed mode, screen-space coordinates are the desktop coordinates. The cursor image is drawn at the specified position minus the hotspot offset specified by the IDirect3DDevice8::SetCursorProperties method.

If the cursor has been hidden by IDirect3DDevice8::ShowCursor, then the cursor is not drawn.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetCursorProperties, IDirect3DDevice8::ShowCursor


IDirect3DDevice8::SetCursorProperties

Sets properties for the cursor.

HRESULT SetCursorProperties(
  UINT XHotSpot,
  UINT YHotSpot,
  IDirect3DSurface8* pCursorBitmap
);

Parameters

XHotSpot
[in] X-coordinate offset into the cursor, in pixels from the top-left corner, that is considered the center. When the cursor is given a new position, the image is drawn at an offset from this new position determined by subtracting the hot spot coordinates from the position.
YHotSpot
[in] Y-coordinate offset into the cursor, in pixels from the top-left corner, that is considered the center. When the cursor is given a new position, the image is drawn at an offset from this new position determined by subtracting the hot spot coordinates from the position.
pCursorBitmap
[in] Pointer to an IDirect3DSurface8 interface. This parameter must point to an 8888 ARGB surface (format D3DFORMAT_A8R8G8B8). The contents of this surface will be copied and potentially format-converted into an internal buffer from which the cursor is displayed. The dimensions of this surface must be less than the dimensions of the display mode, and must be a power of two in each direction, although not necessarily the same power of two. The alpha channel must be either 0.0 or 1.0.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Microsoft® Direct3D® cursor functions use either GDI cursor or software emulation, depending on the hardware. Users usually want to respond to a WM_SETCURSOR message. For example, the users might want to write the message handler like this:

case WM_SETCURSOR:
    // Turn off window cursor
    SetCursor( NULL );
    m_pd3dDevice->ShowCursor( TRUE );
    return TRUE; // prevent Windows from setting cursor to window class cursor
break;

Or users might want to call the IDirect3DDevice8::SetCursorProperties method if they want to change the cursor. See the sample code in the Microsoft DirectX® Graphics C/C++ Samples for more details.

The application can determine what hardware support is available for cursors by examining appropriate members of the D3DCAPS8 structure. Typically, hardware supports only 32x32 cursors. Additionally, when windowed, the system may support only 32x32 cursors. In this case, SetCursorProperties still succeeds, but the cursor may be reduced to that size—the hot spot is scaled appropriately.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetCursorPosition, IDirect3DDevice8::ShowCursor, D3DCAPS8


IDirect3DDevice8::SetGammaRamp

Sets the gamma correction ramp for the implicit swap chain.

void SetGammaRamp(
  DWORD Flags,
  CONST D3DGAMMARAMP* pRamp
);

Parameters

Flags
[in] Indicates whether correction should be applied. Gamma correction results in a more consistent display, but can incur processing overhead and should not be used frequently. Short-duration effects such as flashing the whole screen red should not be calibrated, but long-duration gamma changes should be calibrated. One of the following values can be set.
D3DSGR_CALIBRATE
If a gamma calibrator is installed, the ramp will be modified before being sent to the device to account for the system and monitor response curves.

If a calibrator is not installed, the ramp will be passed directly to the device.

D3DSGR_NO_CALIBRATION
No gamma correction is applied. The supplied gamma table is transferred directly to the device.
pRamp
[in] Pointer to a D3DGAMMARAMP structure, representing the gamma correction ramp to be set for the implicit swap chain.

Return Values

None.

Remarks

There is always at least one swap chain (the implicit swap chain) for each device, because Microsoft® Direct3D® for Microsoft DirectX® 8.0 has one swap chain as a property of the device.

Because the gamma ramp is a property of the swap chain, the gamma ramp may be applied when the swap chain is windowed.

The gamma ramp takes effect immediately. No wait for VSYNC is performed.

If the device does not support gamma ramps in the swap chain's current presentation mode (full-screen or windowed), no error return is given. Applications can check the D3DCAPS2_FULLSCREENGAMMA and D3DCAPS2_CANCALIBRATEGAMMA capability bits in the Caps2 member of the D3DCAPS8 structure to determine the capabilities of the device and whether a calibrator is installed.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DSwapChain8, IDirect3DDevice8::GetGammaRamp


IDirect3DDevice8::SetIndices

Sets index data.

HRESULT SetIndices(
  IDirect3DIndexBuffer8* pIndexData
  UINT BaseVertexIndex
);

Parameters

pIndexData
[in] Pointer an IDirect3DIndexBuffer8 interface, representing the index data to be set.
BaseVertexIndex
[in] Base value for vertex indices. This value is added to all indices prior to referencing vertex data, defining a starting position in the vertex streams.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The SetIndices method sets the current index array to an index buffer. The single set of indices is used to index all streams.

The BaseVertexIndex parameter specifies the base value for indices. This base value is added to all indices prior to referencing into the vertex data streams, the result of which is to set a starting position in the vertex data streams. The base vertex index enables multiple indexed primitives to be packed into a single set of vertex data without requiring the indices to be recomputed based on where the corresponding primitive is placed in the vertex data.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetIndices


IDirect3DDevice8::SetLight

Assigns a set of lighting properties for this device.

HRESULT SetLight(
  DWORD Index,
  CONST D3DLIGHT8* pLight
);

Parameters

Index
[in] Zero-based index of the set of lighting properties to set. If a set of lighting properties exists at this index, it is overwritten by the new properties specified in pLight.
pLight
[in] Pointer to a D3DLIGHT8 structure, containing the lighting-parameters to set.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetLight, IDirect3DDevice8::GetLightEnable, IDirect3DDevice8::LightEnable


IDirect3DDevice8::SetMaterial

Sets the material properties for the device.

HRESULT SetMaterial(
   CONST D3DMATERIAL8* pMaterial
);

Parameters

pMaterial
[in] Pointer to a D3DMATERIAL8 structure, describing the material properties to set.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if the pMaterial parameter is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetMaterial


IDirect3DDevice8::SetPaletteEntries

Sets palette entries.

HRESULT SetPaletteEntries(
  UINT PaletteNumber,
  CONST PALETTEENTRY* pEntries
);

Parameters

PaletteNumber
[in] An ordinal value identifying the particular palette upon which the operation is to be performed.
pEntries
[in] Pointer to a PALETTEENTRY structure, representing the palette entries to set. The number of PALETTEENTRY structures pointed to by pEntries is assumed to be 256. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A single logical palette is associated with the device, and is shared by all texture stages.

For more information on PALETTEENTRY see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALETTEENTRY structure does not work as it is documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetCurrentTexturePalette, IDirect3DDevice8::GetPaletteEntries, IDirect3DDevice8::SetCurrentTexturePalette, Texture Palettes


IDirect3DDevice8::SetPixelShader

Sets the current pixel shader to a previously created pixel shader.

HRESULT SetPixelShader(
  DWORD Handle
);

Parameters

Handle
[in] Handle to the pixel shader, specifying the pixel shader to set. The value for this parameter can be the handle returned by IDirect3DDevice8::CreatePixelShader.

If the handle is NULL, the legacy pixel pipeline is used.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetPixelShader


IDirect3DDevice8::SetPixelShaderConstant

Sets the values in the pixel constant array.

HRESULT SetPixelShaderConstant(
  DWORD Register,
  CONST void* pConstantData,
  DWORD ConstantCount
);

Parameters

Register
[in] Register address at which to start loading data into the pixel constant array.
pConstantData
[in] Pointer to the data block holding the values to load into the pixel constant array. The size of the data block is (ConstantCount * 4 * sizeof(float)).
ConstantCount
[in] Number of constants to load into the pixel constant array. Each constant is comprised of four floating-point values.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This is the method used to load the constant registers of the pixel shader assembler.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetPixelShaderConstant


IDirect3DDevice8::SetRenderState

Sets a single device render-state parameter.

HRESULT SetRenderState(
  D3DRENDERSTATETYPE State,
  DWORD Value
);

Parameters

State
[in] Device state variable that is being modified. This parameter can be any member of the D3DRENDERSTATETYPE enumerated type.
Value
[in] New value for the device render state to be set. The meaning of this parameter is dependent on the value specified for State. For example, if State were D3DRS_SHADEMODE, the second parameter would be one member of the D3DSHADEMODE enumerated type.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one of the arguments is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetRenderState, IDirect3DDevice8::SetTransform


IDirect3DDevice8::SetRenderTarget

Sets a new color buffer, depth buffer, or both for the device.

HRESULT SetRenderTarget(
  IDirect3DSurface8* pRenderTarget,
  IDirect3DSurface8* pNewZStencil
);

Parameters

pRenderTarget
[in] Pointer to a new color buffer. If NULL, the existing color buffer is retained. If this parameter is not NULL, the reference count on the new render target is incremented. Devices always have to be associated with a color buffer.

The new render target surface must have at least D3DUSAGE_RENDERTARGET specified.

pNewZStencil
[in] Pointer to a new depth-stencil buffer. If there is an existing depth-stencil buffer, it is released. If this parameter is not NULL, the reference count on the new depth-stencil buffer surface is incremented. Applications can change the render target without changing the depth buffer by passing in the ppZStencilSurface parameter of IDirect3DDevice8::GetDepthStencilSurface.

The new depth-stencil surface must have at least D3DUSAGE_DEPTHSTENCIL and D3DPOOL_DEFAULT specified.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if pRenderTarget or pNewZStencil are not NULL and invalid, or if the new depth buffer is smaller than the new or retained color buffer.

Remarks

Once a color buffer and a depth-stencil surface have been associated with the same device by this method, they are said to be paired.

The device will call AddRef on each non-NULL surface passed to SetRenderTarget. After that the device calls Release on the previously set color buffer.

The previous depth-stencil surface's contents persist after a call to SetRenderTarget to disassociate the previous depth-stencil surface from the device. If the surface is re-associated with the device, then the contents of the surface will be unchanged, providing the color buffer to which the new depth-stencil surface is being paired is the same size and format as the color buffer to which the depth-stencil surface was most recently paired.

Calling this method resets the current viewport of the device to the size of the current render target. This is done regardless of whether the z-buffer is the only one that is being changed.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::CreateDepthStencilSurface, IDirect3DDevice8::GetDepthStencilSurface


IDirect3DDevice8::SetStreamSource

Binds a vertex buffer to a device data stream.

HRESULT SetStreamSource(
  UINT StreamNumber,
  IDirect3DVertexBuffer8* pStreamData,
  UINT Stride
);

Parameters

StreamNumber
[in] Specifies the data stream, in the range from 0 to the maximum number of streams - 1.
pStreamData
[in] Pointer to an IDirect3DVertexBuffer8 interface, representing the vertex buffer to bind to the specified data stream.
Stride
[in] Stride of the component, in bytes. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method increments the reference count of the stream being assigned. When the texture is no longer needed, set the texture at the appropriate stage to NULL. If you fail to do this, the surface is not released, resulting in a memory leak.

When a flexible vertex format (FVF) vertex shader is used, the stream vertex stride in SetStreamSource must match the vertex size, computed from the FVF. When a declaration is used, the stream vertex stride in SetStreamSource should be greater than or equal to the stream size computed from the declaration.

The SetStreamSource method binds a vertex buffer to a device data stream. For details, see Setting the Stream Source.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::DrawIndexedPrimitive, IDirect3DDevice8::DrawIndexedPrimitiveUP, IDirect3DDevice8::DrawPrimitive, IDirect3DDevice8::DrawPrimitiveUP, IDirect3DDevice8::GetStreamSource


IDirect3DDevice8::SetTexture

Assigns a texture to a stage for a device.

HRESULT SetTexture(
  DWORD Stage,
  IDirect3DBaseTexture8* pTexture
);

Parameters

Stage
[in] Stage identifier to which the texture is set. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum value allowed for Stage is 7.
pTexture
[in] Pointer to an IDirect3DBaseTexture8 interface, representing the texture being set. For complex textures, such as mipmaps and cube textures, this parameter must point to the top-level surface.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method increments the reference count of the texture surface being assigned and decrements the reference count of the previously selected texture if there is one. When the texture is no longer needed, set the texture at the appropriate stage to NULL. Failure to do this results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetTexture, IDirect3DDevice8::GetTextureStageState, IDirect3DDevice8::SetTextureStageState


IDirect3DDevice8::SetTextureStageState

Sets the state value for the currently assigned texture.

HRESULT SetTextureStageState(
  DWORD Stage,
  D3DTEXTURESTAGESTATETYPE Type,
  DWORD Value
);

Parameters

Stage
[in] Stage identifier of the texture for which the state value is set. Stage identifiers are zero-based. Devices can have up to eight set textures, so the maximum value allowed for Stage is 7.
Type
[in] Texture state to set. This parameter can be any member of the D3DTEXTURESTAGESTATETYPE enumerated type.
Value
[in] State value to set. The meaning of this value is determined by the Type parameter.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetTextureStageState, IDirect3DDevice8::GetTexture, IDirect3DDevice8::SetTexture


IDirect3DDevice8::SetTransform

Sets a single device transformation-related state.

HRESULT SetTransform(
  D3DTRANSFORMSTATETYPE State,
  CONST D3DMATRIX* pMatrix
);

Parameters

State
[in] Device-state variable that is being modified. This parameter can be any member of the D3DTRANSFORMSTATETYPE enumerated type, or the D3DTS_WORLDMATRIX macro.
pMatrix
[in] Pointer to a D3DMATRIX structure that modifies the current transformation.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one of the arguments is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetTransform, IDirect3DDevice8::SetRenderState, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX


IDirect3DDevice8::SetVertexShader

Sets the current vertex shader to a previously created vertex shader or to a flexible vertex format (FVF) fixed function shader.

HRESULT SetVertexShader(
  DWORD Handle
);

Parameters

Handle
[in] Handle to a vertex shader, specifying the vertex shader to set. The value for this parameter can be the handle returned by IDirect3DDevice8::CreateVertexShader, or an FVF code. An FVF code is a combination of flexible vertex format flags.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The effect of using an FVF code in place of the handle is to enable a fixed-function vertex shader, with an implicit declaration that matches the FVF code contents read from stream zero. Only stream zero is referenced when an FVF-specified shader is bound to the device.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetVertexShader


IDirect3DDevice8::SetVertexShaderConstant

Sets values in the vertex constant array.

HRESULT SetVertexShaderConstant(
  DWORD Register,
  CONST void* pConstantData,
  DWORD  ConstantCount
);

Parameters

Register
[in] Register address at which to start loading data into the vertex constant array.
pConstantData
[in] Pointer to the data block holding the values to load into the vertex constant array. The size of the data block is (ConstantCount * 4 * sizeof(float)).
ConstantCount
[in] Number of constants to load into the vertex constant array. Each constant is comprised of four floating-point values.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This is the method used to load the constant registers of the vertex shader assembler. When loading transformation matrices, the application should transpose them row/column and load them into consecutive constant registers.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetVertexShaderConstant


IDirect3DDevice8::SetViewport

Sets the viewport parameters for the device.

HRESULT SetViewport(
  CONST D3DVIEWPORT8* pViewport
);

Parameters

pViewport
[in] Pointer to a D3DVIEWPORT8 structure, specifying the viewport parameters to set.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL if the pViewport parameter is invalid.

If the viewport parameters described by the D3DVIEWPORT8 structure describe a region that cannot exist within the render target surface, the method fails, returning D3DERR_INVALIDCALL.

Remarks

Any call to SetViewPort between a pair of calls to IDirect3DDevice8::BeginScene and IDirect3DDevice8::EndScene must be made before any geometry is drawn.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetViewport


IDirect3DDevice8::ShowCursor

Displays or hides the cursor.

BOOL ShowCursor(
  BOOL bShow
);

Parameters

bShow
[in] If bShow is TRUE, the cursor is shown. If bShow is FALSE, the cursor is hidden.

Return Values

Value indicating whether the cursor was previously visible. TRUE if the cursor was previously visible, or FALSE if the cursor was not previously visible.

Remarks

Microsoft® Direct3D® cursor functions use either GDI cursor or software emulation, depending on the hardware. Users usually want to respond to a WM_SETCURSOR message. For example, the users might want to write the message handler like this:

case WM_SETCURSOR:
    // Turn off window cursor
    SetCursor( NULL );
    m_pd3dDevice->ShowCursor( TRUE );
    return TRUE; // prevent Windows from setting cursor to window class cursor
break;

Or users might want to call the IDirect3DDevice8::SetCursorProperties method if they want to change the cursor. See the code in the Microsoft DirectX® Graphics C/C++ Samples for more detail.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::SetCursorPosition, IDirect3DDevice8::SetCursorProperties


IDirect3DDevice8::TestCooperativeLevel

Reports the current cooperative-level status of the Microsoft® Direct3D® device for a windowed or full-screen application.

HRESULT TestCooperativeLevel();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK, indicating that the device is operational and the calling application can continue.

If the method fails, the return value can be one of the following values (see Remarks).

D3DERR_DEVICELOST
D3DERR_DEVICENOTRESET

Remarks

If the device is lost but cannot be restored at the current time, IDirect3DDevice8::TestCooperativeLevel returns the D3DERR_DEVICELOST return code. This would be the case, for example, when a full-screen device has lost focus. If an application detects a lost device, it should pause and periodically call TestCooperativeLevel until it receives a return value of D3DERR_DEVICENOTRESET. The application may then attempt to reset the device by calling IDirect3DDevice8::Reset and, if this succeeds, restore the necessary resources and resume normal operation. Note that IDirect3DDevice8::Present will return D3DERR_DEVICELOST if the device is either "lost" or "not reset".

A call to TestCooperative Level will fail if called on a different thread than that used to create the device being reset.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DDevice8::UpdateTexture

Updates the dirty portions of a texture.

HRESULT UpdateTexture(
  IDirect3DBaseTexture8* pSourceTexture,
  IDirect3DBaseTexture8* pDestinationTexture
);

Parameters

pSourceTexture
[in] Pointer to an IDirect3DBaseTexture8 interface, representing the source texture. The source texture must be in system memory (D3DPOOL_SYSTEMMEM).
pDestinationTexture
[in] Pointer to an IDirect3DBaseTexture8 interface, representing the destination texture. The destination texture must be in the D3DPOOL_DEFAULT memory pool.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

You can dirty a portion of a texture by locking it, or by calling one of the following methods.

  • IDirect3DCubeTexture8::AddDirtyRect
  • IDirect3DTexture8::AddDirtyRect
  • IDirect3DVolumeTexture8::AddDirtyBox
  • IDirect3DDevice8::CopyRects

UpdateTexture retrieves the dirty portions of the texture by calculating what has been accumulated since the last update operation.

This method fails if the textures are of different types, if their bottom-level buffers are of different sizes, and also if their matching levels do not match. For example, consider a six level source texture with the following dimensions.

32×16, 16×8, 8×4, 4×2, 2×1, 1×1

This six level source texture could be the source for the following one level destination.

1×1

For the following two level destination.

2×1, 1×1

Or, for the following three level destination.

4×2, 2×1, 1×1

In addition, this method will fail if the textures are of different formats. If the destination texture has fewer levels than the source, only the matching levels are copied.

If the source texture has dirty regions, the copy may be optimized by restricting the copy to only those regions. It is not guaranteed that only those bytes marked dirty will be copied.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3D8::CreateDevice


IDirect3DDevice8::ValidateDevice

Reports the device's ability to render the current texture-blending operations and arguments in a single pass.

HRESULT ValidateDevice(
  DWORD* pNumPasses
);

Parameters

pNumPasses
[out, retval] Pointer to a DWORD value to fill with the number of rendering passes needed to complete the desired effect through multipass rendering.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_CONFLICTINGTEXTUREFILTER
D3DERR_CONFLICTINGTEXTUREPALETTE
D3DERR_TOOMANYOPERATIONS
D3DERR_UNSUPPORTEDALPHAARG
D3DERR_UNSUPPORTEDALPHAOPERATION
D3DERR_UNSUPPORTEDCOLORARG
D3DERR_UNSUPPORTEDCOLOROPERATION
D3DERR_UNSUPPORTEDFACTORVALUE
D3DERR_UNSUPPORTEDTEXTUREFILTER
D3DERR_WRONGTEXTUREFORMAT

Remarks

The ValidateDevice method should be used to validate scenarios only when other capabilities are deficient. For example, in a multistage texturing scenario, you could query the MaxTextureBlendStages and MaxSimultaneousTextures members of a D3DCAPS8 structure to determine if multistage texturing is possible on the device.

Current hardware does not necessarily implement all possible combinations of operations and arguments. You can determine whether a particular blending operation can be performed with given arguments by setting the desired blending operation, and then calling the ValidateDevice method.

The ValidateDevice method uses the current render states, textures, and texture-stage states to perform validation at the time of the call. Changes to these factors after the call invalidate the previous result, and the method must be called again before rendering a scene.

Using diffuse iterated values, either as an argument or as an operation (D3DTA_DIFFUSE or D3DTOP_BLENDDIFFUSEALPHA) is rarely supported on current hardware. Most hardware can introduce iterated color data only at the last texture operation stage.

Try to specify the texture (D3DTA_TEXTURE) for each stage as the first argument, rather than the second argument.

Many cards do not support use of diffuse or scalar values at arbitrary texture stages. Often, these are available only at the first or last texture-blending stage.

Many cards do not have a blending unit associated with the first texture that is capable of more than replicating alpha to color channels or inverting the input. Therefore, your application might need to use only the second texture stage, if possible. On such hardware, the first unit is presumed to be in its default state, which has the first color argument set to D3DTA_TEXTURE with the D3DTOP_SELECTARG1 operation.

Operations on the output alpha that are more intricate than, or substantially different from, the color operations are less likely to be supported.

Some hardware does not support simultaneous use of D3DTA_TFACTOR and D3DTA_DIFFUSE.

Many cards do not support simultaneous use of multiple textures and mipmapped trilinear filtering. If trilinear filtering has been requested for a texture involved in multitexture blending operations and validation fails, turn off trilinear filtering and revalidate. In this case, you might want to perform multipass rendering instead.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::GetTextureStageState, IDirect3DDevice8::SetTextureStageState


IDirect3DIndexBuffer8

Applications use the methods of the IDirect3DIndexBuffer8 interface to manipulate an index buffer resource.

The IDirect3DIndexBuffer8 interface is obtained by calling the IDirect3DDevice8::CreateIndexBuffer method.

The IDirect3DIndexBuffer8 interface inherits the following IDirect3DResource8 methods, which can be organized into these groups.

Devices | GetDevice
Information | GetType
Private Surface Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData
Resource Management | GetPriority
 | PreLoad
 | SetPriority

The methods of the IDirect3DIndexBuffer8 interface can be organized into the following groups.

Information | GetDesc
Locking | Lock
 | Unlock

The IDirect3DIndexBuffer8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DINDEXBUFFER8 and PDIRECT3DINDEXBUFFER8 types are defined as pointers to the IDirect3DIndexBuffer8 interface.

typedef struct IDirect3DIndexBuffer8 *LPDIRECT3DINDEXBUFFER8, *PDIRECT3DINDEXBUFFER8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::CreateIndexBuffer


IDirect3DIndexBuffer8::GetDesc

Retrieves a description of the index buffer resource.

HRESULT GetDesc(
  D3DINDEXBUFFER_DESC* pDesc
);

Parameters

pDesc
[out] Pointer to a D3DINDEXBUFFER_DESC structure, describing the returned index buffer.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DIndexBuffer8::Lock

Locks a range of index data and obtains a pointer to the index buffer memory.

HRESULT Lock(
  UINT OffsetToLock,
  UINT SizeToLock,
  BYTE** ppbData,
  DWORD Flags
);

Parameters

OffsetToLock
[in] Offset into the index data to lock, in bytes.
SizeToLock
[in] Size of the index data to lock, in bytes.
ppbData
[out] Address of a pointer to an array of BYTE values, filled with the returned index data.
Flags
[in] A combination of zero or more locking flags, describing how the index buffer memory should be locked.
D3DLOCK_DISCARD
The application overwrites, with a write-only operation, the entire index buffer. This enables Direct3D to return a pointer to a new memory area so that the dynamic memory access (DMA) and rendering from the old area do not stall.
D3DLOCK_NOOVERWRITE
Indicates that no indices that were referred to in drawing calls since the start of the frame or the last lock without this flag will be modified during the lock. This can enable optimizations when the application is only appending data to the index buffer.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long-duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables some optimization. D3DLOCK_READONLY cannot be specified with D3DLOCK_DISCARD; nor can it be specified on a vertex buffer created with D3DUSAGE_WRITEONLY.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

The D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE flags are valid only on buffers created with D3DUSAGE_DYNAMIC.

See Using Dynamic Vertex and Index Buffers for information on using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the Lock method.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DIndexBuffer8::Unlock


IDirect3DIndexBuffer8::Unlock

Unlocks index data.

HRESULT Unlock();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DIndexBuffer8::Lock


IDirect3DResource8

Applications use the methods of the IDirect3DResource8 interface to query and prepare resources.

To create a texture resource, you can call one of the following methods.

  • IDirect3DDevice8::CreateCubeTexture
  • IDirect3DDevice8::CreateTexture
  • IDirect3DDevice8::CreateVolumeTexture

To create a geometry-oriented resource, you can call one of the following methods.

  • IDirect3DDevice8::CreateIndexBuffer
  • IDirect3DDevice8::CreateVertexBuffer

The methods of the IDirect3DResource8 interface can be organized into the following groups.

Devices | GetDevice
Information | GetType
Private Surface Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData
Resource Management | GetPriority
 | PreLoad
 | SetPriority

The IDirect3DResource8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DRESOURCE8 and PDIRECT3DRESOURCE8 types are defined as pointers to the IDirect3DResource8 interface.

typedef struct IDirect3DResource8 *LPDIRECT3DRESOURCE8, *PDIRECT3DRESOURCE8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DResource8::FreePrivateData

Frees the specified private data associated with this resource.

HRESULT FreePrivateData(
  REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTFOUND

Applies To

This method applies to the following interfaces, which inherit from IDirect3DResource8.

  • IDirect3DBaseTexture8
  • IDirect3DCubeTexture8
  • IDirect3DIndexBuffer8
  • IDirect3DTexture8
  • IDirect3DVertexBuffer8
  • IDirect3DVolumeTexture8

Remarks

Microsoft® Direct3D® calls this method automatically when a resource is released.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DResource8::GetPrivateData, IDirect3DResource8::SetPrivateData


IDirect3DResource8::GetDevice

Retrieves the device associated with a resource.

HRESULT GetDevice(
  IDirect3DDevice8** ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice8 interface to fill with the device pointer, if the query succeeds.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from IDirect3DResource8.

  • IDirect3DBaseTexture8
  • IDirect3DCubeTexture8
  • IDirect3DIndexBuffer8
  • IDirect3DTexture8
  • IDirect3DVertexBuffer8
  • IDirect3DVolumeTexture8

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice8 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DResource8::GetPriority

Retrieves the priority for this resource.

DWORD GetPriority();

Parameters

None.

Return Values

Returns a DWORD value, indicating the priority of the resource.

Applies To

This method applies to the following interfaces, which inherit from IDirect3DResource8.

  • IDirect3DBaseTexture8
  • IDirect3DCubeTexture8
  • IDirect3DIndexBuffer8
  • IDirect3DTexture8
  • IDirect3DVertexBuffer8
  • IDirect3DVolumeTexture8

Remarks

GetPriority is used for priority control of managed resources. This method returns 0 on nonmanaged resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DResource8::SetPriority


IDirect3DResource8::GetPrivateData

Copies the private data associated with the resource to a provided buffer.

HRESULT GetPrivateData(
  REFGUID refguid,
  void* pData,
  DWORD* pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_MOREDATA
D3DERR_NOTFOUND

Applies To

This method applies to the following interfaces, which inherit from IDirect3DResource8.

  • IDirect3DBaseTexture8
  • IDirect3DCubeTexture8
  • IDirect3DIndexBuffer8
  • IDirect3DTexture8
  • IDirect3DVertexBuffer8
  • IDirect3DVolumeTexture8

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DResource8::FreePrivateData, IDirect3DResource8::SetPrivateData


IDirect3DResource8::GetType

Returns the type of the resource.

D3DRESOURCETYPE GetType();

Parameters

None.

Return Values

Returns a member of the D3DRESOURCETYPE enumerated type, identifying the type of the resource.

Applies To

This method applies to the following interfaces, which inherit from IDirect3DResource8.

  • IDirect3DBaseTexture8
  • IDirect3DCubeTexture8
  • IDirect3DIndexBuffer8
  • IDirect3DTexture8
  • IDirect3DVertexBuffer8
  • IDirect3DVolumeTexture8

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DResource8::PreLoad

Preloads a managed resource.

void PreLoad();

Parameters

None.

Return Values

None.

Applies To

This method applies to the following interfaces, which inherit from IDirect3DResource8.

  • IDirect3DBaseTexture8
  • IDirect3DCubeTexture8
  • IDirect3DIndexBuffer8
  • IDirect3DTexture8
  • IDirect3DVertexBuffer8
  • IDirect3DVolumeTexture8

Remarks

Calling this method indicates that the application will need this managed resource shortly. This method has no effect on nonmanaged resources.

PreLoad detects "thrashing" conditions where more resources are being used in each frame than can fit in video memory simultaneously. Under such circumstances Preload silently does nothing.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DResource8::SetPriority

Assigns the resource-management priority for this resource.

DWORD SetPriority(
  DWORD PriorityNew
);

Parameters

PriorityNew
[in] DWORD value that specifies the new resource-management priority for the resource.

Return Values

Returns the previous priority value for the resource.

Applies To

This method applies to the following interfaces, which inherit from IDirect3DResource8.

  • IDirect3DBaseTexture8
  • IDirect3DCubeTexture8
  • IDirect3DIndexBuffer8
  • IDirect3DTexture8
  • IDirect3DVertexBuffer8
  • IDirect3DVolumeTexture8

Remarks

SetPriority is used for priority control of managed resources. This method returns 0 on non-managed resources.

Priorities are used to determine when managed resources are to be removed from memory. A resource assigned a low priority is removed before a resource with a high priority. If two resources have the same priority, the resource that was used more recently is kept in memory; the other resource is removed. Managed resources have a default priority of 0.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DResource8::GetPriority


IDirect3DResource8::SetPrivateData

Associates data with the resource that is intended for use by the application, not by Microsoft® Direct3D®. Data is passed by value, and multiple sets of data can be associated with a single resource.

HRESULT SetPrivateData(
  REFGUID refguid,
  CONST void* pData,
  DWORD SizeOfData,
  DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to be associated with the resource.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D® allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to SetPrivateData with the same GUID, a subsequent call to IDirect3DResource8::FreePrivateData, or when the Direct3D8 object is released. For more information, see Remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Applies To

This method applies to the following interfaces, which inherit from IDirect3DResource8.

  • IDirect3DBaseTexture8
  • IDirect3DCubeTexture8
  • IDirect3DIndexBuffer8
  • IDirect3DTexture8
  • IDirect3DVertexBuffer8
  • IDirect3DVolumeTexture8

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the caller's responsibility to free the memory.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DResource8::FreePrivateData, IDirect3DResource8::GetPrivateData


IDirect3DSurface8

Applications use the methods of the IDirect3DSurface8 interface to query and prepare surfaces.

The methods of the IDirect3DSurface8 interface can be organized into the following groups.

Devices | GetDevice
Information | GetContainer
 | GetDesc
Locking Surfaces | LockRect
 | UnlockRect
Private Surface Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData

The IDirect3DSurface8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DSURFACE8 and PDIRECT3DSURFACE8 types are defined as pointers to the IDirect3DSurface8 interface.

typedef struct IDirect3DSurface8 *LPDIRECT3DSURFACE8, *PDIRECT3DSURFACE8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

Surface Interfaces


IDirect3DSurface8::FreePrivateData

Frees the specified private data associated with this surface.

HRESULT FreePrivateData(
  REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTFOUND

Remarks

Microsoft® Direct3D® calls this method automatically when a surface is released.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DSurface8::GetPrivateData, IDirect3DSurface8::SetPrivateData


IDirect3DSurface8::GetContainer

Provides access to the parent cube texture or texture (mipmap) object, if this surface is a child level of a cube texture or a mipmap.

HRESULT GetContainer(
  REFIID riid
  void** ppContainer
);

Parameters

riid
[in] Reference identifier of the container being requested.
ppContainer
[out] Address of a pointer to fill with the container pointer if the query succeeds. See Remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the surface is created using IDirect3DDevice8::CreateImageSurface, IDirect3DDevice8::CreateRenderTarget, or IDirect3DDevice8::CreateDepthStencilSurface, the surface is considered stand alone. In this case, GetContainer will return the Direct3D device used to create the surface.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DSurface8::GetDevice

Retrieves the device associated with a surface.

HRESULT GetDevice(
  IDirect3DDevice8** ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice8 interface to fill with the device pointer, if the query succeeds.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice8 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DSurface8::GetPrivateData

Copies the private data associated with the surface to a provided buffer.

HRESULT GetPrivateData(
  REFGUID refguid,
  void* pData,
  DWORD* pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data (such as 0), the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_MOREDATA
D3DERR_NOTFOUND

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DSurface8::FreePrivateData, IDirect3DSurface8::SetPrivateData


IDirect3DSurface8::GetDesc

Retrieves a description of the surface.

HRESULT GetDesc(
  D3DSURFACE_DESC* pDesc
);

Parameters

pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing the surface.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DSurface8::LockRect

Locks a rectangle on a surface.

HRESULT LockRect(
  D3DLOCKED_RECT* pLockedRect,
  CONST RECT* pRect,
  DWORD Flags
);

Parameters

pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure, describing the locked region.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT structure. Specifying NULL for this parameter expands the dirty region to cover the entire surface.
Flags
[in] A combination of zero or more locking flags, describing the type of lock to perform.
D3DLOCK_NO_DIRTY_UPDATE
By default, a lock on a resource adds a dirty region to that resource. This flag prevents any changes to the dirty state of the resource. Applications should use this flag when they have additional information about the actual set of regions changed during the lock operation.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long-duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The only lockable format for a depth-stencil surface is D3DFMT_D16_LOCKABLE.

A multisample backbuffer cannot be locked.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DSurface8::UnlockRect


IDirect3DSurface8::SetPrivateData

Associates data with the surface that is intended for use by the application, not by Microsoft® Direct3D®.

HRESULT SetPrivateData(
  REFGUID refguid,
  void* pData,
  DWORD SizeOfData,
  DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to associate with the surface.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to SetPrivateData with the same GUID, a subsequent call to IDirect3DSurface8::FreePrivateData, or when the Direct3D8 object is released. For more information, see Remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the caller's responsibility to free the memory.

Data is passed by value, and multiple sets of data can be associated with a single surface.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DSurface8::FreePrivateData, IDirect3DSurface8::GetPrivateData


IDirect3DSurface8::UnlockRect

Unlocks a rectangle on a surface.

HRESULT UnlockRect();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DSurface8::LockRect


IDirect3DSwapChain8

Applications use the methods of the IDirect3DSwapChain8 interface to manipulate a swap chain.

There is always at least one swap chain for each device, known as the implicit swap chain. However, an additional swap chain for rendering multiple views from the same device can be created by calling the IDirect3DDevice8::CreateAdditionalSwapChain method.

The methods of the IDirect3DSwapChain8 interface can be organized into the following groups.

Presentation | Present
Surface Management | GetBackBuffer

The IDirect3DSwapChain8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DSWAPCHAIN8 and PDIRECT3DSWAPCHAIN8 types are defined as pointers to the IDirect3DSwapChain8 interface.

typedef struct IDirect3DSwapChain8 *LPDIRECT3DSWAPCHAIN8, *PDIRECT3DSWAPCHAIN8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::CreateAdditionalSwapChain


IDirect3DSwapChain8::GetBackBuffer

Retrieves a back buffer from the swap chain of the device.

HRESULT GetBackBuffer(
  UINT  BackBuffer,
  D3DBACKBUFFER_TYPE Type,
  IDirect3DSurface8** ppBackBuffer
);

Parameters

BackBuffer
[in] Index of the back buffer object to return. Back buffers are numbered from 0 to the total number of back buffers - 1. A value of 0 returns the first back buffer, not the front buffer. The front buffer is not accessible through this method.
Type
[in] Stereo view is not supported in DirectX 8.0, so the only valid value for this parameter is D3DBACKBUFFER_TYPE_MONO.
ppBackBuffer
[out, retval] Address of a pointer to an IDirect3DSurface8 interface, representing the returned back buffer surface.

Return Values

If the method succeeds, the return value is D3D_OK.

If BackBuffer exceeds or equals the total number of back buffers, then the function fails and returns D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DSurface8 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DSwapChain8::Present

Presents the contents of the next in the sequence of back buffers owned by the swap chain.

HRESULT Present(
  CONST RECT* pSourceRect,
  CONST RECT* pDestRect,
  HWND hDestWindowOverride,
  CONST RGNDATA* pDirtyRegion
);

Parameters

pSourceRect
[in] Pointer to a RECT structure that contains the source rectangle. This value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY or D3DSWAPEFFECT_COPY_VSYNC. If NULL, the entire source surface is presented. If the rectangle exceeds the source surface, the rectangle is clipped to the source surface.
pDestRect
[in] Pointer to a RECT structure containing the destination rectangle, in window client coordinates. This value must be NULL unless the swap chain was created with D3DSWAPEFFECT_COPY or D3DSWAPEFFECT_COPY_VSYNC. If NULL, the entire client area is filled. If the rectangle exceeds the destination client area, the rectangle is clipped to the destination client area.
hDestWindowOverride
[in] Destination window whose client area is taken as the target for this presentation. If this value is NULL, the hWndDeviceWindow member of D3DPRESENT_PARAMETERS is taken.
pDirtyRegion
[in] This parameter is not used and must be set to NULL.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Remarks

This method performs identically to the IDirect3DDevice8::Present method.

If necessary, a stretch operation is applied to transfer the pixels within the source rectangle to the destination rectangle in the client area of the target window.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::Reset


IDirect3DTexture8

Applications use the methods of the IDirect3DTexture8 interface to manipulate a texture resource.

The IDirect3DTexture8 interface is obtained by calling the IDirect3DDevice8::CreateTexture method.

The IDirect3DTexture8 interface inherits the following IDirect3DResource8 methods, which can be organized into these groups.

Devices | GetDevice
Information | GetType
Private Surface Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData
Resource Management | GetPriority
 | PreLoad
 | SetPriority

The IDirect3DTexture8 interface inherits the following IDirect3DBaseTexture8 methods, which can be organized into these groups.

Detail | GetLOD
 | SetLOD
Information | GetLevelCount

The methods of the IDirect3DTexture8 interface can be organized into the following groups.

Information | GetLevelDesc
Locking Surfaces | LockRect
 | UnlockRect
Miscellaneous | AddDirtyRect
 | GetSurfaceLevel

The IDirect3DTexture8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DTEXTURE8 and PDIRECT3DTEXTURE8 types are defined as pointers to the IDirect3DTexture8 interface.

typedef struct IDirect3DTexture8 *LPDIRECT3DTEXTURE8, *PDIRECT3DTEXTURE8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::CreateTexture


IDirect3DTexture8::AddDirtyRect

Adds a dirty region to a texture resource.

HRESULT AddDirtyRect(
  CONST RECT* pDirtyRect
);

Parameters

pDirtyRect
[in] Pointer to a RECT structure, specifying the dirty region to add. Specifying NULL expands the dirty region to cover the entire texture.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Applications can optimize what subset of a resource is copied by specifying dirty regions on the resource.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DTexture8::GetLevelDesc

Retrieves a level description of a texture resource.

HRESULT GetLevelDesc(
  UINT Level,
  D3DSURFACE_DESC* pDesc
);

Parameters

Level
[in] Identifies a level of the texture resource. This method returns a surface description for the level specified by this parameter.
pDesc
[out] Pointer to a D3DSURFACE_DESC structure, describing the returned level.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one of the arguments is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DTexture8::GetSurfaceLevel

Retrieves the specified texture surface level.

HRESULT GetSurfaceLevel(
  UINT Level,
  IDirect3DSurface8** ppSurfaceLevel
);

Parameters

Level
[in] Identifies a level of the texture resource. This method returns a surface for the level specified by this parameter. The top-level surface is denoted by 0.
ppSurfaceLevel
[out, retval] Address of a pointer to an IDirect3DSurface8 interface, representing the returned surface.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DSurface8 interface. Failure to call IUnknown::Release when finished using this IDirect3DSurface8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DTexture8::LockRect

Locks a rectangle on a texture resource.

HRESULT LockRect(
  UINT Level,
  D3DLOCKED_RECT* pLockedRect,
  CONST RECT* pRect,
  DWORD Flags
);

Parameters

Level
[in] Specifies the level of the texture resource to lock.
pLockedRect
[out] Pointer to a D3DLOCKED_RECT structure, describing the locked region.
pRect
[in] Pointer to a rectangle to lock. Specified by a pointer to a RECT structure. Specifying NULL for this parameter expands the dirty region to cover the entire texture.
Flags
[in] A combination of zero or more locking flags, describing the type of lock to perform.
D3DLOCK_NO_DIRTY_UPDATE
By default, a lock on a resource adds a dirty region to that resource. This flag prevents any changes to the dirty state of the resource. Applications should use this flag when they have additional information about the actual set of regions changed during the lock operation and can then pass this information to IDirect3DTexture8::AddDirtyRect.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long-duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Textures created in D3DPOOL_DEFAULT are not-lockable.

The only lockable format for a depth-stencil surface is D3DFMT_D16_LOCKABLE.

A multisample backbuffer cannot be locked. Video memory textures cannot be locked, but must be modified by calling IDirect3Ddevice8::CopyRects or IDirect3Ddevice8::UpdateTexture. There are exceptions for some proprietary driver pixel formats that Microsoft® DirectX® 8.0 does not recognize. These can be locked.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DTexture8::UnlockRect


IDirect3DTexture8::UnlockRect

Unlocks a rectangle on a texture resource.

HRESULT UnlockRect(
  UINT Level
);

Parameters

Level
[in] Specifies the level of the texture resource to unlock.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DTexture8::LockRect


IDirect3DVertexBuffer8

Applications use the methods of the IDirect3DVertexBuffer8 interface to manipulate vertex buffer resources.

The IDirect3DVertexBuffer8 interface is obtained by calling the IDirect3DDevice8::CreateVertexBuffer method.

The IDirect3DVertexBuffer8 interface inherits the following IDirect3DResource8 methods, which can be organized into these groups.

Devices | GetDevice
Information | GetType
Private Surface Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData
Resource Management | GetPriority
 | PreLoad
 | SetPriority

The methods of the IDirect3DVertexBuffer8 interface can be organized into the following groups.

Information | GetDesc
Locking | Lock
 | Unlock

The IDirect3DVertexBuffer8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DVERTEXBUFFER8 and PDIRECT3DVERTEXBUFFER8 types are defined as pointers to the IDirect3DVertexBuffer8 interface.

typedef struct IDirect3DVertexBuffer8 *LPDIRECT3DVERTEXBUFFER8, *PDIRECT3DVERTEXBUFFER8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::CreateVertexBuffer


IDirect3DVertexBuffer8::GetDesc

Retrieves a description of the vertex buffer resource.

HRESULT GetDesc(
  D3DVERTEXBUFFER_DESC* pDesc
);

Parameters

pDesc
[out] Pointer to a D3DVERTEXBUFFER_DESC structure, describing the returned vertex buffer.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DVertexBuffer8::Lock

Locks a range of vertex data and obtains a pointer to the vertex buffer memory.

HRESULT Lock(
  UINT OffsetToLock,
  UINT SizeToLock,
  BYTE** ppbData,
  DWORD Flags
);

Parameters

OffsetToLock
[in] Offset into the vertex data to lock, in bytes.
SizeToLock
[in] Size of the vertex data to lock, in bytes. Specify 0 to lock the entire vertex buffer.
ppbData
[out] Address of a pointer to an array of BYTE values, filled with the returned vertex data.
Flags
[in] A combination of zero or more locking flags, indicating how the vertex buffer memory should be locked.
D3DLOCK_DISCARD
The application overwrites, with a write-only operation, the entire index buffer. This enables Direct3D to return a pointer to a new memory area so that the dynamic memory access (DMA) and rendering from the old area do not stall. See remarks.
D3DLOCK_NOOVERWRITE
Indicates that no vertices that were referred to in drawing calls since the start of the frame or the last lock without this flag will be modified during the lock. This can enable optimizations when the application is appending data only to the vertex buffer. See Remarks.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long-duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables some optimizations. D3DLOCK_READONLY cannot be specified with D3DLOCK_DISCARD, nor can it be specified on a vertex buffer created with D3DUSAGE_WRITEONLY.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

The D3DLOCK_DISCARD and D3DLOCK_NOOVERWRITE flags are valid only on buffers created with D3DUSAGE_DYNAMIC.

See Using Dynamic Vertex and Index Buffers for information on using D3DLOCK_DISCARD or D3DLOCK_NOOVERWRITE for the Flags parameter of the Lock method.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DVertexBuffer8::Unlock


IDirect3DVertexBuffer8::Unlock

Unlocks vertex data.

HRESULT Unlock();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DVertexBuffer8::Lock


IDirect3DVolume8

Applications use the methods of the IDirect3DVolume8 interface to manipulate volume resources.

The IDirect3DVolume8 interface is obtained by calling the IDirect3DVolumeTexture8::GetVolumeLevel method.

The methods of the IDirect3DVolume8 interface can be organized into the following groups.

Devices | GetDevice
Information | GetContainer
 | GetDesc
Locking Volumes | LockBox
 | UnlockBox
Private Volume Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData

The IDirect3DVolume8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DVOLUME8 and PDIRECT3DVOLUME8 types are defined as pointers to the IDirect3DVolume8 interface.

typedef struct IDirect3DVolume8 *LPDIRECT3DVOLUME8, *PDIRECT3DVOLUME8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DVolume8::FreePrivateData

Frees the specified private data associated with this volume.

HRESULT FreePrivateData(
  REFGUID refguid
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to free.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTFOUND

Remarks

Microsoft® Direct3D® calls this method automatically when a volume is released.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DVolume8::GetPrivateData, IDirect3DVolume8::SetPrivateData


IDirect3DVolume8::GetContainer

Provides access to the parent volume texture object, if this surface is a child level of a volume texture.

HRESULT GetContainer(
  REFIID riid,
  void** ppContainer
);

Parameters

riid
[in] Reference identifier of the volume being requested.
ppContainer
[out, retval] Address of a pointer to fill with the container pointer, if the query succeeds.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DVolume8::GetDevice

Retrieves the device associated with a volume.

HRESULT GetDevice(
  IDirect3DDevice8** ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice8 interface to fill with the device pointer, if the query succeeds.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method allows navigation to the owning device object.

Note Calling this method will increase the internal reference count on the IDirect3DDevice8 interface. Failure to call IUnknown::Release when finished using this IDirect3DDevice8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DVolume8::GetPrivateData

Copies the private data associated with the volume to a provided buffer.

HRESULT GetPrivateData(
  REFGUID refguid,
  void* pData,
  DWORD* pSizeOfData
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to retrieve.
pData
[in, out] Pointer to a previously allocated buffer to fill with the requested private data if the call succeeds. The application calling this method is responsible for allocating and releasing this buffer.
pSizeOfData
[in, out] Pointer to the size of the buffer at pData, in bytes. If this value is less than the actual size of the private data, such as 0, the method sets this parameter to the required buffer size, and the method returns D3DERR_MOREDATA.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_MOREDATA
D3DERR_NOTFOUND

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DVolume8::FreePrivateData, IDirect3DVolume8::SetPrivateData


IDirect3DVolume8::GetDesc

Retrieves a description of the volume.

HRESULT GetDesc(
  D3DVOLUME_DESC* pDesc
);

Parameters

pDesc
[out] Pointer to a D3DVOLUME_DESC structure, describing the volume.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if the argument is invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DVolume8::LockBox

Locks a box on a volume resource.

HRESULT LockBox(
  D3DLOCKED_BOX* pLockedVolume,
  CONST D3DBOX* pBox,
  DWORD Flags
);

Parameters

pLockedVolume
[out] Pointer to a D3DLOCKED_BOX structure, describing the locked region.
pBox
[in] Pointer to a box to lock. Specified by a pointer to a D3DBOX structure. Specifying NULL for this parameter locks the entire volume.
Flags
[in] A combination of zero or more locking flags, describing the type of lock to perform.
D3DLOCK_NO_DIRTY_UPDATE
By default, a lock on a resource adds a dirty region to that resource. This flag prevents any changes to the dirty state of the resource. Applications should use this flag when they have additional information about the actual set of volumes changed during the lock operation.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long-duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DVolume8::UnlockBox


IDirect3DVolume8::SetPrivateData

Associates data with the volume that is intended for use by the application, not by Microsoft® Direct3D®.

HRESULT SetPrivateData(
  REFGUID refguid,
  void* pData,
  DWORD SizeOfData,
  DWORD Flags
);

Parameters

refguid
[in] Reference to (C++) or address of (C) the globally unique identifier that identifies the private data to set.
pData
[in] Pointer to a buffer that contains the data to associate with the volume.
SizeOfData
[in] Size of the buffer at pData, in bytes.
Flags
[in] Value that describes the type of data being passed, or indicates to the application that the data should be invalidated when the resource changes.
(none)
If no flags are specified, Direct3D allocates memory to hold the data within the buffer and copies the data into the new buffer. The buffer allocated by Direct3D is automatically freed, as appropriate.
D3DSPD_IUNKNOWN
The data at pData is a pointer to an IUnknown interface. SizeOfData must be set to the size of a pointer to an IUnknown interface, sizeof(IUnknown*). Direct3D automatically calls IUnknown::AddRef through pData and IUnknown::Release when the private data is destroyed. Private data will be destroyed by a subsequent call to SetPrivateData with the same GUID, a subsequent call to IDirect3DVolume8::FreePrivateData, or when the Direct3D8 object is released. For more information, see Remarks.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

Direct3D does not manage the memory at pData. If this buffer was dynamically allocated, it is the caller's responsibility to free the memory.

Data is passed by value, and multiple sets of data can be associated with a single volume.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DVolume8::FreePrivateData, IDirect3DVolume8::GetPrivateData


IDirect3DVolume8::UnlockBox

Unlocks a box on a volume resource.

HRESULT UnlockBox();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DVolume8::LockBox


IDirect3DVolumeTexture8

Applications use the methods of the IDirect3DVolumeTexture8 interface to manipulate a volume texture resource.

The IDirect3DVolumeTexture8 interface is obtained by calling the IDirect3DDevice8::CreateVolumeTexture method.

The IDirect3DVolumeTexture8 interface inherits the following IDirect3DResource8 methods, which can be organized into these groups.

Devices | GetDevice
Information | GetType
Private Surface Data | FreePrivateData
 | GetPrivateData
 | SetPrivateData
Resource Management | GetPriority
 | PreLoad
 | SetPriority

The IDirect3DVolumeTexture8 interface inherits the following IDirect3DBaseTexture8 methods, which can be organized into these groups.

Detail | GetLOD
 | SetLOD
Information | GetLevelCount

The methods of the IDirect3DVolumeTexture8 interface can be organized into the following groups.

Information | GetLevelDesc
Locking Volumes | LockBox
 | UnlockBox
Miscellaneous | AddDirtyBox
 | GetVolumeLevel

The IDirect3DVolumeTexture8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECT3DVOLUMETEXTURE8 and PDIRECT3DVOLUMETEXTURE8 types are defined as pointers to the IDirect3DVolumeTexture8 interface.

typedef struct IDirect3DVolumeTexture8 *LPDIRECT3DVOLUMETEXTURE8, *PDIRECT3DVOLUMETEXTURE8;

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DDevice8::CreateVolumeTexture


IDirect3DVolumeTexture8::AddDirtyBox

Adds a dirty region to a volume texture resource.

HRESULT AddDirtyBox(
  CONST D3DBOX* pDirtyBox
);

Parameters

pDirtyBox
[in] Pointer to a D3DBOX structure, specifying the dirty region to add. Specifying NULL expands the dirty region to cover the entire volume texture.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Applications can optimize what subset of a resource is copied by specifying boxes on the resource. However, the dirty regions may be expanded to optimize alignment.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DVolumeTexture8::GetLevelDesc

Retrieves a level description of a volume texture resource.

HRESULT GetLevelDesc(
  UINT Level,
  D3DVOLUME_DESC* pDesc
);

Parameters

Level
[in] Identifies a level of the volume texture resource. This method returns a volume description for the level specified by this parameter.
pDesc
[out] Pointer to a D3DVOLUME_DESC structure, describing the returned volume texture level.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL is returned if one or more of the arguments are invalid.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DVolumeTexture8::GetVolumeLevel

Retrieves the specified volume texture level.

HRESULT GetVolumeLevel(
  UINT Level,
  IDirect3DVolume8** ppVolumeLevel
);

Parameters

Level
[in] Identifies a level of the volume texture resource. This method returns a volume for the level specified by this parameter.
ppVolumeLevel
[out, retval] Address of a pointer to an IDirect3DVolume8 interface, representing the returned volume level.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DVolume8 interface. Failure to call IUnknown::Release when finished using this IDirect3DVolume8 interface results in a memory leak.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.


IDirect3DVolumeTexture8::LockBox

Locks a box on a volume texture resource.

HRESULT LockBox(
  UINT Level,
  D3DLOCKED_BOX* pLockedVolume,
  CONST D3DBOX* pBox,
  DWORD Flags
);

Parameters

Level
[in] Specifies the level of the volume texture resource to lock.
pLockedVolume
[out] Pointer to a D3DLOCKED_BOX structure, describing the locked region.
pBox
[in] Pointer to the volume to lock. This parameter is specified by a pointer to a D3DBOX structure. Specifying NULL for this parameter locks the entire volume level.
Flags
[in] A combination of zero or more locking flags, describing the type of lock to perform.
D3DLOCK_NO_DIRTY_UPDATE
By default, a lock on a resource adds a dirty region to that resource. This flag prevents any changes to the dirty state of the resource. Applications should use this flag when they have additional information about the actual set of volumes changed during the lock operation and can then pass this information to IDirect3DVolumeTexture8::AddDirtyBox.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long-duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DVolumeTexture8::UnlockBox


IDirect3DVolumeTexture8::UnlockBox

Unlocks a box on a volume texture resource.

HRESULT UnlockBox(
  UINT Level
);

Parameters

Level
[in] Specifies the level of the volume texture resource to unlock.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib.

See Also

IDirect3DVolumeTexture8::LockBox


Functions

This section contains reference information for the functions that you need to use when you work with Microsoft® Direct3D®. The following function is implemented.

  • Direct3DCreate8


Direct3DCreate8

Creates an instance of a Direct3D8 object.

IDirect3D8* Direct3DCreate8(
  UINT SDKVersion
);

Parameters

SDKVersion
The value of this parameter should be D3D_SDK_VERSION. See Remarks.

Return Values

If successful, this function returns a pointer to an IDirect3D8 interface; otherwise, a NULL pointer is returned.

Remarks

This function creates a Direct3D8 object that supports enumeration and allows the creation of Direct3DDevice8 objects.

The D3D_SDK_VERSION identifier is passed to Direct3DCreate8 in order to ensure that an application was built against the correct header files. This value is incremented whenever a header or other change would require applications to be rebuilt. If the version does not match, Direct3DCreate8 will fail.

Note that calling this function samples the current set of active display adapters. If the user dynamically adds adapters, either by adding devices to the desktop or by hot-docking a laptop, then those devices will not be enumerated for the lifetime of this Direct3D8 object. Creating a new Direct3D8 object will expose the new devices.

Requirements

Header: Declared in D3d8.h.
Import Library: Use D3d8.lib


Macros

This section contains reference information for the macros provided by Microsoft® Direct3D®.

  • D3DCLIPPLANE n
  • D3DCOLOR_ARGB
  • D3DCOLOR_COLORVALUE
  • D3DCOLOR_RGBA
  • D3DCOLOR_XRGB
  • D3DFVF_TEXCOORDSIZE n
  • D3DTS_WORLD
  • D3DTS_WORLD n
  • D3DTS_WORLDMATRIX


D3DCLIPPLANEn

Defines bit patterns that enable user-defined clipping planes. These macros are defined as a convenience when setting values for the D3DRS_CLIPPLANEENABLE render state.

D3DCLIPPLANE0 (1 << 0)
D3DCLIPPLANE1 (1 << 1)
D3DCLIPPLANE2 (1 << 2)
D3DCLIPPLANE3 (1 << 3)
D3DCLIPPLANE4 (1 << 4)
D3DCLIPPLANE5 (1 << 5)

Parameters

None.

Remarks

User-defined clipping planes are enabled when the DWORD value set in the D3DRS_CLIPPLANEENABLE render state contains one or more set bits (that is, is not 0). The value of the render-state DWORD is not important; the system does not interpret the value as a number. Rather, it parses the DWORD, enabling any clipping plane whose corresponding bit is set. Bit 0 controls the state of the first clipping plane (at index 0), bit 1 the second plane, and so on.

The bit patterns that these macros create can be combined by using a logical OR operation to simultaneously enable multiple clipping planes. Omitting one of these macros from the combination effectively disables the clipping plane at that index.

Requirements

Header: Declared in D3d8types.h.


D3DCOLOR_ARGB

Initializes a color with the supplied alpha, red, green, and blue values.

D3DCOLOR_ARGB(a,r,g,b) \
    ((D3DCOLOR)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff)))

Parameters

a, r, g, and b
Alpha, red, green, and blue components of the color. These values must be in the range 0 to 255.

Return Values

Returns the D3DCOLOR value that corresponds to the supplied ARGB values.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DCOLOR_RGBA, D3DCOLOR_XRGB


D3DCOLOR_COLORVALUE

Initializes a color with the supplied red, green, blue, and alpha floating-point values.

D3DCOLOR_COLORVALUE(r,g,b,a) \
    D3DCOLOR_RGBA((DWORD)((r)*255.f),(DWORD)((g)*255.f),(DWORD)((b)*255.f),(DWORD)((a)*255.f))

Parameters

r, g, b, and a
Red, green, blue, and alpha components of the color. These values must be floating-point values in the range 0.0 through 1.0.

Return Values

Returns the D3DCOLOR value that corresponds to the supplied RGBA values.

Requirements

Header: Declared in D3d8types.h.


D3DCOLOR_RGBA

Initializes a color with the supplied red, green, blue, and alpha values.

D3DCOLOR_RGBA(r,g,b,a) D3DCOLOR_ARGB(a,r,g,b)

Parameters

r, g, b, and a
Red, green, blue, and alpha components of the color. These values must be in the range 0 through 255.

Return Values

Returns the D3DCOLOR value that corresponds to the supplied RGBA values.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DCOLOR_ARGB, D3DCOLOR_XRGB


D3DCOLOR_XRGB

Initializes a color with the supplied red, green, and blue values.

D3DCOLOR_XRGB(r,g,b) D3DCOLOR_ARGB(0xff,r,g,b)

Parameters

r, g, and b
Red, green, and blue components of the color. These values must be in the range 0 through 255.

Return Values

Returns the D3DCOLOR value that corresponds to the supplied RGB values.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DCOLOR_ARGB, D3DCOLOR_RGBA


D3DFVF_TEXCOORDSIZEn

Constructs bit patterns that are used to identify texture coordinate formats within a flexible vertex format description. The results of these macros can be combined within a flexible vertex format description by using the OR operator.

D3DFVF_TEXCOORDSIZE1(CoordIndex) (D3DFVF_TEXTUREFORMAT1 << (CoordIndex*2 + 16))
D3DFVF_TEXCOORDSIZE2(CoordIndex) (D3DFVF_TEXTUREFORMAT2)
D3DFVF_TEXCOORDSIZE3(CoordIndex) (D3DFVF_TEXTUREFORMAT3 << (CoordIndex*2 + 16))
D3DFVF_TEXCOORDSIZE4(CoordIndex) (D3DFVF_TEXTUREFORMAT4 << (CoordIndex*2 + 16))

Parameters

CoordIndex
Value that identifies the texture coordinate set at which the texture coordinate size (1-, 2-, 3-, or 4-dimensional) applies.

Remarks

The D3DFVF_TEXCOORDSIZEn macros use the following constants.

#define D3DFVF_TEXTUREFORMAT1 3         // one floating point value
#define D3DFVF_TEXTUREFORMAT2 0         // two floating point values
#define D3DFVF_TEXTUREFORMAT3 1         // three floating point values
#define D3DFVF_TEXTUREFORMAT4 2         // four floating point values

The following flexible vertex format description identifies a vertex format that has a position; a normal; diffuse and specular colors; and two sets of texture coordinates. The first set of texture coordinates includes a single element, and the second set includes two elements:

DWORD dwFVF;
dwFVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE | D3DFVF_SPECULAR |
        D3DFVF_TEXCOORDSIZE1(0) |  \\ Uses 1-D texture coordinates for
                                   \\ texture coordinate set 1 (index
                                   \\ 0).
        D3DFVF_TEXCOORDSIZE2(1);   \\ And 2-D texture coordinates for
                                   \\ texture coordinate set 2 (index
                                   \\ 1).

Requirements

Header: Declared in D3d8types.h.

See Also

Flexible Vertex Format Flags


D3DTS_WORLD

Identifies the transformation matrix being set as the world transformation matrix.

D3DTS_WORLD  D3DTS_WORLDMATRIX(0)

Parameters

None.

Remarks

This macro is provided to facilitate porting existing applications to Microsoft® DirectX® 8.0.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::SetTransform, D3DTS_WORLDMATRIX


D3DTS_WORLDn

Identifies subsequent transformation matrices that can be used to blend vertices by using the corresponding matrix and a blending (beta) weight value specified in the vertex format.

D3DTS_WORLD1 D3DTS_WORLDMATRIX(1)
D3DTS_WORLD2 D3DTS_WORLDMATRIX(2)
D3DTS_WORLD3 D3DTS_WORLDMATRIX(3)

Parameters

None.

Remarks

These macros are provided to facilitate porting existing applications to Microsoft® DirectX® 8.0.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::SetTransform, D3DTS_WORLDMATRIX


D3DTS_WORLDMATRIX

Maps indices in the range 0 through 255 to the corresponding transform states.

D3DTS_WORLDMATRIX(index) (D3DTRANSFORMSTATETYPE)(index + 256)

Parameters

index
An index value in the range 0 through 255.

Remarks

Transform states in the range 256 through 511 are reserved to store up to 256 matrices that can be indexed using 8-bit indices.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::SetTransform


Vertex Shader Declarator Macros

The following section covers the bit assembly macros used to compose the vertex shader declaration DWORD array.

  • D3DVSD_CONST
  • D3DVSD_END
  • D3DVSD_NOP
  • D3DVSD_REG
  • D3DVSD_SKIP
  • D3DVSD_STREAM
  • D3DVSD_STREAM_TESS
  • D3DVSD_TESSNORMAL
  • D3DVSD_TESSUV


D3DVSD_CONST

Loads data into the vertex shader constant memory.

D3DVSD_CONST( _ConstantAddress, _Count ) \
            (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_CONSTMEM) | \
            ((_Count) << D3DVSD_CONSTCOUNTSHIFT) | (_ConstantAddress))

Parameters

_ConstantAddress
Address of the constant array to begin filling data. Possible values range from 0 to 95.
_Count
Number of constant vectors to load (4 DWORDs each) followed by 4*_Count DWORDs of data. See Remarks.

Remarks

The following code example shows how this macro might be used.

D3DVALUE diffuse[] = {1, 1, 1.0f/255.0f, 1};
        DWORD decl[] =
        {
            D3DVSD_CONST(8, 1),
            *(DWORD*)&diffuse[0],
            *(DWORD*)&diffuse[1],
            *(DWORD*)&diffuse[2],
            *(DWORD*)&diffuse[3],
            D3DVSD_STREAM(0),
            D3DVSD_REG( 0, D3DVSDT_FLOAT3),
            D3DVSD_REG( 2, D3DVSDT_D3DCOLOR),
            D3DVSD_STREAM(1),
            D3DVSD_REG( 1, D3DVSDT_FLOAT1),
            D3DVSD_STREAM(2),
            D3DVSD_REG( 3, D3DVSDT_FLOAT2),
            D3DVSD_END()
        };

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::CreateVertexShader


D3DVSD_END

Generates an END token.

#define D3DVSD_END()

Parameters

None.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::CreateVertexShader


D3DVSD_NOP

Generates an NOP token.

#define D3DVSD_NOP()

Parameters

None.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::CreateVertexShader


D3DVSD_REG

Binds a single vertex register to a vertex element from the vertex stream.

D3DVSD_REG( _VertexRegister, _Type ) \
          (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAMDATA) | \
          ((_Type) << D3DVSD_DATATYPESHIFT) | (_VertexRegister))

Parameters

_VertexRegister
Address of the vertex register. Possible values range from 0 through 15. For the fixed function pipeline, the input registers have the following fixed mapping.
D3DVSDE_POSITION
Register 0.
D3DVSDE_BLENDWEIGHT
Register 1.
D3DVSDE_NORMAL
Register 2.
D3DVSDE_PSIZE
Register 3.
D3DVSDE_DIFFUSE
Register 4.
D3DVSDE_SPECULAR
Register 5.
D3DVSDE_TEXCOORD0
Register 6.
D3DVSDE_TEXCOORD1
Register 7.
D3DVSDE_TEXCOORD2
Register 8.
D3DVSDE_TEXCOORD3
Register 9.
D3DVSDE_TEXCOORD4
Register 10.
D3DVSDE_TEXCOORD5
Register 11.
D3DVSDE_TEXCOORD6
Register 12.
D3DVSDE_TEXCOORD7
Register 13.
_Type
Specifies the dimensionality and arithmetic data type. The following values are defined.
D3DVSDT_D3DCOLOR
4-D packed unsigned bytes mapped to 0.0 to 1.0 range. In double word format this is ARGB, or in byte ordering it would be B, G, R, A.
D3DVSDT_FLOAT1
1-D float expanded to (value, 0.0, 0.0, 1.0)
D3DVSDT_FLOAT2
2-D float expanded to (value, value, 0.0, 1.0)
D3DVSDT_FLOAT3
3-D float expanded to (value, value, value, 1.0)
D3DVSDT_FLOAT4
4-D float.
D3DVSDT_UBYTE4
4-D unsigned byte. In double word format this is ABGR, or in byte ordering it would be R, G, B, A.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::CreateVertexShader


D3DVSD_SKIP

Specifies how many DWORDs to skip in the vertex.

D3DVSD_SKIP( _DWORDCount ) \
           (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAMDATA) | 0x10000000 | \
           ((_DWORDCount) << D3DVSD_SKIPCOUNTSHIFT))

Parameters

_DWORDCount
Number of DWORDs to skip in the vertex.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::CreateVertexShader


D3DVSD_STREAM

Sets the current stream.

D3DVSD_STREAM( _StreamNumber ) \
             (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAM) | (_StreamNumber))

Parameters

_StreamNumber
Specifies the stream from which to get data. Possible values range from 0 through dwMaxStreams - 1.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::CreateVertexShader


D3DVSD_STREAM_TESS

Sets the tessellator stream.

D3DVSD_STREAM_TESS( ) \
      (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_STREAM) | (D3DVSD_STREAMTESSMASK))

Parameters

None.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::CreateVertexShader


D3DVSD_TESSNORMAL

Enables tessellator-generated normals.

D3DVSD_TESSNORMAL( _VertexRegisterIn, _VertexRegisterOut ) \
                 (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_TESSELLATOR) | \
                 ((_VertexRegisterIn) << D3DVSD_VERTEXREGINSHIFT) | \
                 ((0x02) << D3DVSD_DATATYPESHIFT) | (_VertexRegisterOut))

Parameters

_VertexRegisterIn
Address of the vertex register whose input stream will be used in normal computation. Possible values range from 0 to 15.
_VertexRegisterOut
Address of the vertex register to output the normal to. Possible values range from 0 to 15.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::CreateVertexShader


D3DVSD_TESSUV

Enables tessellator-generated surface parameters.

D3DVSD_TESSUV( _VertexRegister ) \
             (D3DVSD_MAKETOKENTYPE(D3DVSD_TOKEN_TESSELLATOR) | 0x10000000 | \
             ((0x01) << D3DVSD_DATATYPESHIFT) | (_VertexRegister))

Parameters

_VertexRegister
Address of the vertex register to output parameters. Possible values range from 0 to 15.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::CreateVertexShader


Structures

This section contains information about the structures used with Microsoft® Direct3D®.

  • D3DADAPTER_IDENTIFIER8
  • D3DBOX
  • D3DCAPS8
  • D3DCLIPSTATUS8
  • D3DCOLORVALUE
  • D3DDEVICE_CREATION_PARAMETERS
  • D3DDISPLAYMODE
  • D3DGAMMARAMP
  • D3DINDEXBUFFER_DESC
  • D3DLIGHT8
  • D3DLINEPATTERN
  • D3DLOCKED_BOX
  • D3DLOCKED_RECT
  • D3DMATERIAL8
  • D3DMATRIX
  • D3DPRESENT_PARAMETERS
  • D3DRANGE
  • D3DRASTER_STATUS
  • D3DRECT
  • D3DRECTPATCH_INFO
  • D3DSURFACE_DESC
  • D3DTRIPATCH_INFO
  • D3DVECTOR
  • D3DVERTEXBUFFER_DESC
  • D3DVIEWPORT8
  • D3DVOLUME_DESC


D3DADAPTER_IDENTIFIER8

Contains information identifying the adapter.

typedef struct _D3DADAPTER_IDENTIFIER8 {
    char            Driver[MAX_DEVICE_IDENTIFIER_STRING];
    char            Description[MAX_DEVICE_IDENTIFIER_STRING];

#ifdef _WIN32
    LARGE_INTEGER   DriverVersion;            /* Defined for 32-bit components */
#else
    DWORD           DriverVersionLowPart;     /* Defined for 16-bit driver components */
    DWORD           DriverVersionHighPart;
#endif

    DWORD           VendorId;
    DWORD           DeviceId;
    DWORD           SubSysId;
    DWORD           Revision;

    GUID            DeviceIdentifier;

    DWORD           WHQLLevel;
} D3DADAPTER_IDENTIFIER8;

Members

Driver and Description
Used for presentation to the user. They should not be used to identify particular drivers, since many different strings may be associated with the same device and driver from different vendors.
DriverVersion, DriverVersionLowPart, and DriverVersionHighPart
Identify the version of the Microsoft® Direct3D® driver. It is legal to do < and > comparisons on the 64-bit signed integer value. However, exercise caution if you use this element to identify problematic drivers. Instead, you should use DeviceIdentifier.

The following pseudocode example illustrates the version format encoded in this member.

Product = HIWORD(DriverVersion.HighPart)
Version = LOWORD(DriverVersion.HighPart)
SubVersion = HIWORD(DriverVersion.LowPart)
Build = LOWORD(DriverVersion.LowPart)

See the Microsoft Platform Software Development Kit (SDK) for more information on the HIWORD macro, the LOWORD macro, and the LARGE_INTEGER structure.

VendorId
Can be used to help identify a particular chip set. Query this member to identify the manufacturer. The value may be zero if unknown.
DeviceId
Can be used to help identify a particular chip set. Query this member to identify the type of chip set. The value may be zero if unknown.
SubSysId
Can be used to help identify a particular chip set. Query this member to identify the subsystem, typically the particular board. The value may be zero if unknown.
Revision
Can be used to help identify a particular chip set. Query this member to identify the revision level of the chip set. The value may be zero if unknown.
DeviceIdentifier
Can be queried to check changes in the driver and chip set. This GUID is a unique identifier for the driver and chip set pair. Query this member to track changes to the driver and chip set in order to generate a new profile for the graphics subsystem. DeviceIdentifier can also be used to identify particular problematic drivers.
WHQLLevel
Used to determine the Windows Hardware Quality Lab (WHQL) certification level for this driver and device pair. The DWORD is a packed date structure defining the date of the release of the most recent WHQL test passed by the driver. It is legal to perform < and > operations on this value. The following illustrates the date format.
Bits
31-16:    The year, a decimal number from 1999 upwards.
15-8:     The month, a decimal number from 1 to 12.
7-0:      The day, a decimal number from 1 to 31.

The following values are also used.

0
Not certified.
1
WHQL certified, but no date information is available.

Remarks

MAX_DEVICE_IDENTIFIER_STRING is a constant with the following definition.

#define MAX_DEVICE_IDENTIFIER_STRING        512

The VendorId, DeviceId, SubSysId, and Revision members can be used in tandem to identify particular chip sets. However, use these members with caution.

Requirements

Header: Declared in D3d8types.h.


D3DBOX

Defines a volume.

typedef struct _D3DBOX {
    UINT                Left;
    UINT                Top;
    UINT                Right;
    UINT                Bottom;
    UINT                Front;
    UINT                Back;
} D3DBOX;

Members

Left, Top, Right, Bottom, Front, and Back
Dimensions of the box.

Remarks

D3DBOX includes the left, top, and front edges; however, the right, bottom, and back edges are not included. For example, a box that is 100 units wide and begins at 0 (thus, including the points up to and including 99) would be expressed with a value of 0 for the Left member and a value of 100 for the Right member. Note that a value of 99 is not used for the Right member.

The restrictions on side ordering observed for D3DBOX are left to right, top to bottom, and front to back.

Requirements

Header: Declared in D3d8types.h.


D3DCAPS8

Represents the capabilities of the hardware exposed through the Microsoft® Direct3D® object.

typedef struct _D3DCAPS8 {
    D3DDEVTYPE          DeviceType;
    UINT                AdapterOrdinal;

    DWORD               Caps;
    DWORD               Caps2;
    DWORD               Caps3;
    DWORD               PresentationIntervals;

    DWORD               CursorCaps;

    DWORD               DevCaps;

    DWORD               PrimitiveMiscCaps;
    DWORD               RasterCaps;
    DWORD               ZCmpCaps;
    DWORD               SrcBlendCaps;
    DWORD               DestBlendCaps;
    DWORD               AlphaCmpCaps;
    DWORD               ShadeCaps;
    DWORD               TextureCaps;
    DWORD               TextureFilterCaps;
    DWORD               CubeTextureFilterCaps;
    DWORD               VolumeTextureFilterCaps;
    DWORD               TextureAddressCaps;
    DWORD               VolumeTextureAddressCaps;

    DWORD               LineCaps;

    DWORD               MaxTextureWidth, MaxTextureHeight;
    DWORD               MaxVolumeExtent;

    DWORD               MaxTextureRepeat;
    DWORD               MaxTextureAspectRatio;
    DWORD               MaxAnisotropy;
    float               MaxVertexW;

    float               GuardBandLeft;
    float               GuardBandTop;
    float               GuardBandRight;
    float               GuardBandBottom;

    float               ExtentsAdjust;
    DWORD               StencilCaps;

    DWORD               FVFCaps;
    DWORD               TextureOpCaps;
    DWORD               MaxTextureBlendStages;
    DWORD               MaxSimultaneousTextures;

    DWORD               VertexProcessingCaps;
    DWORD               MaxActiveLights;
    DWORD               MaxUserClipPlanes;
    DWORD               MaxVertexBlendMatrices;
    DWORD               MaxVertexBlendMatrixIndex;

    float               MaxPointSize;

    DWORD               MaxPrimitiveCount;
    DWORD               MaxVertexIndex;
    DWORD               MaxStreams;
    DWORD               MaxStreamStride;

    DWORD               VertexShaderVersion;
    DWORD               MaxVertexShaderConst;

    DWORD               PixelShaderVersion;
    float               MaxPixelShaderValue;
} D3DCAPS8;

Members

DeviceType
Member of the D3DDEVTYPE enumerated type. The device type for which this Direct3DDevice object was created.
AdapterOrdinal
Adapter on which this Direct3DDevice object was created. This ordinal is valid only to pass to methods of the IDirect3D8 interface that created this Direct3DDevice object. The IDirect3D8 interface can always be retrieved by calling IDirect3DDevice8::GetDirect3D.
Caps
The following driver-specific capability.
D3DCAPS_READ_SCANLINE
Display hardware is capable of returning the current scan line.
Caps2
The following driver-specific capabilities.
D3DCAPS2_CANCALIBRATEGAMMA
The system has a calibrator installed that can automatically adjust the gamma ramp so that the result is identical on all systems that have a calibrator. To invoke the calibrator when setting new gamma levels, use the D3DSGR_CALIBRATE flag when calling the IDirect3DDevice8::SetGammaRamp method. Calibrating gamma ramps incurs some processing overhead and should not be used frequently.
D3DCAPS2_CANRENDERWINDOWED
The driver is capable of rendering in windowed mode.
D3DCAPS2_FULLSCREENGAMMA
The driver supports dynamic gamma ramp adjustment in full-screen mode.
D3DCAPS2_NO2DDURING3DSCENE
When the D3DCAPS2_NO2DDURING3DSCENE capability is set by the driver, it means that 2-D operations cannot be performed between calls to IDirect3DDevice8::BeginScene and IDirect3DDevice8::EndScene.

Typically, this capability is set by hardware that partitions the scene and then renders each partition in sequence. The partitioning is performed in the driver, and the hardware contains a small color and depth buffer that corresponds to the size of the image partition. Typically, on this type of rendering hardware, once each part of the image is rendered, the data in the color buffers are written to video memory and the contents of the depth-buffer are discarded. Also, note that 3-D rendering does not start until EndScene is encountered. Next, the scene is processed in regions. Therefore, the processing order cannot be guaranteed. For example, the first region that is processed, typically the upper-left corner of the window, might include the last triangle in the frame. This differs from more traditional graphics systems in which each command is processed sequentially in the order that it was sent. The 2-D operations are implied to occur at some fixed point in the processing. In the systems that set D3DCAPS2_NO2DDURING3DSCENE, the processing order is not guaranteed. Therefore, the display adapter might discard 2-D operations that are encountered during 3-D rendering.

In general, it is recommended that 2-D operations be performed outside of a BeginScene and EndScene pair. If 2-D operations are to be performed between a BeginScene and EndScene pair, then it is necessary to check the D3DCAPS2_NO2DDURING3DSCENE capability. If it is set, the application must expect that any 2-D operation that occurs between BeginScene and EndScene will be discarded. For more information on writing applications for systems that set D3DCAPS2_NO2DDURING3DSCENE, see Remarks.

D3DCAPS2_RESERVED
Reserved; not used.
Caps3
The following driver-specific capability.
D3DCAPS3_RESERVED
Reserved; not used.
PresentationIntervals
Bit mask of values representing what presentation swap intervals are available. For windowed mode, this value must be 0; otherwise, this value must be one of the values enumerated in the PresentationIntervals member of D3DCAPS8.
D3DPRESENT_INTERVAL_IMMEDIATE
The driver supports an immediate presentation swap interval.
D3DPRESENT_INTERVAL_ONE
The driver supports a presentation swap interval of every screen refresh.
D3DPRESENT_INTERVAL_TWO
The driver supports a presentation swap interval of every second screen refresh.
D3DPRESENT_INTERVAL_THREE
The driver supports a presentation swap interval of every third screen refresh.
D3DPRESENT_INTERVAL_FOUR
The driver supports a presentation swap interval of every fourth screen refresh.
CursorCaps
Bit mask indicating what hardware support is available for cursors.
D3DCURSORCAPS_COLOR
A full-color cursor is supported in hardware. Specifically, this flag indicates that the driver supports at least a hardware color cursor in high-resolution modes (with scan lines greater than or equal to 400).
D3DCURSORCAPS_LOWRES
A full-color cursor is supported in hardware. Specifically, this flag indicates that the driver supports a hardware color cursor in both high-resolution and low-resolution modes (with scan lines less than 400).

Direct3D for Microsoft DirectX® 8.0 does not define alpha-blending cursor capabilities.

DevCaps
Flags identifying the capabilities of the device.
D3DDEVCAPS_CANBLTSYSTONONLOCAL
Device supports blits from system-memory textures to nonlocal video-memory textures.
D3DDEVCAPS_CANRENDERAFTERFLIP
Device can queue rendering commands after a page flip. Applications do not change their behavior if this flag is set; this capability simply means that the device is relatively fast.
D3DDEVCAPS_DRAWPRIMTLVERTEX
Device exports a DrawPrimitive-aware hardware abstraction layer (HAL).
D3DDEVCAPS_EXECUTESYSTEMMEMORY
Device can use execute buffers from system memory.
D3DDEVCAPS_EXECUTEVIDEOMEMORY
Device can use execute buffers from video memory.
D3DDEVCAPS_HWRASTERIZATION
Device has hardware acceleration for scene rasterization.
D3DDEVCAPS_HWTRANSFORMANDLIGHT
Device can support transformation and lighting in hardware.
D3DDEVCAPS_NPATCHES
Device supports N patches.
D3DDEVCAPS_PUREDEVICE
Device can support rasterization, transform, lighting, and shading in hardware.
D3DDEVCAPS_QUINTICRTPATCHES
Device supports quintic béziers and B-splines.
D3DDEVCAPS_RTPATCHES
Device supports rectangular and triangular patches.
D3DDEVCAPS_RTPATCHHANDLEZERO
When this device capability is set, the hardware architecture does not require caching of any information, and uncached patches (handle zero) will be drawn as efficiently as cached ones. Note that setting D3DDEVCAPS_RTPATCHHANDLEZERO does not mean that a patch with handle zero can be drawn. A handle-zero patch can always be drawn whether this cap is set or not.
D3DDEVCAPS_SEPARATETEXTUREMEMORIES
Device is texturing from separate memory pools.
D3DDEVCAPS_TEXTURENONLOCALVIDMEM
Device can retrieve textures from non-local video memory.
D3DDEVCAPS_TEXTURESYSTEMMEMORY
Device can retrieve textures from system memory.
D3DDEVCAPS_TEXTUREVIDEOMEMORY
Device can retrieve textures from device memory.
D3DDEVCAPS_TLVERTEXSYSTEMMEMORY
Device can use buffers from system memory for transformed and lit vertices.
D3DDEVCAPS_TLVERTEXVIDEOMEMORY
Device can use buffers from video memory for transformed and lit vertices.
PrimitiveMiscCaps
General capabilities for this primitive. This member can be one or more of the following flags.
D3DPMISCCAPS_BLENDOP
Device supports the alpha-blending operations defined in the D3DBLENDOP enumerated type.
D3DPMISCCAPS_CLIPPLANESCALEDPOINTS
Device correctly clips scaled points of size greater than 1.0 to user-defined clipping planes.
D3DPMISCCAPS_CLIPTLVERTS
Device clips post-transformed vertex primitives.
D3DPMISCCAPS_COLORWRITEENABLE
Device supports per-channel writes for the render target color buffer through the D3DRS_COLORWRITEENABLE state.
D3DPMISCCAPS_CULLCCW
The driver supports counterclockwise culling through the D3DRS_CULLMODE state. (This applies only to triangle primitives.) This flag corresponds to the D3DCULL_CCW member of the D3DCULL enumerated type.
D3DPMISCCAPS_CULLCW
The driver supports clockwise triangle culling through the D3DRS_CULLMODE state. (This applies only to triangle primitives.) This flag corresponds to the D3DCULL_CW member of the D3DCULL enumerated type.
D3DPMISCCAPS_CULLNONE
The driver does not perform triangle culling. This corresponds to the D3DCULL_NONE member of the D3DCULL enumerated type.
D3DPMISCCAPS_LINEPATTERNREP
The driver can handle values other than 1 in the wRepeatFactor member of the D3DLINEPATTERN structure. (This applies only to line-drawing primitives.)
D3DPMISCCAPS_MASKZ
Device can enable and disable modification of the depth buffer on pixel operations.
D3DPMISCCAPS_TSSARGTEMP
Device supports D3DTA_TEMP for temporary register.
RasterCaps
Information on raster-drawing capabilities. This member can be one or more of the following flags.
D3DPRASTERCAPS_ANISOTROPY
Device supports anisotropic filtering.
D3DPRASTERCAPS_ANTIALIASEDGES
Device can anti-alias lines forming the convex outline of objects. For more information, see D3DRS_EDGEANTIALIAS.
D3DPRASTERCAPS_COLORPERSPECTIVE
Device iterates colors perspective correct.
D3DPRASTERCAPS_DITHER
Device can dither to improve color resolution.
D3DPRASTERCAPS_FOGRANGE
Device supports range-based fog. In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene.
D3DPRASTERCAPS_FOGTABLE
Device calculates the fog value by referring to a lookup table containing fog values that are indexed to the depth of a given pixel.
D3DPRASTERCAPS_FOGVERTEX
Device calculates the fog value during the lighting operation, and interpolates the fog value during rasterization.
D3DPRASTERCAPS_MIPMAPLODBIAS
Device supports level-of-detail (LOD) bias adjustments. These bias adjustments enable an application to make a mipmap appear crisper or less sharp than it normally would. For more information about LOD bias in mipmaps, see D3DTSS_MIPMAPLODBIAS.
D3DPRASTERCAPS_PAT
The driver can perform patterned drawing lines or fills with D3DRS_LINEPATTERN for the primitive being queried.
D3DPRASTERCAPS_STRETCHBLTMULTISAMPLE
Device provides limited multisample support through a stretch-blt implementation. When this capability is set, D3DRS_MULTISAMPLEANTIALIAS cannot be turned on and off in the middle of a scene. Multisample masking cannot be performed if this flag is set.
D3DPRASTERCAPS_WBUFFER
Device supports depth buffering using w.
D3DPRASTERCAPS_WFOG
Device supports w-based fog. W-based fog is used when a perspective projection matrix is specified, but affine projections still use z-based fog. The system considers a projection matrix that contains a nonzero value in the [3][4] element to be a perspective projection matrix.
D3DPRASTERCAPS_ZBIAS
Device supports z-bias values. These are integer values assigned to polygons that allow physically coplanar polygons to appear separate. For more information, see D3DRS_ZBIAS.
D3DPRASTERCAPS_ZBUFFERLESSHSR
Device can perform hidden-surface removal (HSR) without requiring the application to sort polygons and without requiring the allocation of a depth-buffer. This leaves more video memory for textures. The method used to perform HSR is hardware-dependent and is transparent to the application.

Z-bufferless HSR is performed if no depth-buffer surface is associated with the rendering-target surface and the depth-buffer comparison test is enabled (that is, when the state value associated with the D3DRS_ZENABLE enumeration constant is set to TRUE).

D3DPRASTERCAPS_ZFOG
Device supports z-based fog.
D3DPRASTERCAPS_ZTEST
Device can perform z-test operations. This effectively renders a primitive and indicates whether any z pixels have been rendered.
ZCmpCaps
Z-buffer comparison capabilities. This member can be one or more of the following flags.
D3DPCMPCAPS_ALWAYS
Always pass the z test.
D3DPCMPCAPS_EQUAL
Pass the z test if the new z equals the current z.
D3DPCMPCAPS_GREATER
Pass the z test if the new z is greater than the current z.
D3DPCMPCAPS_GREATEREQUAL
Pass the z test if the new z is greater than or equal to the current z.
D3DPCMPCAPS_LESS
Pass the z test if the new z is less than the current z.
D3DPCMPCAPS_LESSEQUAL
Pass the z test if the new z is less than or equal to the current z.
D3DPCMPCAPS_NEVER
Always fail the z test.
D3DPCMPCAPS_NOTEQUAL
Pass the z test if the new z does not equal the current z.
SrcBlendCaps
Source-blending capabilities. This member can be one or more of the following flags. (The RGBA values of the source and destination are indicated by the subscripts s and d.)
D3DPBLENDCAPS_BOTHINVSRCALPHA
Source blend factor is (1–As, 1–As, 1–As, 1–As), and destination blend factor is (As, As, As, As); the destination blend selection is overridden.
D3DPBLENDCAPS_BOTHSRCALPHA
The driver supports the D3DBLEND_BOTHSRCALPHA blend mode. (This blend mode is obsolete. For more information, see D3DBLEND.)
D3DPBLENDCAPS_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DPBLENDCAPS_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DPBLENDCAPS_INVDESTALPHA
Blend factor is (1–Ad, 1–Ad, 1–Ad, 1–Ad).
D3DPBLENDCAPS_INVDESTCOLOR
Blend factor is (1–Rd, 1–Gd, 1–Bd, 1–Ad).
D3DPBLENDCAPS_INVSRCALPHA
Blend factor is (1–As, 1–As, 1–As, 1–As).
D3DPBLENDCAPS_INVSRCCOLOR
Blend factor is (1–Rd, 1–Gd, 1–Bd, 1–Ad).
D3DPBLENDCAPS_ONE
Blend factor is (1, 1, 1, 1).
D3DPBLENDCAPS_SRCALPHA
Blend factor is (As, As, As, As).
D3DPBLENDCAPS_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1-Ad).
D3DPBLENDCAPS_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DPBLENDCAPS_ZERO
Blend factor is (0, 0, 0, 0).
DestBlendCaps
Destination-blending capabilities. This member can be the same capabilities that are defined for the SrcBlendCaps member.
AlphaCmpCaps
Alpha-test comparison capabilities. This member can include the same capability flags defined for the ZCmpCaps member. If this member contains only the D3DPCMPCAPS_ALWAYS capability or only the D3DPCMPCAPS_NEVER capability, the driver does not support alpha tests. Otherwise, the flags identify the individual comparisons that are supported for alpha testing.
ShadeCaps
Shading operations capabilities. It is assumed, in general, that if a device supports a given command at all, it supports the D3DSHADE_FLAT mode (as specified in the D3DSHADEMODE enumerated type). This flag specifies whether the driver can also support Gouraud shading and whether alpha color components are supported. When alpha components are not supported, the alpha value of colors generated is implicitly 255. This is the maximum possible alpha (that is, the alpha component is at full intensity).

The color, specular highlights, fog, and alpha interpolants of a triangle each have capability flags that an application can use to find out how they are implemented by the device driver.

This member can be one or more of the following flags.

D3DPSHADECAPS_ALPHAGOURAUDBLEND
Device can support an alpha component for Gouraud-blended transparency (the D3DSHADE_GOURAUD state for the D3DSHADEMODE enumerated type). In this mode, the alpha color component of a primitive is provided at vertices and interpolated across a face along with the other color components.
D3DPSHADECAPS_COLORGOURAUDRGB
Device can support colored Gouraud shading in the RGB color model. In this mode, the color component for a primitive is provided at vertices and interpolated across a face along with the other color components. In the RGB lighting model, the red, green, and blue components are interpolated.
D3DPSHADECAPS_FOGGOURAUD
Device can support fog in the Gouraud shading mode.
D3DPSHADECAPS_SPECULARGOURAUDRGB
Device can support specular highlights in Gouraud shading in the RGB color model.
TextureCaps
Miscellaneous texture-mapping capabilities. This member can be one or more of the following flags.
D3DPTEXTURECAPS_ALPHA
Alpha in texture pixels is supported.
D3DPTEXTURECAPS_ALPHAPALETTE
Device can draw alpha from texture palettes.
D3DPTEXTURECAPS_CUBEMAP
Supports cube textures
D3DPTEXTURECAPS_CUBEMAP_POW2
Device requires that cube texture maps have dimensions specified as powers of 2.
D3DPTEXTURECAPS_MIPCUBEMAP
Device supports mipmapped cube textures.
D3DPTEXTURECAPS_MIPMAP
Device supports mipmapped textures.
D3DPTEXTURECAPS_MIPVOLUMEMAP
Device supports mipmapped volume textures.
D3DPTEXTURECAPS_NONPOW2CONDITIONAL
Conditionally supports the use of textures with dimensions that are not powers of 2. A device that exposes this capability can use such a texture if all of the following requirements are met.
  • The texture addressing mode for the texture stage is set to D3DTADDRESS_CLAMP.
  • Texture wrapping for the texture stage is disabled (D3DRS_WRAPn set to 0).
  • Mipmapping is not in use (use magnification filter only).
D3DPTEXTURECAPS_PERSPECTIVE
Perspective correction texturing is supported.
D3DPTEXTURECAPS_POW2
All textures must have widths and heights specified as powers of 2. This requirement does not apply to either cube textures or volume textures.
D3DPTEXTURECAPS_PROJECTED
Supports the D3DTTFF_PROJECTED texture transformation flag. When applied, the device divides transformed texture coordinates by the last texture coordinate. If this capability is present, then the projective divide occurs per pixel. If this capability is not present, but the projective divide needs to occur anyway, then it is performed on a per-vertex basis by the Direct3D runtime.
D3DPTEXTURECAPS_SQUAREONLY
All textures must be square.
D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE
Texture indices are not scaled by the texture size prior to interpolation.
D3DPTEXTURECAPS_VOLUMEMAP
Device supports volume textures.
D3DPTEXTURECAPS_VOLUMEMAP_POW2
Device requires that volume texture maps have dimensions specified as powers of 2.
TextureFilterCaps
Texture-filtering capabilities for a Direct3DTexture object. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending with the IDirect3DDevice8 interface. This member can be any combination of the following per-stage texture-filtering flags.
D3DPTFILTERCAPS_MAGFAFLATCUBIC
Device supports per-stage flat cubic filtering for magnifying textures. The flat cubic magnification filter is represented by the D3DTEXF_FLATCUBIC member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFANISOTROPIC
Device supports per-stage anisotropic filtering for magnifying textures. The anisotropic magnification filter is represented by the D3DTEXF_ANISOTROPIC member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFGAUSSIANCUBIC
Device supports the per-stage Gaussian cubic filtering for magnifying textures. The Gaussian cubic magnification filter is represented by the D3DTEXF_GAUSSIANCUBIC member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFLINEAR
Device supports per-stage bilinear interpolation filtering for magnifying textures. The bilinear interpolation magnification filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MAGFPOINT
Device supports per-stage point-sample filtering for magnifying textures. The point-sample magnification filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFANISOTROPIC
Device supports per-stage anisotropic filtering for minifying textures. The anisotropic minification filter is represented by the D3DTEXF_ANISOTROPIC member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFLINEAR
Device supports per-stage bilinear interpolation filtering for minifying textures. The bilinear minification filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MINFPOINT
Device supports per-stage point-sample filtering for minifying textures. The point-sample minification filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MIPFLINEAR
Device supports per-stage trilinear interpolation filtering for mipmaps. The trilinear interpolation mipmapping filter is represented by the D3DTEXF_LINEAR member of the D3DTEXTUREFILTERTYPE enumerated type.
D3DPTFILTERCAPS_MIPFPOINT
Device supports per-stage point-sample filtering for mipmaps. The point-sample mipmapping filter is represented by the D3DTEXF_POINT member of the D3DTEXTUREFILTERTYPE enumerated type.
CubeTextureFilterCaps
Texture-filtering capabilities for a Direct3DCubeTexture object. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending with the IDirect3DDevice8 interface. This member can be any combination of the per-stage texture-filtering flags defined for the TextureFilterCaps member.
VolumeTextureFilterCaps
Texture-filtering capabilities for a Direct3DVolumeTexture object. Per-stage filtering capabilities reflect which filtering modes are supported for texture stages when performing multiple-texture blending with the IDirect3DDevice8 interface. This member can be any combination of the per-stage texture-filtering flags defined for the TextureFilterCaps member.
TextureAddressCaps
Texture-addressing capabilities for Direct3DTexture objects. This member can be one or more of the following flags.
D3DPTADDRESSCAPS_BORDER
Device supports setting coordinates outside the range [0.0, 1.0] to the border color, as specified by the D3DTSS_BORDERCOLOR texture-stage state.
D3DPTADDRESSCAPS_CLAMP
Device can clamp textures to addresses.
D3DPTADDRESSCAPS_INDEPENDENTUV
Device can separate the texture-addressing modes of the u and v coordinates of the texture. This ability corresponds to the D3DTSS_ADDRESSU and D3DTSS_ADDRESSV render-state values.
D3DPTADDRESSCAPS_MIRROR
Device can mirror textures to addresses.
D3DPTADDRESSCAPS_MIRRORONCE
Device can take the absolute value of the texture coordinate (thus, mirroring around 0), and then clamp to the maximum value.
D3DPTADDRESSCAPS_WRAP
Device can wrap textures to addresses.
VolumeTextureAddressCaps
Texture-addressing capabilities for Direct3DVolumeTexture objects. This member can be one or more of the flags defined for the TextureAddressCaps member.
LineCaps
Defines the capabilities for line-drawing primitives.
D3DLINECAPS_ALPHACMP
Supports alpha-test comparisons.
D3DLINECAPS_BLEND
Supports source-blending.
D3DLINECAPS_FOG
Supports fog.
D3DLINECAPS_TEXTURE
Supports texture-mapping.
D3DLINECAPS_ZTEST
Supports z-buffer comparisons.
MaxTextureWidth and MaxTextureHeight
Maximum texture width and height for this device.
MaxVolumeExtent
Maximum volume extent.
MaxTextureRepeat
Full range of the integer bits of the post-normalized texture indices. If the D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE bit is set, the device defers scaling by the texture size until after the texture address mode is applied. If not set, the device scales the texture indices by the texture size (largest level of detail) prior to interpolation.

If D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is set, then the exact number of times a texture can be wrapped is MaxTextureRepeat. If D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE is not set, then the exact number of times a texture can be wrapped is (MaxTextureRepeat * texture size). For example, the device has D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE set, MaxTextureRepeat is 32k, and the maximum texture size is 4k. The device uses 27 integer bits (plus 5 fraction bits in a 32 bit (signed) integer), and thus has enough to wrap a 4k texture 32k times (assuming the texture coordinates equally span the positive and negative texture coordinate range). Alternately, the device could not set D3DPTEXTURECAPS_TEXREPEATNOTSCALEDBYSIZE and set MaxTextureRepeat to 2**27.

MaxTextureAspectRatio
Maximum texture aspect ratio supported by the hardware, typically a power of 2.
MaxAnisotropy
Maximum valid value for the D3DTSS_MAXANISOTROPY texture-stage state.
MaxVertexW
Maximum W-based depth value that the device supports.
GuardBandLeft, GuardBandTop, GuardBandRight, and GuardBandBottom
Screen-space coordinates of the guard-band clipping region. Coordinates inside this rectangle but outside the viewport rectangle are automatically clipped.
ExtentsAdjust
Number of pixels to adjust the extents rectangle outward to accommodate anti-aliasing kernels.
StencilCaps
Flags specifying supported stencil-buffer operations. Stencil operations are assumed to be valid for all three stencil-buffer operation render states (D3DRS_STENCILFAIL, D3DRS_STENCILPASS, and D3DRS_STENCILFAILZFAIL).
D3DSTENCILCAPS_DECR
The D3DSTENCILOP_DECR operation is supported.
D3DSTENCILCAPS_DECRSAT
The D3DSTENCILOP_DECRSAT operation is supported.
D3DSTENCILCAPS_INCR
The D3DSTENCILOP_INCR operation is supported.
D3DSTENCILCAPS_INCRSAT
The D3DSTENCILOP_INCRSAT operation is supported.
D3DSTENCILCAPS_INVERT
The D3DSTENCILOP_INVERT operation is supported.
D3DSTENCILCAPS_KEEP
The D3DSTENCILOP_KEEP operation is supported.
D3DSTENCILCAPS_REPLACE
The D3DSTENCILOP_REPLACE operation is supported.
D3DSTENCILCAPS_ZERO
The D3DSTENCILOP_ZERO operation is supported.

For more information, see the D3DSTENCILOP enumerated type.

FVFCaps
Flexible vertex format capabilities.
D3DFVFCAPS_DONOTSTRIPELEMENTS
It is preferable that vertex elements not be stripped. That is, if the vertex format contains elements that are not used with the current render states, there is no need to regenerate the vertices. If this capability flag is not present, stripping extraneous elements from the vertex format provides better performance.
D3DFVFCAPS_PSIZE
The absence of D3DFVFCAPS_PSIZE indicates that the device does not support D3DFVF_PSIZE for pre-transformed vertices. In this case the base point size always comes fromD3DRS_POINTSIZE. This capability applies to fixed-function vertex processing in software only. D3DFVF_PSIZE is always supported when doing software vertex processing.

The output point size written by a vertex shader is always supported, and for vertex shaders any input can contribute to the output point size.

D3DFVF_PSIZE is always supported for post-transformed vertices.

D3DFVFCAPS_TEXCOORDCOUNTMASK
Masks the low WORD of FVFCaps. These bits, cast to the WORD data type, describe the total number of texture coordinate sets that the device can simultaneously use for multiple texture blending. (You can use up to eight texture coordinate sets for any vertex, but the device can blend using only the specified number of texture coordinate sets.)
TextureOpCaps
Combination of flags describing the texture operations supported by this device. The following flags are defined.
D3DTEXOPCAPS_ADD
The D3DTOP_ADD texture-blending operation is supported.
D3DTEXOPCAPS_ADDSIGNED
The D3DTOP_ADDSIGNED texture-blending operation is supported.
D3DTEXOPCAPS_ADDSIGNED2X
The D3DTOP_ADDSIGNED2X texture-blending operation is supported.
D3DTEXOPCAPS_ADDSMOOTH
The D3DTOP_ADDSMOOTH texture-blending operation is supported.
D3DTEXOPCAPS_BLENDCURRENTALPHA
The D3DTOP_BLENDCURRENTALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDDIFFUSEALPHA
The D3DTOP_BLENDDIFFUSEALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDFACTORALPHA
The D3DTOP_BLENDFACTORALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHA
The D3DTOP_BLENDTEXTUREALPHA texture-blending operation is supported.
D3DTEXOPCAPS_BLENDTEXTUREALPHAPM
The D3DTOP_BLENDTEXTUREALPHAPM texture-blending operation is supported.
D3DTEXOPCAPS_BUMPENVMAP
The D3DTOP_BUMPENVMAP texture-blending operation is supported.
D3DTEXOPCAPS_BUMPENVMAPLUMINANCE
The D3DTOP_BUMPENVMAPLUMINANCE texture-blending operation is supported.
D3DTEXOPCAPS_DISABLE
The D3DTOP_DISABLE texture-blending operation is supported.
D3DTEXOPCAPS_DOTPRODUCT3
The D3DTOP_DOTPRODUCT3 texture-blending operation is supported.
D3DTEXOPCAPS_LERP
The D3DTOP_LERP texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE
The D3DTOP_MODULATE texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE2X
The D3DTOP_MODULATE2X texture-blending operation is supported.
D3DTEXOPCAPS_MODULATE4X
The D3DTOP_MODULATE4X texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEALPHA_ADDCOLOR
The D3DTOP_MODULATEALPHA_ADDCOLOR texture-blending operation is supported.
D3DTEXOPCAPS_MODULATECOLOR_ADDALPHA
The D3DTOP_MODULATECOLOR_ADDALPHA texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEINVALPHA_ADDCOLOR
The D3DTOP_MODULATEINVALPHA_ADDCOLOR texture-blending operation is supported.
D3DTEXOPCAPS_MODULATEINVCOLOR_ADDALPHA
The D3DTOP_MODULATEINVCOLOR_ADDALPHA texture-blending operation is supported.
D3DTEXOPCAPS_MULTIPLYADD
The D3DTOP_MULTIPLYADD texture-blending operation is supported.
D3DTEXOPCAPS_PREMODULATE
The D3DTOP_PREMODULATE texture-blending operation is supported.
D3DTEXOPCAPS_SELECTARG1
The D3DTOP_SELECTARG1 texture-blending operation is supported.
D3DTEXOPCAPS_SELECTARG2
The D3DTOP_SELECTARG2 texture-blending operation is supported.
D3DTEXOPCAPS_SUBTRACT
The D3DTOP_SUBTRACT texture-blending operation is supported.
MaxTextureBlendStages
Maximum number of texture-blending stages supported. This value is the number of blenders available. In the DirectX 8.0 programmable pixel pipeline, this should correspond to the number of instructions supported by pixel shaders on this particular implementation.
MaxSimultaneousTextures
Maximum number of textures that can be simultaneously bound to the texture blending stages. This value is the number of textures that can be used in a single pass. In the DirectX 8.0 programmable pixel pipeline, this indicates the number of texture registers supported by pixel shaders on this particular piece of hardware, and the number of texture declaration instructions that can be present.
VertexProcessingCaps
Vertex processing capabilities. For a given physical device, this capability might vary across Direct3D Device Objects depending on the parameters supplied to IDirect3D8::CreateDevice.
D3DVTXPCAPS_DIRECTIONALLIGHTS
Device supports directional lights.
D3DVTXPCAPS_LOCALVIEWER
Device supports local viewer.
D3DVTXPCAPS_MATERIALSOURCE7
Device supports selectable vertex color sources.
D3DVTXPCAPS_POSITIONALLIGHTS
Device supports positional lights (including point lights and spotlights).
D3DVTXPCAPS_TEXGEN
Device can generate texture coordinates.
D3DVTXPCAPS_TWEENING
Device supports vertex tweening.
D3DVTXPCAPS_NO_VSDT_UBYTE4
Device does not support the D3DVSDT_UBYTE4 vertex declaration type.
MaxActiveLights
Maximum number of lights that can be active simultaneously. For a given physical device, this capability might vary across Direct3D Device Objects depending on the parameters supplied to IDirect3D8::CreateDevice.
MaxUserClipPlanes
Maximum number of user-defined clipping planes supported. This member can range from 0 through D3DMAXUSERCLIPPLANES. For a given physical device, this capability may vary across Direct3D Device Objects depending on the parameters supplied to IDirect3D8::CreateDevice.
MaxVertexBlendMatrices
Maximum number of matrices that this device can apply when performing multimatrix vertex blending. For a given physical device, this capability may vary across Direct3D Device Objects depending on the parameters supplied to IDirect3D8::CreateDevice.
MaxVertexBlendMatrixIndex
DWORD value that specifies the maximum matrix index that can be indexed into using the per-vertex indices. The number of matrices is MaxVertexBlendMatrixIndex + 1, which is the size of the matrix palette. If normals are present in the vertex data that needs to be blended for lighting, then the number of matrices is half the number specified by this capability flag. If MaxVertexBlendMatrixIndex is set to zero, the driver does not support indexed vertex blending. If this value is not zero then the valid range of indices is zero through MaxVertexBlendIndexedMatrices.

A zero value for MaxVertexBlendMatrixIndex indicates that the driver does not support indexed matrices.

When software vertex processing is used, 256 matrices could be used for indexed vertex blending, with or without normal blending.

For a given physical device, this capability may vary across Direct3D Device Objects depending on the parameters supplied to IDirect3D8::CreateDevice.

MaxPointSize
Maximum size of a point primitive. If set to 1.0f then device does not support point size control. The range is greater than or equal to 1.0f.
MaxPrimitiveCount
Maximum number of primitives for each DrawPrimitive call.
MaxVertexIndex
Maximum size of indices supported for hardware vertex processing. It is possible to create 32-bit index buffers by specifying D3DFMT_INDEX32; however, you will not be able to render with the index buffer unless this value is greater than 0x0000FFFF.
MaxStreams
Maximum number of concurrent data streams for IDirect3DDevice8::SetStreamSource. The valid range is 1 to 16. Note that if this value is 0, then the driver is not a DirectX 8.0 driver.
MaxStreamStride
Maximum stride for IDirect3DDevice8::SetStreamSource.
VertexShaderVersion
Vertex shader version, indicating the level of vertex shader supported by the device. Only vertex shaders with version numbers equal to or less than this will succeed in calls to IDirect3DDevice8::CreateVertexShader. The level of shader is specified to CreateVertexShader as the first token in the vertex shader token stream.
  • DirectX 7.0 functionality is 0
  • DirectX 8.0 functionality is 01

The main version number is encoded in the second byte. The low byte contains a sub-version number.

MaxVertexShaderConst
Number of vertex shader constant registers.
PixelShaderVersion
Pixel shader version, indicating the level of pixel shader supported by the device. Only pixel shaders with version numbers equal to or less than this will succeed in calls to IDirect3DDevice8::CreatePixelShader.
  • DirectX 8.0 functionality is 01

The main version number is encoded in the second byte. The low byte contains a sub-version number.

MaxPixelShaderValue
Maximum value of pixel shader arithmetic component. This value indicates the internal range of values supported for pixel color blending operations. Within the range that they report to, implementations must allow data pass through pixel processing unmodified (unclamped). Normally, the value of this member is an absolute value. For example, a 1.0 indicates that the range is -1.0 to 1, and an 8.0 indicates that the range is -8.0 to 8.0. Note that the value 0.0 indicates that no signed range is supported; therefore, the range is 0 to 1.0 as in DirectX 6.0 and 7.0

Remarks

The MaxTextureBlendStages and MaxSimultaneousTextures members might seem very similar, but they contain different information. The MaxTextureBlendStages member contains the total number of texture-blending stages supported by the current device, and the MaxSimultaneousTextures member describes how many of those stages can have textures bound to them by using the IDirect3DDevice8::SetTexture method.

When the driver fills this structure, it can set values for execute-buffer capabilities, even when the interface being used to retrieve the capabilities (such as IDirect3DDevice8) does not support execute buffers.

For systems that set the D3DCAPS2_NO2DDURING3DSCENE capability flag, performance problems may occur if you use a texture and then modify it during a scene. This is true on all hardware, but it is more severe on hardware that exposes the D3DCAPS2_NO2DDURING3DSCENE capability. If D3DCAPS2_NO2DDURING3DSCENE is present on the hardware, application-based texture management should ensure that no texture used in the current BeginScene and EndScene block is evicted unless absolutely necessary. In the case of extremely high texture usage within a scene, the results are undefined. This occurs when you modify a texture that you have used in the scene and there is no spare texture memory available. For such systems, the contents of the z buffer become invalid at EndScene. Applications should not call IDirect3DDevice8::CopyRects to or from the back buffer on this type of hardware inside a BeginScene and EndScene pair. In addition, applications should not try to access the z buffer if the D3DPRASTERCAPS_ZBUFFERLESSHSR capability flag is set. Finally, applications should not lock the back buffer or the z buffer inside a BeginScene and EndScene pair.

The following flags concerning mipmapped textures are not supported in DirectX 8.0.

  • D3DPTFILTERCAPS_NEAREST
  • D3DPTFILTERCAPS_LINEAR
  • D3DPTFILTERCAPS_MIPNEAREST
  • D3DPTFILTERCAPS_MIPLINEAR
  • D3DPTFILTERCAPS_LINEARMIPNEAREST
  • D3DPTFILTERCAPS_LINEARMIPLINEAR

Requirements

Header: Declared in D3d8caps.h.

See Also

IDirect3D8::GetDeviceCaps, IDirect3DDevice8::GetDeviceCaps


D3DCLIPSTATUS8

Describes the current clip status.

typedef struct _D3DCLIPSTATUS8 {
   DWORD ClipUnion;
   DWORD ClipIntersection;
} D3DCLIPSTATUS8;

Members

ClipUnion
Clip union flags that describe the current clip status. This member can be one or more of the following flags.
D3DCS_ALL
Combination of all clip flags.
D3DCS_BACK
All vertices are clipped by the back plane of the viewing frustum.
D3DCS_BOTTOM
All vertices are clipped by the bottom plane of the viewing frustum.
D3DCS_FRONT
All vertices are clipped by the front plane of the viewing frustum.
D3DCS_LEFT
All vertices are clipped by the left plane of the viewing frustum.
D3DCS_RIGHT
All vertices are clipped by the right plane of the viewing frustum.
D3DCS_TOP
All vertices are clipped by the top plane of the viewing frustum.
D3DCS_PLANE0 through D3DCS_PLANE5
Application-defined clipping planes.
ClipIntersection
Clip intersection flags that describe the current clip status. This member can take the same flags as ClipUnion.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetClipStatus, IDirect3DDevice8::SetClipStatus


D3DCOLORVALUE

Describes color values.

typedef struct _D3DCOLORVALUE {
    float r;
    float g;
    float b;
    float a;
} D3DCOLORVALUE;

Members

r, g, b, and a
Floating-point values specifying the red, green, blue, and alpha components of a color. These values generally are in the range from 0.0 through 1.0, with 0.0 being black.

Remarks

You can set the members of this structure to values outside the range of 0 through 1 to implement some unusual effects. Values greater than 1 produce strong lights that tend to wash out a scene. Negative values produce dark lights that actually remove light from a scene.

Requirements

Header: Declared in D3d8types.h.

See Also

Color Values for Lights and Materials


D3DDEVICE_CREATION_PARAMETERS

Describes the creation parameters for a device.

typedef struct _D3DDEVICE_CREATION_PARAMETERS {
    UINT          AdapterOrdinal;
    D3DDEVTYPE    DeviceType;
    DWORD         hFocusWindow;
    HWND          BehaviorFlags;
} D3DDEVICE_CREATION_PARAMETERS;

Members

AdapterOrdinal
Ordinal number that denotes the display adapter. D3DADAPTER_DEFAULT is always the primary display adapter.

Use this ordinal as the Adapter parameter for any of the IDirect3D8 methods. Note that different instances of Direct3D8 objects may use different ordinals. For example, adapters can enter and leave a system due to users adding or subtracting monitors from a multiple monitor system, or due to hot-swapping a laptop. Consequently, you should use this ordinal only in a Direct3D8 known to be valid. The only two valid Direct3D8 instances are the Direct3D8 that created this IDirect3DDevice8 interface and the Direct3D8 returned from IDirect3DDevice8::GetDirect3D,as called through this IDirect3DDevice8 interface.

DeviceType
Member of the D3DDEVTYPE enumerated type. Denotes the amount of emulated functionality for this device. The value of this parameter mirrors the value passed to the IDirect3D8::CreateDevice call that created this device.
hFocusWindow
Window handle to which focus belongs for this Microsoft® Direct3D® device. The value of this parameter mirrors the value passed to the IDirect3D8::CreateDevice call that created this device.
BehaviorFlags
A combination of one or more of the following flags that control global behaviors of the Microsoft® Direct3D® device.
D3DCREATE_FPU_PRESERVE
The calling application does not want Direct3D to modify the FPU state in ways that are visible to the application. In this mode, Direct3D saves and restores the FPU state every time it needs to modify the FPU state.
D3DCREATE_HARDWARE_VERTEXPROCESSING
Specifies hardware vertex processing.
D3DCREATE_MIXED_VERTEXPROCESSING
Specifies mixed (both software and hardware) vertex processing.
D3DCREATE_MULTITHREADED
Requests multithread-safe behavior. This causes Direct3D to take the global critical section more frequently.
D3DCREATE_PUREDEVICE
Specifies hardware rasterization, transform, lighting, and shading.
D3DCREATE_SOFTWARE_VERTEXPROCESSING
Specifies software vertex processing.

The value of this parameter mirrors the value passed to the IDirect3D8::CreateDevice call that created this device.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetCreationParameters, IDirect3D8::CreateDevice


D3DDISPLAYMODE

Describes the display mode.

typedef struct _D3DDISPLAYMODE {
    UINT            Width;
    UINT            Height;
    UINT            RefreshRate;
    D3DFORMAT       Format;
} D3DDISPLAYMODE;

Members

Width
Screen width, in pixels.
Height
Screen height, in pixels.
RefreshRate
Refresh rate. The value of 0 indicates an adapter default.
Format
Member of the D3DFORMAT enumerated type, describing the surface format of the display mode.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3D8::EnumAdapterModes, IDirect3D8::GetAdapterDisplayMode, IDirect3DDevice8::GetDisplayMode


D3DGAMMARAMP

Contains red, green, and blue ramp data.

typedef struct _D3DGAMMARAMP {
    WORD                red  [256];
    WORD                green[256];
    WORD                blue [256];
} D3DGAMMARAMP;

Members

red, green, and blue
Array of 256 WORD elements that describe the red, green, and blue gamma ramps.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetGammaRamp, IDirect3DDevice8::SetGammaRamp


D3DINDEXBUFFER_DESC

Describes an index buffer.

typedef struct _D3DINDEXBUFFER_DESC {
    D3DFORMAT           Format;
    D3DRESOURCETYPE     Type;
    DWORD               Usage;
    D3DPOOL             Pool;
    UINT                Size;
} D3DINDEXBUFFER_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the index buffer data.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as an index buffer.
Usage
Combination of one or more of the following flags, specifying the usage for this resource.
D3DUSAGE_DONOTCLIP
Set to indicate that the index buffer content will never require clipping.
D3DUSAGE_RTPATCHES
Set to indicate when the index buffer is to be used for drawing high-order primitives.
D3DUSAGE_NPATCHES
Set to indicate when the index buffer is to be used for drawing N patches.
D3DUSAGE_POINTS
Set to indicate when the index buffer is to be used for drawing point sprites or indexed point lists.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the buffer is to be used with software processing.
D3DUSAGE_WRITEONLY
Informs the system that the application writes only to the index buffer. Using this flag enables the driver to choose the best memory location for efficient write operations and rendering. Attempts to read from an index buffer that is created with this capability can result in degraded performance.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this index buffer.
Size
Size of the index buffer, in bytes.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DIndexBuffer8::GetDesc


D3DLIGHT8

Defines a set of lighting properties.

typedef struct _D3DLIGHT8 {
    D3DLIGHTTYPE    Type;
    D3DCOLORVALUE   Diffuse;
    D3DCOLORVALUE   Specular;
    D3DCOLORVALUE   Ambient;
    D3DVECTOR       Position;
    D3DVECTOR       Direction;
    float           Range;
    float           Falloff;
    float           Attenuation0;
    float           Attenuation1;
    float           Attenuation2;
    float           Theta;
    float           Phi;
} D3DLIGHT8;

Members

Type
Type of the light source. This value is one of the members of the D3DLIGHTTYPE enumerated type.
Diffuse
Diffuse color emitted by the light. This member is a D3DCOLORVALUE structure.
Specular
Specular color emitted by the light. This member is a D3DCOLORVALUE structure.
Ambient
Ambient color emitted by the light. This member is a D3DCOLORVALUE structure.
Position
Position of the light in world space, specified by a D3DVECTOR structure. This member has no meaning for directional lights and is ignored in that case.
Direction
Direction that the light is pointing in world space, specified by a D3DVECTOR structure. This member only has meaning only for directional and spotlights. This vector need not be normalized, but it should have a nonzero length.
Range
Distance beyond which the light has no effect. The maximum allowable value for this member is the square root of FLT_MAX. This member does not affect directional lights.
Falloff
Decrease in illumination between a spotlight's inner cone (the angle specified by Theta) and the outer edge of the outer cone (the angle specified by Phi).

The effect of falloff on the lighting is subtle. Furthermore, a small performance penalty is incurred by shaping the falloff curve. For these reasons, most developers set this value to 1.0.

Attenuation0, Attenuation1, and Attenuation2

Values specifying how the light intensity changes over distance. Attenuation values are ignored for directional lights. These members represent attenuation constants. For information on attenuation, see Light Attenuation Over Distance. Valid values for these members range from 0.0 to infinity. For non-directional lights, all three attenuation values should not be set to 0.0 at the same time.

Theta
Angle, in radians, of a spotlight's inner cone—that is, the fully illuminated spotlight cone. This value must be in the range from 0 through the value specified by Phi.
Phi
Angle, in radians, defining the outer edge of the spotlight's outer cone. Points outside this cone are not lit by the spotlight. This value must be between 0 and pi.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetLight, IDirect3DDevice8::SetLight


D3DLINEPATTERN

Describes a line pattern.

typedef struct _D3DLINEPATTERN {
    WORD    wRepeatFactor;
    WORD    wLinePattern;
} D3DLINEPATTERN;

Members

wRepeatFactor
Number of times to repeat each series of 1s and 0s specified in the wLinePattern member. This allows an application to stretch the line pattern.
wLinePattern
Bits specifying the line pattern. For example, the following value would produce a dotted line: 1100110011001100.

Remarks

These values are used by the D3DRS_LINEPATTERN render state in the D3DRENDERSTATETYPE enumerated type.

A line pattern specifies how a line is drawn. The line pattern is always the same, no matter where it is started. (This differs from stippling, which affects how objects are rendered; that is, to imitate transparency.)

The line pattern specifies up to a 16-pixel pattern of on and off pixels along the line. The wRepeatFactor member specifies how many pixels are repeated for each entry in wLinePattern.

Requirements

Header: Declared in D3d8types.h.


D3DLOCKED_BOX

Describes a locked box (volume).

typedef struct _D3DLOCKED_BOX {
    INT                 RowPitch;
    INT                 SlicePitch;
    void*               pBits;
} D3DLOCKED_BOX;

Members

RowPitch
Byte offset from the left edge of one row to the left edge of the next row.
SlicePitch
Byte offset from the top-left of one slice to the top-left of the next deepest slice.
pBits
Pointer to the beginning of the volume box. If a D3DBOX was provided to the LockRect call, pBits will be appropriately offset from the start of the volume.

Remarks

Volumes can be visualized as being organized into slices of width x height 2-D surfaces stacked up to make a width x height x depth volume. For more information, see Volume Texture Resources.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DVolume8::LockBox, IDirect3DVolumeTexture8::LockBox


D3DLOCKED_RECT

Describes a locked rectangular region.

typedef struct _D3DLOCKED_RECT {
    INT                 Pitch;
    void*               pBits;
} D3DLOCKED_RECT;

Members

Pitch
Pitch of surface, in bytes.
pBits
Pointer to the locked bits. If a RECT was provided to the LockRect call, pBits will be appropriately offset from the start of the surface.

Remarks

The pitch for DXTn formats is different from what was returned in DirectX 7.0. It now refers to a row of blocks. For example, if you have a width of 16, then you will have a pitch of 4 blocks (4*8 for DXT1, 4*16 for DXT2-5.)

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DCubeTexture8::LockRect, IDirect3DSurface8::LockRect, IDirect3DTexture8::LockRect.


D3DMATERIAL8

Specifies material properties.

typedef struct _D3DMATERIAL8 {
    D3DCOLORVALUE   Diffuse;
    D3DCOLORVALUE   Ambient;
    D3DCOLORVALUE   Specular;
    D3DCOLORVALUE   Emissive;
    float           Power;
} D3DMATERIAL8;

Members

Diffuse, Ambient, Specular, and Emissive
Values specifying the diffuse color, ambient color, specular color, and emissive color of the material, respectively. These values are D3DCOLORVALUE structures.
Power
Floating-point value specifying the sharpness of specular highlights. To turn off specular highlights for a material, set this member to 0.0; setting the specular color components to 0 is not enough.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetMaterial, IDirect3DDevice8::SetMaterial


D3DMATRIX

Describes a matrix.

typedef struct _D3DMATRIX {
    union {
        struct {
            float        _11, _12, _13, _14;
            float        _21, _22, _23, _24;
            float        _31, _32, _33, _34;
            float        _41, _42, _43, _44;

        };
        float m[4][4];
    };
} D3DMATRIX;

Remarks

In Microsoft® Direct3D®, the _34 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by –1, instead.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetTransform, IDirect3DDevice8::MultiplyTransform, IDirect3DDevice8::SetTransform


D3DPRESENT_PARAMETERS

Describes the presentation parameters.

typedef struct _D3DPRESENT_PARAMETERS_ {
    UINT                    BackBufferWidth;
    UINT                    BackBufferHeight;
    D3DFORMAT               BackBufferFormat;
    UINT                    BackBufferCount;

    D3DMULTISAMPLE_TYPE     MultiSampleType;

    D3DSWAPEFFECT           SwapEffect;
    HWND                    hDeviceWindow;
    BOOL                    Windowed;
    BOOL                    EnableAutoDepthStencil;
    D3DFORMAT               AutoDepthStencilFormat;
    DWORD                   Flags;

    UINT                    FullScreen_RefreshRateInHz;
    UINT                    FullScreen_PresentationInterval;

} D3DPRESENT_PARAMETERS;

Members

BackBufferWidth and BackBufferHeight
Width and height of the new swap chain's back buffers, in pixels. If Windowed is FALSE (the presentation is full-screen), then these values must equal the width and height of one of the enumerated display modes found through IDirect3D8::EnumAdapterModes. If Windowed is TRUE and either of these values is zero, then the corresponding dimension of the client area of the hDeviceWindow (or the focus window, if hDeviceWindow is NULL) is taken.
BackBufferFormat
Member of the D3DFORMAT enumerated type. This value must be one of the render target formats as validated by IDirect3D8::CheckDeviceType.

If Windowed is set to TRUE, then BackBufferFormat must be set to match the format of the current display mode. Use IDirect3DDevice8::GetDisplayMode to obtain the current format.

BackBufferCount
This value can be 0, 1, 2 or 3. Note that 0 is treated as 1. If the number of back buffers cannot be created, the run time will fail the method call and fill this value with the number of back buffers that could be created. As a result, an application can call the method twice with the same D3DPRESENT_PARAMETERS structure and expect it to work the second time.

One back buffer is considered the minimum number of back buffers. The method call fails if 1 back buffer cannot be created. The value of BackBufferCount influences what set of swap effects are allowed. Specifically, any D3DSWAPEFFECT_COPY swap effect requires that there be exactly one back buffer.

MultiSampleType
Member of the D3DMULTISAMPLE_TYPE enumerated type. The value must be D3DMULTISAMPLE_NONE unless SwapEffect has been set to D3DSWAPEFFECT_DISCARD. Multisampling is supported only if the swap effect is D3DSWAPEFFECT_DISCARD.
SwapEffect
Member of the D3DSWAPEFFECT enumerated type. The run time will guarantee the implied semantics concerning buffer swap behavior. So if Windowed is TRUE and SwapEffect is set to D3DSWAPEFFECT_FLIP, then the run time will create one extra back buffer, and copy whichever becomes the front buffer at presentation time.

D3DSWAPEFFECT_COPY and D3DSWAPEFFECT_COPY_VSYNC require that BackBufferCount be set to 1.

D3DSWAPEFFECT_DISCARD will be enforced in the debug run time by filling any buffer with noise after it is presented.

hDeviceWindow
If full-screen, this is the cover window. If windowed, this will be the default target window for IDirect3DDevice8::Present. If this value is NULL, the focus window will be taken. For applications that use multiple full-screen devices, such as a multimonitor system, exactly one device should use the focus window as the device window. All other devices should have unique device windows. Otherwise, behavior is undefined and applications will not work as expected.

Note that no attempt is made by the run time to reflect user changes in window size. The back buffer is not implicitly reset when this window is reset. However, the Present method does automatically track window position changes.

Windowed
TRUE if the application runs windowed, FALSE if the application runs full-screen.
EnableAutoDepthStencil
If this value is TRUE, Microsoft® Direct3D® will manage depth buffers for the application. The device will create a depth-stencil buffer when it is created. The depth-stencil buffer will be automatically set as the render target of the device. When the device is reset, the depth-stencil buffer will be automatically destroyed and recreated in the new size.

If EnableAutoDepthStencil is TRUE, then AutoDepthStencilFormat must be a valid depth-stencil format.

AutoDepthStencilFormat
Member of the D3DFORMAT enumerated type. The format of the automatic depth-stencil surface that the device will create. This member is ignored unless EnableAutoDepthStencil is TRUE.
Flags
This member can be set to 0, or to the following flag.
D3DPRESENTFLAG_LOCKABLE_BACKBUFFER
Set this flag if the application requires the ability to lock the back-buffer directly. Note that back buffers are not lockable unless the application specifies D3DPRESENTFLAG_LOCKABLE_BACKBUFFER when calling IDirect3D8::CreateDevice or IDirect3DDevice8::Reset . Lockable back buffers incur a performance cost on some graphics hardware configurations.

Performing a lock operation (or using IDirect3DDevice8::CopyRects to read/write) on the lockable back-buffer decreases performance on many cards. In this case, consider using textured triangles to move data to the back buffer.

FullScreen_RefreshRateInHz
The rate at which the display adapter refreshes the screen. For windowed mode, this value must be 0. Otherwise, this value must be one of the refresh rates returned by IDirect3D8::EnumAdapterModes or one of the following values.
D3DPRESENT_RATE_DEFAULT
The run time chooses the presentation rate, or adopts the current rate if windowed.
D3DPRESENT_RATE_UNLIMITED
The presentation rate runs as quickly as the hardware can deliver frames.
FullScreen_PresentationInterval
Maximum rate at which the swap chain's back buffers may be presented. For a windowed swap chain, this value must be D3DPRESENT_INTERVAL_DEFAULT (0). For a full-screen swap chain it may be D3DPRESENT_INTERVAL_DEFAULT or the value corresponding to exactly one of the flags enumerated in the PresentationIntervals member of D3DCAPS8.
D3DPRESENT_INTERVAL_IMMEDIATE
Present operations might be affected immediately. The driver will not wait for the vertical retrace period.
D3DPRESENT_INTERVAL_ONE
The driver will wait for the vertical retrace period. Present operations will not be affected more frequently than the screen refresh.
D3DPRESENT_INTERVAL_TWO
The driver will wait for the vertical retrace period. Present operations will not be affected more frequently than every second screen refresh.
D3DPRESENT_INTERVAL_THREE
The driver will wait for the vertical retrace period. Present operations will not be affected more frequently than every third screen refresh.
D3DPRESENT_INTERVAL_FOUR
The driver will wait for the vertical retrace period. Present operations will not be affected more frequently than every fourth screen refresh.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3D8::CreateDevice, IDirect3DDevice8::CreateAdditionalSwapChain, IDirect3DDevice8::Present, IDirect3DDevice8::Reset


D3DRANGE

Defines a range.

typedef struct _D3DRANGE {
    UINT                Offset;
    UINT                Size;
} D3DRANGE;

Members

Offset
Offset, in bytes.
Size
Size, in bytes.

Requirements

Header: Declared in D3d8types.h.


D3DRASTER_STATUS

Describes the raster status.

typedef struct _D3DRASTER_STATUS {
    BOOL            InVBlank;
    UINT            ScanLine;
} D3DRASTER_STATUS;

Members

InVBlank
TRUE if the raster is in the vertical blank period. FALSE if the raster is not in the vertical blank period.
ScanLine
If InVBlank is FALSE, then this value is an integer roughly corresponding to the current scan line painted by the raster. Scan lines are numbered in the same way as Microsoft® Direct3D® surface coordinates: 0 is the top of the primary surface, extending to the value (height of the surface - 1) at the bottom of the display.

If InVBlank is TRUE, then this value is set to zero and can be ignored.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetRasterStatus


D3DRECT

Defines a rectangle.

typedef struct _D3DRECT {
    LONG x1;
    LONG y1;
    LONG x2;
    LONG y2;
} D3DRECT;

Members

x1 and y1
Coordinates of the upper-left corner of the rectangle.
x2 and y2
Coordinates of the lower-right corner of the rectangle.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::Clear


D3DRECTPATCH_INFO

Describes a rectangular high-order patch.

typedef struct _D3DRECTPATCH_INFO {
    UINT                StartVertexOffsetWidth;
    UINT                StartVertexOffsetHeight;
    UINT                Width;
    UINT                Height;
    UINT                Stride;
    D3DBASISTYPE        Basis;
    D3DORDERTYPE        Order;
} D3DRECTPATCH_INFO;

Members

StartVertexOffsetWidth
Starting vertex offset width, in number of vertices.
StartVertexOffsetHeight
Starting vertex offset height, in number of vertices.
Width
Width of each vertex, in number of vertices.
Height
Height of each vertex, in number of vertices.
Stride
Stride between segments, in number of vertices.
Basis
Member of the D3DBASISTYPE enumerated type, defining the basis type for the rectangular high-order patch.
Order
Member of the D3DORDERTYPE enumerated type, defining the order type for the rectangular high-order patch.

Remarks

To render a stream of individual rectangular patches (non-mosaic), you should interpret your geometry as a long narrow (1 × N) rectangular patch. The D3DRECTPATCH_INFO structure for such a strip (cubic bézier) would be set up in the following manner.

D3DRECTPATCH_INFO RectInfo;

RectInfo.Width = 4;
RectInfo.Height= 4;
RectInfo.Stride= 4;
RectInfo.Basis =  D3DBASIS_BEZIER;
RectInfo.Order =  D3DORDER_CUBIC;
RectInfo.StartVertexOffsetWidth = 0;
RectInfo.StartVertexOffsetHeight = 4*i;  // The variable i is the index of the patch you want to render.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::DrawRectPatch


D3DSURFACE_DESC

Describes a surface.

typedef struct _D3DSURFACE_DESC {
    D3DFORMAT           Format;
    D3DRESOURCETYPE     Type;
    DWORD               Usage;
    D3DPOOL             Pool;
    UINT                Size;
    D3DMULTISAMPLE_TYPE MultiSampleType;
    UINT                Width;
    UINT                Height;
} D3DSURFACE_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a surface.
Usage
Combination of one or more of the following flags, specifying the usage for this resource.
D3DUSAGE_DEPTHSTENCIL
Set to indicate that the surface is to be used as a depth stencil surface.
D3DUSAGE_RENDERTARGET
Set to indicate that the surface is to be used as a render target.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this surface.
Size
Size of the surface, in bytes.
MultiSampleType
Member of the D3DMULTISAMPLE_TYPE enumerated type, specifying the levels of full-scene multisampling supported by the surface.
Width
Width of the surface, in pixels.
Height
Height of the surface, in pixels.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DCubeTexture8::GetLevelDesc, IDirect3DSurface8::GetDesc, IDirect3DTexture8::GetLevelDesc.


D3DTRIPATCH_INFO

Describes a triangular high-order patch.

typedef struct _D3DTRIPATCH_INFO {
    UINT                StartVertexOffset;
    UINT                NumVertices;
    D3DBASISTYPE        Basis;
    D3DORDERTYPE        Order;
} D3DTRIPATCH_INFO;

Members

StartVertexOffset
Starting vertex offset, in number of vertices.
NumVertices
Number of vertices.
Basis
Member of the D3DBASISTYPE enumerated type, defining the basis type for the triangular high-order patch.
Order
Member of the D3DORDERTYPE enumerated type, defining the order type for the triangular high-order patch.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::DrawTriPatch


D3DVECTOR

Defines a vector.

typedef struct _D3DVECTOR {
    float x;
    float y;
    float z;
} D3DVECTOR;

Members

x, y and z
Floating-point values describing the vector.

Requirements

Header: Declared in D3d8types.h.


D3DVERTEXBUFFER_DESC

Describes a vertex buffer.

typedef struct _D3DVERTEXBUFFER_DESC {
    D3DFORMAT           Format;
    D3DRESOURCETYPE     Type;
    DWORD               Usage;
    D3DPOOL             Pool;
    UINT                Size;
    DWORD               FVF;
} D3DVERTEXBUFFER_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the vertex buffer data.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a vertex buffer.
Usage
Combination of one or more of the following flags, specifying the usage for this resource.
D3DUSAGE_DONOTCLIP
Set to indicate that the vertex buffer content will never require clipping.
D3DUSAGE_RTPATCHES
Set to indicate when the vertex buffer is to be used for drawing high-order primitives.
D3DUSAGE_NPATCHES
Set to indicate when the vertex buffer is to be used for drawing N patches.
D3DUSAGE_POINTS
Set to indicate when the vertex buffer is to be used for drawing point sprites or indexed point lists.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the vertex buffer is to be used with software vertex processing.
D3DUSAGE_WRITEONLY
Informs the system that the application writes only to the vertex buffer. Using this flag enables the driver to choose the best memory location for efficient write operations and rendering. Attempts to read from a vertex buffer that is created with this capability can result in degraded performance.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this vertex buffer.
Size
Size of the vertex buffer, in bytes
FVF
Combination of flexible vertex format flags that describes the vertex format of the vertices in this buffer.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DVertexBuffer8::GetDesc


D3DVIEWPORT8

Defines the window dimensions of a render target surface onto which a 3-D volume projects.

typedef struct _D3DVIEWPORT8 {
    DWORD       X;
    DWORD       Y;
    DWORD       Width;
    DWORD       Height;
    float       MinZ;
    float       MaxZ;
} D3DVIEWPORT8;

Members

X and Y
Pixel coordinates of the upper-left corner of the viewport on the render target surface. Unless you want to render to a subset of the surface, these members can be set to 0.
Width and Height
Dimensions of the viewport on the render target surface, in pixels. Unless you are rendering only to a subset of the surface, these members should be set to the dimensions of the render target surface.
MinZ and MaxZ
Values describing the range of depth values into which a scene is to be rendered, the minimum and maximum values of the clip volume. Most applications set these values to 0.0 and 1.0, respectively. Clipping is performed after applying the projection matrix.

Remarks

The X, Y, Width, and Height members describe the position and dimensions of the viewport on the render target surface. Usually, applications render to the entire target surface; when rendering on a 640×480 surface, these members should be 0, 0, 640, and 480, respectively. The MinZ and MaxZ are typically set to 0.0 and 1.0 but can be set to other values to achieve specific effects. For example, you might set them both to 0.0 to force the system to render objects to the foreground of a scene, or both to 1.0 to force the objects into the background.

When the viewport parameters for a device change (due to a call to the IDirect3DDevice8::SetViewport method), the driver builds a new transformation matrix.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetViewport, IDirect3DDevice8::SetViewport


D3DVOLUME_DESC

Describes a volume.

typedef struct _D3DVOLUME_DESC {
    D3DFORMAT           Format;
    D3DRESOURCETYPE     Type;
    DWORD               Usage;
    D3DPOOL             Pool;
    UINT                Size;
    UINT                Width;
    UINT                Height;
    UINT                Depth;
} D3DVOLUME_DESC;

Members

Format
Member of the D3DFORMAT enumerated type, describing the surface format of the volume.
Type
Member of the D3DRESOURCETYPE enumerated type, identifying this resource as a volume.
Usage
Currently not used. Always returned as 0.
Pool
Member of the D3DPOOL enumerated type, specifying the class of memory allocated for this volume.
Size
Size of the volume, in bytes.
Width
Width of the volume, in pixels.
Height
Height of the volume, in pixels.
Depth
Depth of the volume, in pixels.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DVolume8::GetDesc, IDirect3DVolumeTexture8::GetLevelDesc


Enumerated Types

This section contains information about the following enumerated types used with Microsoft® Direct3D®.

  • D3DBACKBUFFER_TYPE
  • D3DBLEND
  • D3DBLENDOP
  • D3DCMPFUNC
  • D3DCUBEMAP_FACES
  • D3DCULL
  • D3DDEBUGMONITORTOKENS
  • D3DDEVTYPE
  • D3DFILLMODE
  • D3DFOGMODE
  • D3DFORMAT
  • D3DBASISTYPE
  • D3DLIGHTTYPE
  • D3DMATERIALCOLORSOURCE
  • D3DMULTISAMPLE_TYPE
  • D3DORDERTYPE
  • D3DPATCHEDGESTYLE
  • D3DPOOL
  • D3DPRIMITIVETYPE
  • D3DRENDERSTATETYPE
  • D3DRESOURCETYPE
  • D3DSHADEMODE
  • D3DSTATEBLOCKTYPE
  • D3DSTENCILOP
  • D3DSWAPEFFECT
  • D3DTEXTUREADDRESS
  • D3DTEXTUREFILTERTYPE
  • D3DTEXTUREOP
  • D3DTEXTURESTAGESTATETYPE
  • D3DTEXTURETRANSFORMFLAGS
  • D3DTRANSFORMSTATETYPE
  • D3DVERTEXBLENDFLAGS
  • D3DZBUFFERTYPE


D3DBACKBUFFER_TYPE

Defines constants that describe the type of back buffer.

typedef enum _D3DBACKBUFFER_TYPE {
    D3DBACKBUFFER_TYPE_MONO         = 0,
    D3DBACKBUFFER_TYPE_LEFT         = 1,
    D3DBACKBUFFER_TYPE_RIGHT        = 2,

    D3DBACKBUFFER_TYPE_FORCE_DWORD  = 0x7fffffff
} D3DBACKBUFFER_TYPE;

Constants

D3DBACKBUFFER_TYPE_MONO
Specifies a non-stereo swap chain.
D3DBACKBUFFER_TYPE_LEFT
Specifies the left side of a stereo pair in a swap chain.
D3DBACKBUFFER_TYPE_RIGHT
Specifies the right side of a stereo pair in a swap chain.
D3DBACKBUFFER_TYPE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Note that stereo view in not supported in DirectX 8.0, so the D3DBACKBUFFER_TYPE_LEFT and D3DBACKBUFFER_TYPE_RIGHT values of this enumerated type are not used by Direct3D.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetBackBuffer, IDirect3DSwapChain8::GetBackBuffer


D3DBLEND

Defines the supported blend mode.

typedef enum _D3DBLEND {
    D3DBLEND_ZERO               =  1,
    D3DBLEND_ONE                =  2,
    D3DBLEND_SRCCOLOR           =  3,
    D3DBLEND_INVSRCCOLOR        =  4,
    D3DBLEND_SRCALPHA           =  5,
    D3DBLEND_INVSRCALPHA        =  6,
    D3DBLEND_DESTALPHA          =  7,
    D3DBLEND_INVDESTALPHA       =  8,
    D3DBLEND_DESTCOLOR          =  9,
    D3DBLEND_INVDESTCOLOR       = 10,
    D3DBLEND_SRCALPHASAT        = 11,
    D3DBLEND_BOTHSRCALPHA       = 12,
    D3DBLEND_BOTHINVSRCALPHA    = 13,

    D3DBLEND_FORCE_DWORD        = 0x7fffffff
} D3DBLEND;

Constants

D3DBLEND_ZERO
Blend factor is (0, 0, 0, 0).
D3DBLEND_ONE
Blend factor is (1, 1, 1, 1).
D3DBLEND_SRCCOLOR
Blend factor is (Rs, Gs, Bs, As).
D3DBLEND_INVSRCCOLOR
Blend factor is (1–Rs, 1–Gs, 1–Bs, 1–As).
D3DBLEND_SRCALPHA
Blend factor is (As, As, As, As).
D3DBLEND_INVSRCALPHA
Blend factor is (1–As, 1–As, 1–As, 1–As).
D3DBLEND_DESTALPHA
Blend factor is (Ad, Ad, Ad, Ad).
D3DBLEND_INVDESTALPHA
Blend factor is (1–Ad, 1–Ad, 1–Ad, 1–Ad).
D3DBLEND_DESTCOLOR
Blend factor is (Rd, Gd, Bd, Ad).
D3DBLEND_INVDESTCOLOR
Blend factor is (1–Rd, 1–Gd, 1–Bd, 1–Ad).
D3DBLEND_SRCALPHASAT
Blend factor is (f, f, f, 1); f = min(As, 1–Ad).
D3DBLEND_BOTHSRCALPHA
Obsolete. For Microsoft® DirectX® 6.0 and later, you can achieve the same affect by setting the source and destination blend factors to D3DBLEND_SRCALPHA and D3DBLEND_INVSRCALPHA in separate calls.
D3DBLEND_BOTHINVSRCALPHA
Source blend factor is (1–As, 1–As, 1–As, 1–As), and destination blend factor is (As, As, As, As); the destination blend selection is overridden. This blend mode is supported only for the D3DRS_SRCBLEND render state.
D3DBLEND_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

In the member descriptions above, the RGBA values of the source and destination are indicated by the subscripts s and d.

The values in this enumerated type are used by the D3DRS_DESTBLEND render state.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRENDERSTATETYPE


D3DBLENDOP

Defines the supported blend operations.

typedef enum _D3DBLENDOP {
    D3DBLENDOP_ADD              = 1,
    D3DBLENDOP_SUBTRACT         = 2,
    D3DBLENDOP_REVSUBTRACT      = 3,
    D3DBLENDOP_MIN              = 4,
    D3DBLENDOP_MAX              = 5,

    D3DBLENDOP_FORCE_DWORD      = 0x7fffffff
} D3DBLENDOP;

Constants

D3DBLENDOP_ADD
The result is the destination added to the source.

Result = Source + Destination

D3DBLENDOP_SUBTRACT
The result is the destination subtracted from to the source.

Result = Source - Destination

D3DBLENDOP_REVSUBTRACT
The result is the source subtracted from the destination.

Result = Destination - Source

D3DBLENDOP_MIN
The result is the minimum of the source and destination.

Result = MIN(Source, Destination)

D3DBLENDOP_MAX
The result is the maximum of the source and destination.

Result = MAX(Source, Destination)

D3DBLENDOP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

This enumerated type defines values used by the D3DRS_BLENDOP render state.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DCAPS8, D3DRENDERSTATETYPE


D3DCMPFUNC

Defines the supported compare functions.

typedef enum _D3DCMPFUNC {
    D3DCMP_NEVER                = 1,
    D3DCMP_LESS                 = 2,
    D3DCMP_EQUAL                = 3,
    D3DCMP_LESSEQUAL            = 4,
    D3DCMP_GREATER              = 5,
    D3DCMP_NOTEQUAL             = 6,
    D3DCMP_GREATEREQUAL         = 7,
    D3DCMP_ALWAYS               = 8,

    D3DCMP_FORCE_DWORD          = 0x7fffffff
} D3DCMPFUNC;

Constants

D3DCMP_NEVER
Always fail the test.
D3DCMP_LESS
Accept the new pixel if its value is less than the value of the current pixel.
D3DCMP_EQUAL
Accept the new pixel if its value equals the value of the current pixel.
D3DCMP_LESSEQUAL
Accept the new pixel if its value is less than or equal to the value of the current pixel.
D3DCMP_GREATER
Accept the new pixel if its value is greater than the value of the current pixel.
D3DCMP_NOTEQUAL
Accept the new pixel if its value does not equal the value of the current pixel.
D3DCMP_GREATEREQUAL
Accept the new pixel if its value is greater than or equal to the value of the current pixel.
D3DCMP_ALWAYS
Always pass the test.
D3DCMP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type define the supported compare functions for the D3DRS_ZFUNC, D3DRS_ALPHAFUNC, and D3DRS_STENCILFUNC render states.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRENDERSTATETYPE


D3DCUBEMAP_FACES

Defines the faces of a cubemap.

typedef enum _D3DCUBEMAP_FACES {
    D3DCUBEMAP_FACE_POSITIVE_X     = 0,
    D3DCUBEMAP_FACE_NEGATIVE_X     = 1,
    D3DCUBEMAP_FACE_POSITIVE_Y     = 2,
    D3DCUBEMAP_FACE_NEGATIVE_Y     = 3,
    D3DCUBEMAP_FACE_POSITIVE_Z     = 4,
    D3DCUBEMAP_FACE_NEGATIVE_Z     = 5,

    D3DCUBEMAP_FACE_FORCE_DWORD    = 0xffffffff
} D3DCUBEMAP_FACES;

Constants

D3DCUBEMAP_FACE_POSITIVE_X
Positive x-face of the cubemap.
D3DCUBEMAP_FACE_NEGATIVE_X
Negative x-face of the cubemap.
D3DCUBEMAP_FACE_POSITIVE_Y
Positive y-face of the cubemap.
D3DCUBEMAP_FACE_NEGATIVE_Y
Negative y-face of the cubemap.
D3DCUBEMAP_FACE_POSITIVE_Z
Positive z-face of the cubemap.
D3DCUBEMAP_FACE_NEGATIVE_Z
Negative z-face of the cubemap.
D3DCUBEMAP_FACE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DCubeTexture8::AddDirtyRect, IDirect3DCubeTexture8::GetCubeMapSurface, IDirect3DCubeTexture8::LockRect, IDirect3DCubeTexture8::UnlockRect


D3DCULL

Defines the supported culling modes.

typedef enum _D3DCULL {
    D3DCULL_NONE                = 1,
    D3DCULL_CW                  = 2,
    D3DCULL_CCW                 = 3,

    D3DCULL_FORCE_DWORD         = 0x7fffffff
} D3DCULL;

Constants

D3DCULL_NONE
Do not cull back faces.
D3DCULL_CW
Cull back faces with clockwise vertices.
D3DCULL_CCW
Cull back faces with counterclockwise vertices.
D3DCULL_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_CULLMODE render state. The culling modes define how back faces are culled when rendering a geometry.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DCAPS8, D3DRENDERSTATETYPE


D3DDEBUGMONITORTOKENS

Defines the debug monitor tokens.

typedef enum _D3DDEBUGMONITORTOKENS {
    D3DDMT_ENABLE          = 0,
    D3DDMT_DISABLE         = 1,

    D3DDMT_FORCE_DWORD     = 0x7fffffff
} D3DDEBUGMONITORTOKENS;

Constants

D3DDMT_ENABLE
Enable the debug monitor.
D3DDMT_DISABLE
Disable the debug monitor.
D3DDMT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_DEBUGMONITORTOKEN render state and are only relevant for debug builds.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRENDERSTATETYPE


D3DDEVTYPE

Defines device types.

typedef enum _D3DDEVTYPE {
    D3DDEVTYPE_HAL         = 1,
    D3DDEVTYPE_REF         = 2,
    D3DDEVTYPE_SW          = 3,

    D3DDEVTYPE_FORCE_DWORD = 0xffffffff
} D3DDEVTYPE;

Constants

D3DDEVTYPE_HAL
Hardware rasterization and shading with software, hardware, or mixed transform and lighting.
D3DDEVTYPE_REF
Microsoft® Direct3D® features are implemented in software; however, the reference rasterizer does make use of special CPU instructions whenever it can.
D3DDEVTYPE_SW
A pluggable software device that has been registered with Direct3D using IDirect3D8::RegisterSoftwareDevice.
D3DDEVTYPE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3D8::CheckDeviceFormat, IDirect3D8::CheckDeviceMultiSampleType, IDirect3D8::CheckDeviceType, IDirect3D8::CreateDevice, IDirect3D8::GetDeviceCaps, D3DDEVICE_CREATION_PARAMETERS


D3DFILLMODE

Defines constants describing the fill mode.

typedef enum _D3DFILLMODE {
    D3DFILL_POINT               = 1,
    D3DFILL_WIREFRAME           = 2,
    D3DFILL_SOLID               = 3,

    D3DFILL_FORCE_DWORD         = 0x7fffffff
} D3DFILLMODE;

Constants

D3DFILL_POINT
Fill points.
D3DFILL_WIREFRAME
Fill wireframes. This fill mode currently does not work for clipped primitives when you use the DrawPrimitive methods.
D3DFILL_SOLID
Fill solids.
D3DFILL_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_FILLMODE render state.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRENDERSTATETYPE


D3DFOGMODE

Defines constants that describe the fog mode.

typedef enum _D3DFOGMODE {
    D3DFOG_NONE                 = 0,
    D3DFOG_EXP                  = 1,
    D3DFOG_EXP2                 = 2,
    D3DFOG_LINEAR               = 3,

    D3DFOG_FORCE_DWORD          = 0x7fffffff
} D3DFOGMODE;

Constants

D3DFOG_NONE
No fog effect.
D3DFOG_EXP
Fog effect intensifies exponentially, according to the following formula.

D3DFOG_EXP2
Fog effect intensifies exponentially with the square of the distance, according to the following formula.

D3DFOG_LINEAR
Fog effect intensifies linearly between the start and end points, according to the following formula.

This is the only fog mode currently supported.

D3DFOG_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The values in this enumerated type are used by the D3DRS_FOGTABLEMODE and D3DRS_FOGVERTEXMODE render states.

Fog can be considered a measure of visibility—the lower the fog value produced by a fog equation, the less visible an object is.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRENDERSTATETYPE


D3DFORMAT

Defines the various types of surface formats.

typedef enum _D3DFORMAT {
    D3DFMT_UNKNOWN              =   0,

    D3DFMT_R8G8B8               =  20,
    D3DFMT_A8R8G8B8             =  21,
    D3DFMT_X8R8G8B8             =  22,
    D3DFMT_R5G6B5               =  23,
    D3DFMT_X1R5G5B5             =  24,
    D3DFMT_A1R5G5B5             =  25,
    D3DFMT_A4R4G4B4             =  26,
    D3DFMT_R3G3B2               =  27,
    D3DFMT_A8                   =  28,
    D3DFMT_A8R3G3B2             =  29,
    D3DFMT_X4R4G4B4             =  30,

    D3DFMT_A8P8                 =  40,
    D3DFMT_P8                   =  41,

    D3DFMT_L8                   =  50,
    D3DFMT_A8L8                 =  51,
    D3DFMT_A4L4                 =  52,

    D3DFMT_V8U8                 =  60,
    D3DFMT_L6V5U5               =  61,
    D3DFMT_X8L8V8U8             =  62,
    D3DFMT_Q8W8V8U8             =  63,
    D3DFMT_V16U16               =  64,
    D3DFMT_W11V11U10            =  65,

    D3DFMT_UYVY                 =  MAKEFOURCC('U', 'Y', 'V', 'Y'),
    D3DFMT_YUY2                 =  MAKEFOURCC('Y', 'U', 'Y', '2'),
    D3DFMT_DXT1                 =  MAKEFOURCC('D', 'X', 'T', '1'),
    D3DFMT_DXT2                 =  MAKEFOURCC('D', 'X', 'T', '2'),
    D3DFMT_DXT3                 =  MAKEFOURCC('D', 'X', 'T', '3'),
    D3DFMT_DXT4                 =  MAKEFOURCC('D', 'X', 'T', '4'),
    D3DFMT_DXT5                 =  MAKEFOURCC('D', 'X', 'T', '5'),

    D3DFMT_D16_LOCKABLE         =  70,
    D3DFMT_D32                  =  71,
    D3DFMT_D15S1                =  73,
    D3DFMT_D24S8                =  75,
    D3DFMT_D16                  =  80,
    D3DFMT_D24X8                =  77,
    D3DFMT_D24X4S4              =  79,

    D3DFMT_VERTEXDATA           = 100,
    D3DFMT_INDEX16              = 101,
    D3DFMT_INDEX32              = 102,

    D3DFMT_FORCE_DWORD          = 0xFFFFFFFF
} D3DFORMAT;

Constants

D3DFMT_UNKNOWN
Surface format is unknown.
D3DFMT_R8G8B8
24-bit RGB pixel format.
D3DFMT_A8R8G8B8
32-bit ARGB pixel format with alpha.
D3DFMT_X8R8G8B8
32-bit RGB pixel format where 8 bits are reserved for each color.
D3DFMT_R5G6B5
16-bit RGB pixel format.
D3DFMT_X1R5G5B5
16-bit pixel format where 5 bits are reserved for each color.
D3DFMT_A1R5G5B5
16-bit pixel format where 5 bits are reserved for each color and 1 bit is reserved for alpha (transparent texel).
D3DFMT_A4R4G4B4
16-bit ARGB pixel format.
D3DFMT_R3G3B2
8-bit RGB texture format.
D3DFMT_A8
8-bit alpha only.
D3DFMT_A8R3G3B2
16-bit ARGB texture format.
D3DFMT_X4R4G4B4
16-bit RGB pixel format where 4 bits are reserved for each color.
D3DFMT_A8P8
Surface is 8-bit color indexed with 8 bits of alpha.
D3DFMT_P8
Surface is 8-bit color indexed.
D3DFMT_L8
8-bit luminance only.
D3DFMT_A8L8
16-bit alpha luminance.
D3DFMT_A4L4
8-bit alpha luminance.
D3DFMT_V8U8
16-bit bump-map format.
D3DFMT_L6V5U5
16-bit bump-map format with luminance.
D3DFMT_X8L8V8U8
32-bit bump-map format with luminance where 8 bits are reserved for each element.
D3DFMT_Q8W8V8U8
32-bit bump-map format.
D3DFMT_V16U16
32-bit bump-map format.
D3DFMT_W11V11U10
32-bit bump-map format.
D3DFMT_UYVY
UYVY format (PC98 compliance).
D3DFMT_YUY2
YUY2 format (PC98 compliance).
D3DFMT_DXT1
DXT1 compression texture format.
D3DFMT_DXT2
DXT2 compression texture format.
D3DFMT_DXT3
DXT3 compression texture format.
D3DFMT_DXT4
DXT4 compression texture format.
D3DFMT_DXT5
DXT5 compression texture format.
D3DFMT_D16_LOCKABLE
16-bit z-buffer bit depth. This is an application-lockable surface format.
D3DFMT_D32
32-bit z-buffer bit depth.
D3DFMT_D15S1
16-bit z-buffer bit depth where 15 bits are reserved for the depth channel and 1 bit is reserved for the stencil channel.
D3DFMT_D24S8
32-bit z-buffer bit depth where 24 bits are reserved for the depth channel and 8 bits are reserved for the stencil channel.
D3DFMT_D16
16-bit z-buffer bit depth.
D3DFMT_D24X8
32-bit z-buffer bit depth where 24 bits are reserved for the depth channel.
D3DFMT_D24X4S4
32-bit z-buffer bit depth where 24 bits are reserved for the depth channel and 4 bits are reserved for the stencil channel.
D3DFMT_VERTEXDATA
Describes a vertex buffer surface.
D3DFMT_INDEX16
16-bit index buffer bit depth.
D3DFMT_INDEX32
32-bit index buffer bit depth.
D3DFMT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Note that render target formats are restricted to D3DFMT_X1R5G5B5, D3DFMT_R5G6B5, D3DFMT_X8R8G8B8, and D3DFMT_A8R8G8B8.

The order of the bits are from the most significant bit (MSB) first, so D3DFMT_A8L8 indicates that the high byte of this two-byte format is alpha. D3DFMT_D16 indicates a 16-bit integer value and an application-lockable surface.

All depth-stencil formats except D3DFMT_D16_LOCKABLE indicate no particular bit ordering per pixel, and are not application-lockable, and the driver is allowed to consume more than the indicated number of bits per depth channel (but not stencil channel).

Pixel formats are denoted by opaque DWORD identifiers. The format of these DWORDs has been chosen to enable the expression of IHV-defined extension formats, and also to include the well-established FOURCC method. The set of formats understood by the Microsoft® Direct3D® runtime is defined by D3DFORMAT.

Note that IHV-supplied formats and many FOURCC codes are not listed in the D3DFORMAT enumeration. The formats in this enumeration are unique in that they are sanctioned by the runtime, meaning that the reference rasterizer will operate on all these types. The IHV-supplied formats will be supported by the individual IHVs on a card-by-card basis.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3D8::CheckDeviceFormat, Four-Character Codes (FOURCC)


D3DBASISTYPE

Defines the basis type of a high-order patch surface.

typedef enum _D3DBASISTYPE{
   D3DBASIS_BEZIER        = 0,
   D3DBASIS_BSPLINE       = 1,
   D3DBASIS_INTERPOLATE   = 2,

   D3DBASIS_FORCE_DWORD   = 0x7fffffff
} D3DBASISTYPE;

Constants

D3DBASIS_BEZIER
Input vertices are treated as a series of bézier patches. The number of vertices specified must be divisible by 3 + 1. Portions of the mesh beyond this criterion will not be rendered. Full continuity is assumed between sub-patches in the interior of the surface rendered by each call. Only the vertices at the corners of each sub-patch are guaranteed to lie on the resulting surface.
D3DBASIS_BSPLINE
Input vertices are treated as control points of a B-spline surface. The number of apertures rendered is 2 less than the number of apertures in that direction. In general, the generated surface does not contain the control vertices specified.
D3DBASIS_INTERPOLATE
An interpolating basis defines the surface so that the surface goes through all the input vertices specified.
D3DBASIS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The members of D3DBASISTYPE specify the formulation to be used in evaluating the high-order patch surface primitive during tessellation.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRECTPATCH_INFO, D3DTRIPATCH_INFO


D3DLIGHTTYPE

Defines the light type.

typedef enum _D3DLIGHTTYPE {
    D3DLIGHT_POINT          = 1,
    D3DLIGHT_SPOT           = 2,
    D3DLIGHT_DIRECTIONAL    = 3,

    D3DLIGHT_FORCE_DWORD    = 0x7fffffff
} D3DLIGHTTYPE;

Constants

D3DLIGHT_POINT
Light is a point source. The light has a position in space and radiates light in all directions.
D3DLIGHT_SPOT
Light is a spotlight source. This light is like a point light, except that the illumination is limited to a cone. This light type has a direction and several other parameters that determine the shape of the cone it produces. For information about these parameters, see the D3DLIGHT8 structure.
D3DLIGHT_DIRECTIONAL
Light is a directional source. This is equivalent to using a point light source at an infinite distance.
D3DLIGHT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Directional lights are slightly faster than point light sources, but point lights look a little better. Spotlights offer interesting visual effects but are computationally expensive.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DLIGHT8


D3DMATERIALCOLORSOURCE

Defines the location at which a color or color component must be accessed for lighting calculations.

typedef enum _D3DMATERIALCOLORSOURCE {
    D3DMCS_MATERIAL         = 0,
    D3DMCS_COLOR1           = 1,
    D3DMCS_COLOR2           = 2,

    D3DMCS_FORCE_DWORD      = 0x7fffffff
} D3DMATERIALCOLORSOURCE;

Constants

D3DMCS_MATERIAL
Use the color from the current material.
D3DMCS_COLOR1
Use the diffuse vertex color.
D3DMCS_COLOR2
Use the specular vertex color.
D3DMCS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

These flags are used to set the value of the following render states in the D3DRENDERSTATETYPE enumerated type.

  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE
  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRENDERSTATETYPE


D3DMULTISAMPLE_TYPE

Defines levels of full-scene multisampling that the device can apply.

typedef enum _D3DMULTISAMPLE_TYPE {
    D3DMULTISAMPLE_NONE            =  0,
    D3DMULTISAMPLE_2_SAMPLES       =  2,
    D3DMULTISAMPLE_3_SAMPLES       =  3,
    D3DMULTISAMPLE_4_SAMPLES       =  4,
    D3DMULTISAMPLE_5_SAMPLES       =  5,
    D3DMULTISAMPLE_6_SAMPLES       =  6,
    D3DMULTISAMPLE_7_SAMPLES       =  7,
    D3DMULTISAMPLE_8_SAMPLES       =  8,
    D3DMULTISAMPLE_9_SAMPLES       =  9,
    D3DMULTISAMPLE_10_SAMPLES      = 10,
    D3DMULTISAMPLE_11_SAMPLES      = 11,
    D3DMULTISAMPLE_12_SAMPLES      = 12,
    D3DMULTISAMPLE_13_SAMPLES      = 13,
    D3DMULTISAMPLE_14_SAMPLES      = 14,
    D3DMULTISAMPLE_15_SAMPLES      = 15,
    D3DMULTISAMPLE_16_SAMPLES      = 16,

    D3DMULTISAMPLE_FORCE_DWORD     = 0xffffffff
} D3DMULTISAMPLE_TYPE;

Constants

D3DMULTISAMPLE_NONE
No level of full-scene multisampling is available.
D3DMULTISAMPLE_2_SAMPLES through D3DMULTISAMPLE_16_SAMPLES
The level of full-scene multisampling available.
D3DMULTISAMPLE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

In addition to enabling full-scene multisampling at IDirect3DDevice8::Reset time, there will be render states that turn various aspects on and off at fine-grained levels.

Multisampling is valid only on a swap chain that is being created or reset with the D3DSWAPEFFECT_DISCARD swap effect.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3D8::CheckDeviceMultiSampleType, IDirect3DDevice8::CreateDepthStencilSurface, IDirect3DDevice8::CreateRenderTarget, D3DPRESENT_PARAMETERS, D3DSURFACE_DESC


D3DORDERTYPE

Defines the order type of a high-order surface.

typedef enum _D3DORDERTYPE {
   D3DORDER_LINEAR      = 1,
   D3DORDER_CUBIC       = 3,
   D3DORDER_QUINTIC     = 5,

   D3DORDER_FORCE_DWORD = 0x7fffffff
} D3DORDERTYPE;

Constants

D3DORDER_LINEAR
Linear order type.
D3DORDER_CUBIC
Cubic order type.
D3DORDER_QUINTIC
Quintic order type.
D3DORDER_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRECTPATCH_INFO, D3DTRIPATCH_INFO


D3DPATCHEDGESTYLE

Defines whether the current tessellation mode is discrete or continuous.

typedef enum _D3DPATCHEDGESTYLE {
   D3DPATCHEDGE_DISCRETE    = 0,
   D3DPATCHEDGE_CONTINUOUS  = 1,

   D3DPATCHEDGE_FORCE_DWORD = 0x7fffffff,
} D3DPATCHEDGESTYLE;

Constants

D3DPATCHEDGE_DISCRETE
Discrete edge style. In discrete mode, you can specify float tessellation but it will be truncated to integers.
D3DPATCHEDGE_CONTINUOUS
Continuous edge style. In continuous mode, tessellation is specified as float values which can be smoothly varied to reduce "popping" artifacts.
D3DPATCHEDGE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Note that continuous tessellation produces a completely different tessellation pattern from the discrete one for the same tessellation values (this is more apparent in wire-frame mode). Thus, 4.0 continuous is not the same as 4 discrete.

Requirements

Header: Declared in D3d8types.h.


D3DPOOL

Defines the memory class that holds a resource's buffers.

typedef enum _D3DPOOL {
    D3DPOOL_DEFAULT                 = 0,
    D3DPOOL_MANAGED                 = 1,
    D3DPOOL_SYSTEMMEM               = 2,

    D3DPOOL_FORCE_DWORD             = 0x7fffffff
} D3DPOOL;

Constants

D3DPOOL_DEFAULT
Resources are placed in the memory pool most appropriate for the set of usages requested for the given resource. This is usually video memory, including both local video memory and AGP memory. The D3DPOOL_DEFAULT pool is separate from D3DPOOL_MANAGED and D3DPOOL_SYTEMMEM, and it specifies that the resource is placed in the preferred memory for device access. Note that D3DPOOL_DEFAULT never indicates that either D3DPOOL_MANAGED or D3DPOOL_SYSTEMMEM should be chosen as the memory pool type for this resource. Textures placed in the D3DPOOL_DEFAULT pool cannot be locked and are therefore not directly accessible. Instead, you must use functions such as IDirect3Ddevice8::CopyRects and IDirect3dDevice8::UpdateTexture. D3DPOOL_MANAGED is probably a better choice than D3DPOOL_DEFAULT for most applications. Note that some textures created in driver proprietary pixel formats, unknown to the Direct3D runtime, can be locked. Also note that—unlike textures—swapchain back-buffers, render targets, vertex buffers, and index buffers can be locked.

When a device is lost, resources created using D3DPOOL_DEFAULT must be released before calling IDirect3DDevice8::Reset. See Lost Devices for more information.

D3DPOOL_MANAGED
Resources are copied automatically to device-accessible memory as needed. Managed resources are backed by system memory and do not need to be recreated when a device is lost. See Managing Resources for more information. Managed resources can be locked. Only the system-memory copy is directly modified. Direct3D copies your changes to driver-accessible memory as needed.
D3DPOOL_SYSTEMMEM
Memory that is not typically accessible by the 3-D device. Consumes system RAM but does not reduce pageable RAM. These resources do not need to be recreated when a device is lost. Resources in this pool can be locked and can be used as the source for a IDirect3DDevice8::CopyRects or IDirect3DDevice8::UpdateTexture operation to a memory resource created with D3DPOOL_DEFAULT.
D3DPOOL_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Pools cannot be mixed for different objects contained within one resource (mip levels in a mipmap), and once a pool is chosen it cannot be changed.

Applications should use D3DPOOL_MANAGED for most static resources because this saves the application from having to deal with lost devices. (Managed resources are restored by the runtime.) This is especially beneficial for UMA systems. Dynamic texture resources can also be a good match for D3DPOOL_MANAGED, in spite of the high frequency at which they change. Other dynamic resources are not a good match for D3DPOOL_MANAGED. In fact, index buffers and vertex buffers cannot be created using D3DPOOL_MANAGED together with D3DUSAGE_DYNAMIC.

For dynamic textures, it is sometimes desirable to use a pair of video memory and system memory textures, allocating the video memory using D3DPOOL_DEFAULT and the system memory using D3DPOOL_SYSTEMMEM. You can lock and modify the bits of the system memory texture using a locking method. Then you can update the video memory texture using IDirect3DDevice8::UpdateTexture.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::CreateCubeTexture, IDirect3DDevice8::CreateIndexBuffer, IDirect3DDevice8::CreateTexture, IDirect3DDevice8::CreateVolumeTexture, IDirect3DDevice8::CreateVertexBuffer, D3DINDEXBUFFER_DESC, D3DSURFACE_DESC, D3DVERTEXBUFFER_DESC, D3DVOLUME_DESC


D3DPRIMITIVETYPE

Defines the primitives supported by Microsoft® Direct3D®.

typedef enum _D3DPRIMITIVETYPE {
    D3DPT_POINTLIST             = 1,
    D3DPT_LINELIST              = 2,
    D3DPT_LINESTRIP             = 3,
    D3DPT_TRIANGLELIST          = 4,
    D3DPT_TRIANGLESTRIP         = 5,
    D3DPT_TRIANGLEFAN           = 6,

    D3DPT_FORCE_DWORD           = 0x7fffffff
} D3DPRIMITIVETYPE;

Constants

D3DPT_POINTLIST
Renders the vertices as a collection of isolated points.
D3DPT_LINELIST
Renders the vertices as a list of isolated straight line segments. Calls using this primitive type fail if the count is less than 2 or is odd.
D3DPT_LINESTRIP
Renders the vertices as a single polyline. Calls using this primitive type fail if the count is less than 2.
D3DPT_TRIANGLELIST
Renders the specified vertices as a sequence of isolated triangles. Each group of three vertices defines a separate triangle.

Backface culling is affected by the current winding-order render state.

D3DPT_TRIANGLESTRIP
Renders the vertices as a triangle strip. The backface-culling flag is automatically flipped on even-numbered triangles.
D3DPT_TRIANGLEFAN
Renders the vertices as a triangle fan.
D3DPT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Using Triangle Strips or Triangle Fans is often more efficient than using triangle lists because fewer vertices are duplicated.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::DrawIndexedPrimitive, IDirect3DDevice8::DrawIndexedPrimitiveUP, IDirect3DDevice8::DrawPrimitive, IDirect3DDevice8::DrawPrimitiveUP


D3DRENDERSTATETYPE

Defines device render states

typedef enum _D3DRENDERSTATETYPE {
    D3DRS_ZENABLE                   =   7,
    D3DRS_FILLMODE                  =   8,
    D3DRS_SHADEMODE                 =   9,
    D3DRS_LINEPATTERN               =  10,
    D3DRS_ZWRITEENABLE              =  14,
    D3DRS_ALPHATESTENABLE           =  15,
    D3DRS_LASTPIXEL                 =  16,
    D3DRS_SRCBLEND                  =  19,
    D3DRS_DESTBLEND                 =  20,
    D3DRS_CULLMODE                  =  22,
    D3DRS_ZFUNC                     =  23,
    D3DRS_ALPHAREF                  =  24,
    D3DRS_ALPHAFUNC                 =  25,
    D3DRS_DITHERENABLE              =  26,
    D3DRS_ALPHABLENDENABLE          =  27,
    D3DRS_FOGENABLE                 =  28,
    D3DRS_SPECULARENABLE            =  29,
    D3DRS_ZVISIBLE                  =  30,
    D3DRS_FOGCOLOR                  =  34,
    D3DRS_FOGTABLEMODE              =  35,
    D3DRS_FOGSTART                  =  36,
    D3DRS_FOGEND                    =  37,
    D3DRS_FOGDENSITY                =  38,
    D3DRS_EDGEANTIALIAS             =  40,
    D3DRS_ZBIAS                     =  47,
    D3DRS_RANGEFOGENABLE            =  48,

    D3DRS_STENCILENABLE             =  52,
    D3DRS_STENCILFAIL               =  53,
    D3DRS_STENCILZFAIL              =  54,
    D3DRS_STENCILPASS               =  55,
    D3DRS_STENCILFUNC               =  56,
    D3DRS_STENCILREF                =  57,
    D3DRS_STENCILMASK               =  58,
    D3DRS_STENCILWRITEMASK          =  59,
    D3DRS_TEXTUREFACTOR             =  60,

    D3DRS_WRAP0                     = 128,
    D3DRS_WRAP1                     = 129,
    D3DRS_WRAP2                     = 130,
    D3DRS_WRAP3                     = 131,
    D3DRS_WRAP4                     = 132,
    D3DRS_WRAP5                     = 133,
    D3DRS_WRAP6                     = 134,
    D3DRS_WRAP7                     = 135,
    D3DRS_CLIPPING                  = 136,
    D3DRS_LIGHTING                  = 137,
    D3DRS_AMBIENT                   = 139,
    D3DRS_FOGVERTEXMODE             = 140,
    D3DRS_COLORVERTEX               = 141,
    D3DRS_LOCALVIEWER               = 142,
    D3DRS_NORMALIZENORMALS          = 143,
    D3DRS_DIFFUSEMATERIALSOURCE     = 145,
    D3DRS_SPECULARMATERIALSOURCE    = 146,
    D3DRS_AMBIENTMATERIALSOURCE     = 147,
    D3DRS_EMISSIVEMATERIALSOURCE    = 148,
    D3DRS_VERTEXBLEND               = 151,
    D3DRS_CLIPPLANEENABLE           = 152,

    D3DRS_SOFTWAREVERTEXPROCESSING  = 153,

    D3DRS_POINTSIZE                 = 154,
    D3DRS_POINTSIZE_MIN             = 155,
    D3DRS_POINTSPRITEENABLE         = 156,

    D3DRS_POINTSCALEENABLE          = 157,
    D3DRS_POINTSCALE_A              = 158,
    D3DRS_POINTSCALE_B              = 159,
    D3DRS_POINTSCALE_C              = 160,

    D3DRS_MULTISAMPLEANTIALIAS      = 161,
    D3DRS_MULTISAMPLEMASK           = 162,

    D3DRS_PATCHEDGESTYLE            = 163,
    D3DRS_PATCHSEGMENTS             = 164,

    D3DRS_DEBUGMONITORTOKEN         = 165,
    D3DRS_POINTSIZE_MAX             = 166,
    D3DRS_INDEXEDVERTEXBLENDENABLE  = 167,
    D3DRS_COLORWRITEENABLE          = 168,
    D3DRS_TWEENFACTOR               = 170,
    D3DRS_BLENDOP                   = 171,

    D3DRS_FORCE_DWORD               = 0x7fffffff
} D3DRENDERSTATETYPE;

Constants

D3DRS_ZENABLE
Depth-buffering state as one member of the D3DZBUFFERTYPE enumerated type. Set this state to D3DZB_TRUE to enable z-buffering, D3DZB_USEW to enable w-buffering, or D3DZB_FALSE to disable depth buffering.

The default value for this render state is D3DZB_TRUE if a depth stencil was created along with the swap chain by setting the EnableAutoDepthStencil member of the D3DPRESENT_PARAMETERS structure to TRUE, and D3DZB_FALSE otherwise.

D3DRS_FILLMODE
One or more members of the D3DFILLMODE enumerated type. The default value is D3DFILL_SOLID.
D3DRS_SHADEMODE
One or more members of the D3DSHADEMODE enumerated type. The default value is D3DSHADE_GOURAUD.
D3DRS_LINEPATTERN
D3DLINEPATTERN structure. The default values are 0 for wRepeatPattern, and 0 for wLinePattern.
D3DRS_ZWRITEENABLE
TRUE to enable the application to write to the depth buffer. The default value is TRUE. This member enables an application to prevent the system from updating the depth buffer with new depth values. If FALSE, depth comparisons are still made according to the render state D3DRS_ZFUNC, assuming that depth buffering is taking place, but depth values are not written to the buffer.
D3DRS_ALPHATESTENABLE
TRUE to enable alpha tests. The default value is FALSE. This member enables applications to turn off the tests that accept or reject a pixel, based on its alpha value.

The incoming alpha value is compared with the reference alpha value, using the comparison function provided by the D3DRS_ALPHAFUNC render state. When this mode is enabled, alpha blending occurs only if the test succeeds.

D3DRS_LASTPIXEL
FALSE to enable drawing the last pixel in a line or triangle. The default value is TRUE.
D3DRS_SRCBLEND
One member of the D3DBLEND enumerated type. The default value is D3DBLEND_ONE.
D3DRS_DESTBLEND
One member of the D3DBLEND enumerated type. The default value is D3DBLEND_ZERO.
D3DRS_CULLMODE
Specifies how back-facing triangles are culled, if at all. This can be set to one member of the D3DCULL enumerated type. The default value is D3DCULL_CCW.
D3DRS_ZFUNC
One member of the D3DCMPFUNC enumerated type. The default value is D3DCMP_LESSEQUAL. This member enables an application to accept or reject a pixel, based on its distance from the camera.

The depth value of the pixel is compared with the depth-buffer value. If the depth value of the pixel passes the comparison function, the pixel is written.

The depth value is written to the depth buffer only if the render state is TRUE.

Software rasterizers and many hardware accelerators work faster if the depth test fails, because there is no need to filter and modulate the texture if the pixel is not going to be rendered.

D3DRS_ALPHAREF
Value that specifies a reference alpha value against which pixels are tested when alpha-testing is enabled. This is an 8-bit value placed in the low 8 bits of the DWORD render-state value. Values can range from 0x00000000 through 0x000000FF.
D3DRS_ALPHAFUNC
One member of the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS. This member enables an application to accept or reject a pixel, based on its alpha value.
D3DRS_DITHERENABLE
TRUE to enable dithering. The default value is FALSE.
D3DRS_ALPHABLENDENABLE
TRUE to enable alpha-blended transparency. The default value is FALSE.

The type of alpha blending is determined by the D3DRS_SRCBLEND and D3DRS_DESTBLEND render states.

Applications should check the D3DDEVCAPS_DRAWPRIMTLVERTEX flag in the DevCaps member of the D3DCAPS8 structure to find out whether this render state is supported.

D3DRS_FOGENABLE
TRUE to enable fog blending. The default value is FALSE. For more information on using fog blending, see Fog.
D3DRS_SPECULARENABLE
TRUE to enable specular highlights. The default value is FALSE.

Specular highlights are calculated as though every vertex in the object being lit were at the object's origin. This gives the expected results as long as the object is modeled around the origin and the distance from the light to the object is relatively large. In other cases the results as undefined.

When this member is set to TRUE, the specular color is added to the base color after the texture cascade but before alpha blending.

D3DRS_ZVISIBLE
Not supported.
D3DRS_FOGCOLOR
Value whose type is D3DCOLOR. The default value is 0. For more information on fog color, see Fog Color.
D3DRS_FOGTABLEMODE
The fog formula to be used for pixel fog. Set to one of the members of the D3DFOGMODE enumerated type. The default value is D3DFOG_NONE. For more information on pixel fog, see Pixel Fog.
D3DRS_FOGSTART
Depth at which pixel or vertex fog effects begin for linear fog mode. Depth is specified in world space for vertex fog, and either device space [0.0, 1.0] or world space for pixel fog. For pixel fog, these values are in device space when the system uses z for fog calculations, and world-space when the system is using eye-relative fog (w-fog). For more information, see Fog Parameters and Eye-Relative vs. Z-based Depth.

Values for this render state are floating-point values. Because the IDirect3DDevice8::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pd3dDevice8->SetRenderState(D3DRS_FOGSTART, *((DWORD*) (&fFogStart)));
D3DRS_FOGEND
Depth at which pixel or vertex fog effects end for linear fog mode. Depth is specified in world space for vertex fog, and either device space [0.0, 1.0] or world space for pixel fog. For pixel fog, these values are in device space when the system uses z for fog calculations, and world-space when the system is using eye-relative fog (w-fog). For more information, see Fog Parameters and Eye-Relative vs. Z-based Depth.

Values for this render state are floating-point values. Because the IDirect3DDevice8::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pd3dDevice8->SetRenderState(D3DRS_FOGEND, *((DWORD*) (&fFogEnd)));
D3DRS_FOGDENSITY
Fog density for pixel or vertex fog used in the exponential fog modes (D3DFOG_EXP and D3DFOG_EXP2). Valid density values range from 0.0 through 1.0. The default value is 1.0. For more information, see Fog Parameters.

Values for this render state are floating-point values. Because the IDirect3DDevice8::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.

pd3dDevice8->SetRenderState(D3DRS_FOGDENSITY, *((DWORD*) (&fFogDensity)));
D3DRS_EDGEANTIALIAS
TRUE to antialias lines forming the convex outline of objects. The default value is FALSE. If TRUE, applications should render only lines, and only to the exterior edges of polygons in a scene. The behavior is undefined if triangles or points are drawn when this render state is set. Antialiasing is performed by averaging the values of neighboring pixels. Although this is not the best way to perform antialiasing, it can be very efficient; hardware that supports this kind of operation is becoming more common.

You can enable edge antialiasing only on devices that expose the D3DPRASTERCAPS_ANTIALIASEDGES capability. For more information on edge antialiasing, see Edge Antialiasing and Antialiasing State.

D3DRS_ZBIAS
Integer value in the range 0 through 16 that causes polygons that are physically coplanar to appear separate. Polygons with a high z-bias value appear in front of polygons with a low value, without requiring sorting for drawing order. Polygons with a value of 1 appear in front of polygons with a value of 0, and so on. The default value is 0. For more information, see Using Depth Buffers.
D3DRS_RANGEFOGENABLE
TRUE to enable range-based vertex fog. The default value is FALSE, in which case the system uses depth-based fog. In range-based fog, the distance of an object from the viewer is used to compute fog effects, not the depth of the object (that is, the z-coordinate) in the scene. In range-based fog, all fog methods work as usual, except that they use range instead of depth in the computations.

Range is the correct factor to use for fog computations, but depth is commonly used instead because range is expensive to compute and depth is generally already available. Using depth to calculate fog has the undesirable effect of having the fogginess of peripheral objects change as the viewer's eye moves—in this case, the depth changes, and the range remains constant.

Because no hardware currently supports per-pixel range-based fog, range correction is offered only for vertex fog.

For more information, see Range-Based Fog and Vertex Fog.

D3DRS_STENCILENABLE
TRUE to enable stenciling, or FALSE to disable stenciling. The default value is FALSE.

For more information, see Stencil Buffers.

D3DRS_STENCILFAIL
Stencil operation to perform if the stencil test fails. This can be one member of the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.

For more information, see Stencil Buffers.

D3DRS_STENCILZFAIL
Stencil operation to perform if the stencil test passes and the depth test (z-test) fails. This can be one of the members of the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.
D3DRS_STENCILPASS
Stencil operation to perform if both the stencil and the depth (z) tests pass. This can be one member of the D3DSTENCILOP enumerated type. The default value is D3DSTENCILOP_KEEP.
D3DRS_STENCILFUNC
Comparison function for the stencil test. This can be one member of the D3DCMPFUNC enumerated type. The default value is D3DCMP_ALWAYS.

The comparison function is used to compare the reference value to a stencil buffer entry. This comparison applies only to the bits in the reference value and stencil buffer entry that are set in the stencil mask (set by the D3DRS_STENCILMASK render state). If TRUE, the stencil test passes.

D3DRS_STENCILREF
Integer reference value for the stencil test. The default value is 0.
D3DRS_STENCILMASK
Mask applied to the reference value and each stencil buffer entry to determine the significant bits for the stencil test. The default mask is 0xFFFFFFFF.
D3DRS_STENCILWRITEMASK
Write mask applied to values written into the stencil buffer. The default mask is 0xFFFFFFFF.
D3DRS_TEXTUREFACTOR
Color used for multiple-texture blending with the D3DTA_TFACTOR texture-blending argument or the D3DTOP_BLENDFACTORALPHA texture-blending operation. The associated value is a D3DCOLOR variable.
D3DRS_WRAP0 through D3DRS_WRAP7
Texture-wrapping behavior for multiple sets of texture coordinates. Valid values for these render states can be any combination of the D3DWRAPCOORD_0 (or D3DWRAP_U), D3DWRAPCOORD_1 (or D3DWRAP_V), D3DWRAPCOORD_2 (or D3DWRAP_W), and D3DWRAPCOORD_3 flags. These cause the system to wrap in the direction of the first, second, third, and fourth dimensions, sometimes referred to at the s, t, r, and q directions, for a given texture. The default value for these render states is 0 (wrapping disabled in all directions).
D3DRS_CLIPPING
TRUE to enable primitive clipping by Microsoft® Direct3D®, or FALSE to disable it. The default value is TRUE.
D3DRS_LIGHTING
TRUE to enable Direct3D lighting, or FALSE to disable it. The default value is TRUE. Only vertices that include a vertex normal are properly lit; vertices that do not contain a normal employ a dot product of 0 in all lighting calculations.
D3DRS_AMBIENT
Ambient light color. This value is of type D3DCOLOR. The default value is 0.
D3DRS_FOGVERTEXMODE
Fog formula to be used for vertex fog. Set to one member of the D3DFOGMODE enumerated type. The default value is D3DFOG_NONE.
D3DRS_COLORVERTEX
TRUE to enable per-vertex color, or FALSE to disable it. The default value is TRUE. Enabling per-vertex color allows the system to include the color defined for individual vertices in its lighting calculations.

For more information, see the following render states.

  • D3DRS_DIFFUSEMATERIALSOURCE
  • D3DRS_SPECULARMATERIALSOURCE
  • D3DRS_AMBIENTMATERIALSOURCE
  • D3DRS_EMISSIVEMATERIALSOURCE
D3DRS_LOCALVIEWER
TRUE to enable camera-relative specular highlights, or FALSE to use orthogonal specular highlights. The default value is TRUE. Applications that use orthogonal projection should specify false.
D3DRS_NORMALIZENORMALS
TRUE to enable automatic normalization of vertex normals, or FALSE to disable it. The default value is FALSE. Enabling this feature causes the system to normalize the vertex normals for vertices after transforming them to camera space, which can be computationally expensive.
D3DRS_DIFFUSEMATERIALSOURCE
Diffuse color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR1. The value for this render state is used only if the D3DRS_COLORVERTEX render state is set to TRUE.
D3DRS_SPECULARMATERIALSOURCE
Specular color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR2.
D3DRS_AMBIENTMATERIALSOURCE
Ambient color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_COLOR2.
D3DRS_EMISSIVEMATERIALSOURCE
Emissive color source for lighting calculations. Valid values are members of the D3DMATERIALCOLORSOURCE enumerated type. The default value is D3DMCS_MATERIAL.
D3DRS_VERTEXBLEND
Number of matrices to use to perform geometry blending, if any. Valid values are members of the D3DVERTEXBLENDFLAGS enumerated type. The default value is D3DVBF_DISABLE.
D3DRS_CLIPPLANEENABLE
Enables or disables user-defined clipping planes. Valid values are any DWORD in which the status of each bit (set or not set) toggles the activation state of a corresponding user-defined clipping plane. The least significant bit (bit 0) controls the first clipping plane at index 0, and subsequent bits control the activation of clipping planes at higher indexes. If a bit is set, the system applies the appropriate clipping plane during scene rendering. The default value is 0.

The D3DCLIPPLANEn macros are defined to provide a convenient way to enable clipping planes.

D3DRS_SOFTWAREVERTEXPROCESSING
BOOL value that enables applications to query and select hardware or software vertex processing. For a D3DDEVTYPE_SW device type this value is fixed to TRUE. This value can be set by the application for a D3DDEVTYPE_REF device type. For a D3DDEVTYPE_HAL device type, this value can be set only by the application when D3DDEVCAPS_HWTRANSFORMANDLIGHT is set; otherwise this flag is fixed to TRUE. When variable, the default value is FALSE.

Changing the vertex processing render state in mixed vertex processing mode will reset the current stream, indices, and vertex shader to their default values of NULL or 0.

D3DRS_POINTSIZE
Float value that specifies the size to use for point size computation in cases where point size is not specified for each vertex. This value is not used when the vertex contains point size. This value is in screen space units if D3DRS_POINTSCALEENABLE is FALSE; otherwise this value is in world space units. The default value is 1.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice8::SetRenderState method accepts DWORD values, you application must cast a variable that contains the value, as shown in the following code example.
pd3dDevice8->SetRenderState(D3DRS_PATCHSEGMENTS, *((DWORD*)&PointSize));
D3DRS_POINTSIZE_MIN
Float value that specifies the minimum size of point primitives. Point primitives are clamped to this size during rendering. Setting this to values smaller than 1.0 results in points dropping out when the point does not cover a pixel center and antialiasing is disabled or being rendered with reduced intensity when antialiasing is enabled. The default value is 1.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice8::SetRenderState method accepts DWORD values, you application must cast a variable that contains the value, as shown in the following code example.
pd3dDevice8->SetRenderState(D3DRS_PATCHSEGMENTS, *((DWORD*)&PointSizeMin));
D3DRS_POINTSPRITEENABLE
BOOL value. When TRUE, texture coordinates of point primitives are set so that full textures are mapped on each point. When FALSE, the vertex texture coordinates are used for the entire point. The default value is FALSE. You can achieve DirectX 7 style single-pixel points by setting D3DRS_POINTSCALEENABLE to FALSE and D3DRS_POINTSIZE to 1.0, which are the default values.
D3DRS_POINTSCALEENABLE
BOOL value that controls computation of size for point primitives. When TRUE, the point size is interpreted as a camera space value and is scaled by the distance function and the frustum to viewport Y axis scaling to compute the final screen space point size. When FALSE, the point size is interpreted as screen space and used directly. The default value is FALSE.
D3DRS_POINTSCALE_A
Float value that controls for distance-based size attenuation for point primitives. Active only whenD3DRS_POINTSCALEENABLE is TRUE. The default value is 1.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice8::SetRenderState method accepts DWORD values, you application must cast a variable that contains the value, as shown in the following code example.
pd3dDevice8->SetRenderState(D3DRS_PATCHSEGMENTS, *((DWORD*)&PointScaleA));
D3DRS_POINTSCALE_B
Float value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is TRUE. The default value is 0.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice8::SetRenderState method accepts DWORD values, you application must cast a variable that contains the value, as shown in the following code example.
pd3dDevice8->SetRenderState(D3DRS_PATCHSEGMENTS, *((DWORD*)&PointScaleB));
D3DRS_POINTSCALE_C
Float value that controls for distance-based size attenuation for point primitives. Active only when D3DRS_POINTSCALEENABLE is TRUE. The default value is 0.0f. The range for this value is greater than or equal to 0.0f. Because the IDirect3DDevice8::SetRenderState method accepts DWORD values, you application must cast a variable that contains the value, as shown in the following code example.
pd3dDevice8->SetRenderState(D3DRS_PATCHSEGMENTS, *((DWORD*)&PointScaleC));
D3DRS_MULTISAMPLEANTIALIAS
BOOL value that determines how individual samples are computed when using a multisample render target buffer. When set to TRUE, the multiple samples are computed so that full-scene antialiasing is performed by sampling at different sample positions for each multiple sample. When set to FALSE, the multiple samples are all written with the same sample value—sampled at the pixel center, which allows non-antialiased rendering to a multisample buffer. This render state has no effect when rendering to a single sample buffer. The default value is TRUE.
D3DRS_MULTISAMPLEMASK
Each bit in this mask, starting at the LSB, controls modification of one of the samples in a multisample render target. Thus, for an 8-sample render target, the low byte contains the 8 write enables for each of the 8 samples. This render state has no effect when rendering to a single sample buffer. The default value is 0xFFFFFFFF.

This render state enables use of a multisample buffer as an accumulation buffer, doing multipass rendering of geometry where each pass updates a subset of samples.

D3DRS_PATCHEDGESTYLE
Sets whether patch edges will use float style tessellation. Possible values are defined by the D3DPATCHEDGESTYLE enumerated type.
D3DRS_PATCHSEGMENTS
Sets the number of segments as a float value for each edge when drawing patches. Because the IDirect3DDevice8::SetRenderState method accepts DWORD values, your application must cast a variable that contains the value, as shown in the following code example.
pd3dDevice8->SetRenderState(D3DRS_PATCHSEGMENTS, *((DWORD*)&NumSegments));
D3DRS_DEBUGMONITORTOKEN
Set only for debugging the monitor. Possible values are defined by the D3DDEBUGMONITORTOKENS enumerated type. Note that if D3DRS_DEBUGMONITORTOKEN is set, the call is treated as passing a token to the debug monitor. For example, if, after passing D3DDMT_ENABLE or D3DDMT_DISABLE to D3DRS_DEBUGMONITORTOKEN, other token values are passed in, the state (enabled or disabled) of the debug monitor will still persist.

This state is only useful for debug builds. The debug monitor defaults to D3DDMT_ENABLE.

D3DRS_POINTSIZE_MAX
Float value that specifies the maximum size to which point sprites will be clamped. The value must be less than or equal to the MaxPointSize member of D3DCAPS8 and greater than or equal to D3DRS_POINTSIZE_MIN. Because the IDirect3DDevice8::SetRenderState method accepts DWORD values, you application must cast a variable that contains the value, as shown in the following code example.
pd3dDevice8->SetRenderState(D3DRS_PONTSIZE_MAX, *((DWORD*)&PointSizeMax));
D3DRS_INDEXEDVERTEXBLENDENABLE
BOOL value that enables or disables indexed vertex blending. When set to TRUE, indexed vertex blending is enabled. When set to FALSE, indexed vertex blending is disabled. If this render state is enabled, the user must pass matrix indices as a packed DWORD with every vertex. When the render state is disabled and vertex blending is enabled through the D3DRS_VERTEXBLEND state, it is equivalent to having matrix indices 0, 1, 2, 3 in every vertex.
D3DRS_COLORWRITEENABLE
UINT value that enables a per-channel write for the render target color buffer. A set bit results in the color channel being updated during 3-D rendering. A clear bit results in the color channel being unaffected. This functionality is available if the D3DPMISCCAPS_COLORWRITEENABLE capabilities bit is set in the PrimitiveMiscCaps member of the D3DCAPS8 structure for the device. This render state does not affect the clear operation. The default value is 0x0000000F.

Valid values for this render state can be any combination of the D3DCOLORWRITEENABLE_ALPHA, D3DCOLORWRITEENABLE_BLUE, D3DCOLORWRITEENABLE_GREEN, or D3DCOLORWRITEENABLE_RED flags.

D3DRS_TWEENFACTOR
Float value that controls the tween factor. Because the IDirect3DDevice8::SetRenderState method accepts DWORD values, you application must cast a variable that contains the value, as shown in the following code example.
pd3dDevice8->SetRenderState(D3DRS_PATCHSEGMENTS, *((DWORD*)&TweenFactor));
D3DRS_BLENDOP
Value used to select the arithmetic operation applied when the alpha blending render state, D3DRS_ALPHABLENDENABLE, is set to TRUE. Valid values are defined by the D3DBLENDOP enumerated type. The default value is D3DBLENDOP_ADD.

If the D3DPMISCCAPS_BLENDOP device capability is not supported, then D3DBLENDOP_ADD is performed.

D3DRS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Direct3D defines the D3DRENDERSTATE_WRAPBIAS constant as a convenience for applications to enable or disable texture wrapping, based on the zero-based integer of a texture coordinate set (rather than explicitly using one of the D3DRS_WRAPn state values). Add the D3DRENDERSTATE_WRAPBIAS value to the zero-based index of a texture coordinate set to calculate the D3DRS_WRAPn value that corresponds to that index, as shown in the following example.

// Enable U/V wrapping for textures that use the texture
// coordinate set at the index within the dwIndex variable.
HRESULT hr = pd3dDevice->SetRenderState(
    dwIndex + D3DRENDERSTATE_WRAPBIAS,
    D3DWRAPCOORD_0 | D3DWRAPCOORD_1);

// If dwIndex is 3, the value that results from
// the addition equals D3DRS_WRAP3 (131).

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetRenderState, IDirect3DDevice8::SetRenderState


D3DRESOURCETYPE

Defines resource types.

typedef enum _D3DRESOURCETYPE {
    D3DRTYPE_SURFACE                =  1,
    D3DRTYPE_VOLUME                 =  2,
    D3DRTYPE_TEXTURE                =  3,
    D3DRTYPE_VOLUMETEXTURE          =  4,
    D3DRTYPE_CUBETEXTURE            =  5,
    D3DRTYPE_VERTEXBUFFER           =  6,
    D3DRTYPE_INDEXBUFFER            =  7,

    D3DRTYPE_FORCE_DWORD            = 0x7fffffff
} D3DRESOURCETYPE;

Constants

D3DRTYPE_SURFACE
Surface resource.
D3DRTYPE_VOLUME
Volume resource.
D3DRTYPE_TEXTURE
Texture resource.
D3DRTYPE_VOLUMETEXTURE
Volume texture resource.
D3DRTYPE_CUBETEXTURE
Cube texture resource.
D3DRTYPE_VERTEXBUFFER
Vertex buffer resource.
D3DRTYPE_INDEXBUFFER
Index buffer resource.
D3DRTYPE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DResource8::GetType


D3DSHADEMODE

Defines constants that describe the supported shading modes.

typedef enum _D3DSHADEMODE {
    D3DSHADE_FLAT               = 1,
    D3DSHADE_GOURAUD            = 2,
    D3DSHADE_PHONG              = 3,

    D3DSHADE_FORCE_DWORD        = 0x7fffffff
} D3DSHADEMODE;

Constants

D3DSHADE_FLAT
Flat shading mode. The color and specular component of the first vertex in the triangle are used to determine the color and specular component of the face. These colors remain constant across the triangle; that is, they are not interpolated. The specular alpha is interpolated. See Remarks.
D3DSHADE_GOURAUD
Gouraud shading mode. The color and specular components of the face are determined by a linear interpolation between all three of the triangle's vertices.
D3DSHADE_PHONG
Not supported.
D3DSHADE_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The first vertex of a triangle for flat shading mode is defined in the following manner.

  • For a triangle list, the first vertex of the triangle i is i * 3.
  • For a triangle strip, the first vertex of the triangle i is vertex i.
  • For a triangle fan, the first vertex of the triangle i is vertex i + 1.

The members of this enumerated type define the vales for the D3DRS_SHADEMODE render state.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRENDERSTATETYPE


D3DSTATEBLOCKTYPE

Defines logical groups of device states.

typedef enum _D3DSTATEBLOCKTYPE {
    D3DSBT_ALL           = 1,
    D3DSBT_PIXELSTATE    = 2,
    D3DSBT_VERTEXSTATE   = 3,

    D3DSBT_FORCE_DWORD   = 0xffffffff
} D3DSTATEBLOCKTYPE;

Constants

D3DSBT_ALL
Capture all of the following device states.
All current render states. | All current clipplanes.
All current texture stage states. | The current material.
All current textures. | All current lights and enabled light parameters.
The current palette. | The current pixel shader.
All current streams. | The current pixel shader constants.
The current viewport. | The current vertex shader.
All current transforms. | The current vertex shader constants.

D3DSBT_PIXELSTATE
Capture the current pixel shader and pixel shader constants, as well as all of the following pixel-related device states.

Render States
D3DRS_ALPHABLENDENABLE D3DRS_ALPHAFUNC
D3DRS_ALPHAREF D3DRS_ALPHATESTENABLE
D3DRS_BLENDOP D3DRS_COLORWRITEENABLE
D3DRS_DESTBLEND D3DRS_DITHERENABLE
D3DRS_EDGEANTIALIAS D3DRS_FILLMODE
D3DRS_FOGDENSITY D3DRS_FOGEND
D3DRS_FOGSTART D3DRS_LASTPIXEL
D3DRS_LINEPATTERN D3DRS_SHADEMODE
D3DRS_SRCBLEND D3DRS_STENCILENABLE
D3DRS_STENCILFAIL D3DRS_STENCILFUNC
D3DRS_STENCILMASK D3DRS_STENCILPASS
D3DRS_STENCILREF D3DRS_STENCILWRITEMASK
D3DRS_STENCILZFAIL D3DRS_TEXTUREFACTOR
D3DRS_WRAP0 through D3DRS_WRAP7 D3DRS_ZBIAS
D3DRS_ZENABLE D3DRS_ZFUNC
D3DRS_ZWRITEENABLE

Texture Stage States
D3DTSS_ADDRESSU D3DTSS_ADDRESSV
D3DTSS_ADDRESSW D3DTSS_ALPHAARG0
D3DTSS_ALPHAARG1 D3DTSS_ALPHAARG2
D3DTSS_ALPHAOP D3DTSS_BORDERCOLOR
D3DTSS_BUMPENVLOFFSET D3DTSS_BUMPENVLSCALE
D3DTSS_BUMPENVMAT00 D3DTSS_BUMPENVMAT01
D3DTSS_BUMPENVMAT10 D3DTSS_BUMPENVMAT11
D3DTSS_COLORARG0 D3DTSS_COLORARG1
D3DTSS_COLORARG2 D3DTSS_COLOROP
D3DTSS_MAGFILTER D3DTSS_MAXANISOTROPY
D3DTSS_MAXMIPLEVEL D3DTSS_MINFILTER
D3DTSS_MIPFILTER D3DTSS_MIPMAPLODBIAS
D3DTSS_RESULTARG D3DTSS_TEXCOORDINDEX
D3DTSS_TEXTURETRANSFORMFLAGS

D3DSBT_VERTEXSTATE
Capture all the current lights, the current vertex shader and vertex shader constants, and the texture stage states specified by D3DTSS_TEXCOORDINDEX and D3DTSS_TEXTURETRANSFORMFLAGS. In addition, this flag captures all of the following vertex-related device states.

Render States
D3DRS_AMBIENT D3DRS_AMBIENTMATERIALSOURCE
D3DRS_CLIPPING D3DRS_CLIPPLANEENABLE
D3DRS_COLORVERTEX D3DRS_DIFFUSEMATERIALSOURCE
D3DRS_EMISSIVEMATERIALSOURCE D3DRS_FOGDENSITY
D3DRS_FOGEND D3DRS_FOGSTART
D3DRS_FOGTABLEMODE D3DRS_FOGVERTEXMODE
D3DRS_INDEXEDVERTEXBLENDENABLE D3DRS_LIGHTING
D3DRS_LOCALVIEWER D3DRS_MULTISAMPLEANTIALIAS
D3DRS_MULTISAMPLEMASK D3DRS_NORMALIZENORMALS
D3DRS_PATCHEDGESTYLE D3DRS_PATCHSEGMENTS
D3DRS_POINTSCALE_A D3DRS_POINTSCALE_B
D3DRS_POINTSCALE_C D3DRS_POINTSCALEENABLE
D3DRS_POINTSIZE D3DRS_POINTSIZE_MAX
D3DRS_POINTSIZE_MIN D3DRS_POINTSPRITEENABLE
D3DRS_RANGEFOGENABLE D3DRS_SOFTWAREVERTEXPROCESSING
D3DRS_SPECULARMATERIALSOURCE D3DRS_TWEENFACTOR
D3DRS_VERTEXBLEND

D3DSBT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The D3DSBT_PIXELSTATE and D3DSBT_VERTEXSTATE values identify different logical groups of device states, though some states are common to both groups. The union of D3DSBT_PIXELSTATE and D3DSBT_VERTEXSTATE is not equal to D3DSBT_ALL. The D3DSBT_PIXELSTATE and D3DSBT_VERTEXSTATE values enable the capture of these frequently modified states between calls to IDirect3Ddevice8::DrawPrimitive without incurring the performance penalty of capturing the entire state.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::CreateStateBlock


D3DSTENCILOP

Defines stencil operations.

typedef enum _D3DSTENCILOP {
    D3DSTENCILOP_KEEP           = 1,
    D3DSTENCILOP_ZERO           = 2,
    D3DSTENCILOP_REPLACE        = 3,
    D3DSTENCILOP_INCRSAT        = 4,
    D3DSTENCILOP_DECRSAT        = 5,
    D3DSTENCILOP_INVERT         = 6,
    D3DSTENCILOP_INCR           = 7,
    D3DSTENCILOP_DECR           = 8,

    D3DSTENCILOP_FORCE_DWORD    = 0x7fffffff
} D3DSTENCILOP;

Constants

D3DSTENCILOP_KEEP
Do not update the entry in the stencil buffer. This is the default value.
D3DSTENCILOP_ZERO
Set the stencil-buffer entry to 0.
D3DSTENCILOP_REPLACE
Replace the stencil-buffer entry with reference value.
D3DSTENCILOP_INCRSAT
Increment the stencil-buffer entry, clamping to the maximum value. See Remarks for information on the maximum stencil-buffer values.
D3DSTENCILOP_DECRSAT
Decrement the stencil-buffer entry, clamping to zero.
D3DSTENCILOP_INVERT
Invert the bits in the stencil-buffer entry.
D3DSTENCILOP_INCR
Increment the stencil-buffer entry, wrapping to zero if the new value exceeds the maximum value. See Remarks for information on the maximum stencil-buffer values.
D3DSTENCILOP_DECR
Decrement the stencil-buffer entry, wrapping to the maximum value if the new value is less than zero.
D3DSTENCILOP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Stencil-buffer entries are integer values ranging from 0 through 2n –1, where n is the bit depth of the stencil buffer.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRENDERSTATETYPE


D3DSWAPEFFECT

Defines swap effects.

typedef enum _D3DSWAPEFFECT {
    D3DSWAPEFFECT_DISCARD         = 1,
    D3DSWAPEFFECT_FLIP            = 2,
    D3DSWAPEFFECT_COPY            = 3,
    D3DSWAPEFFECT_COPY_VSYNC      = 4,

    D3DSWAPEFFECT_FORCE_DWORD     = 0xFFFFFFFF
} D3DSWAPEFFECT;

Constants

D3DSWAPEFFECT_DISCARD
When a swap chain is created with a swap effect of D3DSWAPEFFECT_FLIP, D3DSWAPEFFECT_COPY or D3DSWAPEFFECT_COPY_VSYNC, the runtime will guarantee that a IDirect3DDevice8::Present operation will not affect the content of any of the back buffers. Unfortunately, meeting this guarantee can involve substantial video memory or processing overheads, especially when implementing flip semantics for a windowed swap chain or copy semantics for a full-screen swap chain. An application may use the D3DSWAPEFFECT_DISCARD swap effect to avoid these overheads and to enable the display driver to select the most efficient presentation technique for the swap chain. This is also the only swap effect that may be used when specifying a value other than D3DMULTISAMPLE_NONE for the MultiSampleType member of D3DPRESENT_PARAMETERS.

Like a swap chain that uses D3DSWAPEFFECT_FLIP, a swap chain that uses D3DSWAPEFFECT_DISCARD might include more than one back buffer, any of which may be accessed using IDirect3DDevice8::GetBackBuffer or IDirect3DSwapChain8::GetBackBuffer. The swap chain is best envisaged as a queue in which 0 always indexes the back buffer that will be displayed by the next Present operation and from which buffers are discarded once they have been displayed.

An application that uses this swap effect cannot make any assumptions about the contents of a discarded back buffer and should therefore update an entire back buffer before invoking a Present operation that would display it. Although this is not enforced, the debug version of the runtime will overwrite the contents of discarded back buffers with random data to enable developers to verify that their applications are updating the entire back buffer surfaces correctly.

For a full-screen swap chain, the presentation rate is determined by the value assigned to the FullScreen_PresentationInterval member of the D3DPRESENT_PARAMETERS structure when the device or swap chain is created. Unless this value is D3DPRESENT_INTERVAL_IMMEDIATE, the presentation will be synchronized with the vertical sync of the monitor. For a windowed swap chain, the presentation is implemented by means of copy operations and always occurs immediately.

D3DSWAPEFFECT_FLIP
The swap chain might include multiple back buffers and is best envisaged as a circular queue that includes the front buffer. Within this queue, the back buffers are always numbered sequentially from 0 to (N -1), where N is the number of back buffers, so that 0 denotes the least recently presented buffer. When Present is invoked, the queue is "rotated" so that the front buffer becomes back buffer (N - 1), while the back buffer 0 becomes the new front buffer.

For a full-screen swap chain, the presentation rate is determined by the value assigned to the FullScreen_PresentationInterval member of the D3DPRESENT_PARAMETERS structure when the device or swap chain is created. Unless this value is D3DPRESENT_INTERVAL_IMMEDIATE, the presentation will be synchronized with the vertical sync of the monitor. For a windowed swap chain, the flipping is implemented by means of copy operations and the presentation always occurs immediately.

D3DSWAPEFFECT_COPY
This swap effect may be specified only for a swap chain comprising a single back buffer. Whether the swap chain is windowed or full-screen, the runtime will guarantee the semantics implied by a copy-based Present operation, namely that the operation leaves the content of the back buffer unchanged, instead of replacing it with the content of the front buffer as a flip-based Present operation would.

For a windowed swap chain, a Present operation causes the back buffer content to be copied to the client area of the target window immediately. No attempt is made to synchronize the copy with the vertical retrace period of the display adapter, so "tearing" effects may be observed. In windowed applications you might want to use D3DSWAPEFFECT_COPY_VSYNC instead to eliminate, or at least minimize, such tearing effects.

For a full-screen swap chain, the runtime uses a combination of flip operations and copy operations, supported if necessary by hidden back buffers, to accomplish the Present operation. Accordingly, the presentation is synchronized with the display adapter's vertical retrace and its rate is constrained by the chosen presentation interval. A swap chain specified with the D3DPRESENT_INTERVAL_IMMEDIATE flag is the only exception. (Refer to the description of the FullScreen_PresentationInterval member of the D3DPRESENT_PARAMETERS structure.) In this case, a Present operation copies the back buffer content directly to the front buffer without waiting for the vertical retrace.

D3DSWAPEFFECT_COPY_VSYNC
Like D3DSWAPEFFECT_COPY, this swap effect may be used only with a swap chain made of a single back buffer. It guarantees that a Present operation applied to the swap chain will exhibit copy semantics, as described above for D3DSWAPEFFECT_COPY.

For a windowed swap chain, a Present operation causes the back buffer content to be copied to the client area of the target window. The runtime will attempt to eliminate tearing effects by avoiding the copy operation while the adapter is scanning within the destination rectangle on the display. It will also perform at most one such copy operation during the adapter's refresh period and thus limit the presentation frequency. Note, however, that if the adapter does not support the ability to report the raster status, the swap chain will behave as though it had been created with the D3DSWAPEFFECT_COPY swap effect. (Refer to the description of the D3DCAPS_READ_SCANLINE flag value for the Caps member of D3DCAPS8.)

For a full-screen swap chain, D3DSWAPEFFECT_COPY_VSYNC is identical to D3DSWAPEFFECT_COPY, except that the D3DPRESENT_INTERVAL_IMMEDIATE flag is meaningless when used in conjunction with D3DSWAPEFFECT_COPY_VSYNC. (Refer to the description of the FullScreen_PresentationInterval member of the D3DPRESENT_PARAMETERS structure.)

D3DSWAPEFFECT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The state of the back buffer after a call to Present is well-defined by each of these swap effects, and whether the Microsoft® Direct3D® device was created with a full-screen swap chain or a windowed swap chain has no effect on this state. In particular, the D3DSWAPEFFECT_FLIP swap effect operates the same whether windowed or full-screen, and the Direct3D runtime guarantees this by creating extra buffers. As a result, it is recommended that applications use D3DSWAPEFFECT_DISCARD whenever possible to avoid any such penalties. This is because this swap effect will always be the most efficient in terms of memory consumption and performance.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::Reset, D3DPRESENT_PARAMETERS


D3DTEXTUREADDRESS

Defines constants that describe the supported texture-addressing modes.

typedef enum _D3DTEXTUREADDRESS {
    D3DTADDRESS_WRAP            = 1,
    D3DTADDRESS_MIRROR          = 2,
    D3DTADDRESS_CLAMP           = 3,
    D3DTADDRESS_BORDER          = 4,
    D3DTADDRESS_MIRRORONCE      = 5,

    D3DTADDRESS_FORCE_DWORD     = 0x7fffffff
} D3DTEXTUREADDRESS;

Constants

D3DTADDRESS_WRAP
Tile the texture at every integer junction. For example, for u values between 0 and 3, the texture is repeated three times; no mirroring is performed.
D3DTADDRESS_MIRROR
Similar to D3DTADDRESS_WRAP, except that the texture is flipped at every integer junction. For u values between 0 and 1, for example, the texture is addressed normally; between 1 and 2, the texture is flipped (mirrored); between 2 and 3, the texture is normal again, and so on.
D3DTADDRESS_CLAMP
Texture coordinates outside the range [0.0, 1.0] are set to the texture color at 0.0 or 1.0, respectively.
D3DTADDRESS_BORDER
Texture coordinates outside the range [0.0, 1.0] are set to the border color.
D3DTADDRESS_MIRRORONCE
Similar to D3DTADDRESS_MIRROR and D3DTADDRESS_CLAMP. Takes the absolute value of the texture coordinate (thus, mirroring around 0), and then clamps to the maximum value. The most common usage is for volume textures, where support for the full D3DTADDRESS_MIRRORONCE texture-addressing mode is not necessary, but the data is symmetric around the one axis.
D3DTADDRESS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DTEXTURESTAGESTATETYPE


D3DTEXTUREFILTERTYPE

Defines texture filtering modes for a texture stage.

typedef enum _D3DTEXTUREFILTERTYPE {
    D3DTEXF_NONE            = 0,
    D3DTEXF_POINT           = 1,
    D3DTEXF_LINEAR          = 2,
    D3DTEXF_ANISOTROPIC     = 3,
    D3DTEXF_FLATCUBIC       = 4,
    D3DTEXF_GAUSSIANCUBIC   = 5,

    D3DTEXF_FORCE_DWORD     = 0x7fffffff
} D3DTEXTUREFILTERTYPE;

Constants

D3DTEXF_NONE
Mipmapping disabled. The rasterizer should use the magnification filter instead.
D3DTEXF_POINT
Point filtering used as a texture magnification or minification filter. The texel with coordinates nearest to the desired pixel value is used.

The texture filter to be used between mipmap levels is nearest-point mipmap filtering. The rasterizer uses the color from the texel of the nearest mipmap texture.

D3DTEXF_LINEAR
Bilinear interpolation filtering used as a texture magnification or minification filter. A weighted average of a 2×2 area of texels surrounding the desired pixel is used.

The texture filter to use between mipmap levels is trilinear mipmap interpolation. The rasterizer linearly interpolates pixel color, using the texels of the two nearest mipmap textures.

D3DTEXF_ANISOTROPIC
Anisotropic texture filtering used as a texture magnification or minification filter. Compensates for distortion caused by the difference in angle between the texture polygon and the plane of the screen.
D3DTEXF_FLATCUBIC
Flat-cubic filtering used as a texture magnification filter.
D3DTEXF_GAUSSIANCUBIC
Gaussian-cubic filtering used as a texture magnification filter.
D3DTEXF_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Not all valid filtering modes for a device will apply to volume maps. In general, D3DTEXF_POINT and D3DTEXF_LINEAR magnification filters will be supported for volume maps. If D3DPTEXTURECAPS_MIPVOLUMEMAP is set, then the D3DTEXF_POINT mipmap filter and D3DTEXF_POINT and D3DTEXF_LINEAR minification filters will be supported for volume maps. The device may or may not support the D3DTEXF_LINEAR mipmap filter for volume maps. DirectX 8 devices that support anisotropic filtering for 2-D maps do not necessarily support anisotropic filtering for volume maps. However, applications that enable anisotropic filtering will receive the best available filtering (probably linear) if anisotropic filtering is not supported.

Set a texture stage's magnification filter by calling the IDirect3DDevice8::SetTextureStageState method with the D3DTSS_MAGFILTER value as the second parameter and one member of this enumeration as the third parameter.

Set a texture stage's minification filter by calling SetTextureStageState with the D3DTSS_MINFILTER value as the second parameter and one member of this enumeration as the third parameter.

Set the texture filter to use between mipmap levels by calling SetTextureStageState with the D3DTSS_MIPFILTER value as the second parameter and one member of this enumeration as the third parameter.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DTEXTURESTAGESTATETYPE


D3DTEXTUREOP

Defines per-stage texture-blending operations.

typedef enum _D3DTEXTUREOP {
    D3DTOP_DISABLE                   =  1,
    D3DTOP_SELECTARG1                =  2,
    D3DTOP_SELECTARG2                =  3,
    D3DTOP_MODULATE                  =  4,
    D3DTOP_MODULATE2X                =  5,
    D3DTOP_MODULATE4X                =  6,
    D3DTOP_ADD                       =  7,
    D3DTOP_ADDSIGNED                 =  8,
    D3DTOP_ADDSIGNED2X               =  9,
    D3DTOP_SUBTRACT                  = 10,
    D3DTOP_ADDSMOOTH                 = 11,
    D3DTOP_BLENDDIFFUSEALPHA         = 12,
    D3DTOP_BLENDTEXTUREALPHA         = 13,
    D3DTOP_BLENDFACTORALPHA          = 14,
    D3DTOP_BLENDTEXTUREALPHAPM       = 15,
    D3DTOP_BLENDCURRENTALPHA         = 16,
    D3DTOP_PREMODULATE               = 17,
    D3DTOP_MODULATEALPHA_ADDCOLOR    = 18,
    D3DTOP_MODULATECOLOR_ADDALPHA    = 19,
    D3DTOP_MODULATEINVALPHA_ADDCOLOR = 20,
    D3DTOP_MODULATEINVCOLOR_ADDALPHA = 21,
    D3DTOP_BUMPENVMAP                = 22,
    D3DTOP_BUMPENVMAPLUMINANCE       = 23,
    D3DTOP_DOTPRODUCT3               = 24,
    D3DTOP_MULTIPLYADD               = 25,
    D3DTOP_LERP                      = 26,

    D3DTOP_FORCE_DWORD               = 0x7fffffff,
} D3DTEXTUREOP;

Constants

Control members
D3DTOP_DISABLE
Disables output from this texture stage and all stages with a higher index. To disable texture mapping, set this as the color operation for the first texture stage (stage 0). Alpha operations cannot be disabled when color operations are enabled. Setting the alpha operation to D3DTOP_DISABLE when color blending is enabled causes undefined behavior.
D3DTOP_SELECTARG1
Use this texture stage's first color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture-stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

D3DTOP_SELECTARG2
Use this texture stage's second color or alpha argument, unmodified, as the output. This operation affects the color argument when used with the D3DTSS_COLOROP texture stage state, and the alpha argument when used with D3DTSS_ALPHAOP.

Modulation members
D3DTOP_MODULATE
Multiply the components of the arguments.

D3DTOP_MODULATE2X
Multiply the components of the arguments, and shift the products to the left 1 bit (effectively multiplying them by 2) for brightening.

D3DTOP_MODULATE4X
Multiply the components of the arguments, and shift the products to the left 2 bits (effectively multiplying them by 4) for brightening.

Addition and subtraction members
D3DTOP_ADD
Add the components of the arguments.

D3DTOP_ADDSIGNED
Add the components of the arguments with a –0.5 bias, making the effective range of values from –0.5 through 0.5.

D3DTOP_ADDSIGNED2X
Add the components of the arguments with a –0.5 bias, and shift the products to the left 1 bit.

D3DTOP_SUBTRACT
Subtract the components of the second argument from those of the first argument.

D3DTOP_ADDSMOOTH
Add the first and second arguments; then subtract their product from the sum.

Linear alpha blending members
D3DTOP_BLENDDIFFUSEALPHA,D3DTOP_BLENDTEXTUREALPHA, D3DTOP_BLENDFACTORALPHA, and D3DTOP_BLENDCURRENTALPHA
Linearly blend this texture stage, using the interpolated alpha from each vertex (D3DTOP_BLENDDIFFUSEALPHA), alpha from this stage's texture (D3DTOP_BLENDTEXTUREALPHA), a scalar alpha (D3DTOP_BLENDFACTORALPHA) set with the D3DRS_TEXTUREFACTOR render state, or the alpha taken from the previous texture stage (D3DTOP_BLENDCURRENTALPHA).

D3DTOP_BLENDTEXTUREALPHAPM
Linearly blend a texture stage that uses a premultiplied alpha.

Specular mapping members
D3DTOP_PREMODULATE
Modulate this texture stage with the next texture stage.
D3DTOP_MODULATEALPHA_ADDCOLOR
Modulate the color of the second argument, using the alpha of the first argument; then add the result to argument one. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATECOLOR_ADDALPHA
Modulate the arguments; then add the alpha of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVALPHA_ADDCOLOR
Similar to D3DTOP_MODULATEALPHA_ADDCOLOR, but use the inverse of the alpha of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

D3DTOP_MODULATEINVCOLOR_ADDALPHA
Similar to D3DTOP_MODULATECOLOR_ADDALPHA, but use the inverse of the color of the first argument. This operation is supported only for color operations (D3DTSS_COLOROP).

Bump-mapping members
D3DTOP_BUMPENVMAP
Perform per-pixel bump mapping, using the environment map in the next texture stage, without luminance. This operation is supported only for color operations (D3DTSS_COLOROP).
D3DTOP_BUMPENVMAPLUMINANCE
Perform per-pixel bump mapping, using the environment map in the next texture stage, with luminance. This operation is supported only for color operations (D3DTSS_COLOROP).
D3DTOP_DOTPRODUCT3
Modulate the components of each argument as signed components, add their products; then replicate the sum to all color channels, including alpha. This operation is supported for color and alpha operations.

In DirectX 6.0 and 7.0 multitexture operations the above inputs are all shifted down by half (y = x - 0.5) before use to simulate signed data, and the scalar result is automatically clamped to positive values and replicated to all three output channels. Also, note that as a color operation this does not updated the alpha it just updates the rgb components.

However, in DirectX 8.0 shaders you can specify that the output be routed to the .rgb or the .a components or both (the default). You can also specify a separate scalar operation on the alpha channel.

Triadic texture blending members
D3DTOP_MULTIPLYADD
Performs a multiply-accumulate operation. It takes the last two arguments, multiplies them together, and adds them to the remaining input/source argument, and places that into the result.

SRGBA = Arg1 + Arg2 * Arg3

D3DTOP_LERP
Linearly interpolates between the 2nd and 3rd source arguments by a proportion specified in the 1st source argument.

SRGBA = (Arg1) * Arg2 + (1-Arg1) * Arg3.

Miscellaneous member
D3DTOP_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

The members of this type are used when setting color or alpha operations by using the D3DTSS_COLOROP or D3DTSS_ALPHAOP values with the IDirect3DDevice8::SetTextureStageState method.

In the above formulas, SRGBA is the RGBA color produced by a texture operation, and Arg1, Arg2, and Arg3 represent the complete RGBA color of the texture arguments. Individual components of an argument are shown with subscripts. For example, the alpha component for argument 1 would be shown as Arg1A.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DTEXTURESTAGESTATETYPE


D3DTEXTURESTAGESTATETYPE

Defines texture stage states.

typedef enum _D3DTEXTURESTAGESTATETYPE {
    D3DTSS_COLOROP               =  1,
    D3DTSS_COLORARG1             =  2,
    D3DTSS_COLORARG2             =  3,
    D3DTSS_ALPHAOP               =  4,
    D3DTSS_ALPHAARG1             =  5,
    D3DTSS_ALPHAARG2             =  6,
    D3DTSS_BUMPENVMAT00          =  7,
    D3DTSS_BUMPENVMAT01          =  8,
    D3DTSS_BUMPENVMAT10          =  9,
    D3DTSS_BUMPENVMAT11          = 10,
    D3DTSS_TEXCOORDINDEX         = 11,
    D3DTSS_ADDRESSU              = 13,
    D3DTSS_ADDRESSV              = 14,
    D3DTSS_BORDERCOLOR           = 15,
    D3DTSS_MAGFILTER             = 16,
    D3DTSS_MINFILTER             = 17,
    D3DTSS_MIPFILTER             = 18,
    D3DTSS_MIPMAPLODBIAS         = 19,
    D3DTSS_MAXMIPLEVEL           = 20,
    D3DTSS_MAXANISOTROPY         = 21,
    D3DTSS_BUMPENVLSCALE         = 22,
    D3DTSS_BUMPENVLOFFSET        = 23,
    D3DTSS_TEXTURETRANSFORMFLAGS = 24,
    D3DTSS_ADDRESSW              = 25,
    D3DTSS_COLORARG0             = 26,
    D3DTSS_ALPHAARG0             = 27,
    D3DTSS_RESULTARG             = 28,

    D3DTSS_FORCE_DWORD           = 0x7fffffff
} D3DTEXTURESTAGESTATETYPE;

Constants

D3DTSS_COLOROP
The texture-stage state is a texture color blending operation identified by one member of the D3DTEXTUREOP enumerated type. The default value for the first texture stage (stage 0) is D3DTOP_MODULATE, and for all other stages the default is D3DTOP_DISABLE.
D3DTSS_COLORARG1
The texture-stage state is the first color argument for the stage, identified by a texture argument flag. The default argument is D3DTA_TEXTURE.

Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0)

D3DTSS_COLORARG2
The texture-stage state is the second color argument for the stage, identified by a texture argument flag. The default argument is D3DTA_CURRENT.

Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0)

D3DTSS_ALPHAOP
The texture-stage state is a texture alpha blending operation identified by one member of the D3DTEXTUREOP enumerated type. The default value for the first texture stage (stage 0) is D3DTOP_SELECTARG1, and for all other stages the default is D3DTOP_DISABLE.
D3DTSS_ALPHAARG1
The texture-stage state is the first alpha argument for the stage, identified by a texture argument flag. The default argument is D3DTA_TEXTURE. If no texture is set for this stage, the default argument is D3DTA_DIFFUSE.

Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0)

D3DTSS_ALPHAARG2
The texture-stage state is the second alpha argument for the stage, identified by a texture argument flag. The default argument is D3DTA_CURRENT.

Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0)

D3DTSS_BUMPENVMAT00
The texture-stage state is a floating-point value for the [0][0] coefficient in a bump-mapping matrix. The default value is 0.0.
D3DTSS_BUMPENVMAT01
The texture-stage state is a floating-point value for the [0][1] coefficient in a bump-mapping matrix. The default value is 0.0.
D3DTSS_BUMPENVMAT10
The texture-stage state is a floating-point value for the [1][0] coefficient in a bump-mapping matrix. The default value is 0.0.
D3DTSS_BUMPENVMAT11
The texture-stage state is a floating-point value for the [1][1] coefficient in a bump-mapping matrix. The default value is 0.0.
D3DTSS_TEXCOORDINDEX
Index of the texture coordinate set to use with this texture stage. This flag is used only for fixed-function vertex processing. For example, it should not be used with vertex shaders. When rendering using vertex shaders, each stage's texture coordinate index must be set to its default value. The default index for each stage is equal to the stage index. Set this state to the zero-based index of the coordinate set for each vertex that this texture stage uses. You can specify up to eight sets of texture coordinates per vertex. If a vertex does not include a set of texture coordinates at the specified index, the system defaults to the u and v coordinates (0,0).

Additionally, applications can include, as logical Or with the index being set, one of the following flags to request that Microsoft® Direct3D® automatically generate the input texture coordinates for a texture transformation. With the exception of D3DTSS_TCI_PASSTHRU, which resolves to zero, if any of the following values is included with the index being set, the system uses the index strictly to determine texture wrapping mode. These flags are most useful when performing environment mapping.

D3DTSS_TCI_PASSTHRU
Use the specified texture coordinates contained within the vertex format. This value resolves to zero.
D3DTSS_TCI_CAMERASPACENORMAL
Use the vertex normal, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEPOSITION
Use the vertex position, transformed to camera space, as the input texture coordinates for this stage's texture transformation.
D3DTSS_TCI_CAMERASPACEREFLECTIONVECTOR
Use the reflection vector, transformed to camera space, as the input texture coordinate for this stage's texture transformation. The reflection vector is computed from the input vertex position and normal vector.
D3DTSS_ADDRESSU
Member of the D3DTEXTUREADDRESS enumerated type. Selects the texture-addressing method for the u coordinate. The default is D3DTADDRESS_WRAP.
D3DTSS_ADDRESSV
Member of the D3DTEXTUREADDRESS enumerated type. Selects the texture-addressing method for the v coordinate. The default value is D3DTADDRESS_WRAP.
D3DTSS_BORDERCOLOR
D3DCOLOR value that describes the color to use for rasterizing texture coordinates outside the [0.0,1.0] range. The default color is 0x00000000.
D3DTSS_MAGFILTER
Member of the D3DTEXTUREFILTERTYPE enumerated type that indicates the texture magnification filter to use when rendering the texture onto primitives. The default value is D3DTEXF_POINT.
D3DTSS_MINFILTER
Member of the D3DTEXTUREFILTERTYPE enumerated type that indicates the texture minification filter to use when rendering the texture onto primitives. The default value is D3DTEXF_POINT.
D3DTSS_MIPFILTER
Member of the D3DTEXTUREFILTERTYPE enumerated type that indicates the texture filter to use between mipmap levels. The default value is D3DTEXF_NONE.
D3DTSS_MIPMAPLODBIAS
Level of detail bias for mipmaps. Can be used to make textures appear more chunky or more blurred. The default value is zero. Values for this state are floating-point values. Because the IDirect3DDevice8::SetTextureStageState and IDirect3DDevice8::GetTextureStageState accept DWORD values, your application must cast a variable that contains the value, as shown in the following code example.
pd3dDevice->SetTextureStageState(D3DTSS_MIPMAPLODBIAS, *((LPDWORD) (&fBias)));

Each unit of bias (+/-1.0) alters the selection by exactly one mipmap level. A negative bias causes the use of larger mipmap levels; the result is a sharper but more aliased image. A positive bias causes the use of smaller mipmap levels; the result is a more blurred image. A positive bias also causes less texture data to be referenced, which can boost performance on some systems.

D3DTSS_MAXMIPLEVEL
Maximum mipmap level of detail that the application allows, expressed as an index from the top of the mipmap chain. Lower values identify higher levels of detail within the mipmap chain. Zero, which is the default, indicates that all levels can be used. Nonzero values indicate that the application cannot display mipmaps that have a higher level of detail than the mipmap at the specified index.
D3DTSS_MAXANISOTROPY
Maximum level of anisotropy. The default value is 1.
D3DTSS_BUMPENVLSCALE
Floating-point scale value for bump-map luminance. The default value is 0.0.
D3DTSS_BUMPENVLOFFSET
Floating-point offset value for bump-map luminance. The default value is 0.0.
D3DTSS_TEXTURETRANSFORMFLAGS
Member of the D3DTEXTURETRANSFORMFLAGS enumerated type that controls the transformation of texture coordinates for this texture stage. The default value is D3DTTFF_DISABLE.
D3DTSS_ADDRESSW
Member of the D3DTEXTUREADDRESS enumerated type. Selects the texture-addressing method for the w coordinate. The default value is D3DTADDRESS_WRAP.
D3DTSS_COLORARG0
Settings for the third color operand for triadic operations (multiply add and linear interpolation), identified by a texture argument flag. This setting is supported if the D3DTEXOPCAPS_MULTIPLYADD or D3DTEXOPCAPS_LERP device capabilities are present.

Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0)

D3DTSS_ALPHAARG0
Settings for the alpha channel selector operand for triadic operations (multiply add and linear interpolation), identified by a texture argument flag. This setting is supported if the D3DTEXOPCAPS_MULTIPLYADD or D3DTEXOPCAPS_LERP device capabilities are present.

Specify D3DTA_TEMP to select a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0)

D3DTSS_RESULTARG
Setting to select destination register for the result of this stage, identified by a texture argument flag. This value can be set to D3DTA_CURRENT (the default value) or to D3DTA_TEMP, which is a single temporary register that can be read into subsequent stages as an input argument. The final color passed to the fog blender and frame buffer is taken from D3DTA_CURRENT, so the last active texture stage state must be set to write to current.

This setting is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present.

D3DTSS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Members of this enumerated type are used with the IDirect3DDevice8::GetTextureStageState and IDirect3DDevice8::SetTextureStageState methods to retrieve and set texture state values.

The valid range of values for the D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, and D3DTSS_BUMPENVMAT11 bump-mapping matrix coefficients is greater than or equal to –8.0 and less than 8.0. This range, expressed in mathematical notation is [–8.0,8.0).

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetTextureStageState, IDirect3DDevice8::SetTextureStageState


D3DTEXTURETRANSFORMFLAGS

Defines texture-stage state values.

typedef enum _D3DTEXTURETRANSFORMFLAGS {
    D3DTTFF_DISABLE         =   0,
    D3DTTFF_COUNT1          =   1,
    D3DTTFF_COUNT2          =   2,
    D3DTTFF_COUNT3          =   3,
    D3DTTFF_COUNT4          =   4,
    D3DTTFF_PROJECTED       = 256,

    D3DTTFF_FORCE_DWORD     = 0x7fffffff
} D3DTEXTURETRANSFORMFLAGS;

Constants

D3DTTFF_DISABLE
Texture coordinates are passed directly to the rasterizer.
D3DTTFF_COUNT1
The rasterizer should expect 1-D texture coordinates.
D3DTTFF_COUNT2
The rasterizer should expect 2-D texture coordinates.
D3DTTFF_COUNT3
The rasterizer should expect 3-D texture coordinates.
D3DTTFF_COUNT4
The rasterizer should expect 4-D texture coordinates.
D3DTTFF_PROJECTED
The texture coordinates are all divided by the last element before being passed to the rasterizer. For example, if this flag is specified with the D3DTTFF_COUNT3 flag, the first and second texture coordinates is divided by the third coordinate before being passed to the rasterizer.
D3DTTFF_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

These flags are used to set the value of the D3DTSS_TEXTURETRANSFORMFLAGS texture stage state for the D3DTEXTURESTAGESTATETYPE enumerated type.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DTEXTURESTAGESTATETYPE


D3DTRANSFORMSTATETYPE

Defines constants that describe transformation state values.

typedef enum _D3DTRANSFORMSTATETYPE {
    D3DTS_VIEW            =  2,
    D3DTS_PROJECTION      =  3,
    D3DTS_TEXTURE0        = 16,
    D3DTS_TEXTURE1        = 17,
    D3DTS_TEXTURE2        = 18,
    D3DTS_TEXTURE3        = 19,
    D3DTS_TEXTURE4        = 20,
    D3DTS_TEXTURE5        = 21,
    D3DTS_TEXTURE6        = 22,
    D3DTS_TEXTURE7        = 23,

    D3DTS_FORCE_DWORD     = 0x7fffffff
} D3DTRANSFORMSTATETYPE;

Constants

D3DTS_VIEW
Identifies the transformation matrix being set as the view transformation matrix. The default value is NULL (the identity matrix).
D3DTS_PROJECTION
Identifies the transformation matrix being set as the projection transformation matrix. The default value is NULL (the identity matrix).
D3DTS_TEXTURE0 through D3DTS_TEXTURE7
Identifies the transformation matrix being set for the specified texture stage.
D3DTS_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Macros

D3DTS_WORLD
Equivalent to D3DTS_WORLDMATRIX(0).
D3DTS_WORLDMATRIX(index)
Identifies the transform matrix to set for the world matrix at index. Multiple world matrices are used only for Vertex Blending. Otherwise only D3DTS_WORLD is used.

Remarks

The transform states in the range 256 through 511 are reserved to store up to 256 world matrices that can be indexed using the D3DTS_WORLDMATRIX and D3DTS_WORLD macros.

Requirements

Header: Declared in D3d8types.h.

See Also

IDirect3DDevice8::GetTransform, IDirect3DDevice8::MultiplyTransform, IDirect3DDevice8::SetTransform, D3DTS_WORLD, D3DTS_WORLD n, D3DTS_WORLDMATRIX


D3DVERTEXBLENDFLAGS

Defines flags used to control the number or matrices that the system applies when performing multimatrix vertex blending.

typedef enum _D3DVERTEXBLENDFLAGS {
    D3DVBF_DISABLE  =   0,
    D3DVBF_1WEIGHTS =   1,
    D3DVBF_2WEIGHTS =   2,
    D3DVBF_3WEIGHTS =   3,
    D3DVBF_TWEENING = 255,
    D3DVBF_0WEIGHTS = 256
} D3DVERTEXBLENDFLAGS;

Constants

D3DVBF_DISABLE
Disable vertex blending; apply only the world matrix set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation state is 0.
D3DVBF_1WEIGHTS
Enable vertex blending between the two matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0 and 1.
D3DVBF_2WEIGHTS
Enable vertex blending between the three matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0, 1, and 2.
D3DVBF_3WEIGHTS
Enable vertex blending between the four matrices set by the D3DTS_WORLDMATRIX macro, where the index value for the transformation states are 0, 1, 2, and 3.
D3DVBF_TWEENING
Vertex blending is done by using the value assigned to D3DRS_TWEENFACTOR.
D3DVBF_0WEIGHTS
Use a single matrix with a weight of 1.0.

Remarks

Members of this type are used with the D3DRS_VERTEXBLEND render state.

Geometry blending (multimatrix vertex blending) requires that your application use a vertex format that has blending (beta) weights for each vertex.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRENDERSTATETYPE, D3DTS_WORLD, D3DTS_WORLDn, D3DTS_WORLDMATRIX,


D3DZBUFFERTYPE

Defines constants that describe depth-buffer formats.

typedef enum _D3DZBUFFERTYPE {
    D3DZB_FALSE                 = 0,
    D3DZB_TRUE                  = 1,
    D3DZB_USEW                  = 2,

    D3DZB_FORCE_DWORD           = 0x7fffffff
} D3DZBUFFERTYPE;

Constants

D3DZB_FALSE
Disable depth buffering.
D3DZB_TRUE
Enable z-buffering.
D3DZB_USEW
Enable w-buffering.
D3DZB_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

Members of this enumerated type are used with the D3DRS_ZENABLE render state.

Requirements

Header: Declared in D3d8types.h.

See Also

D3DRENDERSTATETYPE


Other Types

This section contains information about the following Microsoft® Direct3D® type that is neither a structure nor enumerated type.

  • D3DCOLOR


D3DCOLOR

Defines the fundamental Microsoft® Direct3D® color type.

typedef DWORD D3DCOLOR;

Requirements

Header: Declared in D3d8types.h.


Texture Argument Flags

Each texture stage for a device can have two texture arguments that affect the color or alpha channel of the texture.

Set and retrieve texture arguments by calling the IDirect3DDevice8::SetTextureStageState and IDirect3DDevice8::GetTextureStageState methods, and specifying the D3DTSS_COLORARG0, D3DTSS_COLORARG1, D3DTSS_COLORARG2, D3DTSS_ALPHAARG0, D3DTSS_ALPHAARG1, D3DTSS_ALPHAARG2, or D3DTSS_RESULTARG member of the D3DTEXTURESTAGESTATETYPE enumerated type.

The following flags, organized as arguments and modifiers, can be used with color and alpha arguments for a texture stage. You can combine an argument flag with a modifier, but two argument flags cannot be combined.

Argument flags
D3DTA_CURRENT
The texture argument is the result of the previous blending stage. In the first texture stage (stage 0), this argument is equivalent to D3DTA_DIFFUSE. If the previous blending stage uses a bump-map texture (the D3DTOP_BUMPENVMAP operation), the system chooses the texture from the stage before the bump-map texture. If s represents the current texture stage and s – 1 contains a bump-map texture, this argument becomes the result output by texture stage s – 2. Permissions are read/write.
D3DTA_DIFFUSE
The texture argument is the diffuse color interpolated from vertex components during Gouraud shading. If the vertex does not contain a diffuse color, the default color is 0xFFFFFFFF. Permissions are read-only.
D3DTA_SELECTMASK
Mask value for all arguments; not used when setting texture arguments.
D3DTA_SPECULAR
The texture argument is the specular color interpolated from vertex components during Gouraud shading. If the vertex does not contain a specular color, the default color is 0xFFFFFFFF. Permissions are read only.
D3DTA_TEMP
The texture argument is a temporary register color for read or write. D3DTA_TEMP is supported if the D3DPMISCCAPS_TSSARGTEMP device capability is present. The default value for the register is (0.0, 0.0, 0.0, 0.0). Permissions are read/write.
D3DTA_TEXTURE
The texture argument is the texture color for this texture stage. Permissions are read-only.
D3DTA_TFACTOR
The texture argument is the texture factor set in a previous call to the IDirect3DDevice8::SetRenderState with the D3DRS_TEXTUREFACTOR render-state value. Permissions are read-only.
Modifier flags
D3DTA_ALPHAREPLICATE
Replicate the alpha information to all color channels before the operation completes. This is a read modifier.
D3DTA_COMPLEMENT
Invert the argument so that, if the result of the argument were referred to by the variable x, the value would be 1.0 minus x. This is a read modifier.


Flexible Vertex Format Flags

The flexible vertex format (FVF) is used to describe the contents of vertices stored interleaved in a single data stream. A FVF code is generally used to specify data to be processed by fixed function vertex processing.

The following flags describe a vertex format. For information regarding vertex formats, see About Vertex Formats.

Flexible vertex format (FVF) flags
D3DFVF_DIFFUSE
Vertex format includes a diffuse color component.
D3DFVF_NORMAL
Vertex format includes a vertex normal vector. This flag cannot be used with the D3DFVF_XYZRHW flag.
D3DFVF_PSIZE
Vertex format specified in point size. This size is expressed in camera space units for vertices that are not transformed and lit, and in device-space units for transformed and lit vertices.
D3DFVF_SPECULAR
Vertex format includes a specular color component.
D3DFVF_XYZ
Vertex format includes the position of an untransformed vertex. This flag cannot be used with the D3DFVF_XYZRHW flag.
D3DFVF_XYZRHW
Vertex format includes the position of a transformed vertex. This flag cannot be used with the D3DFVF_XYZ or D3DFVF_NORMAL flags.
D3DFVF_XYZB1 through D3DFVF_XYZB5
Vertex format contains position data, and a corresponding number of weighting (beta) values to use for multimatrix vertex blending operations. Currently, Microsoft® Direct3D® can blend with up to three weighting values and four blending matrices. For more information on using blending matrices, see Indexed Vertex Blending.
Texture-related FVF flags
D3DFVF_TEX0 through D3DFVF_TEX8
Number of texture coordinate sets for this vertex. The actual values for these flags are not sequential.
D3DFVF_TEXTUREFORMAT1 through D3DFVF_TEXTUREFORMAT4
Number of values that define a texture coordinate set. The D3DFVF_TEXTUREFORMAT1 indicates one-dimensional texture coordinates, D3DFVF_TEXTUREFORMAT2 indicates two-dimensional texture coordinates, and so on. These flags are rarely used alone; they are used with the D3DFVF_TEXCOORDSIZEn macros.
Mask values
D3DFVF_POSITION_MASK
Mask for position bits.
D3DFVF_RESERVED0 and D3DFVF_RESERVED2
Mask values for reserved bits in the flexible vertex format. Do not use.
D3DFVF_TEXCOUNT_MASK
Mask value for texture flag bits.
Miscellaneous
D3DFVF_LASTBETA_UBYTE4
When using indexed vertex blending and a fixed function FVF vertex shader, you must specify this flag for the vertex shader.
D3DFVF_TEXCOUNT_SHIFT
The number of bits by which to shift an integer value that identifies the number of a texture coordinates for a vertex. This value might be used as follows:
    DWORD dwNumTextures = 1;  // Vertex has only one set of
// coordinates.

    // Shift the value for use when creating an FVF combination.
    dwFVF = dwNumTextures<<D3DFVF_TEXCOUNT_SHIFT;

    /*
     * Now, create an FVF combination using the shifted value.
     */

The following example shows some other common flag combinations.

    // Lightweight, untransformed vertex for lit, untextured,
    // Gouraud-shaded content.
    dwFVF = ( D3DFVF_XYZ | D3DFVF_DIFFUSE );

    // Untransformed vertex for unlit, untextured, Gouraud-shaded
    // content with diffuse material color specified per vertex.
    dwFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE );

    // Untransformed vertex for light-map-based lighting.
    dwFVF = ( D3DFVF_XYZ | D3DFVF_TEX2 );

    // Transformed vertex for light-map-based lighting
    // with shared rhw.
    dwFVF = ( D3DFVF_XYZRHW | D3DFVF_TEX2 );

    // Heavyweight vertex for unlit, colored content with two
    // sets of texture coordinates.
    dwFVF = ( D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_DIFFUSE |
              D3DFVF_SPECULAR | D3DFVF_TEX2 );

See Also

About Vertex Formats, Geometry Blending


Four-Character Codes (FOURCC)

Microsoft® Direct3D® and the Direct3DX utility library use a special set of codes that are four characters in length. These codes, called four-character codes or FOURCCs, are stored in file headers of files that contain multimedia data, such as bitmap images, sound, or video. FOURCCs describe the software technology that was used to produce multimedia data. By implication, they also describe the format of the data itself.

Direct3D applications use FOURCCs for image color and format conversion.

FOURCCs are registered with Microsoft by the vendors of the respective multimedia software technologies. Some common FOURCCs appear in the following list.

FOURCC | Company | Technology name
AUR2 | AuraVision Corporation | AuraVision Aura 2: YUV 422
AURA | AuraVision Corporation | AuraVision Aura 1: YUV 411
CHAM | Winnov, Inc. | MM_WINNOV_CAVIARA_CHAMPAGNE
CVID | Supermac | Cinepak by Supermac
CYUV | Creative Labs, Inc. | Creative Labs YUV
DXT1 | Microsoft Corporation | DirectX Texture Compression Format 1
DXT2 | Microsoft Corporation | DirectX Texture Compression Format 2
DXT3 | Microsoft Corporation | DirectX Texture Compression Format 3
DXT4 | Microsoft Corporation | DirectX Texture Compression Format 4
DXT5 | Microsoft Corporation | DirectX Texture Compression Format 5
FVF1 | Iterated Systems, Inc. | Fractal Video Frame
IF09 | Intel Corporation | Intel Intermediate YUV9
IV31 | Intel Corporation | Indeo 3.1
JPEG | Microsoft Corporation | Still Image JPEG DIB
MJPG | Microsoft Corporation | Motion JPEG DIB Format
MRLE | Microsoft Corporation | Run Length Encoding
MSVC | Microsoft Corporation | Video 1
PHMO | IBM Corporation | Photomotion
RT21 | Intel Corporation | Indeo 2.1
ULTI | IBM Corporation | Ultimotion
V422 | Vitec Multimedia | 24-bit YUV 4:2:2
V655 | Vitec Multimedia | 16-bit YUV 4:2:2
VDCT | Vitec Multimedia | Video Maker Pro DIB
VIDS | Vitec Multimedia | YUV 4:2:2 CCIR 601 for V422
YU92 | Intel Corporation | YUV
YUV8 | Winnov, Inc. | MM_WINNOV_CAVIAR_YUV8
YUV9 | Intel Corporation | YUV9
YUYV | Canopus, Co., Ltd. | BI_YUYV, Canopus
ZPEG | Metheus | Video Zipper


Return Values

Errors are represented by negative values and cannot be combined. The following lists the values that can be returned by Microsoft® Direct3D® methods. See the individual method descriptions for lists of the values that each can return. These lists are not necessarily comprehensive.

D3D_OK
No error occurred.
D3DERR_CONFLICTINGRENDERSTATE
The currently set render states cannot be used together.
D3DERR_CONFLICTINGTEXTUREFILTER
The current texture filters cannot be used together.
D3DERR_CONFLICTINGTEXTUREPALETTE
The current textures cannot be used simultaneously. This generally occurs when a multitexture device requires that all palletized textures simultaneously enabled also share the same palette.
D3DERR_DEVICELOST
The device is lost and cannot be restored at the current time, so rendering is not possible.
D3DERR_DEVICENOTRESET
The device cannot be reset.
D3DERR_DRIVERINTERNALERROR
Internal driver error.
D3DERR_INVALIDCALL
The method call is invalid. For example, a method's parameter may have an invalid value.
D3DERR_INVALIDDEVICE
The requested device type is not valid.
D3DERR_MOREDATA
There is more data available than the specified buffer size can hold.
D3DERR_NOTAVAILABLE
This device does not support the queried technique.
D3DERR_NOTFOUND
The requested item was not found.
D3DERR_OUTOFVIDEOMEMORY
Direct3D does not have enough display memory to perform the operation.
D3DERR_TOOMANYOPERATIONS
The application is requesting more texture-filtering operations than the device supports.
D3DERR_UNSUPPORTEDALPHAARG
The device does not support a specified texture-blending argument for the alpha channel.
D3DERR_UNSUPPORTEDALPHAOPERATION
The device does not support a specified texture-blending operation for the alpha channel.
D3DERR_UNSUPPORTEDCOLORARG
The device does not support a specified texture-blending argument for color values.
D3DERR_UNSUPPORTEDCOLOROPERATION
The device does not support a specified texture-blending operation for color values.
D3DERR_UNSUPPORTEDFACTORVALUE
The device does not support the specified texture factor value.
D3DERR_UNSUPPORTEDTEXTUREFILTER
The device does not support the specified texture filter.
D3DERR_WRONGTEXTUREFORMAT
The pixel format of the texture surface is not valid.
E_FAIL
An undetermined error occurred inside the Direct3D subsystem.
E_INVALIDARG
An invalid parameter was passed to the returning function
E_INVALIDCALL
The method call is invalid. For example, a method's parameter may have an invalid value.
E_OUTOFMEMORY
Direct3D could not allocate sufficient memory to complete the call.
S_OK
No error occurred.


Direct3DX C/C++ Reference

This section contains reference information for the API elements provided by the Direct3DX utility library. Reference material is divided into the following categories.

  • Interfaces
  • Functions
  • Macros
  • Structures
  • C++ Specific Features
  • Return Values


Interfaces

This section contains reference information for the COM interfaces provided by the Direct3DX utility library. The following interfaces are used with the Direct3DX utility library.

  • ID3DXBaseMesh
  • ID3DXBuffer
  • ID3DXEffect
  • ID3DXFont
  • ID3DXMatrixStack
  • ID3DXMesh
  • ID3DXPMesh
  • ID3DXRenderToSurface
  • ID3DXSkinMesh
  • ID3DXSPMesh
  • ID3DXSprite
  • ID3DXTechnique


ID3DXBaseMesh

Applications use the methods of the ID3DXBaseMesh interface to manipulate and query mesh and progressive mesh objects.

The methods of the ID3DXBaseMesh interface can be organized into the following groups.

Buffers | GetIndexBuffer
 | GetVertexBuffer
 | LockIndexBuffer
 | LockVertexBuffer
 | UnlockIndexBuffer
 | UnlockVertexBuffer
Copying | CloneMesh
 | CloneMeshFVF
Faces | GetNumFaces
Information | GetDevice
 | GetOptions
Rendering | DrawSubset
 | GetAttributeTable
Vertices | GetDeclaration
 | GetFVF
 | GetNumVertices

The ID3DXBaseMesh interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

A mesh is an object made up of a set of polygonal faces. A mesh defines a set of vertices and a set of faces (the faces are defined in terms of the vertices and normals of the mesh).

The LPD3DXBASEMESH type is defined as a pointer to the ID3DXBaseMesh interface.

typedef struct ID3DXBaseMesh *LPD3DXBASEMESH;

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMesh, ID3DXPMesh


ID3DXBaseMesh::CloneMesh

Clones a mesh using a declarator.

HRESULT CloneMesh(
  DWORD Options,
  CONST DWORD* pDeclaration,
  LPDIRECT3DDEVICE8 pD3DDevice,
  LPD3DXMESH* ppCloneMesh
);

Parameters

Options
[in] A combination of one or more flags specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers. These meshes will have separate index buffers into the shared vertex buffer.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pDeclaration
[in] Pointer to an array of DWORD values, representing the declarator to describe the vertex format of the vertices in the output mesh. This parameter must map directly to an FVF.
pD3DDevice
[in] Pointer to a IDirect3DDevice8 interface representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXBaseMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXBaseMesh::CloneMeshFVF

Clones a mesh using a flexible vertex format (FVF) code.

HRESULT CloneMeshFVF(
  DWORD Options,
  DWORD FVF,
  LPDIRECT3DDEVICE8 pD3DDevice,
  LPD3DXMESH* ppCloneMesh
);

Parameters

Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers. These meshes will have separate index buffers into the shared vertex buffer.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
FVF
[in] Combination of flexible vertex format flags that specifies the vertex format for the vertices in the output mesh.
pD3DDevice
[in] Pointer to a IDirect3DDevice8 interface representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the cloned mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Remarks

CloneMeshFVF can be used to convert a mesh from one FVF to another.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXBaseMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXBaseMesh::DrawSubset

Draws a subset of a mesh.

HRESULT DrawSubset(
  DWORD AttribId
);

Parameters

AttribId
[in] DWORD that specifies which subset of the mesh to draw. This value is used to differentiate faces in a mesh as belonging to one or more attribute groups.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXBaseMesh::GetAttributeTable


ID3DXBaseMesh::GetAttributeTable

Retrieves either an attribute table for a mesh, or the number of entries stored in an attribute table for a mesh.

HRESULT GetAttributeTable(
  D3DXATTRIBUTERANGE* pAttribTable,
  DWORD* pAttribTableSize
);

Parameters

pAttribTable
[in, out] Pointer to an array of D3DXATTRIBUTERANGE structures, representing the entries in the mesh's attribute table. Specify NULL to retrieve the value for pAttribTableSize.
pAttribTableSize
[in, out] Pointer to either the number of entries stored in pAttribTable or a value to be filled in with the number of entries stored in the attribute table for the mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Remarks

An attribute table is created by ID3DXMesh::Optimize and passing D3DXMESHOPT_ATTRSORT for the Flags parameter.

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier when drawing the frame.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXBaseMesh::GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

HRESULT GetDeclaration(
  DWORD Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[in, out] A returned array describing the vertex format of the vertices in the queried mesh. The upper limit of this declarator array is MAX_FVF_DECL_SIZE, limiting the declarator to a maximum of 15 DWORDs.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXBaseMesh::GetFVF


ID3DXBaseMesh::GetDevice

Retrieves the device associated with the mesh.

HRESULT GetDevice(
  LPDIRECT3DDEVICE8* ppDevice

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice8 interface, representing the Microsoft® Direct3D® device object associated with the mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Note Calling this method will increase the internal reference count on the IDirect3DDevice8 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice8 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXBaseMesh::GetFVF

Retrieves the flexible vertex format of the vertices in the mesh.

DWORD GetFVF();

Parameters

None.

Return Values

Returns a combination of flexible vertex format flags that describes the vertex format of the vertices in the queried mesh.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXBaseMesh::GetDeclaration


ID3DXBaseMesh::GetIndexBuffer

Retrieves the data in an index buffer.

HRESULT GetIndexBuffer(
  LPDIRECT3DINDEXBUFFER8* ppIB
);

Parameters

ppIB
[out, retval] Address of a pointer to an IDirect3DIndexBuffer8 interface, representing the index buffer object associated with the mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXBaseMesh::GetNumFaces

Retrieves the number of faces in the mesh.

DWORD GetNumFaces();

Parameters

None.

Return Values

Returns the number of faces in the mesh.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXBaseMesh::GetNumVertices

Retrieves the number of vertices in the mesh.

DWORD GetNumVertices();

Parameters

None.

Return Values

Returns the number of vertices in the mesh.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXBaseMesh::GetOptions

Retrieves the mesh options enabled for this mesh at creation time.

DWORD GetOptions();

Parameters

None.

Return Values

Returns a combination of one or more of the following flags, indicating the options enabled for this mesh at creation time.

D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXBaseMesh::GetVertexBuffer

Retrieves the data in a vertex buffer.

HRESULT GetVertexBuffer(
  LPDIRECT3DVERTEXBUFFER8* ppVB
);

Parameters

ppVB
[out, retval] Address of a pointer to an IDirect3DVertexBuffer8 interface, representing the vertex buffer object associated with the mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXBaseMesh::LockIndexBuffer

Locks an index buffer and obtains a pointer to the index buffer memory.

HRESULT LockIndexBuffer(
  DWORD Flags,
  BYTE** ppData
);

Parameters

Flags
[in] A combination of one or more locking flags, describing how the index buffer memory should be locked.
D3DLOCK_DISCARD
The application overwrites, with a write-only operation, every location within the region being locked. This enables resources stored in non-native formats to save the decompression step.
D3DLOCK_NOOVERWRITE
Indicates that no indices that were referred to in drawing calls since the start of the frame or the last lock without this flag will be modified during the lock. This can enable optimizations when the application is only appending data to the index buffer.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.
ppData
[out, retval] Address of a pointer to an array of BYTE values, filled with the returned index data.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Remarks

When working with index buffers, you are allowed to make multiple lock calls. However, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXBaseMesh::UnlockIndexBuffer


ID3DXBaseMesh::LockVertexBuffer

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

HRESULT LockVertexBuffer(
  DWORD Flags,
  BYTE** ppData
);

Parameters

Flags
[in] A combination of one or more locking flags, indicating how the vertex buffer memory should be locked.
D3DLOCK_DISCARD
The application overwrites, with a write-only operation, every location within the region being locked. This enables resources stored in non-native formats to save the decompression step.
D3DLOCK_NOOVERWRITE
Indicates that no vertices that were referred to in drawing calls since the start of the frame or the last lock without this flag will be modified during the lock. This can enable optimizations when the application is only appending data to the vertex buffer.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.
ppData
[out, retval] Address of a pointer to an array of BYTE values, filled with the returned vertex data.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXBaseMesh::UnlockVertexBuffer


ID3DXBaseMesh::UnlockIndexBuffer

Unlocks an index buffer.

HRESULT UnlockIndexBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXBaseMesh::LockIndexBuffer


ID3DXBaseMesh::UnlockVertexBuffer

Unlocks a vertex buffer.

HRESULT UnlockVertexBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXBaseMesh::LockVertexBuffer


ID3DXBuffer

The ID3DXBuffer interface is used as a data buffer, storing vertex, adjacency, and material information during mesh optimization and loading operations. The buffer object is used to return arbitrary length data.

Also, buffer objects are used to return object code and error messages in methods that assemble vertex and pixel shaders.

The ID3DXBuffer interface is obtained by calling the D3DXCreateBuffer function.

The methods of the ID3DXBuffer interface can be organized into the following group.

Information | GetBufferPointer
 | GetBufferSize

The ID3DXBuffer interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPD3DXBUFFER type is defined as a pointer to the ID3DXBuffer interface.

typedef struct ID3DXBuffer *LPD3DXBUFFER;

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXBuffer::GetBufferPointer

Retrieves a pointer to the data in the buffer.

LPVOID GetBufferPointer();

Parameters

None.

Return Values

Returns a pointer to the data in the buffer.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXBuffer::GetBufferSize

Retrieves the total size of the data in the buffer.

DWORD GetBufferSize();

Parameters

None.

Return Values

Returns the total size of the data in the buffer, in bytes.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXEffect

The ID3DXEffect interface is used to set and query effects, and to choose techniques. An effect object can contain multiple techniques to render the same effect.

  • The ID3DXEffect interface is obtained by calling D3DXCreateEffect

The methods of the ID3DXEffect interface can be organized into the following groups.

Copying | CloneEffect
Effects | SetDword
 | SetFloat
 | SetMatrix
 | SetPixelShader
 | SetTexture
 | SetVector
 | SetVertexShader
Effects Information | GetDword
 | GetFloat
 | GetMatrix
 | GetParameterDesc
 | GetPixelShader
 | GetTexture
 | GetVector
 | GetVertexShader
Information | GetDesc
 | GetDevice
Technique | GetTechnique
 | GetTechniqueDesc

The ID3DXEffect interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPD3DXEFFECT type is defined as a pointer to the ID3DXEffect interface.

typedef struct ID3DXEffect *LPD3DXEFFECT;

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateEffect, D3DXCompileEffect, D3DXCompileEffectFromFileA, D3DXCompileEffectFromFileW


ID3DXEffect::CloneEffect

Creates a clone of an effect.

STDMETHODIMP CloneEffect(
  LPDIRECT3DDEVICE8 pDevice,
  DWORD             Usage,
  LPD3DXEFFECT*     ppEffect
)

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device associated with the effect.
Usage
[in] Usage control for this effect. The following flag can be set.
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the effect will be rendered using software processing.
ppEffect
[out, retval] Pointer to a ID3DXEffect interface, containing the cloned effect.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.


ID3DXEffect::GetDesc

Retrieves a description of the effect.

HRESULT GetDesc(
  D3DXEFFECT_DESC* pDesc
)

Parameters

pDesc
[in, retval] Pointer to a D3DXEFFECT_DESC structure, containing the returned description.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC


ID3DXEffect::GetDevice

Retrieves the device associated with the effect.

HRESULT GetDevice(
  IDirect3DDevice8** ppDevice
)

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice8 interface, representing the device associated with the effect.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count for the IDirect3DDevice8 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice8 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.


ID3DXEffect::GetDword

Retrieves a DWORD value associated with an effect.

HRESULT GetDword(
  DWORD  Name,
  DWORD* pdw
)

Parameters

Name
[in] Name of the parameter to retrieve the DWORD value from. This parameter must be a four-character code. See Remarks.
pdw
[out, retval] Pointer to a DWORD, containing the returned DWORD.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXEffect::SetDword


ID3DXEffect::GetFloat

Retrieves a floating-point value associated with an effect.

HRESULT GetFloat(
  UINT   Name,
  FLOAT* pf
);

Parameters

Name
[in] Name of the parameter to retrieve the floating-point value from. This parameter must be a four-character code. See Remarks.
pf
[out, retval] Pointer to a FLOAT, containing the returned floating-point value.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC , ID3DXEffect::SetFloat


ID3DXEffect::GetMatrix

Retrieves a matrix associated with an effect.

HRESULT GetMatrix(
  UINT       Name,
  D3DMATRIX* pMat
);

Parameters

Name
[in] Name of the parameter to retrieve the matrix from. This parameter must be a four-character code. See Remarks.
pMatrix
[out, retval] Pointer to a D3DMATRIX structure, containing the returned matrix.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC , ID3DXEffect::SetMatrix


ID3DXEffect::GetParameterDesc

Retrieves information about an particular effect parameter.

HRESULT GetParameterDesc(
  UINT                Index,
  D3DXPARAMETER_DESC* pDesc
)

Parameters

Index
[in] Index of the parameter to retrieve information about.
pDesc
[out, retval] Pointer to a D3DXPARAMETER_DESC structure, specifying information about the parameter.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.


ID3DXEffect::GetPixelShader

Retrieves a pixel shader associated with an effect.

HRESULT GetPixelShader(
  DWORD  Name,
  DWORD* pHandle
)

Parameters

Name
[in] Name of the parameter to retrieve the pixel shader from. This parameter must be a four-character code. See Remarks.
pHandle
[out, retval] Pointer to a DWORD, representing the returned pixel shader.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXEffect::SetPixelShader


ID3DXEffect::GetTechnique

Retrieves a technique associated with an effect.

HRESULT GetTechnique(
  UINT            Name,
  ID3DXTechnique* ppTechnique
);

Parameters

Name
[in] Name of the technique to retrieve. This parameter must be a four-character code. See Remarks.
ppTechnique
[out, retval] Pointer to an ID3DXTechnique interface, containing the returned technique.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXTECHNIQUE_DESC , ID3DXEffect::GetTechniqueDesc


ID3DXEffect::GetTechniqueDesc

Retrieves a technique associated with an effect.

HRESULT GetTechniqueDesc(
  UINT                Index,
  D3DXTECHNIQUE_DESC* pDesc
)

Parameters

Index
[in] Name of the technique description to retrieve.
pDesc
[out, retval] Pointer to a D3DXTECHNIQUE_DESC, containing the technique description.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXTECHNIQUE_DESC , ID3DXEffect::GetTechnique


ID3DXEffect::GetTexture

Retrieves a texture associated with an effect.

HRESULT GetTexture(
  UINT                   Name,
  IDirect3DBaseTexture8* pTex
);

Parameters

Name
[in] Name of the parameter to retrieve the texture from. This parameter must be a four-character code. See Remarks.
pTex
[out, retval] Pointer to an IDirect3DBaseTexture8 interface, containing the returned texture.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Note Calling this method will increase the internal reference count on the IDirect3DBaseTexture8 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DTexture8 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXEffect::SetTexture


ID3DXEffect::GetVector

Retrieves a vector associated with an effect.

HRESULT GetVector(
  UINT         Name,
  D3DXVECTOR4* pVec
);

Parameters

Name
[in] Name of the parameter to retrieve the vector from. This parameter must be a four-character code. See Remarks.
pVec
[out, retval] Pointer to a D3DXVECTOR4 structure, containing the returned vector.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC , ID3DXEffect::GetVector


ID3DXEffect::GetVertexShader

Retrieves a vertex shader associated with an effect.

HRESULT GetVertexShader(
  DWORD  Name,
  DWORD* pHandle
)

Parameters

Name
[in] Name of the parameter to retrieve the vertex shader from. This parameter must be a four-character code. See Remarks.
pHandle
[out, retval] Pointer to a DWORD, containing the returned vertex shader.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC , ID3DXEffect::SetVertexShader


ID3DXEffect::SetDword

Sets a DWORD value for an effect.

HRESULT SetDword(
  UINT  Name,
  DWORD dw
);

Parameters

Name
[in] Identifies the name of the effect parameter to set. This parameter must be a four-character code. See Remarks.
dw
[in] Specifies the DWORD value to assign to Name.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC , ID3DXEffect::GetDword


ID3DXEffect::SetFloat

Sets a floating-point value for an effect.

HRESULT SetFloat(
  UINT  Name,
  FLOAT f
);

Parameters

Name
[in] Identifies the name of the effect parameter to set. This parameter must be a four-character code. See Remarks.
f
[in] Specifies the floating-point value to assign to Name.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC , ID3DXEffect::GetFloat


ID3DXEffect::SetMatrix

Sets a matrix for an effect.

HRESULT SetMatrix(
  UINT Name,
  D3DMATRIX* pMat
);

Parameters

Name
[in] Identifies the name of the effect parameter to set. This parameter must be a four-character code. See Remarks.
pMat
[in] Pointer to the D3DMATRIX structure to assign to Name.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC , ID3DXEffect::GetMatrix


ID3DXEffect::SetPixelShader

Sets a pixel shader for an effect.

HRESULT SetPixelShader(
  DWORD Name,
  DWORD Handle
)

Parameters

Name
[in] Identifies the name of the effect parameter to set. This parameter must be a four-character code. See Remarks.
Handle
[in] Specifies the pixel shader to assign to Name.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC , ID3DXEffect::GetPixelShader


ID3DXEffect::SetTexture

Sets a texture for an effect.

HRESULT SetTexture(
  UINT                  Name,
  IDirect3DBaseTexture8 pTexture
);

Parameters

Name
[in] Identifies the name of the effect parameter to set. This parameter must be a four-character code. See Remarks.
pTexture
[in] Pointer to an IDirect3DBaseTexture8 interface, specifying the texture to assign to Name.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Note Calling this method will increase the internal reference count on the IDirect3DBaseTexture8 interface. Be sure to call IUnknown::Release when you are done using this IDirect3BaseTexture8 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC , ID3DXEffect::GetTexture


ID3DXEffect::SetVector

Sets a vector for an effect.

HRESULT SetVector(
  UINT         Name,
  D3DXVECTOR4* pVec
);

Parameters

Name
[in] Identifies the name of the effect parameter to set. This parameter must be a four-character code. See Remarks.
pVector
[in] Pointer to a D3DXVECTOR4 structure, specifying the vector to assign to Name.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC , ID3DXEffect::SetVector


ID3DXEffect::SetVertexShader

Sets a vertex shader for an effect.

HRESULT SetVertexShader(
  DWORD Name,
  DWORD Handle
)

Parameters

Name
[in] Identifies the name of the effect parameter to set. This parameter must be a four-character code. See Remarks.
Handle
[in] Handle to the vertex shader to assign to Name.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXEFFECT_DESC , ID3DXEffect::SetVertexShader


ID3DXFont

The ID3DXFont interface is used to encapsulate the textures and resources needed to render a specific font on a specific device.

The ID3DXFont interface is obtained by calling the D3DXCreateFont or D3DXCreateFontIndirect functions.

The methods of the ID3DXFont interface can be organized into the following groups.

Drawing | Begin
 | DrawTextA
 | DrawTextW
 | End
Information | GetDevice
 | GetLogFont

The ID3DXFont interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPD3DXFONT type is defined as a pointer to the ID3DXFont interface.

typedef interface ID3DXFont *LPD3DXFONT;

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


ID3DXFont::Begin

Prepares a device for drawing text.

HRESULT Begin();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

This method is optional. If a DrawText method is called outside of a Begin and ID3DXFont::End pair, then Microsoft® Direct3D® will call Begin and End.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXFont::End


ID3DXFont::DrawTextA

Draws formatted ANSI text on a Microsoft® Direct3D® device.

INT DrawTextA(
  LPCSTR pString,
  INT Count,
  LPRECT pRect,
  DWORD Format,
  D3DCOLOR Color
);

Parameters

pString
[in] Pointer to the ANSI string to draw. If the Count parameter is –1, the string must be null-terminated.

If Format includes DT_MODIFYSTRING, the function could add up to four additional characters to this string. The buffer containing the string should be large enough to accommodate these extra characters.

Count
[in] Specifies the number of characters in the string. If Count is –1, then the pString parameter is assumed to be a pointer to a null-terminated string and DrawTextA computes the character count automatically.
pRect
[in] Pointer to a RECT structure that contains the rectangle, in logical coordinates, in which the text is to be formatted.
Format
[in] Specifies the method of formatting the text. It can be any combination of the following values.
DT_BOTTOM
Justifies the text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE.
DT_CALCRECT
Determines the width and height of the rectangle. If there are multiple lines of text, DrawTextA uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, DrawTextA modifies the right side of the rectangle so that it bounds the last character in the line. In either case, DrawTextA returns the height of the formatted text but does not draw the text.
DT_CENTER
Centers text horizontally in the rectangle.
DT_EDITCONTROL
Duplicates the text-displaying characteristics of a multiline edit control. Specifically, the average character width is calculated in the same manner as for an edit control, and the function does not display a partially visible last line.
DT_END_ELLIPSIS or DT_PATH_ELLIPSIS
Truncates the string without adding ellipses so that the result fits in the specified rectangle. The string is not modified unless the DT_MODIFYSTRING flag is specified.

Specify DT_END_ELLIPSIS to truncate characters at the end of the string, or DT_PATH_ELLIPSIS to truncate characters in the middle of the string. If the string contains backslash (\) characters, DT_PATH_ELLIPSIS preserves as much of the text as possible after the last backslash.

DT_EXPANDTABS
Expands tab characters. The default number of characters per tab is eight. The DT_WORD_ELLIPSIS, DT_PATH_ELLIPSIS, and DT_END_ELLIPSIS values cannot be used with the DT_EXPANDTABS value.
DT_EXTERNALLEADING
Includes the font external leading in line height. Normally, external leading is not included in the height of a line of text.
DT_HIDEPREFIX
Windows 2000: Ignores the ampersand (&) prefix character in the text. The letter that follows is not underlined, but other mnemonic-prefix characters are still processed.

Example:

input string: "A&bc&&d"

normal: "Abc&d"

HIDEPREFIX: "Abc&d"

Compare with DT_NOPREFIX and DT_PREFIXONLY.

DT_INTERNAL
Uses the system font to calculate text metrics.
DT_LEFT
Aligns text to the left.
DT_MODIFYSTRING
Modifies the string to match the displayed text. This flag has no effect unless the DT_END_ELLIPSIS or DT_PATH_ELLIPSIS flag is specified.
DT_NOCLIP
Draws without clipping. DrawTextA is somewhat faster when DT_NOCLIP is used.
DT_NOFULLWIDTHCHARBREAK
Windows 98, Windows 2000: Prevents a line break at a DBCS (double-wide character string), so that the line breaking rule is equivalent to SBCS strings. For example, this can be used in Korean windows for more readability of icon labels. This is effective only if DT_WORDBREAK is specified.
DT_NOPREFIX
Turns off processing of prefix characters. Normally, DrawTextA interprets the mnemonic-prefix character & as a directive to underscore the character that follows, and the mnemonic-prefix characters && as a directive to print a single &. By specifying DT_NOPREFIX, this processing is turned off. Compare with DT_HIDEPREFIX and DT_PREFIXONLY.
DT_PREFIXONLY
Windows 2000: Draws only an underline at the position of the character following the ampersand (&) prefix character. Does not draw any character in the string.

Example:

input string: "A&bc&&d"

normal: "Abc&d"

PREFIXONLY: " "

Compare with DT_NOPREFIX and DT_HIDEPREFIX.

DT_RIGHT
Aligns text to the right.
DT_RTLREADING
Displays text in right-to-left reading order for bi-directional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right.
DT_SINGLELINE
Displays text on a single line only. Carriage returns and line feeds do not break the line.
DT_TABSTOP
Sets tab stops. Bits 15–8 (high-order byte of the low-order word) of the Format parameter specify the number of characters for each tab. The default number of characters per tab is eight. The DT_CALCRECT, DT_EXTERNALLEADING, DT_INTERNAL, DT_NOCLIP, and DT_NOPREFIX values cannot be used with the DT_TABSTOP value.
DT_TOP
Top-justifies text (single line only).
DT_VCENTER
Centers text vertically (single line only).
DT_WORDBREAK
Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the pRect parameter. A carriage return/line feed sequence also breaks the line.
DT_WORD_ELLIPSIS
Truncates text that does not fit in the rectangle and adds ellipses.
Color
[in] D3DCOLOR type, specifying the color of the text.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA

Remarks

DrawText maps to either DrawTextA or ID3DXFont::DrawTextW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how DrawText is defined.

#ifndef DrawText
#ifdef UNICODE
#define DrawText DrawTextW
#else
#define DrawText DrawTextA
#endif
#endif

The DrawTextA method uses the device context's selected font, text color, and background color to draw the text. Unless the DT_NOCLIP format is used, DrawTextA clips the text so that it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified.

If the selected font is too large for the rectangle, the DrawTextA method does not attempt to substitute a smaller font.

The DrawTextA method supports only fonts whose escapement and orientation are both zero.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXFont::DrawTextW


ID3DXFont::DrawTextW

Draws formatted Unicode™ text on a Microsoft® Direct3D® device.

INT DrawTextW(
  LPCWSTR pString,
  INT Count,
  LPRECT pRect,
  DWORD Format,
  D3DCOLOR Color
);

Parameters

pString
[in] Pointer to the Unicode string to draw. If the Count parameter is –1, the string must be null-terminated.

If Format includes DT_MODIFYSTRING, the function could add up to four additional characters to this string. The buffer containing the string should be large enough to accommodate these extra characters.

Count
[in] Specifies the number of characters in the string. If Count is –1, then the pString parameter is assumed to be a pointer to a null-terminated string and DrawTextW computes the character count automatically.
pRect
[in] Pointer to a RECT structure that contains the rectangle, in logical coordinates, in which the text is to be formatted.
Format
[in] Specifies the method of formatting the text. It can be any combination of the following values.
DT_BOTTOM
Justifies the text to the bottom of the rectangle. This value must be combined with DT_SINGLELINE.
DT_CALCRECT
Determines the width and height of the rectangle. If there are multiple lines of text, DrawTextW uses the width of the rectangle pointed to by the pRect parameter and extends the base of the rectangle to bound the last line of text. If there is only one line of text, DrawTextW modifies the right side of the rectangle so that it bounds the last character in the line. In either case, DrawTextW returns the height of the formatted text but does not draw the text.
DT_CENTER
Centers text horizontally in the rectangle.
DT_EDITCONTROL
Duplicates the text-displaying characteristics of a multiline edit control. Specifically, the average character width is calculated in the same manner as for an edit control, and the function does not display a partially visible last line.
DT_END_ELLIPSIS or DT_PATH_ELLIPSIS
Truncates the string without adding ellipses so that the result fits in the specified rectangle. The string is not modified unless the DT_MODIFYSTRING flag is specified.

Specify DT_END_ELLIPSIS to truncate characters at the end of the string, or DT_PATH_ELLIPSIS to truncate characters in the middle of the string. If the string contains backslash (\) characters, DT_PATH_ELLIPSIS preserves as much of the text as possible after the last backslash.

DT_EXPANDTABS
Expands tab characters. The default number of characters per tab is eight. The DT_WORD_ELLIPSIS, DT_PATH_ELLIPSIS, and DT_END_ELLIPSIS values cannot be used with the DT_EXPANDTABS value.
DT_EXTERNALLEADING
Includes the font external leading in line height. Normally, external leading is not included in the height of a line of text.
DT_HIDEPREFIX
Windows 2000: Ignores the ampersand (&) prefix character in the text. The letter that follows is not underlined, but other mnemonic-prefix characters are still processed.

Example:

input string: "A&bc&&d"

normal: "Abc&d"

HIDEPREFIX: "Abc&d"

Compare with DT_NOPREFIX and DT_PREFIXONLY.

DT_INTERNAL
Uses the system font to calculate text metrics.
DT_LEFT
Aligns text to the left.
DT_MODIFYSTRING
Modifies the string to match the displayed text. This flag has no effect unless the DT_END_ELLIPSIS or DT_PATH_ELLIPSIS flag is specified.
DT_NOCLIP
Draws without clipping. DrawTextW is somewhat faster when DT_NOCLIP is used.
DT_NOFULLWIDTHCHARBREAK
Windows 98, Windows 2000: Prevents a line break at a DBCS (double-wide character string), so that the line breaking rule is equivalent to SBCS strings. For example, this can be used in Korean windows for more readability of icon labels. This is effective only if DT_WORDBREAK is specified.
DT_NOPREFIX
Turns off processing of prefix characters. Normally, DrawTextW interprets the mnemonic-prefix character & as a directive to underscore the character that follows, and the mnemonic-prefix characters && as a directive to print a single &. By specifying DT_NOPREFIX, this processing is turned off. Compare with DT_HIDEPREFIX and DT_PREFIXONLY.
DT_PREFIXONLY
Windows 2000: Draws only an underline at the position of the character following the ampersand (&) prefix character. Does not draw any character in the string.

Example:

input string: "A&bc&&d"

normal: "Abc&d"

PREFIXONLY: " "

Compare with DT_NOPREFIX and DT_HIDEPREFIX.

DT_RIGHT
Aligns text to the right.
DT_RTLREADING
Displays text in right-to-left reading order for bi-directional text when a Hebrew or Arabic font is selected. The default reading order for all text is left-to-right.
DT_SINGLELINE
Displays text on a single line only. Carriage returns and line feeds do not break the line.
DT_TABSTOP
Sets tab stops. Bits 15–8 (high-order byte of the low-order word) of the Format parameter specify the number of characters for each tab. The default number of characters per tab is eight. The DT_CALCRECT, DT_EXTERNALLEADING, DT_INTERNAL, DT_NOCLIP, and DT_NOPREFIX values cannot be used with the DT_TABSTOP value.
DT_TOP
Top-justifies text (single line only).
DT_VCENTER
Centers text vertically (single line only).
DT_WORDBREAK
Breaks words. Lines are automatically broken between words if a word would extend past the edge of the rectangle specified by the pRect parameter. A carriage return/line feed sequence also breaks the line.
DT_WORD_ELLIPSIS
Truncates text that does not fit in the rectangle and adds ellipses.
Color
[in] D3DCOLOR type, specifying the color of the text.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA

Remarks

DrawText maps to either DrawTextW or ID3DXFont::DrawTextA, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how DrawText is defined.

#ifndef DrawText
#ifdef UNICODE
#define DrawText DrawTextW
#else
#define DrawText DrawTextA
#endif
#endif

The DrawTextW method uses the device context's selected font, text color, and background color to draw the text. Unless the DT_NOCLIP format is used, DrawTextW clips the text so that it does not appear outside the specified rectangle. All formatting is assumed to have multiple lines unless the DT_SINGLELINE format is specified.

If the selected font is too large for the rectangle, the DrawTextW method does not attempt to substitute a smaller font.

The DrawTextW method supports only fonts whose escapement and orientation are both zero.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXFont::DrawTextA


ID3DXFont::End

Restores the device state to how it was when ID3DXFont::Begin was called.

HRESULT End();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXFont::Begin


ID3DXFont::GetDevice

Retrieves the Microsoft® Direct3D® device associated with the font object.

HRESULT GetDevice(
  LPDIRECT3DDEVICE8* ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice8 interface, representing the Direct3D device object associated with the font object.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL can be returned if the parameter is invalid.

Note Calling this method will increase the internal reference count on the IDirect3DDevice8 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice8 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


ID3DXFont::GetLogFont

Retrieves the attributes of the font.

HRESULT GetLogFont(
  LOGFONT* pLogFont
);

Parameters

pLogFont
[in, out] Pointer to the returned LOGFONT structure, describing the attributes of the font.

Return Values

If the method succeeds, the return value is D3D_OK.

D3DERR_INVALIDCALL can be returned if the parameter is invalid.

Remarks

For more information on the LOGFONT structure, see the Microsoft® Platform Software Development Kit (SDK).

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


ID3DXMatrixStack

Applications use the methods of the ID3DXMatrixStack interface to manipulate a matrix stack.

The ID3DXMatrixStack interface is obtained by calling the D3DXCreateMatrixStack function.

The methods of the ID3DXMatrixStack interface can be organized into the following groups.

Matrix Multiplication | MultMatrix
 | MultMatrixLocal
Miscellaneous | GetTop
 | LoadIdentity
 | LoadMatrix
 | Pop
 | Push
Rotation | RotateAxis
 | RotateAxisLocal
 | RotateYawPitchRoll
 | RotateYawPitchRollLocal
Scaling | Scale
 | ScaleLocal
Translation | Translate
 | TranslateLocal

The ID3DXMatrixStack interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


ID3DXMatrixStack::GetTop

Retrieves the current matrix at the top of the stack.

D3DXMATRIX* GetTop();

Parameters

None.

Return Values

This method returns a pointer to a D3DXMATRIX structure representing the current matrix.

Remarks

The D3DXMATRIX pointer returned by this method is not guaranteed to be valid after subsequent stack operations.

Note that this method does not remove the current matrix from the top of the stack; rather, it just returns the current matrix.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::Pop, ID3DXMatrixStack::Push


ID3DXMatrixStack::LoadIdentity

Loads identity in the current matrix.

HRESULT LoadIdentity();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The identity matrix is a matrix in which all coefficients are 0.0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1.0. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4×4 matrix.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::LoadMatrix


ID3DXMatrixStack::LoadMatrix

Loads the given matrix into the current matrix.

HRESULT LoadMatrix(
  CONST D3DXMATRIX* pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure loaded into the current matrix.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Note that this method does not add an item to the stack; rather, it replaces the current matrix with the supplied matrix.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::LoadIdentity


ID3DXMatrixStack::MultMatrix

Determines the product of the current matrix and the given matrix.

HRESULT MultMatrix(
  CONST D3DXMATRIX* pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method right-multiplies the given matrix to the current matrix (transformation is about the current world origin).

    m_stack[m_currentPos] = m_stack[m_currentPos] * *pMat;

Note that this method does not add an item to the stack; rather, it replaces the current matrix with the product of the current matrix and the given matrix.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::MultMatrixLocal


ID3DXMatrixStack::MultMatrixLocal

Determines the product of the given matrix and the current matrix.

HRESULT MultMatrixLocal(
  CONST D3DXMATRIX* pMat
);

Parameters

pMat
[in] Pointer to the D3DXMATRIX structure to be multiplied with the current matrix.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method left-multiplies the given matrix to the current matrix (transformation is about the local origin of the object).

    m_stack[m_currentPos] = *pMat * m_stack[m_currentPos];

Note that this method does not add an item to the stack; rather, it replaces the current matrix with the product of the given matrix and the current matrix.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::MultMatrix


ID3DXMatrixStack::Pop

Removes the current matrix from the top of the stack.

HRESULT Pop();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

Note that this method decrements the count of items on the stack by 1, effectively removing the current matrix from the top of the stack and promoting a matrix to the top of the stack. If the current count of items on the stack is 0, then this method returns without performing any action. If the current count of items on the stack is 1, then this method empties the stack.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::GetTop, ID3DXMatrixStack::Push


ID3DXMatrixStack::Push

Adds a matrix to the stack.

HRESULT Push();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method increments the count of items on the stack by 1, duplicating the current matrix. The stack will grow dynamically as more items are added.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::GetTop, ID3DXMatrixStack::Pop


ID3DXMatrixStack::RotateAxis

Determines the product of the current matrix and the computed rotation matrix.

HRESULT RotateAxis(
  CONST D3DXVECTOR3* pV,
  FLOAT Angle
);

Parameters

pV
[in] Pointer to a D3DXVECTOR3 structure that identifies the axis angle.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method right-multiplies the current matrix with the computed rotation matrix, counterclockwise about the given axis with the given angle (rotation is about the current world origin).

    D3DXMATRIX tmp;

    D3DXMatrixRotationAxis( &tmp, pV, angle );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRoll, ID3DXMatrixStack::RotateYawPitchRollLocal


ID3DXMatrixStack::RotateAxisLocal

Determines the product of the computed rotation matrix and the current matrix.

HRESULT RotateAxisLocal(
  CONST D3DXVECTOR3* pV,
  FLOAT Angle
);

Parameters

pV
[in] Pointer to a D3DXVECTOR3 structure that identifies the axis angle.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method left-multiplies the current matrix with the computed rotation matrix, counterclockwise about the given axis with the given angle (rotation is about the local origin of the object).

    D3DXMATRIX tmp;

    D3DXMatrixRotationAxis( &tmp, pV, angle );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateYawPitchRoll, ID3DXMatrixStack::RotateYawPitchRollLocal


ID3DXMatrixStack::RotateYawPitchRoll

Determines the product of the current matrix and the computed rotation matrix (composed of a given yaw, pitch, and roll).

HRESULT RotateYawPitchRoll(
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll
);

Parameters

Yaw
[in] The yaw around the y-axis in radians.
Pitch
[in] The pitch around the x-axis in radians.
Roll
[in] The roll around the z-axis in radians.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed rotation matrix. All angles are counterclockwise and rotation is about the current world origin.

    D3DXMATRIX tmp;

    D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRollLocal


ID3DXMatrixStack::RotateYawPitchRollLocal

Determines the product of the computed rotation matrix (composed of a given yaw, pitch, and roll) and the current matrix.

HRESULT RotateYawPitchRollLocal(
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll
);

Parameters

Yaw
[in] The yaw around the y-axis in radians.
Pitch
[in] The pitch around the x-axis in radians.
Roll
[in] The roll around the z-axis in radians.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed rotation matrix. All angles are counterclockwise and rotation is about the local origin of the object.

    D3DXMATRIX tmp;

    D3DXMatrixRotationYawPitchRoll( &tmp, yaw, pitch, roll );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::RotateAxis, ID3DXMatrixStack::RotateAxisLocal, ID3DXMatrixStack::RotateYawPitchRoll


ID3DXMatrixStack::Scale

Determines the product of the current matrix and the computed scale matrix composed from the given point (x, y, and z).

HRESULT Scale(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The scaling component in the x-direction.
y
[in] The scaling component in the y-direction.
z
[in] The scaling component in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed scale matrix (transformation is about the current world origin).

    D3DXMATRIX tmp;

    D3DXMatrixScaling( &tmp, x, y, z );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::ScaleLocal


ID3DXMatrixStack::ScaleLocal

Determines the product of the computed scale matrix composed from the given point (x, y, and z) and the current matrix.

HRESULT Scale(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The scaling component in the x-direction.
y
[in] The scaling component in the y-direction.
z
[in] The scaling component in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed scale matrix (transformation is about the local origin of the object).

    D3DXMATRIX tmp;

    D3DXMatrixScaling( &tmp, x, y, z );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::Scale


ID3DXMatrixStack::Translate

Determines the product of the current matrix and the computed translation matrix determined by the given factors (x, y, and z).

HRESULT Translate(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The translation factor in the x-direction.
y
[in] The translation factor in the y-direction.
z
[in] The translation factor in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method right-multiplies the current matrix with the computed translation matrix (transformation is about the current world origin).

    D3DXMATRIX tmp;

    D3DXMatrixTranslation( &tmp, x, y, z );
    m_stack[m_currentPos] = m_stack[m_currentPos] * tmp;

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::TranslateLocal


ID3DXMatrixStack::TranslateLocal

Determines the product of the computed translation matrix determined by the given factors (x, y, and z) and the current matrix.

HRESULT TranslateLocal(
  FLOAT x,
  FLOAT y,
  FLOAT z
);

Parameters

x
[in] The translation factor in the x-direction.
y
[in] The translation factor in the y-direction.
z
[in] The translation factor in the z-direction.

Return Values

If the method succeeds, the return value is D3D_OK.

Remarks

This method left-multiplies the current matrix with the computed translation matrix (transformation is about the local origin of the object).

    D3DXMATRIX tmp;

    D3DXMatrixTranslation( &tmp, x, y, z );
    m_stack[m_currentPos] = tmp * m_stack[m_currentPos];

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMatrixStack::Translate


ID3DXMesh

Applications use the methods of the ID3DXMesh interface to manipulate mesh objects.

The ID3DXMesh interface is obtained by calling either the D3DXCreateMesh or D3DXCreateMeshFVF functions.

The ID3DXMesh interface inherits the following ID3DXBaseMesh methods, which can be organized into the following groups.

Buffers | GetIndexBuffer
 | GetVertexBuffer
 | LockIndexBuffer
 | LockVertexBuffer
 | UnlockIndexBuffer
 | UnlockVertexBuffer
Copying | CloneMesh
 | CloneMeshFVF
Faces | GetNumFaces
Information | GetDevice
 | GetOptions
Rendering | DrawSubset
 | GetAttributeTable
Vertices | GetFVF
 | GetNumVertices

The methods of the ID3DXMesh interface can be organized into the following groups.

Locking | LockAttributeBuffer
 | UnlockAttributeBuffer
Miscellaneous | ConvertAdjacencyToPointReps
 | ConvertPointRepsToAdjacency
 | GenerateAdjacency
Optimization | Optimize
 | OptimizeInplace

The ID3DXMesh interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPD3DXMESH type is defined as a pointer to the ID3DXMesh interface.

typedef struct ID3DXMesh *LPD3DXMESH;

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

Mesh Functions


ID3DXMesh::ConvertAdjacencyToPointReps

Generates point representatives for the mesh.

HRESULT ConvertAdjacencyToPointReps(
  CONST DWORD* pAdjacency,
  DWORD* PointRep
);

Parameters

pAdjacency
[in] Pointer to the face adjacency array of the mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.
PointRep
[in, out] Pointer to a destination buffer for the point representatives of the mesh. The point representatives are stored as an array of indices with one element per vertex.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDMESH
E_OUTOFMEMORY

Remarks

Point representatives are a method of describing mesh adjacency by fusing two vertices with the same x-, y-, and z- coordinates but with different normal coordinates, u- and v-coordinates, color data, and so on. In a perfectly smooth mesh (a mesh without creases, boundaries, or holes), point representatives are redundant. In that case, it is possible to compute adjacent triangles by using a hash table to locate edges that share vertex indices. In the case of creases and texture boundaries, the point representatives are required to give a unique vertex index to use in a hash table for a group of co-located vertices that make up a vertex in the mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMesh::ConvertPointRepsToAdjacency


ID3DXMesh::ConvertPointRepsToAdjacency

Converts point representative data stored in Microsoft® DirectX® (.x) files to face adjacency information that is more flexible for optimization and simplification operations.

HRESULT ConvertPointRepsToAdjacency(
  CONST DWORD* pPRep,
  DWORD* pAdjacency
);

Parameters

pPRep
[in] Pointer to the point representatives for the mesh. The point representatives are stored as an array of indices with one element per vertex.
pAdjacency
[in, out] Pointer to a destination buffer for the face adjacency array of the mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

Point representatives are a method of describing mesh adjacency by fusing two vertices with the same x-, y-, and z- coordinates but with different normal coordinates, u- and v-coordinates, color data, an so on. In a perfectly smooth mesh (a mesh without creases, boundaries, or holes), point representatives are redundant. In that case, it is possible to compute adjacent triangles by using a hash table to locate edges that share vertex indices. In the case of creases and texture boundaries, the point representatives are required to give a unique vertex index to use in a hash table for a group of co-located vertices that make up a vertex in the mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMesh::ConvertAdjacencyToPointReps


ID3DXMesh::GenerateAdjacency

Uses an epsilon value to generate face adjacency information that is more flexible for optimization and simplification operations.

HRESULT GenerateAdjacency(
  FLOAT Epsilon,
  DWORD* pAdjacency
);

Parameters

Epsilon
[in] Separation distance under which vertices are welded. This parameter is currently ignored and uses an epsilon of 0.0.
pAdjacency
[in, out] Pointer to a destination buffer for the face adjacency array of the mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

This method only logically welds the vertices and no changes are made to the mesh. D3DXWeldVertices should be called after this method if modifying the mesh is desired.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXMesh::LockAttributeBuffer

Locks an attribute buffer and obtains a pointer to the attribute buffer memory.

HRESULT LockAttributeBuffer(
  DWORD Flags,
  DWORD** ppData
);

Parameters

Flags
[in] A combination of one or more locking flags, indicating how the attribute buffer memory should be locked.
D3DLOCK_DISCARD
The application overwrites, with a write-only operation, every location within the region being locked. This enables resources stored in non-native formats to save the decompression step.
D3DLOCK_NOOVERWRITE
Indicates that no information referred to in drawing calls since the start of the frame or the last lock without this flag will be modified during the lock. This can enable optimizations when the application is only appending data to the vertex buffer.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but it can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.
ppData
[out, retval] Address of a pointer to an array of DWORD values, filled with the returned attribute buffer data.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMesh::UnlockAttributeBuffer, D3DXATTRIBUTERANGE


ID3DXMesh::Optimize

Controls the reordering of mesh faces and vertices to optimize performance, generating an output mesh.

HRESULT Optimize(
  DWORD Flags,
  CONST DWORD* pAdjacencyIn,
  DWORD* pAdjacencyOut,
  DWORD* pFaceRemap,
  LPD3DXBUFFER* ppVertexRemap,
  LPD3DXMESH* ppOptMesh
);

Parameters

Flags
[in] A combination of one or more flags, specifying the type of optimization to perform. The following flags are defined.
D3DXMESHOPT_ATTRSORT
Reorders faces to optimize for fewer attribute bundle state changes and enhanced ID3DXBaseMesh::DrawSubset performance.
D3DXMESHOPT_COMPACT
Reorders faces to remove unused vertices and faces.
D3DXMESHOPT_IGNOREVERTS
Optimize the faces only; do not optimize the vertices.
D3DXMESHOPT_SHAREVB
Share vertex buffers.
D3DXMESHOPT_STRIPREORDER
Reorders faces to maximize length of adjacent triangles.
D3DXMESHOPT_VERTEXCACHE
Reorders faces to increase the cache hit rate of vertex caches.

Note that the D3DXMESHOPT_STRIPREORDER and D3DXMESHOPT_VERTEXCACHE optimization flags are mutually exclusive.

pAdjacencyIn
[in, out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh.
pAdjacencyOut
[in, out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.
pFaceRemap
[in, out] Pointer to a destination buffer containing the new index for each face.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface; containing the new index for each vertex.
ppOptMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the optimized mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

This method is very similar to the ID3DXBaseMesh::CloneMesh method, except that it can perform optimization while generating the new clone of the mesh.

The output mesh inherits all of the creation parameters of the input mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXMesh::OptimizeInplace

Controls the reordering of mesh faces and vertices to optimize performance.

HRESULT OptimizeInplace(
  DWORD Flags,
  CONST DWORD* pAdjacencyIn,
  DWORD* pAdjacencyOut,
  DWORD* pFaceRemap,
  LPD3DXBUFFER* ppVertexRemap
);

Parameters

Flags
[in] A combination of one or more flags, specifying the type of optimization to perform. The following flags are defined.
D3DXMESHOPT_ATTRSORT
Reorders faces to optimize for fewer attribute bundle state changes and enhanced ID3DXBaseMesh::DrawSubset performance.
D3DXMESHOPT_COMPACT
Reorders faces to remove unused vertices and faces.
D3DXMESHOPT_IGNOREVERTS
Optimize the faces only; do not optimize the vertices.
D3DXMESHOPT_STRIPREORDER
Reorders faces to maximize length of adjacent triangles.
D3DXMESHOPT_VERTEXCACHE
Reorders faces to increase the cache hit rate of vertex caches.

Note that the D3DXMESHOPT_STRIPREORDER and D3DXMESHOPT_VERTEXCACHE optimization flags are mutually exclusive.

pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh.
pAdjacencyOut
[out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface; containing the new index for each vertex.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_CANNOTATTRSORT
E_OUTOFMEMORY

Notes This method will fail if the mesh is sharing its vertex buffer with another mesh, unless the D3DXMESHOPT_IGNOREVERTS flag is set in the Flags parameter.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXMesh::UnlockAttributeBuffer

Unlocks an attribute buffer.

HRESULT UnlockAttributeBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXMesh::LockAttributeBuffer


ID3DXPMesh

Applications use the methods of the ID3DXPMesh interface to manipulate progressive mesh objects. A progressive mesh enables progressive refinement of the mesh object.

The ID3DXPMesh interface is obtained by calling the D3DXGeneratePMesh function.

The ID3DXPMesh interface inherits the following ID3DXBaseMesh methods, which can be organized into the following groups.

Buffers | GetIndexBuffer
 | GetVertexBuffer
 | LockIndexBuffer
 | LockVertexBuffer
 | UnlockIndexBuffer
 | UnlockVertexBuffer
Copying | CloneMesh
 | CloneMeshFVF
Faces | GetNumFaces
Information | GetDevice
 | GetOptions
Rendering | DrawSubset
 | GetAttributeTable
Vertices | GetFVF
 | GetNumVertices

The methods of the ID3DXPMesh interface can be organized into the following groups.

Copying | ClonePMesh
 | ClonePMeshFVF
Faces | GetMaxFaces
 | GetMinFaces
 | SetNumFaces
Miscellaneous | GetAdjacency
 | Save
Optimization | Optimize
Vertices | GetMaxVertices
 | GetMinVertices
 | SetNumVertices

The ID3DXPMesh interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPD3DXPMESH type is defined as a pointer to the ID3DXPMesh interface.

typedef struct ID3DXPMesh *LPD3DXPMESH;

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

Mesh Functions


ID3DXPMesh::ClonePMesh

Clones a progressive mesh using a declarator.

HRESULT ClonePMesh(
  DWORD Options,
  CONST DWORD* pDeclaration,
  LPDIRECT3DDEVICE8 pDevice,
  LPD3DXPMESH* ppCloneMesh
);

Parameters

Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers. These meshes will have separate index buffers into the shared vertex buffer.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pDeclaration
[in] Pointer to an array of DWORD values, representing the declarator that describes the vertex format of the vertices in the output mesh. This parameter must map directly to an FVF.
pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXBaseMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXPMesh::ClonePMeshFVF

Clones a progressive mesh using a flexible vertex format (FVF) code.

HRESULT ClonePMeshFVF(
  DWORD Options,
  DWORD FVF,
  LPDIRECT3DDEVICE8 pDevice,
  LPD3DXPMESH* ppCloneMesh
);

Parameters

Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers. These meshes will have separate index buffers into the shared vertex buffer.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
FVF
[in] Combination of flexible vertex format flags that specifies the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device object associated with the mesh.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

ClonePMeshFVF can be used to convert a progressive mesh from one FVF to another.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXBaseMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXPMesh::GetAdjacency

Returns the face adjacency array of the mesh.

HRESULT GetAdjacency(
  DWORD* pAdjacency
);

Parameters

pAdjacency
[out] Pointer to the returned face adjacency array of the mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh. The size of the adjacency array is the maximum number of faces multiplied by 3.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXPMesh::GetMaxFaces


ID3DXPMesh::GetMaxFaces

Retrieves the maximum number of faces that the progressive mesh supports.

DWORD GetMaxFaces();

Parameters

None.

Return Values

Returns the maximum number of faces supported by the progressive mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXPMesh::GetMaxVertices

Retrieves the maximum number of vertices that the progressive mesh supports.

DWORD GetMaxVertices();

Parameters

None.

Return Values

Returns the maximum number of vertices supported by the progressive mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXPMesh::GetMinFaces

Retrieves the minimum number of faces that the progressive mesh supports.

DWORD GetMinFaces();

Parameters

None.

Return Values

Returns the minimum number of faces supported by the progressive mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXPMesh::GetMinVertices

Retrieves the minimum number of vertices that the progressive mesh supports.

DWORD GetMinVertices();

Parameters

None.

Return Values

Returns the minimum number of vertices supported by the progressive mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXPMesh::Optimize

Controls the reordering of mesh faces and vertices to optimize performance, generating an output mesh.

HRESULT Optimize(
  DWORD Flags,
  DWORD* pAdjacencyOut,
  DWORD* pFaceRemap,
  LPD3DXBUFFER* ppVertexRemap,
  LPD3DXMESH* ppOptMesh
);

Parameters

Flags
[in] A combination of one or more flags, specifying the type of optimization to perform. The following flags are defined.
D3DXMESHOPT_ATTRSORT
Reorders faces to optimize for fewer attribute bundle state changes and enhanced ID3DXBaseMesh::DrawSubset performance.
D3DXMESHOPT_COMPACT
Reorders faces to remove unused vertices and faces.
D3DXMESHOPT_IGNOREVERTS
Optimize the faces only; do not optimize the vertices.
D3DXMESHOPT_SHAREVB
Share vertex buffers.
D3DXMESHOPT_STRIPREORDER
Reorders faces to maximize length of adjacent triangles.
D3DXMESHOPT_VERTEXCACHE
Reorders faces to increase the cache hit rate of vertex caches.

Note that the D3DXMESHOPT_STRIPREORDER and D3DXMESHOPT_VERTEXCACHE optimization flags are mutually exclusive.

pAdjacencyOut
[out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh. The size of this array is the maximum number of faces multiplied by 3.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface; containing the new index for each vertex.
ppOptMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the optimized mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXPMesh::Save

Saves the progressive mesh to the specified stream object.

HRESULT Save(
  IStream* pStream,
  LPD3DXMATERIAL pMaterials,
  DWORD NumMaterials
);

Parameters

pStream
[in] Pointer to an IStream interface, representing the stream object to which the file data is written.
pMaterials
[in] Pointer to an array of D3DXMATERIAL structures, containing material information to be saved in the stream object.
NumMaterials
[in] Number of D3DXMATERIAL structures in the pMaterials array

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

For more information on the IStream interface, see the Microsoft® Platform Software Development Kit (SDK).

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXPMesh::SetNumFaces

Sets the current level of detail to as close to the specified number of faces as possible.

HRESULT SetNumFaces(
  DWORD Faces
);

Parameters

Faces
[in] Target number of faces. This value specifies the desired change in the level of detail (LOD).

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the number of faces is greater than the maximum number of faces, it is capped at the maximum number of faces returned by ID3DXPMesh::GetMaxFaces. If the number of faces is less than the minimum number of faces, it is capped at the minimum number of faces returned by ID3DXPMesh::GetMinFaces.

The number of faces after this call may be off by one because some edge collapse may introduce or remove one face or two. For example, if you try setting the number of faces to an intermediate value such as 5, when 4 and 6 are possible, 4 will always be the result.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXPMesh::SetNumVertices

Sets the current level of detail to as close to the specified number of vertices as possible.

HRESULT SetNumVertices(
  DWORD Vertices
);

Parameters

Vertices
[in] Target number of vertices. This value specifies the desired change in the level of detail (LOD).

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If the number of vertices is greater than the maximum number of vertices, it is capped at the maximum number of vertices returned by ID3DXPMesh::GetMaxVertices. If the number of vertices is less than the minimum number of vertices, it is capped at the minimum number of vertices returned by ID3DXPMesh::GetMinVertices.

The number of vertices after this call may be off by one because some edge collapse may introduce or remove one face or two. For example, if you try setting the number of faces to an intermediate value such as 5, when 4 and 6 are possible, 4 will always be the result.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXRenderToSurface

The ID3DXRenderToSurface interface is used to generalize the process of rendering to surfaces. If the surface is not a render target, a compatible render target is used, and the result is copied to the surface at the end of the scene.

The ID3DXRenderToSurface interface is obtained by calling the D3DXCreateRenderToSurface function.

The methods of the ID3DXRenderToSurface interface can be organized into the following groups.

Information | GetDesc
 | GetDevice
Rendering | BeginScene
 | EndScene

The ID3DXRenderToSurface interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPD3DXRENDERTOSURFACE type is defined as a pointer to the ID3DXRenderToSurface interface.

typedef interface ID3DXRenderToSurface* LPD3DXRENDERTOSURFACE;

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


ID3DXRenderToSurface::BeginScene

Begins a scene.

HRESULT BeginScene(
  LPDIRECT3DSURFACE8 pSurface,
  CONST D3DVIEWPORT8* pViewport
);

Parameters

pSurface
[in] Pointer to an IDirect3DSurface8 interface, representing the render surface.
pViewport
[in] Pointer to a D3DVIEWPORT8 structure, describing the viewport for the scene.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXRenderToSurface::EndScene


ID3DXRenderToSurface::EndScene

Ends a scene.

HRESULT EndScene();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXRenderToSurface::BeginScene


ID3DXRenderToSurface::GetDesc

Retrieves the parameters of the render surface.

HRESULT GetDesc(
  D3DXRTE_DESC* pParameters
);

Parameters

pParameters

[out] Pointer to a D3DXRTS_DESC structure, describing the parameters of the render surface.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


ID3DXRenderToSurface::GetDevice

Retrieves the Microsoft® Direct3D® device associated with the render surface.

HRESULT GetDevice(
  LPDIRECT3DDEVICE8* ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice8 interface, representing the Direct3D device object associated with the render surface.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DDevice8 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice8 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh

Applications use the methods of the ID3DXSkinMesh interface to manipulate skin mesh objects.

The ID3DXSkinMesh interface is obtained by calling one of the following functions.

  • D3DXCreateSkinMesh
  • D3DXCreateSkinMeshFromMesh
  • D3DXCreateSkinMeshFVF

To load a skin mesh from a Microsoft® DirectX® (.x) file data object, use the D3DXLoadSkinMeshFromXof function.

Skinning is the technique of having different vertices of a mesh be transformed by multiple transform matrices and the results of the vertex being transformed with each individual matrix blended together to obtain the final transformed vertex.

This process is commonly called skinning because it is used to deform a mesh defining a skin of some character based on the animation of a skeleton of bones. In the simplest case of rigid animation, different parts of the character mesh are associated with a unique skeleton bone and vertices are transformed using the transform of that bone.

When discussing skinning, it is useful to define the following terms.

  • Skin. The triangle mesh being rendered using deformations. Typically this is the model of the character in some convenient pose.
  • Bone. A transform matrix that affects one or more vertices of the skin.
  • Skeleton. A hierarchy of all the bones that affect a skin mesh.
  • Pose. A set of bone transforms that completely defines the transforms for all the bones that affect a given skin mesh.
  • Initial Pose. This is the pose in which the mesh was associated with the skeleton. When the skeleton is in this pose, the deformed mesh is identical to the original undeformed mesh.
  • Bone Space Transform. This transform transforms the mesh into the local space of a particular bone.
  • Bone Weight. The amount of influence a bone has on a given vertex. A weight of 1 means that the vertex is only affected by that bone and 0 means it is unaffected by the bone. The sum of weights of all the bones that affect a vertex should add up to 1 for all vertices.

A skinned character is defined by a set of meshes and a set of bones that affect the vertices of the meshes. The bones are represented as a transform hierarchy. For each mesh, there is a matrix for every bone that affects it that transforms the mesh into the local coordinate space of the bone. This matrix is the bone space transform of the bone for the mesh. This is defined at the time the skeleton is associated with the mesh in the authoring process.

The methods of the ID3DXSkinMesh interface can be organized into the following groups.

Buffers | GetIndexBuffer
 | GetVertexBuffer
Conversion | ConvertToBlendedMesh
 | ConvertToIndexedBlendedMesh
Information | GetBoneInfluence
 | GetDevice
 | GetMaxFaceInfluences
 | GetMaxVertexInfluences
 | GetNumBoneInfluences
 | GetNumBones
 | GetOptions
Faces | GetNumFaces
Locking | LockAttributeBuffer
 | LockIndexBuffer
 | LockVertexBuffer
 | UnlockAttributeBuffer
 | UnlockIndexBuffer
 | UnlockVertexBuffer
Miscellaneous | GenerateSkinnedMesh
 | GetOriginalMesh
 | SetBoneInfluence
 | UpdateSkinnedMesh
Vertices | GetDeclaration
 | GetFVF
 | GetNumVertices

The ID3DXSkinMesh interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPD3DXSKINMESH type is defined as a pointer to the ID3DXSkinMesh interface.

typedef struct ID3DXSkinMesh* LPD3DXSKINMESH;

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::ConvertToBlendedMesh

Returns a blended mesh.

HRESULT ConvertToBlendedMesh(
  DWORD Options,
  CONST LPDWORD pAdjacencyIn,
  LPDWORD pAdjacencyOut,
  DWORD* pNumBoneCombinations,
  LPD3DXBUFFER* ppBoneCombinationTable,
  LPD3DXMESH* ppMesh
);

Parameters

Options
[in] A combination of one or more flags specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_USEHWONLY
Use hardware processing only. This flag should only be specified for a hardware processing device. On a mixed mode device this flag will cause the system to either use hardware only, or if the hardware is not capable it will approximate using the software capabilities.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh.
pAdjacencyOut
[in, out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.
pNumBoneCombinations
[in, out] Number of entries.
ppBoneCombinationTable
[in, out] Address of a pointer to an array of D3DXBONECOMBINATION structures. The count of structures is pNumBoneCombinations. Each bone combination table defines the four bones that you can draw at a time.
ppMesh
[in, out] Address of a pointer to an ID3DXMesh interface, representing the blended mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be E_OUTOFMEMORY.

Remarks

This method takes a skin mesh and converts it into a blended mesh ( a mesh with bone influences) using the Microsoft® Direct3D® vertex blending functionality available in Microsoft® DirectX® 7.x. For more information, see Geometry Blending.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::ConvertToIndexedBlendedMesh

Returns an indexed blended mesh.

HRESULT ConvertToIndexedBlendedMesh(
  DWORD Options,
  CONST LPDWORD pAdjacencyIn,
  DWORD PaletteSize,
  LPDWORD pAdjacencyOut,
  DWORD* pNumBoneCombinations
  LPD3DXBUFFER* ppBoneCombinationTable
  LPD3DXMESH* ppMesh,
);

Parameters

Options
[in] A combination of one or more flags specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pAdjacencyIn
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh.
PaletteSize
[in] The palette size.
pAdjacencyOut
[in, out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.
pNumBoneCombinations
[in, out] Number of entries.
ppBoneCombinationTable
[in, out] Address of a pointer to an array of D3DXBONECOMBINATION structures. The count of structures is pNumBoneCombinations. Each bone combination table defines the four bones that you can draw at a time.
ppMesh
[in, out] Address of a pointer to an ID3DXMesh interface, representing the indexed blended mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method takes a skin mesh and converts it into an indexed blended mesh using the Microsoft® Direct3D® indexed vertex blending functionality available in Microsoft DirectX® 8.0. Indexed vertex blending uses indices to index into a matrix palette. For more information, see Geometry Blending. Converting a skin mesh into an indexed blended mesh enables you to render the mesh in a single drawing call.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::GenerateSkinnedMesh

Generates a skinned mesh.

HRESULT GenerateSkinnedMesh(
  DWORD Options,
  FLOAT minWeight,
  CONST LPDWORD pAdjacencyIn,
  LPDWORD pAdjacencyOut,
  LPD3DXMESH* ppMesh
);

Parameters

Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
minWeight
[in] Sets the minimum weight clamping value.
pAdjacencyIn
[in, out] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh.
pAdjacencyOut
[in, out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.
ppMesh
[out, retval] Pointer to an ID3DXMesh interface, representing the generated skinned mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The mesh generated by this method is the one that should be supplied to ID3DXSkinMesh::UpdateSkinnedMesh each time the skeleton transforms are modified.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::UpdateSkinnedMesh


ID3DXSkinMesh::GetBoneInfluence

Returns a list of values indicating how a bone affects the skin mesh.

HRESULT GetBoneInfluence(
  DWORD Bone,
  DWORD* pVertices,
  FLOAT* pWeights
);

Parameters

Bone
[in] Bone to query.
pVertices
[in, out] Reference to the list of vertices affected by the bone.
pWeights
[in, out] List of weights associated with each vertex in the list of vertices affected by the bone.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::GetBoneInfluence

Built on Wednesday, October 04, 2000


ID3DXSkinMesh::GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

HRESULT GetDeclaration(
  DWORD Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[out] A returned array describing the vertex format of the vertices in the queried mesh. The upper limit of this declarator array is MAX_FVF_DECL_SIZE, limiting the declarator to a maximum of 15 DWORDs.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::GetFVF


ID3DXSkinMesh::GetDevice

Retrieves the device associated with the skin mesh.

HRESULT GetDevice(
  LPDIRECT3DDEVICE8* ppDevice

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice8 interface, representing the Microsoft® Direct3D® device object associated with the skin mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in d3dx8mesh.h.
Import Library: Use d3dx8.lib.


ID3DXSkinMesh::GetFVF

Retrieves the flexible vertex format of the vertices in the skin mesh.

DWORD GetFVF();

Parameters

None.

Return Values

Returns a combination of flexible vertex format flags that describe the vertex format of the vertices in the skin mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::GetDeclaration


ID3DXSkinMesh::GetIndexBuffer

Retrieves the data in an index buffer.

HRESULT GetIndexBuffer(
  LPDIRECT3DINDEXBUFFER8* ppIB
);

Parameters

ppIB
[out, retval] Address of a pointer to an IDirect3DIndexBuffer8 interface, representing the index buffer object associated with the skin mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::GetMaxFaceInfluences

Return the maximum number of face influences.

HRESULT GetMaxFaceInfluences(
  DWORD* maxFaceInfluences
);

Parameters

maxFaceInfluences
[out, retval] Maximum number of influences affecting any single face in the skin mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Each face can be affected by n bones. The following diagram shows a face affected by 6 bones (the union of bones effecting each vertex of the face).

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::GetMaxVertexInfluences

Returns the maximum number of vertex influences.

HRESULT GetMaxVertexInfluences(
  DWORD* maxVertexInfluences
);

Parameters

maxVertexInfluences
[out, retval] Maximum number of influences affecting any single vertex in the skin mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

Each vertex can be affected by n bones. If this method returns a value of 17, up to 17 bones affect a single vertex of the skin mesh. So, there are 17 separate weights on that vertex which add up to 1.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::GetNumBoneInfluences

Returns the number of influences (weights) on a given bone.

DWORD GetNumBoneInfluences(
  DWORD Bone
);

Parameters

Bone
[in] The bone to query.

Return Values

Returns the number of weights on the given bone. If Bone is an invalid bone number, GetNumBoneInfluences returns 0.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::GetNumBones

Returns the number of bones in the skin mesh.

DWORD GetNumBones();

Parameters

None.

Return Values

Number of bones in the skin mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::GetNumFaces

Retrieves the number of faces in the skin mesh.

DWORD GetNumFaces();

Parameters

None.

Return Values

Returns the number of faces in the skin mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::GetNumVertices

Retrieves the number of vertices in the skin mesh.

DWORD GetNumVertices();

Parameters

None.

Return Values

Returns the number of vertices in the skin mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::GetOptions

Retrieves the mesh options enabled for this skin mesh at creation time.

DWORD GetOptions();

Parameters

None.

Return Values

Returns a combination of one or more of the following flags, indicating the options enabled for this mesh at creation time.

D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_USEHWONLY
Use hardware processing only. This flag should only be specified for a hardware processing device. On a mixed mode device this flag will cause the system to either use hardware only, or if the hardware is not capable it will approximate using the software capabilities.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::GetOriginalMesh

Returns the skin mesh in its original (default) pose.

HRESULT GetOriginalMesh(
  LPD3DXMESH* ppMesh
);

Parameters

ppMesh
[out, retval] Pointer to an ID3DXMesh interface that will contain the original mesh after the method returns. Note that when this method returns, the reference count for the returned mesh is incremented.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the ID3DXMesh interface. Be sure to call IUnknown::Release when you are done using this ID3DXMesh interface or you will have a memory leak.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::GetVertexBuffer

Retrieves the data in a vertex buffer.

HRESULT GetVertexBuffer(
  LPDIRECT3DVERTEXBUFFER8* ppVB
);

Parameters

ppVB
[out, retval] Address of a pointer to an IDirect3DVertexBuffer8 interface, representing the vertex buffer object associated with the skin mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::LockAttributeBuffer

Locks an attribute buffer and obtains a pointer to the attribute buffer memory.

HRESULT LockAttributeBuffer(
  DWORD Flags,
  DWORD** ppData
);

Parameters

Flags
[in] A combination of one or more locking flags, indicating how the attribute buffer memory should be locked.
D3DLOCK_DISCARD
The application overwrites, with a write-only operation, every location within the region being locked. This enables resources stored in non-native formats to save the decompression step.
D3DLOCK_NOOVERWRITE
Indicates that no information referred to in drawing calls since the start of the frame or the last lock without this flag will be modified during the lock. This can enable optimizations when the application is only appending data to the vertex buffer.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but it can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.
ppData
[out, retval] Address of a pointer to an array of DWORD values, filled with the returned attribute buffer data.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::UnlockAttributeBuffer


ID3DXSkinMesh::LockIndexBuffer

Locks an index buffer and obtains a pointer to the index buffer memory.

HRESULT LockIndexBuffer(
  DWORD Flags,
  BYTE** ppData
);

Parameters

Flags
[in] A combination of one or more locking flags, describing how the index buffer memory should be locked.
D3DLOCK_DISCARD
The application overwrites, with a write-only operation, every location within the region being locked. This enables resources stored in non-native formats to save the decompression step.
D3DLOCK_NOOVERWRITE
Indicates that no indices that were referred to in drawing calls since the start of the frame or the last lock without this flag will be modified during the lock. This can enable optimizations when the application is only appending data to the index buffer.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.
ppData
[out, retval] Address of a pointer to an array of BYTE values, filled with the returned index data.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with index buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set index buffer.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::UnlockIndexBuffer


ID3DXSkinMesh::LockVertexBuffer

Locks a vertex buffer and obtains a pointer to the vertex buffer memory.

HRESULT LockVertexBuffer(
  DWORD Flags,
  BYTE** ppData
);

Parameters

Flags
[in] A combination of one or more locking flags, indicating how the vertex buffer memory should be locked.
D3DLOCK_DISCARD
The application overwrites, with a write-only operation, every location within the region being locked. This enables resources stored in non-native formats to save the decompression step.
D3DLOCK_NOOVERWRITE
Indicates that no vertices that were referred to in drawing calls since the start of the frame or the last lock without this flag will be modified during the lock. This can enable optimizations when the application is only appending data to the vertex buffer.
D3DLOCK_NOSYSLOCK
The default behavior of a video memory lock is to reserve a system-wide critical section, guaranteeing that no display mode changes will occur for the duration of the lock. This flag causes the system-wide critical section not to be held for the duration of the lock.

The lock operation is slightly more expensive, but can enable the system to perform other duties, such as moving the mouse cursor. This flag is useful for long duration locks, such as the lock of the back buffer for software rendering that would otherwise adversely affect system responsiveness.

D3DLOCK_READONLY
The application will not write to the buffer. This enables resources stored in non-native formats to save the recompression step when unlocking.
ppData
[out, retval] Address of a pointer to an array of BYTE values, filled with the returned vertex data.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

When working with vertex buffers, you are allowed to make multiple lock calls; however, you must ensure that the number of lock calls match the number of unlock calls. DrawPrimitive calls will not succeed with any outstanding lock count on any currently set vertex buffer.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::UnlockVertexBuffer


ID3DXSkinMesh::SetBoneInfluence

Sets the bone influence for a bone in the skin mesh.

HRESULT SetBoneInfluence(
  DWORD Bone,
  DWORD numInfluences,
  CONST DWORD* pVertices,
  CONST FLOAT* pWeights
);

Parameters

Bone
[in] Bone for which to set the influences.
numInfluences
[in] Number of influences to set for the bone.
pVertices
[in] Pointer to the list of vertices used to set the influences (weights).
pWeights
[in] Pointer to the list of weights to set for the provided vertices. These values are used to programmatically fill in the skinning information for the skin mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be E_OUTOFMEMORY.

Remarks

Using this method provides a mechanism to indicate how the given bone affects the given vertices. This method should be called for each bone that affects the mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSkinMesh::UnlockAttributeBuffer

Unlocks an attribute buffer.

HRESULT UnlockAttributeBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::LockAttributeBuffer


ID3DXSkinMesh::UnlockIndexBuffer

Unlocks an index buffer.

HRESULT UnlockIndexBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::LockIndexBuffer


ID3DXSkinMesh::UnlockVertexBuffer

Unlocks a vertex buffer.

HRESULT UnlockVertexBuffer();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::LockVertexBuffer


ID3DXSkinMesh::UpdateSkinnedMesh

Updates a skin mesh.

HRESULT UpdateSkinnedMesh(
  CONST D3DXMATRIX* pBoneTransforms,
  LPD3DXMESH pMesh
);

Parameters

pBoneTransforms
[in] Pointer to an array of D3DXMATRIX structures, representing the new bone transforms. The length of this array is the count of all the bones in the skin mesh.
pMesh
[out, retval] Pointer to an ID3DXMesh interface, representing the updated skinned mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method updates the vertices blended with the new bone transforms.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::GenerateSkinnedMesh


ID3DXSPMesh

Applications use the methods of the ID3DXSPMesh interface to manipulate simplification mesh objects. A simplification mesh is used to simplify a given mesh to a lower number of faces.

The ID3DXSPMesh interface is obtained by calling the D3DXCreateSPMesh function.

The methods of the ID3DXSPMesh interface can be organized into the following groups.

Copying | CloneMesh
 | CloneMeshFVF
 | ClonePMesh
 | ClonePMeshFVF
Faces | GetMaxFaces
 | GetNumFaces
 | ReduceFaces
Information | GetDevice
 | GetOptions
Vertices | GetDeclaration
 | GetFVF
 | GetMaxVertices
 | GetNumVertices
 | ReduceVertices

The ID3DXSPMesh interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPD3DXSPMESH type is defined as a pointer to the ID3DXSPMesh interface.

typedef struct ID3DXSPMesh *LPD3DXSPMESH;

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

Mesh Functions


ID3DXSPMesh::CloneMesh

Clones a mesh using a declarator.

HRESULT CloneMesh(
  DWORD Options,
  CONST DWORD* pDeclaration,
  LPDIRECT3DDEVICE8 pD3DDevice,
  DWORD* pAdjacency,
  DWORD* pVertexRemap,
  LPD3DXMESH* ppCloneMesh
);

Parameters

Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers. These meshes will have separate index buffers into the shared vertex buffer.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pDeclaration
[in] Pointer to an array of DWORD values, representing the declarator to describe the vertex format of the vertices in the output mesh. This parameter must map directly to an FVF.
pD3DDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device object associated with the mesh.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh.
pVertexRemap
[in] Pointer to an array containing the index for each vertex.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXPMesh interface, representing the cloned mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSPMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXSPMesh::CloneMeshFVF

Clones a mesh using a flexible vertex format (FVF) code.

HRESULT CloneMeshFVF(
  DWORD Options,
  DWORD FVF,
  LPDIRECT3DDEVICE8 pDevice,
  DWORD* pAdjacency,
  DWORD* pVertexRemap,
  LPD3DXMESH* ppCloneMesh
);

Parameters

Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers. These meshes will have separate index buffers into the shared vertex buffer.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
FVF
[in] Combination of flexible vertex format flags that specifies the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device object associated with the mesh.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh.
pVertexRemap
[in] Pointer to an array containing the index for each vertex.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXPMesh interface, representing the cloned mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

CloneMeshFVF can be used to convert a mesh from one FVF to another.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSPMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXSPMesh::ClonePMesh

Clones a progressive mesh using a declarator.

HRESULT ClonePMesh(
  DWORD Options,
  CONST DWORD* pDeclaration,
  LPDIRECT3DDEVICE8 pDevice,
  DWORD* pVertexRemap,
  LPD3DXPMESH* ppCloneMesh
);

Parameters

Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers. These meshes will have separate index buffers into the shared vertex buffer.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pDeclaration
[in] Pointer to an array of DWORD values, representing the declarator to describe the vertex format of the vertices in the output mesh. This parameter must map directly to an FVF.
pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device object associated with the mesh.
pVertexRemap
[in] Pointer to an array containing the index for each vertex.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_CANNOTATTRSORT
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSPMesh::GetDeclaration, D3DXDeclaratorFromFVF


ID3DXSPMesh::ClonePMeshFVF

Clones a progressive mesh using a flexible vertex format (FVF) code.

HRESULT ClonePMeshFVF(
  DWORD Options,
  DWORD FVF,
  LPDIRECT3DDEVICE8 pDevice,
  DWORD* pVertexRemap,
  LPD3DXPMESH* ppCloneMesh
);

Parameters

Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers. These meshes will have separate index buffers into the shared vertex buffer.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
FVF
[in] Combination of flexible vertex format flags that specifies the vertex format for the vertices in the output mesh.
pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device object associated with the mesh.
pVertexRemap
[in] Pointer to an array containing the index for each vertex.
ppCloneMesh
[out, retval] Address of a pointer to an ID3DXPMesh interface, representing the cloned progressive mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_CANNOTATTRSORT
E_OUTOFMEMORY

Remarks

ClonePMeshFVF can be used to convert a progressive mesh from one FVF to another.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSPMesh::GetFVF, D3DXFVFFromDeclarator


ID3DXSPMesh::GetDeclaration

Retrieves a declaration describing the vertices in the mesh.

HRESULT GetDeclaration(
  DWORD Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

Declaration
[out] A returned array describing the vertex format of the vertices in the queried mesh. The upper limit of this declarator array is MAX_FVF_DECL_SIZE, limiting the declarator to a maximum of 15 DWORDs.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Applies To

This method applies to the following interfaces, which inherit from ID3DXBaseMesh.

  • ID3DXMesh
  • ID3DXPMesh

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSPMesh::GetFVF


ID3DXSPMesh::GetDevice

Retrieves the device object associated with the simplification mesh.

HRESULT GetDevice(
  LPDIRECT3DDEVICE8* ppDevice

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice8 interface, representing the Microsoft® Direct3D® device object associated with the simplification mesh.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DDevice8 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice8 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSPMesh::GetFVF

Retrieves the flexible vertex format of the vertices in the simplification mesh.

DWORD GetFVF();

Parameters

None.

Return Values

Returns a combination of flexible vertex format flags that describe the vertex format of the vertices in the simplification mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSPMesh::GetDeclaration


ID3DXSPMesh::GetMaxFaces

Retrieves the maximum number of faces that the simplification mesh supports.

DWORD GetMaxFaces();

Parameters

None.

Return Values

Returns the maximum number of faces in the original mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSPMesh::GetMaxVertices

Retrieves the maximum number of vertices that the simplification mesh supports.

DWORD GetMaxVertices();

Parameters

None.

Return Values

Returns the maximum number of vertices in the original mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSPMesh::GetNumFaces

Retrieves the number of faces in the simplification mesh.

DWORD GetNumFaces();

Parameters

None.

Return Values

Returns the number of faces in the simplification mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSPMesh::GetNumVertices

Retrieves the number of vertices in the simplification mesh.

DWORD GetNumVertices();

Parameters

None.

Return Values

Returns the number of vertices in the simplification mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSPMesh::GetOptions

Retrieves the mesh options enabled for this simplification mesh at creation time.

DWORD GetOptions();

Parameters

None.

Return Values

Returns a combination of one or more of the following flags, indicating the options enabled for this mesh at creation time.

D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SHARE
Forces the cloned meshes to share vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSPMesh::ReduceFaces

Reduces the number of faces in a simplification mesh.

HRESULT ReduceFaces(
  DWORD Faces
);

Parameters

Faces
[in] Number of faces to which to reduce the primitive count.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method performs edge collapses to reduce the number of primitives to the value specified in Faces. It is not always possible to reduce a mesh to the requested value due to certain restrictions.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSPMesh::ReduceVertices

Reduces the number of vertices in a simplification mesh.

HRESULT ReduceVertices(
  DWORD Vertices
);

Parameters

Vertices
[in] Number of vertices to which to reduce the primitive count.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

This method performs edge collapses to reduce the number of primitives to the value specified in Vertices. It is not always possible to reduce a mesh to the requested value due to certain restrictions.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


ID3DXSprite

The ID3DXSprite interface provides a set of methods that simplify the process of drawing sprites using Microsoft® Direct3D®.

The ID3DXSprite interface is obtained by calling the D3DXCreateSprite function.

The methods of the ID3DXSprite interface can be organized into the following groups.

Drawing | Begin
 | Draw
 | DrawTransform
 | End
Information | GetDevice

The ID3DXSprite interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPD3DXSPRITE type is defined as a pointer to the ID3DXSprite interface.

typedef interface ID3DXSprite *LPD3DXSPRITE;

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


ID3DXSprite::Begin

Prepares a device for drawing sprites.

HRESULT Begin();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

Calling Begin is optional. If called outside of a Begin/End sequence, the draw functions will internally call Begin and End. To avoid extra overhead, this method should be used if more than one draw function will be called successively.

ID3DXSprite::Begin cannot be used as a substitute for either IDirect3DDevice8::BeginScene or ID3DXRenderToSurface::BeginScene.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSprite::End


ID3DXSprite::Draw

Draws a simple sprite in screen-space.

HRESULT Draw(
  LPDIRECT3DTEXTURE8 pSrcTexture,
  CONST RECT* pSrcRect,
  CONST D3DXVECTOR2* pScaling,
  CONST D3DXVECTOR2* pRotationCenter,
  FLOAT Rotation,
  CONST D3DVECTOR2* pTranslation,
  D3DCOLOR Color
);

Parameters

pSrcTexture
[in] Pointer to an IDirect3DTexture8 interface, representing the source image used for the sprite.
pSrcRect
[in] A pointer to a RECT structure that indicates what portion of the source texture to use for the sprite. If this parameter is NULL, then the entire source image is used for the sprite; however, you can specify a sub-rectangle of the source image instead. X and y mirroring can be specified easily by swapping the left and top and the right and bottom parameters of this RECT structure.

Before transformation, the size of the sprite is defined by pSrcRect with the top-left corner at the origin (0,0).

pScaling
[in] Pointer to a D3DXVECTOR2 structure, the scaling vector. If this argument is NULL, it is treated as identity.
pRotationCenter
[in] Pointer to a D3DXVECTOR2 structure, a point that identifies the center of rotation. If this argument is NULL, it is treated as the point (0,0), which is the upper-left corner of the texture.
Rotation
[in] Value that specifies the rotation.
pTranslation
[in] Pointer to a D3DXVECTOR2 structure, representing the translation. If this argument is NULL, it is treated as identity.
Color
[in] D3DCOLOR type. The color and alpha channels are modulated by this value.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If ID3DXSprite::Begin has not been called, this method will internally call Begin and ID3DXSprite::End. When making successive calls to ID3DXSprite::Draw and/or ID3DXSprite::DrawTransform, be sure to call Begin to avoid the extra overhead of Draw and DrawTransform internally calling Begin and End each time.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSprite::DrawTransform


ID3DXSprite::DrawTransform

Provides a mechanism for drawing a sprite that is transformed by a specified matrix.

HRESULT DrawTransform(
  LPDIRECT3DTEXTURE8 pSrcTexture,
  CONST RECT* pSrcRect,
  CONST D3DXMATRIX* pTransform,
  D3DCOLOR Color
);

Parameters

pSrcTexture
[in] Pointer to an IDirect3DTexture8 interface, representing the source image used for the sprite.
pSrcRect
[in] A pointer to a RECT structure that indicates what portion of the source texture to use for the sprite. If this parameter is NULL, then the entire source image is used for the sprite; however, you can specify a sub-rectangle of the source image instead. X and y mirroring can be specified easily by swapping the left and top and the right and bottom parameters of this RECT structure.

Before transformation, the size of the sprite is defined by pSrcRect with the top-left corner at the origin (0,0).

pTransform
[in] Pointer to a D3DXMATRIX structure, specifying the transformation that will be applied.
Color
[in] D3DCOLOR type. The color and alpha channels are modulated by this value.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Remarks

If ID3DXSprite::Begin has not been called, this method will internally call Begin and ID3DXSprite::End. When making successive calls to ID3DXSprite::Draw and/or ID3DXSprite::DrawTransform, be sure to call Begin to avoid the extra overhead of Draw and DrawTransform internally calling Begin and End each time.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSprite::Draw


ID3DXSprite::End

Restores the device state to how it was when ID3DXSprite::Begin was called.

HRESULT End();

Parameters

None.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

ID3DXSprite::End cannot be used as a substitute for either IDirect3DDevice8::EndScene or ID3DXRenderToSurface::EndScene.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSprite::Begin


ID3DXSprite::GetDevice

Retrieves the Microsoft® Direct3D® device associated with the sprite object.

HRESULT GetDevice(
  LPDIRECT3DDEVICE8* ppDevice
);

Parameters

ppDevice
[out, retval] Address of a pointer to an IDirect3DDevice8 interface, representing the Direct3D device object associated with the sprite object.

Return Values

If the method succeeds, the return value is D3D_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Note Calling this method will increase the internal reference count on the IDirect3DDevice8 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice8 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


ID3DXTechnique

The ID3DXTechnique interface is used to query, validate, and apply techniques.

The ID3DXTechnique interface is obtained by calling the ID3DXEffect::GetTechnique method.

The methods of the ID3DXTechnique interface can be organized into the following groups.

Effects | IsParameterUsed
Information | GetDevice
 | GetDesc
 | GetPassDesc
Validation | Validate
Technique Application | Begin
 | End
 | Pass

The ID3DXTechnique interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPD3DXTECHNIQUE type is defined as a pointer to the ID3DXTechnique interface.

typedef struct ID3DXTechnique* LPD3DXTECHNIQUE;

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.


ID3DXTechnique::Begin

Begins the application of the technique.

HRESULT Begin(
  UINT* pPasses
);

Parameters

pPasses
[out, retval] Pointer to a value indicating the number of passes that need to be taken to render the technique.

Return Values

This method always returns the value S_OK.

Remarks

This method returns the number of passes needed to render the technique. The application must incrementally call ID3DXTechnique::Pass for each pass before drawing the geometry to which the effect needs to be applied. After all passes are rendered, ID3DXTechnique::End must be called.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXTechnique::End, ID3DXTechnique::Pass


ID3DXTechnique::End

End the application of the technique.

HRESULT End();

Parameters

None.

Return Values

This method always returns the value S_OK.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXTechnique::Begin, ID3DXTechnique::Pass


ID3DXTechnique::GetDevice

Retrieves the device associated with the technique.

HRESULT GetDevice(
  IDirect3DDevice8** ppDevice
);

Parameters

ppDevice
Address of a pointer to an IDirect3DDevice8 interface, representing the device associated with the technique.

Return Values

This method always returns the value S_OK.

Note Calling this method will increase the internal reference count on the IDirect3DDevice8 interface. Be sure to call IUnknown::Release when you are done using this IDirect3DDevice8 interface or you will have a memory leak.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.


ID3DXTechnique::GetDesc

Retrieves a description of the technique.

HRESULT GetDesc(
  D3DXTECHNIQUE_DESC* pDesc
);

Parameters

pDesc
[out, retval] A D3DXTECHNIQUE_DESC structure, describing the technique.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.


ID3DXTechnique::GetPassDesc

Retrieves information about a pass for an effect.

HRESULT GetPassDesc(
  UINT           Index,
  D3DXPASS_DESC* pDesc
)

Parameters

Index
Index of the pass to retrieve information about.
pDesc
[out, retval] Pointer to a D3DXPASS_DESC structure, containing the pass description.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.


ID3DXTechnique::IsParameterUsed

Determines if a parameter is used by the technique.

BOOL IsParameterUsed(
  DWORD Name
)

Parameters

Name
Index of parameter to check. This parameter must be a four-character code. See Remarks.

Return Values

Returns TRUE if parameter is being used and returns FALSE if the parameter is not being used.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.


ID3DXTechnique::Pass

Applies the state settings for the specified pass of the technique.

HRESULT Pass(
  UINT Index
);

Parameters

Pass
[in] Identifies the pass to be applied.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

After calling Pass, the application must draw the geometry to the device to which the effect is set.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXTechnique::Begin, ID3DXTechnique::End


ID3DXTechnique::Validate

Validates the technique.

HRESULT Validate();

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.


Functions

This section contains reference information for the functions that you need to implement when you work with the Direct3DX utility library. The following functions are implemented.

  • Effect Functions
  • General Purpose Functions
  • Math Functions
  • Mesh Functions
  • Shader Functions
  • Shape-Drawing Functions
  • Texturing Functions


Effect Functions

Direct3DX supplies the following effect functions.

  • D3DXCompileEffect
  • D3DXCompileEffectFromFileA
  • D3DXCompileEffectFromFileW
  • D3DXCreateEffect


D3DXCompileEffect

Compiles an ASCII effect description into a binary form usable by D3DXCreateEffect.

HRESULT WINAPI D3DXCompileEffect(
  LPCVOID       pSrcData,
  UINT          SrcDataSize,
  LPD3DXBUFFER* ppCompiledEffect,
  LPD3DXBUFFER* ppCompilationErrors
);

Parameters

pSrcData
[in] Pointer to source data, representing the effect to compile.
SrcDataSize
[in] Size of the source data, in bytes.
ppCompiledEffect
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing the compiled effect.
ppCompilationErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing returned ASCII error messages.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

After an effect is compiled, use D3DXCreateEffect to obtain a pointer to a ID3DXEffect interface.

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCompileEffectFromFileA , D3DXCompileEffectFromFileW, D3DXCreateEffect


D3DXCompileEffectFromFileA

Compiles an effect from a file specified by an ANSI string.

HRESULT WINAPI D3DXCompileEffectFromFileA(
  LPCSTR        pSrcFile,
  LPD3DXBUFFER* ppCompiledEffect,
  LPD3DXBUFFER* ppCompilationErrors
);

Parameters

pSrcFile
[in] Pointer to an ANSI string that specifies the file from which to create the effect.
ppCompiledEffect
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing the compiled effect.
ppCompilationErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing the returned ASCII error messages.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

After an effect is compiled, use D3DXCreateEffect to obtain a pointer to a ID3DXEffect interface.

D3DXCompileEffectFromFile maps to either D3DXCompileEffectFromFileA or D3DXCompileEffectFromFileW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCompileEffectFromFile is defined.

#ifdef UNICODE
#define D3DXCompileEffectFromFile D3DXCompileEffectFromFileW
#else
#define D3DXCompileEffectFromFile D3DXCompileEffectFromFileA
#endif

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCompileEffect , D3DXCompileEffectFromFileW, D3DXCreateEffect


D3DXCompileEffectFromFileW

Compiles an effect from a file specified by a Unicode string.

HRESULT WINAPI D3DXCompileEffectFromFileW(
  LPCWSTR       pSrcFile,
  LPD3DXBUFFER* ppCompiledEffect,
  LPD3DXBUFFER* ppCompilationErrors
);

Parameters

pSrcFile
[in] Pointer to a Unicode string that specifies the file from which to create the effect.
ppCompiledEffect
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing the compiled effect.
ppCompilationErrors
[out, retval] Address of a pointer to an ID3DXBuffer interface, containing the returned ASCII error messages.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

After an effect is compiled, use D3DXCreateEffect to obtain a pointer to a ID3DXEffect interface.

D3DXCompileEffectFromFile maps to either D3DXCompileEffectFromFileA or D3DXCompileEffectFromFileW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCompileEffectFromFile is defined.

#ifdef UNICODE
#define D3DXCompileEffectFromFile D3DXCompileEffectFromFileW
#else
#define D3DXCompileEffectFromFile D3DXCompileEffectFromFileA
#endif

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCompileEffect , D3DXCompileEffectFromFileA, D3DXCreateEffect


D3DXCreateEffect

Creates an effect using a compiled source data.

HRESULT WINAPI D3DXCreateEffect(
  LPDIRECT3DDEVICE8 pDevice,
  LPCVOID           pCompiledEffect,
  UINT              CompiledEffectSize,
  DWORD             Usage,
  LPD3DXEFFECT*     ppEffect
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the effect.
pCompiledEffect
[in] Pointer to the compiled source data from which to create the effect.
CompiledEffectSize
[in] Size of the compiled data, in bytes.
Usage
[in] Usage control for this effect. The following flag can be set:
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the effect will be rendered using software processing.
ppEffect
[out, retval] Address of a pointer to an ID3DXEffect interface, representing the created effect.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

Before using CreateEffect, an effect must be compiled by using any of the following functions:

  • D3DXCompileEffect
  • D3DXCompileEffectFromFileA
  • D3DXCompileEffectFromFileW

Requirements

Header: Declared in D3dx8effect.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCompileEffect , D3DXCompileEffectFromFileA, D3DXCompileEffectFromFileW


General Purpose Functions

Direct3DX supplies the following general purpose functions.

  • D3DXCreateFont
  • D3DXCreateFontIndirect
  • D3DXCreateRenderToSurface
  • D3DXCreateSprite
  • D3DXGetErrorStringA
  • D3DXGetErrorStringW
  • D3DXGetFVFVertexSize


D3DXCreateFont

Creates a font object for a device and font.

HRESULT D3DXCreateFont(
  LPDIRECT3DDEVICE8 pDevice,
  HFONT hFont,
  LPD3DXFONT* ppFont
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, the device to be associated with the font object.
hFont
[in] Handle to the font object.
ppFont
[out] Returns a pointer to an ID3DXFont interface, representing the created font object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


D3DXCreateFontIndirect

Creates an font object indirectly for a device and font.

HRESULT D3DXCreateFontIndirect(
  LPDIRECT3DDEVICE8 pDevice,
  CONST LOGFONT* pLogFont,
  LPD3DXFONT* ppFont
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, the device to be associated with the font object.
pLogFont
[in] Pointer to a LOGFONT structure, describing the attributes of the font object to create.
ppFont
[out] Returns a pointer to an ID3DXFont interface, representing the created font object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

For more information on the LOGFONT structure, see the Microsoft® Platform Software Development Kit (SDK).

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


D3DXCreateRenderToSurface

Creates a render surface.

HRESULT D3DXCreateRenderToSurface(
  LPDIRECT3DDEVICE8 pDevice,
  UINT Width,
  UINT Height,
  D3DFORMAT Format,
  BOOL DepthStencil,
  D3DFORMAT DepthStencilFormat,
  LPD3DXRENDERTOSURFACE* ppRenderToSurface
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, the device to be associated with the render surface.
Width
[in] Width of the render surface, in pixels.
Height
[in] Height of the render surface, in pixels.
Format
[in] Member of the D3DFORMAT enumerated type, describing the pixel format of the render surface.
DepthStencil
[in] If TRUE, the render surface supports a depth-stencil surface. Otherwise this member is set to FALSE.
DepthStencilFormat
[in] If DepthStencil is set to TRUE, this parameter is a member of the D3DFORMAT enumerated type, describing the depth-stencil format of the render surface.
ppRenderToSurface
[out, retval] Address of a pointer to an ID3DXRenderToSurface interface, representing the created render surface.

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


D3DXCreateSprite

Creates a sprite object.

HRESULT D3DXCreateSprite(
  LPDIRECT3DDEVICE8 pDevice,
  LPD3DXSPRITE* ppSprite
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, the device to be associated with the sprite.
ppSprite
[out] Address of a pointer to an ID3DXSprite interface, representing the created sprite.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


D3DXGetErrorStringA

Returns the ANSI error string for an HRESULT.

HRESULT D3DXGetErrorStringA(
  HRESULT hr,
  LPSTR pBuffer,
  UINT BufferLen
);

Parameters

hr
[in] The specified HRESULT error code to decipher.
pBuffer
[out] Pointer to the buffer to fill with the ANSI error string.
BufferLen
[in] Number of characters in the buffer. Any error message longer than this length will be truncated.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Remarks

D3DXGetErrorString maps to either D3DXGetErrorStringA or D3DXGetErrorStringW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXGetErrorString is defined.

#ifdef UNICODE
#define D3DXGetErrorString D3DXGetErrorStringW
#else
#define D3DXGetErrorString D3DXGetErrorStringA
#endif

This function interprets all Microsoft® Direct3D® HRESULTS.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

D3DXGetErrorStringW


D3DXGetErrorStringW

Returns the Unicode error string for an HRESULT.

HRESULT D3DXGetErrorStringW(
  HRESULT hr,
  LPWSTR pBuffer,
  UINT BufferLen
);

Parameters

hr
[in] The specified HRESULT error code to decipher.
pBuffer
[out] Pointer to the buffer to fill in with the Unicode error string.
BufferLen
[in] Number of characters in the buffer. Any error message longer than this length is truncated.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

This function Interprets all Microsoft® Direct3D® HRESULTS.

D3DXGetErrorString maps to either D3DXGetErrorStringA or D3DXGetErrorStringW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXGetErrorString is defined.

#ifdef UNICODE
#define D3DXGetErrorString D3DXGetErrorStringW
#else
#define D3DXGetErrorString D3DXGetErrorStringA
#endif

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

D3DXGetErrorStringA


D3DXGetFVFVertexSize

Returns the size of a vertex for a flexible vertex format.

UINT D3DXGetFVFVertexSize(
  DWORD FVF
);

Parameters

FVF
[in] Flexible vertex format to be queried. A combination of flexible vertex format flags.

Return Values

The flexible vertex format vertex size, in bytes.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


Math Functions

The math library provided by the Direct3DX utility library supplies functions to compute both basic and complicated 3-D mathematical operations.

The 3-D math application functions can be organized into the following groups.

Color | D3DXColorAdd
 | D3DXColorAdjustContrast
 | D3DXColorAdjustSaturation
 | D3DXColorLerp
 | D3DXColorModulate
 | D3DXColorNegative
 | D3DXColorScale
 | D3DXColorSubtract
Creation | D3DXCreateMatrixStack
Plane | D3DXPlaneDot
 | D3DXPlaneDotCoord
 | D3DXPlaneDotNormal
 | D3DXPlaneIntersectLine
 | D3DXPlaneFromPointNormal
 | D3DXPlaneNormalize
 | D3DXPlaneFromPoints
 | D3DXPlaneTransform
Quaternion | D3DXQuaternionBaryCentric
 | D3DXQuaternionConjugate
 | D3DXQuaternionDot
 | D3DXQuaternionExp
 | D3DXQuaternionIdentity
 | D3DXQuaternionInverse
 | D3DXQuaternionIsIdentity
 | D3DXQuaternionLength
 | D3DXQuaternionLengthSq
 | D3DXQuaternionLn
 | D3DXQuaternionMultiply
 | D3DXQuaternionNormalize
 | D3DXQuaternionRotationAxis
 | D3DXQuaternionRotationMatrix
 | D3DXQuaternionRotationYawPitchRoll
 | D3DXQuaternionSlerp
 | D3DXQuaternionSquad
 | D3DXQuaternionToAxisAngle
2-D Vector | D3DXVec2Add
 | D3DXVec2BaryCentric
 | D3DXVec2CatmullRom
 | D3DXVec2CCW
 | D3DXVec2Dot
 | D3DXVec2Hermite
 | D3DXVec2Length
 | D3DXVec2LengthSq
 | D3DXVec2Lerp
 | D3DXVec2Maximize
 | D3DXVec2Minimize
 | D3DXVec2Normalize
 | D3DXVec2Scale
 | D3DXVec2Subtract
 | D3DXVec2Transform
 | D3DXVec2TransformCoord
 | D3DXVec2TransformNormal
3-D Vector | D3DXVec3Add
 | D3DXVec3BaryCentric
 | D3DXVec3CatmullRom
 | D3DXVec3Cross
 | D3DXVec3Dot
 | D3DXVec3Hermite
 | D3DXVec3Length
 | D3DXVec3LengthSq
 | D3DXVec3Lerp
 | D3DXVec3Maximize
 | D3DXVec3Minimize
 | D3DXVec3Normalize
 | D3DXVec3Project
 | D3DXVec3Scale
 | D3DXVec3Subtract
 | D3DXVec3Transform
 | D3DXVec3TransformCoord
 | D3DXVec3TransformNormal
 | D3DXVec3Unproject
4-D Matrix | D3DXMatrixAffineTransformation
 | D3DXMatrixfDeterminant
 | D3DXMatrixIdentity
 | D3DXMatrixInverse
 | D3DXMatrixIsIdentity
 | D3DXMatrixLookAtRH
 | D3DXMatrixLookAtLH
 | D3DXMatrixMultiply
 | D3DXMatrixOrthoRH
 | D3DXMatrixOrthoLH
 | D3DXMatrixOrthoOffCenterRH
 | D3DXMatrixOrthoOffCenterLH
 | D3DXMatrixPerspectiveRH
 | D3DXMatrixPerspectiveLH
 | D3DXMatrixPerspectiveFovRH
 | D3DXMatrixPerspectiveFovLH
 | D3DXMatrixPerspectiveOffCenterRH
 | D3DXMatrixPerspectiveOffCenterLH
 | D3DXMatrixReflect
 | D3DXMatrixRotationAxis
 | D3DXMatrixRotationQuaternion
 | D3DXMatrixRotationX
 | D3DXMatrixRotationY
 | D3DXMatrixRotationYawPitchRoll
 | D3DXMatrixRotationZ
 | D3DXMatrixScaling
 | D3DXMatrixShadow
 | D3DXMatrixTransformation
 | D3DXMatrixTranslation
 | D3DXMatrixTranspose
4-D Vector | D3DXVec4Add
 | D3DXVec4BaryCentric
 | D3DXVec4CatmullRom
 | D3DXVec4Cross
 | D3DXVec4Dot
 | D3DXVec4Hermite
 | D3DXVec4Length
 | D3DXVec4LengthSq
 | D3DXVec4Lerp
 | D3DXVec4Maximize
 | D3DXVec4Minimize
 | D3DXVec4Normalize
 | D3DXVec4Scale
 | D3DXVec4Subtract
 | D3DXVec4Transform

Note All the math functions can take the same object as the passed [in] and returned [out] parameters. Also, out parameters are typically returned as return values, so that the output of one math function may be used as a parameter for another math function.


D3DXColorAdd

Adds two color values together to create a new color value.

D3DXCOLOR* D3DXColorAdd(
  D3DXCOLOR* pOut,
  CONST D3DXCOLOR* pC1,
  CONST D3DXCOLOR* pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the sum of two color values.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorAdd function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXColorModulate, D3DXColorSubtract


D3DXColorAdjustContrast

Adjusts the contrast value of a color.

D3DXCOLOR* D3DXColorAdjustContrast(
  D3DXCOLOR* pOut,
  D3DXCOLOR* pC,
  FLOAT c
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
c
[in] Contrast value. This parameter linearly interpolates between 50 percent gray and the color, pC. There are not limits on the value of c. If this parameter is zero, then the returned color is 50 percent gray. If this parameter is 1, then the returned color is the original color.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the result of the contrast adjustment.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorAdjustContrast function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between 50 percent gray and a specified contrast value, as shown in the following example.

    pOut->r = 0.5f + c * (pC->r - 0.5f);

If c is greater than 0 and less than 1, the contrast is decreased. If c is greater than 1, then the contrast is increased.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXColorAdjustSaturation


D3DXColorAdjustSaturation

Adjusts the saturation value of a color.

D3DXCOLOR* D3DXColorAdjustSaturation(
  D3DXCOLOR* pOut,
  D3DXCOLOR* pC,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Saturation value. This parameter linearly interpolates between the color converted to gray-scale and the original color, pC. There are no limits on the value of s. If s is 0, then the returned color is the gray-scale color. If s is 1, the returned color is the original color.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the result of the saturation adjustment.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorAdjustSaturation function can be used as a parameter for another function.

This function interpolates the red, green, and blue color components of a D3DXCOLOR structure between an unsaturated color and a color, as shown in the following example.

    // Approximate values for each component's contribution to luminance.
    // Based upon the NTSC standard described in ITU-R Recommendation BT.709.
    FLOAT grey = pC->r * 0.2125f + pC->g * 0.7154f + pC->b * 0.0721f;

    pOut->r = grey + s * (pC->r - grey);

If s is greater than 0 and less than 1, the saturation is decreased. If s is greater than 1, the saturation is increased.

The gray-scale color is computed as: r = g = b = 0.2125*r + 0.7154*g + 0.0721*b.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXColorAdjustContrast


D3DXColorLerp

Uses linear interpolation to create a color value.

D3DXCOLOR* D3DXColorLerp(
  D3DXCOLOR* pOut,
  CONST D3DXCOLOR* pC1,
  CONST D3DXCOLOR* pC2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Parameter that linearly interpolates between the colors, pC1 and pC2, treating them both as 4-D vectors. There are no limits on the value of s.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the result of the linear interpolation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorLerp function can be used as a parameter for another function.

This function interpolates the red, green, blue, and alpha components of a D3DXCOLOR structure between two colors, as shown in the following example.

    pOut->r = pC1->r + s * (pC2->r - pC1->r);

If you are linearly interpolating between the colors A and B, and s is 0, the resulting color is A. If s is 1, the resulting color is color B.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXColorModulate, D3DXColorNegative, D3DXColorScale


D3DXColorModulate

Blends two colors.

D3DXCOLOR* D3DXColorModulate(
  D3DXCOLOR* pOut,
  CONST D3DXCOLOR* pC1,
  CONST D3DXCOLOR* pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the result of the blending operation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorModulate function can be used as a parameter for another function.

This function blends together two colors by multiplying matching color components, as shown in the following example.

    pOut->r = pC1->r * pC2->r;

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXColorLerp, D3DXColorNegative, D3DXColorScale


D3DXColorNegative

Creates the negative color value of a color value.

D3DXCOLOR* D3DXColorNegative(
  D3DXCOLOR* pOut,
  CONST D3DXCOLOR* pC
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the negative color value of the color value.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorNegative function can be used as a parameter for another function.

This function returns the negative color value by subtracting 1.0 from the color components of the D3DXCOLOR structure, as shown in the following example.

    pOut->r = 1.0f - pC->r;

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorScale


D3DXColorScale

Scales a color value.

D3DXCOLOR* D3DXColorScale(
  D3DXCOLOR* pOut,
  CONST D3DXCOLOR* pC,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC
[in] Pointer to a source D3DXCOLOR structure.
s
[in] Scale factor. It scales the color, treating it like a 4-D vector. There are no limits on the value of s. If s is 1, the resulting color is the original color.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the scaled color value.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorScale function can be used as a parameter for another function.

This function computes the scaled color value by multiplying the color components of the D3DXCOLOR structure by the specified scale factor, as shown in the following example.

    pOut->r = pC->r * s;

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXColorLerp, D3DXColorModulate, D3DXColorNegative


D3DXColorSubtract

Subtracts two color values to create a new color value.

D3DXCOLOR* D3DXColorSubtract(
  D3DXCOLOR* pOut,
  CONST D3DXCOLOR* pC1,
  CONST D3DXCOLOR* pC2
);

Parameters

pOut
[in, out] Pointer to a D3DXCOLOR structure that is the result of the operation.
pC1
[in] Pointer to a source D3DXCOLOR structure.
pC2
[in] Pointer to a source D3DXCOLOR structure.

Return Values

This function returns a pointer to a D3DXCOLOR structure that is the difference between two color values.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXColorSubtract function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXColorAdd


D3DXCreateMatrixStack

Creates an instance of the ID3DXMatrixStack interface.

HRESULT D3DXCreateMatrixStack(
  DWORD Flags,
  ID3DXMatrixStack** ppStack
);

Parameters

Flags
[in] Not implemented. Specify zero.
ppStack
[out] Address of a pointer filled with an ID3DXMatrixStack interface pointer if the function succeeds.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXMatrixAffineTransformation

Builds an affine transformation matrix.

D3DXMATRIX* D3DXMatrixAffineTransformation(
  D3DXMATRIX* pOut,
  FLOAT scaling,
  CONST D3DXVECTOR3* pRotationCenter,
  CONST D3DXQUATERNION* pRotation,
  CONST D3DXVECTOR3* pTranslation
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
scaling
[in] Scaling factor.
pRotationCenter
[in] Pointer to a D3DXVECTOR3 structure, a point identifying the center of rotation. If this argument is NULL, it is treated as identity.
pRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the rotation. If this argument is NULL, it is treated as identity.
pTranslation
[in] Pointer to a D3DXVECTOR3 structure, representing the translation. If this argument is NULL, it is treated as identity.

Return Values

Pointer to a D3DXMATRIX structure that is an affine transformation matrix.

Remarks

The D3DXMatrixAffineTransformation function calculates the affine transformation matrix with the following formula: Ms * Mrc-1 * Mr * Mrc * Mt, where Ms is the scaling matrix, Mrc is the center of rotation matrix, Mr is the rotation matrix, and Mt is the translation matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixAffineTransformation function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXMatrixfDeterminant

Returns the determinant of a matrix.

FLOAT D3DXMatrixfDeterminant(
  CONST D3DXMATRIX* pM
);

Parameters

pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

The value of the matrix, the determinant.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXMatrixIdentity

Creates an identity matrix.

D3DXMATRIX* D3DXMatrixIdentity(
  D3DXMATRIX* pOut
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.

Return Values

Pointer to a D3DXMATRIX structure that is the identity matrix.

Remarks

The identity matrix is a matrix in which all coefficients are 0 except the [1,1][2,2][3,3][4,4] coefficients, which are set to 1. The identity matrix is special in that when it is applied to vertices, they are unchanged. The identity matrix is used as the starting point for matrices that will modify vertex values to create rotations, translations, and any other transformations that can be represented by a 4×4 matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixIdentity function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixIsIdentity


D3DXMatrixInverse

Calculates the inverse of a matrix.

D3DXMATRIX* D3DXMatrixInverse(
  D3DXMATRIX* pOut,
  FLOAT* pDeterminant,
  CONST D3DXMATRIX* pM
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pDeterminant
[in, out] After this function returns, pointer to a FLOAT value that is the determinant of the matrix, pM.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXMATRIX structure that is the inverse of the matrix.

Remarks

This function accepts any arbitrary matrix.

Matrix inversion may fail, in which case NULL is returned by the D3DXMatrixInverse function. The determinant of pM is returned if the pDeterminant parameter is non-NULL.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixInverse function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXMatrixIsIdentity

Determines if a matrix is an identity matrix.

BOOL D3DXMatrixIsIdentity(
  CONST D3DXMATRIX* pM
);

Parameters

pM
[in] Pointer to the D3DXMATRIX structure that will be tested for identity.

Return Values

If the matrix is an identity matrix, this function returns TRUE. Otherwise, this function returns FALSE.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixIdentity


D3DXMatrixLookAtRH

Builds a right-handed, look-at matrix.

D3DXMATRIX* D3DXMatrixLookAtRH(
  D3DXMATRIX* pOut,
  CONST D3DXVECTOR3* pEye,
  CONST D3DXVECTOR3* pAt,
  CONST D3DXVECTOR3* pUp
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
[in] Pointer to the D3DXVECTOR3 structure that defines the eye point. This value is used in translation.
pAt
[in] Pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
[in] Pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Values

Pointer to a D3DXMATRIX structure that is a right-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAtRH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixLookAtLH


D3DXMatrixLookAtLH

Builds a left-handed, look-at matrix.

D3DXMATRIX* D3DXMatrixLookAtLH(
  D3DXMATRIX* pOut,
  CONST D3DXVECTOR3* pEye,
  CONST D3DXVECTOR3* pAt,
  CONST D3DXVECTOR3* pUp
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pEye
[in] Pointer to the D3DXVECTOR3 structure that defines the eye point. This value is used in translation.
pAt
[in] Pointer to the D3DXVECTOR3 structure that defines the camera look-at target.
pUp
[in] Pointer to the D3DXVECTOR3 structure that defines the current world's up, usually [0, 1, 0].

Return Values

Pointer to a D3DXMATRIX structure that is a left-handed, look-at matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixLookAtLH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixLookAtRH


D3DXMatrixMultiply

Determines the product of two matrices.

D3DXMATRIX* D3DXMatrixMultiply(
  D3DXMATRIX* pOut,
  CONST D3DXMATRIX* pM1,
  CONST D3DXMATRIX* pM2
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM1
[in] Pointer to a source D3DXMATRIX structure.
pM2
[in] Pointer to a source D3DXMATRIX structure.

Return Values

Pointer to a D3DXMATRIX structure that is the product of two matrices.

Remarks

The result represents the transformation M2 followed by the transformation M1 (Out = M1 * M2).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixMultiply function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionMultiply


D3DXMatrixOrthoRH

Builds a right-handed orthogonal projection matrix.

D3DXMATRIX* D3DXMatrixOrthoRH(
  D3DXMATRIX* pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view-volume.
h
[in] Height of the view-volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to a D3DXMATRIX structure that is a right-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

All the parameters of the D3DXMatrixOrthoRH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoRH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterRH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoLH

Builds a left-handed orthogonal projection matrix.

D3DXMATRIX* D3DXMatrixOrthoLH(
  D3DXMATRIX* pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view-volume.
h
[in] Height of the view-volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to a D3DXMATRIX structure that is a left-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

All the parameters of the D3DXMatrixOrthoLH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoLH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoOffCenterRH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoOffCenterRH

Builds a customized, right-handed orthogonal projection matrix.

D3DXMATRIX* D3DXMatrixOrthoOffCenterRH(
  D3DXMATRIX* pOut,
  FLOAT l,
  FLOAT r,
  FLOAT t,
  FLOAT b,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of view-volume.
r
[in] Maximum x-value of view-volume.
t
[in] Minimum y-value of view-volume.
b
[in] Maximum y-value of view-volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to a D3DXMATRIX structure that is a customized, right-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

The D3DXMatrixOrthoRH function is a special case of the D3DXMatrixOrthoOffCenterRH function. To create the same projection using D3DXMatrixOrthoOffCenterRH, use the following values: l = -w/2, r = w/2, b = -h/2, and t = h/2.

All the parameters of the D3DXMatrixOrthoOffCenterRH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenterRH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterLH


D3DXMatrixOrthoOffCenterLH

Builds a customized, left-handed orthogonal projection matrix.

D3DXMATRIX* D3DXMatrixOrthoOffCenterLH(
  D3DXMATRIX* pOut,
  FLOAT l,
  FLOAT r,
  FLOAT t,
  FLOAT b,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] Minimum x-value of view-volume.
r
[in] Maximum x-value of view-volume.
t
[in] Minimum y-value of view-volume.
b
[in] Maximum y-value of view-volume.
zn
[in] Minimum z-value of the view volume.
zf
[in] Maximum z-value of the view volume.

Return Values

Pointer to a D3DXMATRIX structure that is a customized, left-handed orthogonal projection matrix.

Remarks

An orthogonal matrix is an invertible matrix for which the inverse of the matrix is equal to the transpose of the matrix.

The D3DXMatrixOrthoLH function is a special case of the D3DXMatrixOrthoOffCenterLH function. To create the same projection using D3DXMatrixOrthoOffCenterLH, use the following values: l = -w/2, r = w/2, b = -h/2, and t = h/2.

All the parameters of the D3DXMatrixOrthoOffCenterLH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixOrthoOffCenterLH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixOrthoRH, D3DXMatrixOrthoLH, D3DXMatrixOrthoOffCenterRH


D3DXMatrixPerspectiveRH

Builds a right-handed perspective projection matrix.

D3DXMATRIX* D3DXMatrixPerspectiveRH(
  D3DXMATRIX* pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view-volume at the near view-plane.
h
[in] Height of the view-volume at the near view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveRH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveRH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveFovLH

Builds a left-handed perspective projection matrix based on a field of view (FOV).

D3DXMATRIX* D3DXMatrixPerspectiveFovLH(
  D3DXMATRIX* pOut,
  FLOAT fovy,
  FLOAT Aspect,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
fovy
[in] Field of view, in radians.
Aspect
[in] Aspect ratio.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFovLH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveFovRH

Builds a right-handed perspective projection matrix based on a field of view (FOV).

D3DXMATRIX* D3DXMatrixPerspectiveFovRH(
  D3DXMATRIX* pOut,
  FLOAT fovy,
  FLOAT Aspect,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
fovy
[in] Field of view, in radians.
Aspect
[in] Aspect ratio.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a right-handed perspective projection matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveFovRH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveLH

Builds a left-handed perspective projection matrix

D3DXMATRIX* D3DXMatrixPerspectiveLH(
  D3DXMATRIX* pOut,
  FLOAT w,
  FLOAT h,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
w
[in] Width of the view-volume at the near view-plane.
h
[in] Height of the view-volume at the near view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a left-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveLH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveLH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveOffCenterRH

Builds a customized, right-handed perspective projection matrix.

D3DXMATRIX* D3DXMatrixPerspectiveOffCenterRH(
  D3DXMATRIX* pOut,
  FLOAT l,
  FLOAT r,
  FLOAT t,
  FLOAT b,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] X-value of the near view-plane.
r
[in] X-value of the far view-plane.
t
[in] Y-value of the near view-plane.
b
[in] Y-value of the far view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a customized, right-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterRH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenterRH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterLH


D3DXMatrixPerspectiveOffCenterLH

Builds a customized, left-handed perspective projection matrix.

D3DXMATRIX* D3DXMatrixPerspectiveOffCenterLH(
  D3DXMATRIX* pOut,
  FLOAT l,
  FLOAT r,
  FLOAT t,
  FLOAT b,
  FLOAT zn,
  FLOAT zf
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
l
[in] X-value of the near view-plane.
r
[in] X-value of the far view-plane.
t
[in] Y-value of the near view-plane.
b
[in] Y-value of the far view-plane.
zn
[in] Z-value of the near view-plane.
zf
[in] Z-value of the far view-plane.

Return Values

Pointer to a D3DXMATRIX structure that is a customized, left-handed perspective projection matrix.

Remarks

All the parameters of the D3DXMatrixPerspectiveOffCenterLH function are distances in camera-space. The parameters describe the dimensions of the view-volume.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixPerspectiveOffCenterLH function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixPerspectiveRH, D3DXMatrixPerspectiveLH, D3DXMatrixPerspectiveFovRH, D3DXMatrixPerspectiveFovLH, D3DXMatrixPerspectiveOffCenterRH


D3DXMatrixReflect

Builds a matrix that reflects the coordinate system about a plane.

D3DXMATRIX* D3DXMatrixReflect(
  D3DXMATRIX* pOut,
  CONST D3DXPLANE* pPlane
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pPlane
[in] Pointer to the source D3DXPLANE structure.

Return Values

Pointer to a D3DXMATRIX structure that reflects the coordinate system about the source plane.

Remarks

This function normalizes the plane equation before it creates the reflected matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixReflect function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXMatrixRotationAxis

Builds a matrix that rotates around an arbitrary axis.

D3DXMATRIX* D3DXMatrixRotationAxis(
  D3DXMATRIX* pOut,
  CONST D3DXVECTOR3* pV,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pV
[in] Pointer to the D3DXVECTOR3 structure that identifies the axis angle.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationAxis function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationQuaternion

Builds a matrix from a quaternion.

D3DXMATRIX* D3DXMatrixRotationQuaternion(
  D3DXMATRIX* pOut,
  CONST D3DXQUATERNION* pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXMATRIX structure built from the source quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationQuaternion function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationX

Builds a matrix that rotates around the x-axis.

D3DXMATRIX* D3DXMatrixRotationX(
  D3DXMATRIX* pOut,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the x-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationX function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationY

Builds a matrix that rotates around the y-axis.

D3DXMATRIX* D3DXMatrixRotationY(
  D3DXMATRIX* pOut,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the y-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationY function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationYawPitchRoll, D3DXMatrixRotationZ


D3DXMatrixRotationYawPitchRoll

Builds a matrix with a specified yaw, pitch, and roll.

D3DXMATRIX* D3DXMatrixRotationYawPitchRoll(
  D3DXMATRIX* pOut,
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll,
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Yaw
[in] Yaw around the y-axis, in radians.
Pitch
[in] Pitch around the x-axis, in radians.
Roll
[in] Roll around the z-axis, in radians.

Return Values

Pointer to a D3DXMATRIX structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationYawPitchRoll function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationZ


D3DXMatrixRotationZ

Builds a matrix that rotates around the z-axis.

D3DXMATRIX* D3DXMatrixRotationZ(
  D3DXMATRIX* pOut,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXMATRIX structure rotated around the z-axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixRotationZ function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixRotationAxis, D3DXMatrixRotationQuaternion, D3DXMatrixRotationX, D3DXMatrixRotationY, D3DXMatrixRotationYawPitchRoll


D3DXMatrixScaling

Builds a matrix that scales along the x-, y-, and z-axes.

D3DXMATRIX* D3DXMatrixScaling(
  D3DXMATRIX* pOut,
  FLOAT sx,
  FLOAT sy,
  FLOAT sz,
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
sx
[in] Scaling factor that is applied along the x-axis.
sy
[in] Scaling factor that is applied along the y-axis.
sz
[in] Scaling factor that is applied along the z-axis.

Return Values

Pointer to a D3DXMATRIX structure that is the scaled matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixScaling function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXMatrixShadow

Builds a matrix that flattens geometry into a plane.

D3DXMATRIX* D3DXMatrixShadow(
  D3DXMATRIX* pOut,
  CONST D3DXVECTOR4* pLight,
  CONST D3DXPLANE* pPlane
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pLight
[in] Pointer to a D3DXVECTOR4 structure describing the light's position.
pPlane
[in] Pointer to the source D3DXPLANE structure.

Return Values

Pointer to a D3DXMATRIX structure that flattens geometry into a plane.

Remarks

The D3DXMatrixShadow function flattens geometry into a plane, as if casting a shadow from a light.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixShadow function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXMatrixTransformation

Builds a transformation matrix.

D3DXMATRIX* D3DXMatrixTransformation(
  D3DXMATRIX* pOut,
  CONST D3DXVECTOR3* pScalingCenter,
  CONST D3DXQUATERNION* pScalingRotation,
  CONST D3DXVECTOR3* pScaling,
  CONST D3DXVECTOR3* pRotationCenter,
  CONST D3DXQUATERNION* pRotation,
  CONST D3DXVECTOR3* pTranslation,
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pScalingCenter
[in] Pointer to a D3DXVECTOR3 structure, identifying the scaling center point. If this argument is NULL, it is treated as identity.
pScalingRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the scaling rotation If this argument is NULL, it is treated as identity.
pScaling
[in] Pointer to a D3DXVECTOR3 structure, the scaling vector. If this argument is NULL, it is treated as identity.
pRotationCenter
[in] Pointer to a D3DXVECTOR3 structure, a point that identifies the center of rotation. If this argument is NULL, it is treated as identity.
pRotation
[in] Pointer to a D3DXQUATERNION structure that specifies the rotation. If this argument is NULL, it is treated as identity.
pTranslation
[in] Pointer to a D3DXVECTOR3 structure, representing the translation. If this argument is NULL, it is treated as identity.

Return Values

Pointer to a D3DXMATRIX structure that is the transformation matrix.

Remarks

The D3DXMatrixTransformation function calculates the transformation matrix with the following formula: Msc-1 * Msr-1 * Ms * Msr * Msc * Mrc-1 * Mr * Mrc * Mt, where Msc is the center scaling matrix, Msr is the scaling rotation matrix, Ms is the scaling matrix, Mrc is the center of rotation matrix, Mr is the rotation matrix, and Mt is the translation matrix.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTransformation function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixAffineTransformation


D3DXMatrixTranslation

Builds a matrix using the specified offsets.

D3DXMATRIX* D3DXMatrixTranslation(
  D3DXMATRIX* pOut,
  FLOAT x,
  FLOAT y,
  FLOAT z,
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
x
[in] X-coordinate offset.
y
[in] Y-coordinate offset.
z
[in] Z-coordinate offset.

Return Values

Pointer to a D3DXMATRIX structure that is the translated matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTranslation function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXMatrixTranspose

Returns the matrix transpose of a matrix.

D3DXMATRIX* D3DXMatrixTranspose(
  D3DXMATRIX* pOut,
  CONST D3DXMATRIX* pM
);

Parameters

pOut
[in, out] Pointer to the D3DXMATRIX structure that is the result of the operation.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to the D3DXMATRIX structure that is the matrix transpose of the matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXMatrixTranspose function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXPlaneDot

Computes the dot-product of a plane and a 4-D vector.

FLOAT D3DXPlaneDot(
  CONST D3DXPLANE* pP,
  CONST D3DXVECTOR4* pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a D3DXVECTOR4 structure.

Return Values

The dot-product of the plane and 4-D vector.

Remarks

Given a plane (a, b, c, d) and a 4-D vector (x, y, z, w) the return value of this function is a*x + b*y + c*z + d*w. The D3DXPlaneDot function is useful for determining the plane's relationship with a homogeneous coordinate. For example, this function could be used to determine if a particular coordinate is on a particular plane, or on which side of a particular plane a particular coordinate lies.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXPlaneDotCoord, D3DXPlaneDotNormal


D3DXPlaneDotCoord

Computes the dot-product of a plane and a 3-D vector. The w parameter of the vector is assumed to be 1.

FLOAT D3DXPlaneDotCoord(
  CONST D3DXPLANE* pP,
  CONST D3DXVECTOR3* pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

The dot-product of the plane and 3-D vector.

Remarks

Given a plane (a, b, c, d) and a 3-D vector (x, y, z) the return value of this function is a*x + b*y + c*z + d*1. The D3DXPlaneDotCoord function is useful for determining the plane's relationship with a coordinate in 3-D space.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXPlaneDot, D3DXPlaneDotNormal


D3DXPlaneDotNormal

Computes the dot-product of a plane and a 3-D vector. The w parameter of the vector is assumed to be 0.

FLOAT D3DXPlaneDotNormal(
  CONST D3DXPLANE* pP,
  CONST D3DXVECTOR3* pV
);

Parameters

pP
[in] Pointer to a source D3DXPLANE structure.
pV
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

The dot-product of the plane and 3-D vector.

Remarks

Given a plane (a, b, c, d) and a 3-D vector (x, y, z) the return value of this function is a*x + b*y + c*z + d*0. The D3DXPlaneDotNormal function is useful for calculating the angle between the normal of the plane, and another normal.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXPlaneDot, D3DXPlaneDotCoord


D3DXPlaneFromPointNormal

Constructs a plane from a point and a normal.

D3DXPLANE* D3DXPlaneFromPointNormal(
  D3DXPLANE* pOut,
  CONST D3DXVECTOR3* pPoint,
  CONST D3DXVECTOR3* pNormal
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pPoint
[in] Pointer to a D3DXVECTOR3 structure, defining the point used to construct the plane.
pNormal
[in] Pointer to a D3DXVECTOR3 structure, defining the normal used to construct the plane.

Return Values

Pointer to the D3DXPLANE structure constructed from the point and the normal.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPointNormal function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXPlaneFromPoints


D3DXPlaneFromPoints

Constructs a plane from three points.

D3DXPLANE* D3DXPlaneFromPoints(
  D3DXPLANE* pOut,
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pV2,
  CONST D3DXVECTOR3* pV3
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pV1
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.
pV2
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.
pV3
[in] Pointer to a D3DXVECTOR3 structure, defining one of the points used to construct the plane.

Return Values

Pointer to the D3DXPLANE structure constructed from the given points.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneFromPoints function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXPlaneFromPointNormal


D3DXPlaneIntersectLine

Finds the intersection between a plane and a line.

D3DXVECTOR3* D3DXPlaneIntersectLine(
  D3DXVECTOR3* pOut,
  CONST D3DXPLANE* pP,
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pV2
);

Parameters

pOut
[in, out] Pointer to a D3DXVECTOR3 structure, identifying the intersection between the specified plane and line.
pP
[in] Pointer to the source D3DXPLANE structure.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, defining a line starting point.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, defining a line ending point.

Return Values

Pointer to a D3DXVECTOR3 structure that is the intersection between the specified plane and line.

Remarks

If the line is parallel to the plane, NULL is returned.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneIntersectLine function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXPlaneNormalize

Returns the normal of a plane.

D3DXPLANE* D3DXPlaneNormalize(
  D3DXPLANE* pOut,
  CONST D3DXPLANE* pP
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pP
[in] Pointer to the source D3DXPLANE structure.

Return Values

Pointer to a D3DXPLANE structure, representing the normal of the plane.

Remarks

D3DXPlaneNormalize normalizes a plane so that |a,b,c| == 1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneNormalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXPlaneTransform

Transforms a plane by a given matrix.

D3DXPLANE* D3DXPlaneTransform(
  D3DXPLANE* pOut,
  CONST D3DXPLANE* pP,
  CONST D3DXMATRIX* pM
);

Parameters

pOut
[in, out] Pointer to the D3DXPLANE structure that is the result of the operation.
pP
[in] Pointer to the source D3DXPLANE structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXPLANE structure, representing the transformed plane.

Remarks

The matrix, pM, must be an affine transform.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXPlaneTransform function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXQuaternionBaryCentric

Returns a quaternion in Barycentric coordinates.

D3DXQUATERNION* D3DXQuaternionBaryCentric(
  D3DXQUATERNION* pOut,
  CONST D3DXQUATERNION* pQ1,
  CONST D3DXQUATERNION* pQ2,
  CONST D3DXQUATERNION* pQ3,
  CONST D3DXQUATERNION* pQ4,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.
pQ3
[in] Pointer to a source D3DXQUATERNION structure.
pQ4
[in] Pointer to a source D3DXQUATERNION structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXQUATERNION structure in Barycentric coordinates.

Remarks

To compute the Barycentric coordinates, the D3DXQuaternionBaryCentric function implements the following series of spherical linear interpolation operations: Slerp(Slerp(Q1, Q2, f+g), Slerp(Q1, Q3, f+g), g/(f+g))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionBaryCentric function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXQuaternionConjugate

Returns the conjugate of a quaternion.

D3DXQUATERNION* D3DXQuaternionConjugate(
  D3DXQUATERNION* pOut,
  CONST D3DXQUATERNION* pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the conjugate of the quaternion.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionConjugate function will return the quaternion (-x, -y, -z, w).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionConjugate function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionInverse


D3DXQuaternionDot

Returns the dot-product of two quaternions.

FLOAT D3DXQuaternionDot(
  D3DXQUATERNION* pQ1,
  CONST D3DXQUATERNION* pQ2
);

Parameters

pQ1
[out] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.

Return Values

The dot-product of two quaternions.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXQuaternionExp

Calculates the exponential.

D3DXQUATERNION* D3DXQuaternionExp(
  D3DXQUATERNION* pOut,
  CONST D3DXQUATERNION* pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the exponential.

Remarks

The D3DXQuaternionExp function works only with pure quaternions, where w == 0.

This function is implemented in the following manner.

q = (0, theta * v)
exp(q) = (cos(theta), sin(theta) * v)

The D3DXQuaternionExp and D3DXQuaternionLn functions are useful when using the D3DXQuaternionSquad function. Given a set of quaternion keys (q0, q1, q2, ..., qn), you can compute the inner quadrangle points (a1, a2, a3, ..., an-1) as shown in the following example, to insure that the tangents are continuous across adjacent segments.

        a1    a2    a3
  q0    q1    q2    q3    q4

a[i] = q[i] * exp( -(ln(inv(q[i])*q[i+1]) + ln(inv(q[i])*q[i-1])) / 4 )

Once (a1, a2, a3, ...) are computed, you can use the results to interpolate along the curve.

qt = Squad(t, q[i], a[i], a[i+1], q[i+1])

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionExp function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionLn, D3DXQuaternionSquad


D3DXQuaternionIdentity

Returns the identity quaternion.

D3DXQUATERNION* D3DXQuaternionIdentity(
  D3DXQUATERNION* pOut
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.

Return Values

Pointer to the D3DXQUATERNION structure that is the identity quaternion.

Remarks

Given a quaternion (x, y, z, w), the D3DXQuaternionIdentity function will return the quaternion (0, 0, 0, 1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionIdentity function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionIsIdentity


D3DXQuaternionInverse

Conjugates and renormalizes a quaternion.

D3DXQUATERNION* D3DXQuaternionInverse(
  D3DXQUATERNION* pOut,
  CONST D3DXQUATERNION* pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the inverse quaternion of the quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionInverse function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionConjugate, D3DXQuaternionNormalize


D3DXQuaternionIsIdentity

Determines if a quaternion is an identity quaternion.

BOOL D3DXQuaternionIsIdentity(
  CONST D3DXQUATERNION* pQ
);

Parameters

pQ
[in] Pointer to the D3DXQUATERNION structure that will be tested for identity.

Return Values

If the quaternion is an identity quaternion, this function returns TRUE. Otherwise, this function returns FALSE.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionIdentity


D3DXQuaternionLength

Returns the length of a quaternion.

FLOAT D3DXQuaternionLength(
  CONST D3DXQUATERNION* pQ
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

The quaternion's length.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionLengthSq


D3DXQuaternionLengthSq

Returns the square of the length of a quaternion.

FLOAT D3DXQuaternionLengthSq(
  CONST D3DXQUATERNION* pQ
);

Parameters

pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

The quaternion's squared length.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionLength


D3DXQuaternionLn

Calculates the natural logarithm.

D3DXQUATERNION* D3DXQuaternionLn(
  D3DXQUATERNION* pOut,
  CONST D3DXQUATERNION* pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the natural logarithm.

Remarks

The D3DXQuaternionLn function works only for unit quaternions.

This function is implemented in the following manner.

q = (cos(theta), sin(theta) * v)
|v| = 1
ln(q) = (0, theta * v)

The D3DXQuaternionExp and D3DXQuaternionLn functions are useful when using the D3DXQuaternionSquad function. Given a set of quaternion keys (q0, q1, q2, ..., qn), you can compute the inner quadrangle points (a1, a2, a3, ..., an-1) to insure that the tangents are continuous across adjacent segments.

        a1    a2    a3
  q0    q1    q2    q3    q4

a[i] = q[i] * exp( -(ln(inv(q[i])*q[i+1]) + ln(inv(q[i])*q[i-1])) / 4 )

Once (a1, a2, a3, ...) are computed, you can use the results to interpolate along the curve.

qt = Squad(t, q[i], a[i], a[i+1], q[i+1])

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionLn function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionExp, D3DXQuaternionSquad


D3DXQuaternionMultiply

Multiplies two quaternions.

D3DXQUATERNION* D3DXQuaternionMultiply(
  D3DXQUATERNION* pOut,
  CONST D3DXQUATERNION* pQ1,
  CONST D3DXQUATERNION* pQ2
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the product of two quaternions.

Remarks

The result represents the rotation Q2 followed by the rotation Q1 (Out = Q2 * Q1). The output is actually Q2*Q1 (not Q1*Q2). This is done so that D3DXQuaternionMultiply maintain the same semantics as D3DXMatrixMultiply because unit quaternions can be considered as another way to represent rotation matrices.

Transformations are concatenated in the same order for both the D3DXQuaternionMultiply and D3DXMatrixMultiply functions. For example, assuming mX and mY represent the same rotations as qX and qY, both m and q will represent the same rotations.

D3DXMatrixMultiply(&m, &mX, &mY);

D3DXQuaternionMultiply(&q, &qX, &qY);

The multiplication of quaternions is not commutative.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionMultiply function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXMatrixMultiply


D3DXQuaternionNormalize

Returns the normal of a quaternion.

D3DXQUATERNION* D3DXQuaternionNormalize(
  D3DXQUATERNION* pOut,
  CONST D3DXQUATERNION* pQ
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ
[in] Pointer to the source D3DXQUATERNION structure.

Return Values

Pointer to a D3DXQUATERNION structure that is the normal of the quaternion.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionNormalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionInverse


D3DXQuaternionRotationAxis

Rotates a quaternion about an arbitrary axis.

D3DXQUATERNION* D3DXQuaternionRotationAxis(
  D3DXQUATERNION* pOut,
  CONST D3DXVECTOR3* pV,
  FLOAT Angle
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pV
[in] Pointer to the D3DXVECTOR3 structure that identifies the axis angle.
Angle
[in] Angle of rotation, in radians. Angles are measured clockwise when looking along the rotation axis toward the origin.

Return Values

Pointer to a D3DXQUATERNION structure rotated around the specified axis.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationAxis function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionRotationMatrix, D3DXQuaternionRotationYawPitchRoll


D3DXQuaternionRotationMatrix

Builds a quaternion from a rotation matrix.

D3DXQUATERNION* D3DXQuaternionRotationMatrix(
  D3DXQUATERNION* pOut,
  CONST D3DXMATRIX* pM
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to the D3DXQUATERNION structure built from a rotation matrix.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationMatrix function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationYawPitchRoll


D3DXQuaternionRotationYawPitchRoll

Builds a quaternion with the given yaw, pitch, and roll.

D3DXQUATERNION* D3DXQuaternionRotationYawPitchRoll(
  D3DXQUATERNION* pOut,
  FLOAT Yaw,
  FLOAT Pitch,
  FLOAT Roll
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
Yaw
[in] Yaw around the y-axis, in radians.
Pitch
[in] Pitch around the x-axis, in radians.
Roll
[in] Roll around the z-axis, in radians.

Return Values

Pointer to a D3DXQUATERNION structure with the specified yaw, pitch, and roll.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionRotationYawPitchRoll function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionRotationAxis, D3DXQuaternionRotationMatrix


D3DXQuaternionSlerp

Interpolates between two quaternions, using spherical linear interpolation.

D3DXQUATERNION* D3DXQuaternionSlerp(
  D3DXQUATERNION* pOut,
  CONST D3DXQUATERNION* pQ1,
  CONST D3DXQUATERNION* pQ2,
  FLOAT t
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.
t
[in] Parameter that indicates how far to interpolate between the quaternions.

Return Values

Pointer to a D3DXQUATERNION structure that is the result of the interpolation.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSlerp function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXQuaternionSquad

Interpolates between quaternions, using spherical quadrangle interpolation.

D3DXQUATERNION* D3DXQuaternionSquad(
  D3DXQUATERNION* pOut,
  CONST D3DXQUATERNION* pQ1,
  CONST D3DXQUATERNION* pQ2,
  CONST D3DXQUATERNION* pQ3,
  CONST D3DXQUATERNION* pQ4,
  FLOAT t
);

Parameters

pOut
[in, out] Pointer to the D3DXQUATERNION structure that is the result of the operation.
pQ1
[in] Pointer to a source D3DXQUATERNION structure.
pQ2
[in] Pointer to a source D3DXQUATERNION structure.
pQ3
[in] Pointer to a source D3DXQUATERNION structure.
pQ4
[in] Pointer to a source D3DXQUATERNION structure.
t
[in] Parameter that indicates how far to interpolate between the quaternions.

Return Values

Pointer to a D3DXQUATERNION structure that is the result of the spherical quadrangle interpolation.

Remarks

This function uses the following sequence of spherical linear interpolation operations: Slerp(Slerp(Q1, Q4, t), Slerp(Q2, Q3, t), 2t(1-t))

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXQuaternionSquad function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXQuaternionExp, D3DXQuaternionLn


D3DXQuaternionToAxisAngle

Computes a quaternion's axis and angle of rotation.

void D3DXQuaternionToAxisAngle(
  CONST D3DXQUATERNION* pQ,
  D3DXVECTOR3* pAxis,
  FLOAT* pAngle
);

Parameters

pQ
[in, out] Pointer to the source D3DXQUATERNION structure.
pAxis
[in, out] When this function returns, pointer to a D3DXVECTOR3 structure that identifies the quaternion's axis.
pAngle
[in, out] When this function returns, pointer to a FLOAT value that identifies the quaternion's angle of rotation in radians.

Return Values

None.

Remarks

This function expects unit quaternions.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec2Add

Adds two 2-D vectors.

D3DXVECTOR2* D3DXVec2Add(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV1,
  CONST D3DXVECTOR2* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the sum of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Add function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2Subtract, D3DXVec2Scale


D3DXVec2BaryCentric

Returns a point in Barycentric coordinates, using the specified 2-D vectors.

D3DXVECTOR2* D3DXVec2BaryCentric(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV1,
  CONST D3DXVECTOR2* pV2,
  D3DXVECTOR2* pV3,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.
pV3
[in] Pointer to a source D3DXVECTOR2 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR2 structure in Barycentric coordinates.

Remarks

The D3DXVec2BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result, and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates simply represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2BaryCentric function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec2CatmullRom

Performs a Catmull-Rom interpolation, using the specified 2-D vectors.

D3DXVECTOR2* D3DXVec2CatmullRom(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV1,
  CONST D3DXVECTOR2* pV2,
  CONST D3DXVECTOR2* pV3,
  CONST D3DXVECTOR2* pV4,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pV4
[[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR2 structure that is the result of the Catmull-Rom interpolation.

Remarks

The D3DXVec2CatmullRom function interpolates between the position V1 when s is equal to 0, and between the position V2 when s is equal to 1, using Catmull-Rom interpolation.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec2CCW

Returns the z-component by taking the cross product of two 2-D vectors.

FLOAT D3DXVec2CCW(
  CONST D3DXVECTOR2* pV1,
  CONST D3DXVECTOR2* pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

The z-component.

Remarks

This function determines the z-component by determining the cross-product based on the following formula: ((x1,y1,0) cross (x2,y2,0)). Or as shown in the following example.

pV1->x * pV2->y - pV1->y * pV2->x

If the value of the z-component is positive, the vector V2 is counter-clockwise from the vector V1. This information is useful for back-face culling.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2Dot


D3DXVec2Dot

Determines the dot-product of two 2-D vectors.

FLOAT D3DXVec2Dot(
  CONST D3DXVECTOR2* pV1,
  CONST D3DXVECTOR2* pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

The dot-product.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2CCW


D3DXVec2Hermite

Performs a Hermite spline interpolation, using the specified 2-D vectors.

D3DXVECTOR2* D3DXVec2Hermite(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV1,
  CONST D3DXVECTOR2* pT1,
  CONST D3DXVECTOR2* pV2,
  CONST D3DXVECTOR2* pT2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR2 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR2 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR2 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR2 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec2Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation. This function interpolates between the position V1 and the tangent T1, when s is equal to 0, and between the position V2 and the tangent T2, when s is equal to 1.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Hermite function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec2Length

Returns the length of a 2-D vector.

FLOAT D3DXVec2Length(
  CONST D3DXVECTOR2* pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Values

The vector's length.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2LengthSq


D3DXVec2LengthSq

Returns the square of the length of a 2-D vector.

FLOAT D3DXVec2LengthSq(
  CONST D3DXVECTOR2* pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Values

The vector's squared length.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2Length


D3DXVec2Lerp

Performs a linear interpolation between two 2-D vectors.

D3DXVECTOR2* D3DXVec2Lerp(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV1,
  CONST D3DXVECTOR2* pV2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Values

Pointer to a D3DXVECTOR2 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Lerp function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec2Maximize

Returns a 2-D vector that is made up of the largest components of two 2-D vectors.

D3DXVECTOR2* D3DXVec2Maximize(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV1,
  CONST D3DXVECTOR2* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Maximize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2Minimize


D3DXVec2Minimize

Returns a 2-D vector that is made up of the smallest components of two 2-D vectors.

D3DXVECTOR2* D3DXVec2Minimize(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV1,
  CONST D3DXVECTOR2* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Minimize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2Maximize


D3DXVec2Normalize

Returns the normalized version of a 2-D vector.

D3DXVECTOR2* D3DXVec2Normalize(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the normalized version of the vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Normalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec2Scale

Scales a 2-D vector.

D3DXVECTOR2* D3DXVec2Scale(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
s
[in] Scaling value.

Return Values

Pointer to a D3DXVECTOR2 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Scale function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2Add, D3DXVec2Subtract


D3DXVec2Subtract

Subtracts two 2-D vectors.

D3DXVECTOR2* D3DXVec2Subtract(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV1,
  CONST D3DXVECTOR2* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR2 structure.
pV2
[in] Pointer to a source D3DXVECTOR2 structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Subtract function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2Add, D3DXVec2Scale


D3DXVec2Transform

Transforms a 2-D vector by a given matrix.

D3DXVECTOR4* D3DXVec2Transform(
  D3DXVECTOR4** pOut,
  CONST D3DXVECTOR2* pV,
  CONST D3DXMATRIX* pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, 0, 1), by the matrix, pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2Transform function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2TransformCoord, D3DXVec2TransformNormal


D3DXVec2TransformCoord

Transforms a 2-D vector by a given matrix, projecting the result back into w = 1.

D3DXVECTOR2* D3DXVec2TransformCoord(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV,
  CONST D3DXMATRIX* pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, 0, 1), by the matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformCoord function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2Transform, D3DXVec2TransformNormal


D3DXVec2TransformNormal

Transforms the 2-D vector normal by the given matrix.

D3DXVECTOR2* D3DXVec2TransformNormal(
  D3DXVECTOR2* pOut,
  CONST D3DXVECTOR2* pV,
  CONST D3DXMATRIX* pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR2 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR2 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR2 structure that is the transformed vector.

Remarks

This function transforms the vector normal (x, y, 0, 0) of the vector, pV, by the matrix, pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec2TransformNormal function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec2Transform, D3DXVec2TransformCoord


D3DXVec3Add

Adds two 3-D vectors.

D3DXVECTOR3* D3DXVec3Add(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the sum of the two 3-D vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Add function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Subtract, D3DXVec3Scale


D3DXVec3BaryCentric

Returns a point in Barycentric coordinates, using the specified 3-D vectors.

D3DXVECTOR3* D3DXVec3BaryCentric(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pV2,
  D3DXVECTOR3* pV3,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.
pV3
[in] Pointer to a source D3DXVECTOR3 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR3 structure in Barycentric coordinates.

Remarks

The D3DXVec3BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates simply represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3BaryCentric function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec3CatmullRom

Performs a Catmull-Rom interpolation, using the specified 3-D vectors.

D3DXVECTOR3* D3DXVec3CatmullRom(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pV2,
  CONST D3DXVECTOR3* pV3,
  CONST D3DXVECTOR3* pV4,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pV4
[[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR3 structure that is the result of the Catmull-Rom interpolation.

Remarks

The D3DXVec3CatmullRom function interpolates between the position V1 when s is equal to 0, and between the position V2 when s is equal to 1, using Catmull-Rom interpolation.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec3Cross

Determines the cross-product of two 3-D vectors.

D3DXVECTOR3* D3DXVec3Cross(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the cross product of two 3-D vectors.

Remarks

This function determines the cross-product with the following code.

    D3DXVECTOR3 v;

    v.x = pV1->y * pV2->z - pV1->z * pV2->y;
    v.y = pV1->z * pV2->x - pV1->x * pV2->z;
    v.z = pV1->x * pV2->y - pV1->y * pV2->x;

    *pOut = v;

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Cross function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Dot


D3DXVec3Dot

Determines the dot-product of two 3-D vectors.

FLOAT D3DXVec3Dot(
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

The dot-product.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Cross


D3DXVec3Hermite

Performs a Hermite spline interpolation, using the specified 3-D vectors.

D3DXVECTOR3* D3DXVec3Hermite(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pT1,
  CONST D3DXVECTOR3* pV2,
  CONST D3DXVECTOR3* pT2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR3 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR3 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR3 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR3 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec3Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation. This function interpolates between the position V1 and the tangent T1, when s is equal to zero, and between the position V2 and the tangent T2, when s is equal to one.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Hermite function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec3Length

Returns the length of a 3-D vector.

FLOAT D3DXVec3Length(
  CONST D3DXVECTOR3* pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Values

The vector's length.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3LengthSq


D3DXVec3LengthSq

Returns the square of the length of a 3-D vector.

FLOAT D3DXVec3LengthSq(
  CONST D3DXVECTOR3* pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Values

The vector's squared length.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Length


D3DXVec3Lerp

Performs a linear interpolation between two 3-D vectors.

D3DXVECTOR3* D3DXVec3Lerp(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pV2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Values

Pointer to a D3DXVECTOR3 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Lerp function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec3Maximize

Returns a 3-D vector that is made up of the largest components of two 3-D vectors.

D3DXVECTOR3* D3DXVec3Maximize(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Maximize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Minimize


D3DXVec3Minimize

Returns a 3-D vector that is made up of the smallest components of two 3-D vectors.

D3DXVECTOR3* D3DXVec3Minimize(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Minimize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Maximize


D3DXVec3Normalize

Returns the normalized version of a 3-D vector.

D3DXVECTOR3* D3DXVec3Normalize(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the normalized version of the specified vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Normalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec3Project

Projects a vector from object space into screen space.

D3DXVECTOR3* D3DXVec3Project(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV
  CONST D3DVIEWPORT8* pViewport,
  CONST D3DXMATRIX* pProjection
  CONST D3DXMATRIX* pView,
  CONST D3DXMATRIX* pWorld
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pViewport
[in] Pointer to a D3DVIEWPORT8 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.

Return Values

Pointer to a D3DXVECTOR3 structure that is the vector projected from object space to screen space.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Project function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Unproject


D3DXVec3Scale

Scales a 3-D vector.

D3DXVECTOR3* D3DXVec3Scale(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
s
[in] Scaling value.

Return Values

Pointer to a D3DXVECTOR3 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Scale function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Add, D3DXVec3Subtract


D3DXVec3Subtract

Subtracts two 3-D vectors.

D3DXVECTOR3* D3DXVec3Subtract(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV1,
  CONST D3DXVECTOR3* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR3 structure.
pV2
[in] Pointer to a source D3DXVECTOR3 structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Subtract function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Add, D3DXVec3Scale


D3DXVec3Transform

Transforms a 3-D vector by a given matrix.

D3DXVECTOR4* D3DXVec3Transform(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR3* pV,
  CONST D3DXMATRIX* pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix, pM.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Transform function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3TransformCoord, D3DXVec3TransformNormal


D3DXVec3TransformCoord

Transforms a 3-D vector by a given matrix, projecting the result back into w = 1.

D3DXVECTOR3* D3DXVec3TransformCoord(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV,
  CONST D3DXMATRIX* pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector, pV (x, y, z, 1), by the matrix, pM, projecting the result back into w=1.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformCoord function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Transform, D3DXVec3TransformNormal


D3DXVec3TransformNormal

Transforms the 3-D vector normal by the given matrix.

D3DXVECTOR3* D3DXVec3TransformNormal(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV,
  CONST D3DXMATRIX* pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR3 structure that is the transformed vector.

Remarks

This function transforms the vector normal (x, y, z, 0) of the vector, pV, by the matrix, pM.

If you transform a normal by a non-affine matrix, the matrix you pass to this function should be the transpose of the inverse of the matrix you would use to transform a coordinate.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3TransformNormal function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec3Unproject

Projects a vector from screen space into object space.

D3DXVECTOR3* D3DXVec3Unproject(
  D3DXVECTOR3* pOut,
  CONST D3DXVECTOR3* pV
  CONST D3DVIEWPORT8* pViewport,
  CONST D3DXMATRIX* pProjection
  CONST D3DXMATRIX* pView,
  CONST D3DXMATRIX* pWorld
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR3 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR3 structure.
pViewport
[in] Pointer to a D3DVIEWPORT8 structure, representing the viewport.
pProjection
[in] Pointer to a D3DXMATRIX structure, representing the projection matrix.
pView
[in] Pointer to a D3DXMATRIX structure, representing the view matrix.
pWorld
[in] Pointer to a D3DXMATRIX structure, representing the world matrix.

Return Values

Pointer to a D3DXVECTOR3 structure that is the vector projected from screen space to screen object.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec3Unproject function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Project


D3DXVec4Add

Adds two 4-D vectors.

D3DXVECTOR4* D3DXVec4Add(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV1,
  CONST D3DXVECTOR4* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the sum of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Add function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec4Subtract, D3DXVec4Scale


D3DXVec4BaryCentric

Returns a point in Barycentric coordinates, using the specified 4-D vectors.

D3DXVECTOR4* D3DXVec4BaryCentric(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV1,
  CONST D3DXVECTOR4* pV2,
  CONST D3DXVECTOR4* pV3,
  FLOAT f,
  FLOAT g
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
pV3
[in] Pointer to a source D3DXVECTOR4 structure.
f
[in] Weighting factor. See Remarks.
g
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR4 structure in Barycentric coordinates.

Remarks

The D3DXVec4BaryCentric function provides a way to understand points in and around a triangle, independent of where the triangle is actually located. This function returns the resulting point by using the following equation: V1 + f(V2-V1) + g(V3-V1).

Any point in the plane V1V2V3 can be represented by the Barycentric coordinate (f,g).The parameter f controls how much V2 gets weighted into the result and the parameter g controls how much V3 gets weighted into the result. Lastly, 1-f-g controls how much V1 gets weighted into the result.

Note the following relations.

  • If (f>=0 && g>=0 && 1-f-g>=0), the point is inside the triangle V1V2V3.
  • If (f==0 && g>=0 && 1-f-g>=0), the point is on the line V1V3.
  • If (f>=0 && g==0 && 1-f-g>=0), the point is on the line V1V2.
  • If (f>=0 && g>=0 && 1-f-g==0), the point is on the line V2V3.

Barycentric coordinates are a form of general coordinates. In this context, using Barycentric coordinates simply represents a change in coordinate systems. What holds true for Cartesian coordinates holds true for Barycentric coordinates.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4BaryCentric function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec4CatmullRom

Performs a Catmull-Rom interpolation, using the specified 4-D vectors.

D3DXVECTOR4* D3DXVec4CatmullRom(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV1,
  CONST D3DXVECTOR4* pV2,
  CONST D3DXVECTOR4* pV3,
  CONST D3DXVECTOR4* pV4,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV2
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV3
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pV4
[[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR4 structure that is the result of the Catmull-Rom interpolation.

Remarks

The D3DXVec4CatmullRom function interpolates between the position V1 when s is equal to 0, and between the position V2 when s is equal to 1, using Catmull-Rom interpolation.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec4Cross

Determines the cross-product in four dimensions.

D3DXVECTOR4* D3DXVec4Cross(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV1,
  CONST D3DXVECTOR4* pV2,
  CONST D3DXVECTOR4* pV3
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
pV3
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the cross product.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Cross function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec4Dot


D3DXVec4Dot

Determines the dot-product of two 4-D vectors.

FLOAT D3DXVec4Dot(
  CONST D3DXVECTOR4* pV1,
  CONST D3DXVECTOR4* pV2
);

Parameters

pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

The dot-product.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec4Cross


D3DXVec4Hermite

Performs a Hermite spline interpolation, using the specified 4-D vectors.

D3DXVECTOR4* D3DXVec4Hermite(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV1,
  CONST D3DXVECTOR4* pT1,
  CONST D3DXVECTOR4* pV2,
  CONST D3DXVECTOR4* pT2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pT1
[in] Pointer to a source D3DXVECTOR4 structure, a tangent vector.
pV2
[in] Pointer to a source D3DXVECTOR4 structure, a position vector.
pT2
[in] Pointer to a source D3DXVECTOR4 structure, a tangent vector.
s
[in] Weighting factor. See Remarks.

Return Values

Pointer to a D3DXVECTOR4 structure that is the result of the Hermite spline interpolation.

Remarks

The D3DXVec4Hermite function interpolates from (positionA, tangentA) to (positionB, tangentB) using Hermite spline interpolation. This function interpolates between the position V1 and the tangent T1, when s is equal to zero, and between the position V2 and the tangent T2, when s is equal to one.

Hermite splines are useful for controlling animation because the curve runs through all the control points. Also, because the position and tangent are explicitly specified at the ends of each segment, it is easy to create a C2 continuous curve as long as you make sure that your starting position and tangent match the ending values of the last segment.

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Hermite function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec4Length

Returns the length of a 4-D vector.

FLOAT D3DXVec4Length(
  CONST D3DXVECTOR4* pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Values

The vector's length.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec4LengthSq


D3DXVec4LengthSq

Returns the square of the length of a 4-D vector.

FLOAT D3DXVec4LengthSq(
  CONST D3DXVECTOR4* pV
);

Parameters

pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Values

The vector's squared length.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec4Length


D3DXVec4Lerp

Performs a linear interpolation between two 4-D vectors.

D3DXVECTOR4* D3DXVec4Lerp(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV1,
  CONST D3DXVECTOR4* pV2,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.
s
[in] Parameter that linearly interpolates between the vectors.

Return Values

Pointer to a D3DXVECTOR4 structure that is the result of the linear interpolation.

Remarks

This function performs the linear interpolation based on the following formula: V1 + s(V2-V1).

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Lerp function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec4Maximize

Returns a 4-D vector that is made up of the largest components of two 4-D vectors.

D3DXVECTOR4* D3DXVec4Maximize(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV1,
  CONST D3DXVECTOR4* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is made up of the largest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Maximize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec4Minimize


D3DXVec4Minimize

Returns a 4-D vector that is made up of the smallest components of two 4-D vectors.

D3DXVECTOR4* D3DXVec4Minimize(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV1,
  CONST D3DXVECTOR4* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is made up of the smallest components of the two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Minimize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec4Maximize


D3DXVec4Normalize

Returns the normalized version of a 4-D vector.

D3DXVECTOR4* D3DXVec4Normalize(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the normalized version of the vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Normalize function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


D3DXVec4Scale

Scales a 4-D vector.

D3DXVECTOR4* D3DXVec4Scale(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV,
  FLOAT s
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.
s
[in] Scaling value.

Return Values

Pointer to the D3DXVECTOR4 structure that is the scaled vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Scale function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec4Add, D3DXVec4Subtract


D3DXVec4Subtract

Subtracts two 4-D vectors.

D3DXVECTOR4* D3DXVec4Subtract(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV1,
  CONST D3DXVECTOR4* pV2
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV1
[in] Pointer to a source D3DXVECTOR4 structure.
pV2
[in] Pointer to a source D3DXVECTOR4 structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the difference of two vectors.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Subtract function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.

See Also

D3DXVec3Add, D3DXVec3Scale


D3DXVec4Transform

Transforms a 4-D vector by a given matrix.

D3DXVECTOR4* D3DXVec4Transform(
  D3DXVECTOR4* pOut,
  CONST D3DXVECTOR4* pV,
  CONST D3DXMATRIX* pM
);

Parameters

pOut
[in, out] Pointer to the D3DXVECTOR4 structure that is the result of the operation.
pV
[in] Pointer to the source D3DXVECTOR4 structure.
pM
[in] Pointer to the source D3DXMATRIX structure.

Return Values

Pointer to a D3DXVECTOR4 structure that is the transformed 4-D vector.

Remarks

The return value for this function is the same value returned in the pOut parameter. In this way, the D3DXVec4Transform function can be used as a parameter for another function.

Requirements

Header: Declared in D3dx8math.h.
Import Library: Use D3dx8.lib.


Mesh Functions

Direct3DX supplies the following mesh functions.

  • D3DXBoxBoundProbe
  • D3DXCleanMesh
  • D3DXComputeBoundingBox
  • D3DXComputeBoundingSphere
  • D3DXComputeNormals
  • D3DXCreateBuffer
  • D3DXCreateMesh
  • D3DXCreateMeshFVF
  • D3DXCreatePMeshFromStream
  • D3DXCreateSkinMesh
  • D3DXCreateSkinMeshFromMesh
  • D3DXCreateSkinMeshFVF
  • D3DXCreateSPMesh
  • D3DXDeclaratorFromFVF
  • D3DXFVFFromDeclarator
  • D3DXGeneratePMesh
  • D3DXIntersect
  • D3DXLoadMeshFromX
  • D3DXLoadMeshFromXof
  • D3DXLoadSkinMeshFromXof
  • D3DXSaveMeshToX
  • D3DXSimplifyMesh
  • D3DXSphereBoundProbe
  • D3DXTesselateMesh
  • D3DXValidMesh
  • D3DXWeldVertices


D3DXBoxBoundProbe

Determines if a ray intersects the volume of a box's bounding box.

BOOL D3DXBoxBoundProbe(
  CONST D3DXVECTOR3* pMin,
  CONST D3DXVECTOR3* pMax,
  D3DXVECTOR3* pRayPosition,
  D3DXVECTOR3* pRayDirection
);

Parameters

pMin
[out] Pointer to a D3DXVECTOR3 structure, describing the lower-left corner of the bounding box. See Remarks.
pMax
[out] Pointer to a D3DXVECTOR3 structure, describing the upper-right corner of the bounding box. See Remarks.
pRayPosition
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDirection
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.

Return Values

Returns TRUE if the ray intersects the volume of the box's bounding box. Otherwise, returns FALSE.

Remarks

D3DXBoxBoundProbe determines if the ray intersects the volume of the box's bounding box, not just the surface of the box.

The D3DXVECTOR3 values passed to D3DXBoxBoundProbe are xmin, xmax, ymin, ymax, zmin, and zmax. Thus, the following defines the corners of the bounding box.

xmax, ymax, zmax
xmax, ymax, zmin
xmax, ymin, zmax
xmax, ymin, zmin
xmin, ymax, zmax
xmin, ymax, zmin
xmin, ymin, zmax
xmin, ymin, zmin

The depth of the bounding box in the z direction is zmax - zmin, in the y direction is ymax - ymin, and in the x direction is xmax - xmin. For example, with the following minimum and maximum vectors, min (-1, -1, -1) and max (1, 1, 1), the bounding box is defined in the following manner.

 1,  1,  1
 1,  1, -1
 1, -1,  1
 1, -1, -1
-1,  1,  1
-1,  1, -1
-1, -1,  1
-1, -1, -1

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

D3DXComputeBoundingBox


D3DXCleanMesh

Cleans a mesh, preparing it for simplification.

HRESULT D3DXCleanMesh(
  LPD3DXMESH pMeshIn,
  CONST DWORD* pAdjacency,
  LPD3DXMESH* ppMeshOut
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to be cleaned.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be cleaned.
ppMeshOut
[out] An address of a pointer to an ID3DXMesh interface, representing the returned cleaned mesh. The same mesh is returned that was passed in if no cleaning was necessary.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

This method cleans the mesh by adding another vertex where two fans of triangles share the same vertex.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXComputeBoundingBox

Computes a bounding box.

HRESULT D3DXComputeBoundingBox(
  PVOID pPointsFVF,
  DWORD NumVertices,
  DWORD FVF,
  D3DXVECTOR3* pMin,
  D3DXVECTOR3* pMax
);

Parameters

pPointsFVF
[in] Pointer to a buffer containing the vertex data around which to calculate the bounding box.
NumVertices
[in] Number of vertices.
FVF
[in] Combination of flexible vertex format flags that describes the vertex format.
pMin
[out] Pointer to a D3DXVECTOR3 structure, describing the returned lower-left corner of the bounding box. See remarks.
pMax
[out] Pointer to a D3DXVECTOR3 structure, describing the returned upper-right corner of the bounding box. See remarks.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one D3DERR_INVALIDCALL.

Remarks

The D3DXVECTOR3 values returned by D3DXComputeBoundingBox are xmin, xmax, ymin, ymax, zmin, and zmax. Thus, the following defines the corners of the bounding box.

xmax, ymax, zmax
xmax, ymax, zmin
xmax, ymin, zmax
xmax, ymin, zmin
xmin, ymax, zmax
xmin, ymax, zmin
xmin, ymin, zmax
xmin, ymin, zmin

The depth of the bounding box in the z direction is zmax - zmin, in the y direction is ymax - ymin, and in the x direction is xmax - xmin. For example, with the following minimum and maximum vectors, min (-1, -1, -1) and max (1, 1, 1), the bounding box is defined in the following manner.

 1,  1,  1
 1,  1, -1
 1, -1,  1
 1, -1, -1
-1,  1,  1
-1,  1, -1
-1, -1,  1
-1, -1, -1

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXComputeBoundingSphere

Computes a bounding sphere.

HRESULT D3DXComputeBoundingSphere(
  PVOID pvPointsFVF,
  DWORD NumVertices,
  DWORD FVF,
  D3DXVECTOR3* pCenter,
  FLOAT* pRadius
);

Parameters

pvPointsFVF
[in] Pointer to a buffer containing the vertex data around which to calculate the bounding sphere.
NumVertices
[in] Number of vertices.
FVF
[in] Combination of flexible vertex format flags that describes the vertex format.
pCenter
[out] D3DXVECTOR3 structure, defining the coordinate center of the returned bounding sphere.
pRadius
[out] Radius of the returned bounding sphere.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one D3DERR_INVALIDCALL.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXComputeNormals

Computes normals for each vertex in a mesh.

HRESULT D3DXComputeNormals(
  LPD3DXBASEMESH pMesh
);

Parameters

pMesh
[in, out] Pointer to an ID3DXBaseMesh interface, representing the normalized mesh object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one D3DERR_INVALIDCALL.

Note The input mesh must have the D3DFVF_NORMAL flag specified in its FVF.

A normal for a vertex is generated by averaging the normals of all faces that share that vertex.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXCreateBuffer

Creates a buffer object.

HRESULT D3DXCreateBuffer(
  DWORD NumBytes,
  LPD3DXBUFFER* ppBuffer
);

Parameters

NumBytes
[in] Size of the buffer to create, in bytes.
ppBuffer
[out] Address of a pointer to an ID3DXBuffer interface, representing the created buffer object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXCreateMesh

Creates a mesh object using a declarator.

HRESULT D3DXCreateMesh(
  DWORD NumFaces,
  DWORD NumVertices,
  DWORD Options,
  CONST DWORD* pDeclaration,
  LPDIRECT3DDEVICE8 pDevice,
  LPD3DXMESH* ppMesh
);

Parameters

NumFaces
[in] Number of faces for the mesh. This parameter must be greater than 0.
NumVertices
[in] Number of vertices for the mesh. This parameter must be greater than 0.
Options
[in] A combination of one or more flags, specifying options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pDeclaration
[in] Pointer to a DWORD value, representing the declarator that describes the vertex format for the returned mesh. This parameter must map directly to an FVF.
pDevice
[in] Pointer to an IDirect3DDevice8 interface, the device object to be associated with the mesh.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the created mesh object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

D3DXDeclaratorFromFVF


D3DXCreateMeshFVF

Creates a mesh object using a flexible vertex format (FVF) code.

HRESULT D3DXCreateMeshFVF(
  DWORD NumFaces,
  DWORD NumVertices,
  DWORD Options,
  DWORD FVF,
  LPDIRECT3DDEVICE8 pDevice,
  LPD3DXMESH* ppMesh
);

Parameters

NumFaces
[in] Number of faces for the mesh. This parameter must be greater than 0.
NumVertices
[in] Number of vertices for the mesh. This parameter must be greater than 0.
Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
FVF
[in] Combination of flexible vertex format flags that describes the vertex format for the returned mesh.
pDevice
[in] Pointer to an IDirect3DDevice8 interface, the device object to be associated with the mesh.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the created mesh object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

D3DXFVFFromDeclarator


D3DXCreatePMeshFromStream

Creates a progressive mesh from a stream object.

HRESULT D3DXCreatePMeshFromStream(
  IStream* pStream,
  DWORD Options,
  LPDIRECT3DDEVICE8 pD3DDevice,
  LPD3DXBUFFER* ppMaterials,
  DWORD* pNumMaterials,
  LPD3DXPMESH* ppPMesh
);

Parameters

pStream
[in] Pointer to an IStream interface, representing the stream object from which to create the progressive mesh. The data in this stream was generated with the ID3DXPMesh::Save method.
Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pD3DDevice
[in] Pointer to an IDirect3DDevice8 interface, the device object to be associated with the progressive mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of D3DXMATERIAL structures, containing information saved in the stream object.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppPMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the created progressive mesh.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

For more information on the IStream interface, see the Microsoft Platform Software Development Kit (SDK).

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXPMesh::Save


D3DXCreateSkinMesh

Creates an empty skin mesh object using a declarator.

HRESULT D3DXCreateSkinMesh(
  DWORD numFaces,
  DWORD numVertices,
  DWORD numBones,
  DWORD Options,
  CONST DWORD* pDeclaration,
  LPDIRECT3DDEVICE8 pDevice,
  LPD3DXSKINMESH* ppSkinMesh
);

Parameters

numFaces
[in] Number of faces for the skin mesh.
numVertices
[in] Number of vertices for the skin mesh.
numBones
[in] Number of bones for the skin mesh.
Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pDeclaration
[in] Pointer to a DWORD value, representing the declarator that describes the vertex format for the returned skin mesh.
pDevice
[in] Pointer to an IDirect3DDevice8 interface, the device object to be associated with the skin mesh.
ppSkinMesh
[out, retval] Address of a pointer to an ID3DXSkinMesh interface, representing the created skin mesh object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be E_OUTOFMEMORY.

Remarks

Use ID3DXSkinMesh::SetBoneInfluence to populate the empty skin mesh object returned by this method.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::SetBoneInfluence


D3DXCreateSkinMeshFromMesh

Creates a skin mesh from another mesh.

HRESULT D3DXCreateSkinMeshFromMesh(
  LPD3DXMESH pMesh,
  DWORD numBones,
  LPD3DXSKINMESH* ppSkinMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh object, the mesh from which to create the skin mesh.
numBones
[in] Number of bones for the skin mesh.
ppSkinMesh
[out, retval] Address of a pointer to an ID3DXSkinMesh interface, representing the created skin mesh object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXCreateSkinMeshFVF

Creates an empty skin mesh object using a flexible vertex format (FVF) code.

HRESULT D3DXCreateSkinMeshFVF(
  DWORD numFaces,
  DWORD numVertices,
  DWORD numBones,
  DWORD Options,
  DWORD FVF,
  LPDIRECT3DDEVICE8 pDevice,
  LPD3DXSKINMESH* ppSkinMesh
);

Parameters

numFaces
[in] Number of faces for the skin mesh.
numVertices
[in] Number of vertices for the skin mesh.
numBones
[in] Number of bones for the skin mesh.
Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
FVF
[in] Combination of flexible vertex format flags that describes the vertex format for the returned skin mesh.
pDevice
[in] Pointer to an IDirect3DDevice8 interface, the device object to be associated with the skin mesh.
ppSkinMesh
[out, retval] Address of a pointer to an ID3DXSkinMesh interface, representing the created skin mesh object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

Use ID3DXSkinMesh::SetBoneInfluence to populate the empty skin mesh object returned by this method.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

ID3DXSkinMesh::SetBoneInfluence


D3DXCreateSPMesh

Creates a simplification mesh.

HRESULT D3DXCreateSPMesh(
  LPD3DXMESH pMesh,
  CONST DWORD* pAdjacency,
  CONST LPD3DXATTRIBUTEWEIGHTS pVertexAttributeWeights,
  CONST FLOAT* pVertexWeights,
  LPD3DXSPMESH* ppSMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the mesh to simplify.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the created simplification mesh.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0. Note that the higher the vertex weight for a given vertex, the less likely it is to be simplified away.
ppSMesh
[out] Address of a pointer to an ID3DXSPMesh interface, representing the created simplification mesh.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DXERR_CANNOTATTRSORT
D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

A simplification mesh is used to simplify a mesh to a lower number of triangles and faces.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;

AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXDeclaratorFromFVF

Returns a declarator from a flexible vertex format (FVF) code.

HRESULT D3DXDeclaratorFromFVF(
  DWORD FVF,
  DWORD Declaration[MAX_FVF_DECL_SIZE]
);

Parameters

FVF
[in] Combination of flexible vertex format flags that describes the FVF from which to generate the returned declarator array.
Declaration
[out] A returned array describing the vertex format of the vertices in the queried mesh. The upper limit of this declarator array is MAX_FVF_DECL_SIZE, limiting the declarator to a maximum of 15 DWORDs.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one D3DXERR_INVALIDMESH.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also'

D3DXFVFFromDeclarator


D3DXFVFFromDeclarator

Returns a flexible vertex format (FVF) code from a declarator.

HRESULT D3DXFVFFromDeclarator(
  CONST DWORD* pDeclarator,
  DWORD* pFVF
);

Parameters

pDeclarator
[in] Pointer to a DWORD value, representing the declarator from which to generate the FVF code.
pFVF
[out] Pointer to a DWORD value, representing the returned combination of flexible vertex format flags that describes the vertex format returned from the declarator.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Note This function will fail for any declarator that doesn't map directly to an FVF.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.

See Also

D3DXDeclaratorFromFVF


D3DXGeneratePMesh

Generates a progressive mesh.

HRESULT D3DXGeneratePMesh(
  LPD3DXMESH pMesh,
  CONST DWORD* pAdjacency,
  CONST LPD3DXATTRIBUTEWEIGHTS pVertexAttributeWeights,
  CONST FLOAT* pVertexWeights,
  DWORD MinValue,
  DWORD Options,
  LPD3DXPMESH* ppPMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the source mesh.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the created progressive mesh.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0. Note that the higher the vertex weight for a given vertex, the less likely it is to be simplified away.
MinValue
[in] Number of vertices or faces, depending on the flag set in the Options parameter, by which to simplify the source mesh.
Options
[in] Specifies simplification options for the mesh. One of the following flags can be set.
D3DXMESHSIMP_FACE
The mesh will be simplified by the number of faces specified in the MinValue parameter.
D3DXMESHSIMP_VERTEX
The mesh will be simplified by the number of vertices specified in the MinValue parameter.
ppPMesh
[out] Address of a pointer to an ID3DXPMesh interface, representing the created progressive mesh.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DXERR_CANNOTATTRSORT
D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

This function generates a mesh where the level of detail (LOD) can be adjusted from the current value to the MinValue.

If the simplification process cannot reduce the mesh to MinValue, the call still succeeds because MinValueis a desired minimum, not an absolute minimum.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;

AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXIntersect

Determines if a ray intersects with a mesh.

HRESULT D3DXIntersect(
  LPD3DXBASEMESH pMesh,
  CONST D3DXVECTOR3* pRayPos,
  CONST D3DXVECTOR3* pRayDir,
  BOOL* pHit,
  DWORD* pFaceIndex,
  FLOAT* pU,
  FLOAT* pV,
  FLOAT* pDist
);

Parameters

pMesh
[in] Pointer to an ID3DXBaseMesh interface, representing the mesh to be tested.
pRayPos
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDir
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.
pHit
[out] Pointer to a BOOL. If the ray intersects a triangular face on the mesh, this value will be set to TRUE. Otherwise, this value is set to FALSE.
pFaceIndex
[out] Pointer to an index value of the face closest to the ray origin, if pHit is TRUE.
pU
[out] Pointer to a Barycentric hit coordinate.
pV
[out] Pointer to a Barycentric hit coordinate.
pDist
[out] Pointer to a ray intersection parameter distance.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be E_OUTOFMEMORY.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXLoadMeshFromX

Loads a mesh from a Microsoft® DirectX® (.x) file.

HRESULT D3DXLoadMeshFromX(
  LPSTR pFilename,
  DWORD Options,
  LPDIRECT3DDEVICE8 pDevice,
  LPD3DXBUFFER* ppAdjacency,
  LPD3DXBUFFER* ppMaterials,
  PDWORD pNumMaterials,
  LPD3DXMESH* ppMesh
);

Parameters

pFilename
[in] Pointer to a string that specifies the name of the DirectX file to load.
Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pDevice
[in] Pointer to an IDirect3DDevice8 interface, the device object associated with the mesh.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of D3DXMATERIAL structures, containing information saved in the Microsoft® DirectX® file.
pNumMaterials
[out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Note All the meshes in the file will be collapsed into one output mesh. If the file contains a frame hierarchy, all the transformations will be applied to the mesh.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXLoadMeshFromXof

Loads a mesh from a Microsoft® DirectX® (.x) file data object.

HRESULT D3DXLoadMeshFromXof(
  LPDIRECTXFILEDATA pXofObjMesh,
  DWORD Options,
  LPDIRECT3DDEVICE8 pD3DDevice,
  LPD3DXBUFFER* ppAdjacency,
  LPD3DXBUFFER* ppMaterials,
  PDWORD pNumMaterials,
  LPD3DXMESH* ppMesh
);

Parameters

pXofObjMesh
[in] Pointer to an IDirectXFileData interface, representing the Microsoft® DirectX® file data object to load.
Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D®.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pD3DDevice
[in] Pointer to an IDirect3DDevice8 interface, the device object associated with the mesh.
ppAdjacency
[in, out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[in, out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of D3DXMATERIAL structures.
pNumMaterials
[in, out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppMesh
[out, retval] Address of a pointer to an ID3DXMesh interface, representing the loaded mesh.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXLoadSkinMeshFromXof

Loads a skin mesh from a Microsoft® DirectX® (.x) file data object.

HRESULT D3DXLoadSkinMeshFromXof(
  LPDIRECTXFILEDATA pXofObjMesh,
  DWORD Options,
  LPDIRECT3DDEVICE8 pD3DDevice,
  LPD3DXBUFFER* ppAdjacency,
  LPD3DXBUFFER* ppMaterials,
  PDWORD pMatOut,
  LPD3DXBUFFER* ppBoneNames,
  LPD3DXBUFFER* ppBoneTransforms,
  LPD3DXSKINMESH* ppMesh
);

Parameters

pXofObjMesh
[in] Pointer to an IDirectXFileData interface, representing the DirectX file data object to load.
Options
[in] A combination of one or more flags, specifying creation options for the mesh. The following flags are defined.
D3DXMESH_32BIT
The mesh has 32-bit indices instead of 16-bit indices. A 32-bit mesh can support up to 2^32-1 faces and vertices. This flag is not supported and should not be used.
D3DXMESH_DONOTCLIP
Use the D3DUSAGE_DONOTCLIP usage flag for vertex and index buffers.
D3DXMESH_DYNAMIC
Equivalent to specifying both D3DXMESH_VB_DYNAMIC and D3DXMESH_IB_DYNAMIC.
D3DXMESH_RTPATCHES
Use the D3DUSAGE_RTPATCHES usage flag for vertex and index buffers.
D3DXMESH_NPATCHES
Specifying this flag causes the vertex and index buffer of the mesh to be created with D3DUSAGE_NPATCHES flag. This is required if the mesh object is to be rendered using N-Patch enhancement using Microsoft® Direct3D.
D3DXMESH_MANAGED
Equivalent to specifying both D3DXMESH_VB_MANAGED and D3DXMESH_IB_MANAGED.
D3DXMESH_POINTS
Use the D3DUSAGE_POINTS usage flag for vertex and index buffers.
D3DXMESH_IB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for index buffers.
D3DXMESH_IB_MANAGED
Use the D3DPOOL_MANAGED memory class for index buffers.
D3DXMESH_IB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for index buffers.
D3DXMESH_IB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for index buffers.
D3DXMESH_SYSTEMMEM
Equivalent to specifying both D3DXMESH_VB_SYSTEMMEM and D3DXMESH_IB_SYSTEMMEM.
D3DXMESH_VB_DYNAMIC
Use the D3DUSAGE_DYNAMIC usage flag for vertex buffers.
D3DXMESH_VB_MANAGED
Use the D3DPOOL_MANAGED memory class for vertex buffers.
D3DXMESH_VB_SYSTEMMEM
Use the D3DPOOL_SYSTEMMEM memory class for vertex buffers.
D3DXMESH_VB_WRITEONLY
Use the D3DUSAGE_WRITEONLY usage flag for vertex buffers.
D3DXMESH_WRITEONLY
Equivalent to specifying both D3DXMESH_VB_WRITEONLY and D3DXMESH_IB_WRITEONLY.
pD3DDevice
[in] Pointer to an IDirect3DDevice8 interface, the device object associated with the mesh.
ppAdjacency
[in, out] Address of a pointer to an ID3DXBuffer interface. When this method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
ppMaterials
[in, out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of D3DXMATERIAL structures.
pMatOut
[in, out] Pointer to the number of D3DXMATERIAL structures in the ppMaterials array, when the method returns.
ppBoneNames
[in, out] Address of a pointer to an ID3DXBuffer interface, containing the bone names.
ppBoneTransforms
[in, out] Address of a pointer to an ID3DXBuffer interface, containing the bone transforms.
ppMesh
[out, retval] Address of a pointer to an ID3DXSkinMesh interface, representing the loaded mesh.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

This method takes a pointer to an internal object in the .x file, enabling you to load the frame hierarchy.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXSaveMeshToX

Saves a mesh to a Microsoft® DirectX® (.x) file.

HRESULT D3DXSaveMeshToX(
  LPSTR pFilename,
  LPD3DXMESH pMesh,
  CONST DWORD* pAdjacency,
  CONST LPD3DXMATERIAL pMaterials,
  DWORD NumMaterials,
  DWORD Format
);

Parameters

pFilename
[in] Pointer to a string that specifies the name of the DirectX file identifying the saved mesh.
pMesh
[in] Pointer to an ID3DXMesh interface, representing the mesh to save to a DirectX file.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh.
pMaterials
[in] Pointer to an array of D3DXMATERIAL structures, containing material information to be saved in the DirectX file.
NumMaterials
[in] Number of D3DXMATERIAL structures in the rgMaterials array
Format
[in] Indicates the format to use when saving the DirectX file. For more information, see Remarks.
DXFILEFORMAT_BINARY
Indicates a binary file.
DXFILEFORMAT_COMPRESSED
Indicates a compressed file.
DXFILEFORMAT_TEXT
Indicates a text file.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Remarks

The default value for the file format is DXFILEFORMAT_BINARY. The file format values can be combined together in a logical OR to create compressed text or compressed binary files. If a file is specified as both binary (0) and text (1), it will be saved as a text file because the value will be indistinguishable from the text file format value (0 + 1 = 1). If you indicate that the file format should be text and compressed, the file will first be written out as text and then compressed. However, compressed text files are not as efficient as binary text files, so in most cases you will want to indicate binary and compressed. Setting a file to be compressed without specifying a format will result in a binary, compressed file.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXSimplifyMesh

Simplifies a mesh.

HRESULT D3DXSimplifyMesh(
  LPD3DXMESH pMesh,
  CONST DWORD* pAdjacency,
  CONST LPD3DXATTRIBUTEWEIGHTS pVertexAttributeWeights,
  CONST FLOAT* pVertexWeights,
  DWORD MinValue,
  DWORD* Options,
  LPD3DXMESH* ppMesh
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh interface, representing the source mesh.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be simplified.
pVertexAttributeWeights
[in] Pointer to a D3DXATTRIBUTEWEIGHTS structure, containing the weight for each vertex component. If this parameter is set to NULL, a default structure is used. See Remarks.
pVertexWeights
[in] Pointer to an array of vertex weights. If this parameter is set to NULL, all vertex weights are set to 1.0.
MinValue
[in] Number of vertices or faces, depending on the flag set in the Options parameter, by which to simplify the source mesh.
Options
[in] Specifies simplification options for the mesh. One of the following flags can be set.
D3DXMESHSIMP_FACE
The mesh will be simplified by the number of faces specified in the MinValue parameter.
D3DXMESHSIMP_VERTEX
The mesh will be simplified by the number of vertices specified in the MinValue parameter.
ppMesh
[out] Address of a pointer to an ID3DXMesh interface, representing the returned simplification mesh.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

This function generates a mesh that has minValue vertices or faces.

If the simplification process cannot reduce the mesh to minValue, the call still succeeds because minValue is a desired minimum, not an absolute minimum.

If pVertexAttributeWeights is set to NULL, the following values are assigned to the default D3DXATTRIBUTEWEIGHTS structure.

D3DXATTRIBUTEWEIGHTS AttributeWeights;

AttributeWeights.Position  = 1.0;
AttributeWeights.Boundary =  1.0;
AttributeWeights.Normal   =  1.0;
AttributeWeights.Diffuse  =  0.0;
AttributeWeights.Specular =  0.0;
AttributeWeights.Tex[8]   =  {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0};

This default structure is what most applications should use because it considers only geometric and normal adjustment. Only in special cases will the other member fields need to be modified.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXSphereBoundProbe

Determines if a ray intersects the volume of a sphere's bounding box.

BOOL D3DXSphereBoundProbe(
  CONST D3DXVECTOR3* pCenter,
  FLOAT Radius,
  D3DXVECTOR3* pRayPosition,
  D3DXVECTOR3* pRayDirection
);

Parameters

pCenter
[in] Pointer to a D3DXVECTOR3 structure, specifying the center coordinate of the sphere.
Radius
[in] Radius of the sphere.
pRayPosition
[in] Pointer to a D3DXVECTOR3 structure, specifying the origin coordinate of the ray.
pRayDirection
[in] Pointer to a D3DXVECTOR3 structure, specifying the direction of the ray.

Return Values

Returns TRUE if the ray intersects the volume of the sphere's bounding box. Otherwise, returns FALSE.

Remarks

D3DXSphereBoundProbe determines if the ray intersects the volume of the sphere's bounding box, not just the surface of the sphere.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXTesselateMesh

Tessellates a mesh.

HRESULT D3DXTesselateMesh(
  LPD3DXMESH pMeshIn,
  CONST DWORD* pAdjacency,
  FLOAT NumSegs,
  BOOL bQuadraticNormals
  LPD3DXMESH* ppMeshOut
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to tessellate.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh.
NumSegs
[in] Number of segments per edge to tessellate.
bQuadraticNormals
[in] If set to TRUE, use quadratic interpolation for normals. If set to FALSE, use linear interpolation.
ppMeshOut
[out] Address of a pointer to an ID3DXMesh interface, representing the returned tessellated mesh.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Note This function tessellates by using the n-Patch algorithm.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXValidMesh

Validates a mesh.

HRESULT D3DXValidMesh(
  LPD3DXMESH pMeshIn,
  CONST DWORD* pAdjacency
);

Parameters

pMeshIn
[in] Pointer to an ID3DXMesh interface, representing the mesh to be tested.
pAdjacency
[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the mesh to be tested.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DXERR_INVALIDMESH
D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

This method validates the mesh by checking for invalid indices and adding another vertex where two fans of triangles share the same vertex.

Error information is available from the debug spew.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


D3DXWeldVertices

Welds replicated vertices together that have attributes that are equal.

HRESULT D3DXValidMesh(
  CONST LPD3DXMESH pMesh,
  float fEpsilon,
  CONST DWORD* pAdjacencyIn,
  DWORD* pAdjacencyOut,
  DWORD* pFaceRemap,
  LPD3DXBUFFER* ppVertexRemap
);

Parameters

pMesh
[in] Pointer to an ID3DXMesh object, the mesh from which to weld vertices.
fEpsilon
[in] Difference in vertex attributes, under which vertices are welded.
pAdjacencyIn

[in] Pointer to an array of three DWORDs per face that specify the three neighbors for each face in the source mesh. If this parameter is set to NULL, then ID3DXMesh::GenerateAdjacency will be called to create logical adjacency information.

pAdjacencyOut
[in, out] Pointer to a destination buffer for the face adjacency array of the optimized mesh. The face adjacency is stored as an array of arrays. The innermost array is three indices of adjacent triangles, and the outer array is one set of face adjacency per triangle in the mesh.
pFaceRemap
[out] Pointer to a destination buffer containing the new index for each face.
ppVertexRemap
[out] Address of a pointer to an ID3DXBuffer interface, containing the new index for each vertex.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

This method uses the provided adjacency information to determine the points that are replicated. This method uses an epsilon compare to merge vertices and requires vertices with equal position to already have been calculated and represented by point representative data.

This method takes logically welded vertices and combines the ones that have similar components. Such as normals within fEpsilon or texture coordinates within fEpsilon.

Requirements

Header: Declared in D3dx8mesh.h.
Import Library: Use D3dx8.lib.


Shader Functions

Direct3DX supplies the following shader functions.

  • D3DXAssembleShader
  • D3DXAssembleShaderFromFileA
  • D3DXAssembleShaderFromFileW

The assembler assumes that is assembling a vertex shader (version 1.0) unless a version token is encountered at the start of the assembly. For information on the Direct3DX vertex and pixel shader assemblers, see Direct3DX Shader Assemblers Reference.


D3DXAssembleShader

Assembles an ASCII description of a shader into binary form, where the shader source is in memory.

HRESULT D3DXAssembleShader(
  LPCVOID pSrcData,
  UINT SrcDataLen,
  DWORD Flags,
  LPD3DXBUFFER* ppConstants,
  LPD3DXBUFFER* ppCompiledShader,
  LPD3DXBUFFER* ppCompilationErrors
);

Parameters

pSrcData
[in] Pointer to the source code.
SrcDataLen
[in] Size of the source code, in bytes.
Flags
[in] A combination of the following flags, specifying assembly options.
D3DXASM_DEBUG
Inserts debugging information as comments in the assembled shader.
D3DXASM_SKIPVALIDATION
Do not validate the generated code against known capabilities and constraints. This option is recommended only when assembling a shader you know will function (that is, the shader has been assembled before without this option.)
ppConstants
[out] Returns a pointer to an ID3DXBuffer interface, representing the returned constant declarations. These constants are returned as a vertex shader declaration fragment. It is up to the application to insert the contents of this buffer into their declaration. For pixel shaders this parameter is meaningless because constant declarations are included in the assembled shader. This parameter is ignored if it is NULL.
ppCompiledShader
[out] Returns a pointer to an ID3DXBuffer interface, representing the returned compiled object code. This parameter is ignored if it is NULL.
ppCompilationErrors
[out] Returns a pointer to an ID3DXBuffer interface, representing the returned ASCII error messages. This parameter is ignored if it is NULL.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.


D3DXAssembleShaderFromFileA

Assembles an ASCII description of a shader into binary form, where the source file name is an ANSI string.

HRESULT D3DXAssembleShaderFromFileA(
  LPCSTR pSrcFile,
  DWORD Flags,
  LPD3DXBUFFER* ppConstants,
  LPD3DXBUFFER* ppCompiledShader,
  LPD3DXBUFFER* ppCompilationErrors
);

Parameters

pSrcFile
[in] Pointer to the source file name, in ANSI format.
Flags
[in] A combination of the following flags, specifying assembly options.
D3DXASM_DEBUG
Inserts debugging information as comments in the assembled shader.
D3DXASM_SKIPVALIDATION
Do not validate the generated code against known capabilities and constraints. This option is recommended only when assembling a shader you know will function (that is, the shader has been assembled before without this option.)
ppConstants
[out] Returns a pointer to an ID3DXBuffer interface, representing the returned constant declarations. These constants are returned as a vertex shader declaration fragment. It is up to the application to insert the contents of this buffer into their declaration. For pixel shaders this parameter is meaningless because constant declarations are included in the assembled shader. This parameter is ignored if it is NULL.
ppCompiledShader
[out] Returns a pointer to an ID3DXBuffer interface, representing the returned compiled object code. This parameter is ignored if it is NULL.
ppCompilationErrors
[out] Returns a pointer to an ID3DXBuffer interface, representing the returned ASCII error messages. This parameter is ignored if it is NULL.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

D3DXAssembleShaderFromFile maps to either D3DXAssembleShaderFromFileA or D3DXAssembleShaderFromFileW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings.

The following code fragment shows how D3DXAssembleShaderFromFile is defined.

#ifdef UNICODE
#define D3DXAssembleShaderFromFile D3DXAssembleShaderFromFileW
#else
#define D3DXAssembleShaderFromFile D3DXAssembleShaderFromFileA
#endif

The following example wrapper function, PreprocessAndAssembleShaderFromFile, shows how you can invoke the C preprocessor on your vertex shader code before invoking the assembler with D3DXAssembleShaderFromFile.

HRESULT PreprocessAndAssembleShaderFromFile(
        LPCSTR          szFile,
        DWORD           Flags,
        LPD3DXBUFFER*   ppConstants,
        LPD3DXBUFFER*   ppCode,
        LPD3DXBUFFER*   ppErrors)
{
    char szPath[_MAX_PATH];
    char szTemp[_MAX_PATH];
    char szCmd [_MAX_PATH];

    GetTempPath(sizeof(szPath), szPath);
    GetTempFileName(szPath, "vsa", 0, szTemp);

    _snprintf(szCmd, sizeof(szCmd), "cl /nologo /E %s > %s", szFile, szTemp);

    if(0 != system(szCmd))
        return D3DERR_INVALIDCALL;

    return D3DXAssembleShaderFromFile(szTemp, Flags, ppConstants, ppCode, ppErrors);
}

Note that for this function to work you must have Microsoft®Visual C++® installed and your environment set up so that Cl.exe is in your path.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

D3DXAssembleShaderFromFileW


D3DXAssembleShaderFromFileW

Assembles an ASCII description of a shader into binary form, where the source file name is a Unicode string.

HRESULT D3DXAssembleShaderFromFileW(
  LPCWSTR pSrcFile,
  DWORD Flags,
  LPD3DXBUFFER* ppConstants,
  LPD3DXBUFFER* ppCompiledShader,
  LPD3DXBUFFER* ppCompilationErrors
);

Parameters

pSrcFile
[in] Pointer to the source file name, in Unicode format.
Flags
[in] A combination of the following flags, specifying assembly options.
D3DXASM_DEBUG
Inserts debugging information as comments in the assembled shader.
D3DXASM_SKIPVALIDATION
Do not validate the generated code against known capabilities and constraints. This option is recommended only when assembling a shader you know will function (that is, the shader has been assembled before without this option.)
ppConstants
[out] Returns a pointer to an ID3DXBuffer interface, representing the returned constant declarations. These constants are returned as a vertex shader declaration fragment. It is up to the application to insert the contents of this buffer into their declaration. For pixel shaders this parameter is meaningless because constant declarations are included in the assembled shader. This parameter is ignored if it is NULL.
ppCompiledShader
[out] Returns a pointer to an ID3DXBuffer interface, representing the returned compiled object code. This parameter is ignored if it is NULL.
ppCompilationErrors
[out] Returns a pointer to an ID3DXBuffer interface, representing the returned ASCII error messages. This parameter is ignored if it is NULL.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

D3DXAssemblePixelShaderFromFile maps to either D3DXAssembleShaderFromFileA or D3DXAssembleShaderFromFileW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings.

The following code fragment shows how D3DXAssembleShaderFromFile is defined.

#ifdef UNICODE
#define D3DXAssembleShaderFromFile D3DXAssembleShaderFromFileW
#else
#define D3DXAssembleShaderFromFile D3DXAssembleShaderFromFileA
#endif

The following example wrapper function, PreprocessAndAssembleShaderFromFile, shows how you can invoke the C preprocessor on your vertex shader code before invoking the assembler with D3DXAssembleShaderFromFile.

HRESULT
    PreprocessAndAssembleShaderFromFile(
        LPCSTR          szFile,
        DWORD           Flags,
        LPD3DXBUFFER*   ppConstants,
        LPD3DXBUFFER*   ppCode,
        LPD3DXBUFFER*   ppErrors)
{
    char szPath[_MAX_PATH];
    char szTemp[_MAX_PATH];
    char szCmd [_MAX_PATH];

    GetTempPath(sizeof(szPath), szPath);
    GetTempFileName(szPath, "vsa", 0, szTemp);

    _snprintf(szCmd, sizeof(szCmd), "cl /nologo /E %s > %s", szFile, szTemp);

    if(0 != system(szCmd))
        return D3DERR_INVALIDCALL;

    return D3DXAssembleShaderFromFile(szTemp, Flags, ppConstants, ppCode, ppErrors);
}

Note that for this function to work you must have Microsoft®Visual C++® installed and your environment set up so that Cl.exe is in your path.

Requirements

Header: Declared in D3dx8core.h.
Import Library: Use D3dx8.lib.

See Also

D3DXAssembleShaderFromFileA


Shape Drawing Functions

Microsoft DirectX 8.0 (C++)

Shape-Drawing Functions

Direct3DX supplies the following shape-drawing functions.

  • D3DXCreateBox
  • D3DXCreateCylinder
  • D3DXCreatePolygon
  • D3DXCreateSphere
  • D3DXCreateTeapot
  • D3DXCreateTextA
  • D3DXCreateTextW
  • D3DXCreateTorus

All shapes are returned as mesh objects.

These functions can be used in either a left-handed or right-handed coordinate system.


D3DXCreateBox

Uses a left-handed coordinate system to create a mesh containing an axis-aligned box.

HRESULT D3DXCreateBox(
  LPDIRECT3DDEVICE8 pDevice,
  FLOAT Width,
  FLOAT Height,
  FLOAT Depth,
  LPD3DXMESH* ppMesh,
  LPD3DXBUFFER* ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device associated with the created box mesh.
Width
[in] Width of the box, along the x-axis.
Height
[in] Height of the box, along the y-axis.
Depth
[in] Depth of the box, along the z-axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

The created box is centered at the origin.

Requirements

Header: Declared in D3dx8shape.h.
Import Library: Use D3dx8.lib.


D3DXCreateCylinder

Uses a left-handed coordinate system to create a mesh containing a cylinder.

HRESULT D3DXCreateCylinder(
  LPDIRECT3DDEVICE8 pDevice,
  FLOAT Radius1,
  FLOAT Radius2,
  FLOAT Length,
  UINT Slices,
  UINT Stacks,
  LPD3DXMESH* ppMesh,
  LPD3DXBUFFER* ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device associated with the created cylinder mesh.
Radius1
[in] Radius at the negative Z end. Value should be greater than or equal to 0.0f.
Radius2
[in] Radius at the positive Z end. Value should be greater than or equal to 0.0f.
Length
[in] Length of the cylinder along the z-axis.
Slices
[in] Number of slices about the main axis.
Stacks
[in] Number of stacks along the main axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

The created cylinder is centered at the origin, and its axis is aligned with the z-axis.

Requirements

Header: Declared in D3dx8shape.h.
Import Library: Use D3dx8.lib.


D3DXCreatePolygon

Uses a left-handed coordinate system to create a mesh containing an n-sided polygon.

HRESULT D3DXCreatePolygon(
  LPDIRECT3DDEVICE8 pDevice,
  FLOAT Length,
  UINT Sides,
  LPD3DXMESH* ppMesh,
  LPD3DXBUFFER* ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device associated with the created polygon mesh.
Length
[in] Length of each side.
Sides
[in] Number of sides for the polygon. Value must be greater than or equal to 3.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

The created polygon is centered at the origin.

Requirements

Header: Declared in D3dx8shape.h.
Import Library: Use D3dx8.lib.


D3DXCreateSphere

Uses a left-handed coordinate system to create a mesh containing a sphere.

HRESULT D3DXCreateSphere(
  LPDIRECT3DDEVICE8 pDevice,
  FLOAT Radius,
  UINT Slices,
  UINT Stacks,
  LPD3DXMESH* ppMesh,
  LPD3DXBUFFER* ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device associated with the created sphere mesh.
Radius
[in] Radius of the sphere. This value should be greater than or equal to 0.0f.
Slices
[in] Number of slices about the main axis.
Stacks
[in] Number of stacks along the main axis.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

The created sphere is centered at the origin, and its axis is aligned with the z-axis.

Requirements

Header: Declared in D3dx8shape.h.
Import Library: Use D3dx8.lib.


D3DXCreateTeapot

Uses a left-handed coordinate system to create a mesh containing a teapot.

HRESULT D3DXCreateTeapot(
  LPDIRECT3DDEVICE8 pDevice,
  LPD3DXMESH* ppMesh,
  LPD3DXBUFFER* ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device associated with the created teapot mesh.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Requirements

Header: Declared in D3dx8shape.h.
Import Library: Use D3dx8.lib.


D3DXCreateTextA

Creates a mesh containing the specified ANSI text using the font associated with the device context.

HRESULT D3DXCreateTextA(
  LPDIRECT3DDEVICE8 pDevice,
  HDC hDC,
  LPCSTR pText,
  FLOAT Deviation,
  FLOAT Extrusion,
  LPD3DXMESH* ppMesh,
  LPGLYPHMETRICSFLOAT pGlyphMetrics
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device associated with the created text mesh.
hDC
[in] Device context, containing the font for output. The font selected by the device context must be a TrueType font.
pText
[in] Pointer to an ANSI string, specifying the text to generate.
Deviation
[in] Maximum chordal deviation from true font outlines.
Extrusion
[in] Amount to extrude text in the negative Z direction.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
pGlyphMetrics
[out] Pointer to an array of GLYPHMETRICSFLOAT structures to receive the glyph metric data. Each GLYPHMETRICSFLOAT structure in the array contains information about the placement and orientation of the corresponding glyph in the string. The number of elements in the array should be equal to the number of characters in the string. Note that the origin in each structure is not relative to the entire string, but rather is relative to that character cell. To compute the entire bounding box, add the increment for each glyph while traversing the string.

If you are not concerned with the glyph sizes, you can pass NULL to pGlyphMetrics.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

D3DXCreateText maps to either D3DXCreateTextA or D3DXCreateTextW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateText is defined.

#ifdef UNICODE
#define D3DXCreateText D3DXCreateTextW
#else
#define D3DXCreateText D3DXCreateTextA
#endif

For more information on the GLYPHMETRICSFLOAT structure, see the Microsoft® Platform Software Development Kit (SDK).

Requirements

Header: Declared in D3dx8shape.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextW


D3DXCreateTextW

Creates a mesh containing the specified Unicode text using the font associated with the device context.

HRESULT D3DXCreateTextW(
  LPDIRECT3DDEVICE8 pDevice,
  HDC hDC,
  LPCSTR pText,
  FLOAT Deviation,
  FLOAT Extrusion,
  LPD3DXMESH* ppMesh,
  LPGLYPHMETRICSFLOAT pGlyphMetrics
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device associated with the created text mesh.
hDC
[in] Device context, containing the font for output. The font selected by the device context must be a TrueType font.
pText
[in] Pointer to a Unicode string, specifying the text to generate.
Deviation
[in] Maximum chordal deviation from true font outlines.
Extrusion
[in] Amount to extrude text in the negative Z direction.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
pGlyphMetrics
[out] Pointer to an array of GLYPHMETRICSFLOAT structures to receive the glyph metric data. Each GLYPHMETRICSFLOAT structure in the array contains information about the placement and orientation of the corresponding glyph in the string. The number of elements in the array should be equal to the number of characters in the string. Note that the origin in each structure is not relative to the entire string, but rather is relative to that character cell. To compute the entire bounding box, add the increment for each glyph while traversing the string.

If you are not concerned with the glyph sizes, you can pass NULL to pGlyphMetrics.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

D3DXCreateText maps to either D3DXCreateTextA or D3DXCreateTextW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateText is defined.

#ifdef UNICODE
#define D3DXCreateText D3DXCreateTextW
#else
#define D3DXCreateText D3DXCreateTextA
#endif

For more information on the GLYPHMETRICSFLOAT structure, see the Microsoft® Platform Software Development Kit (SDK).

Requirements

Header: Declared in D3dx8shape.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextA


D3DXCreateTorus

Uses a left-handed coordinate system to create a mesh containing a torus.

HRESULT D3DXCreateTorus(
  LPDIRECT3DDEVICE8 pDevice,
  FLOAT InnerRadius,
  FLOAT OuterRadius,
  UINT Sides,
  UINT Rings,
  LPD3DXMESH* ppMesh,
  LPD3DXBUFFER* ppAdjacency
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device associated with the created torus mesh.
InnerRadius
[in] Inner-radius of the torus. Value should be greater than or equal to 0.0f.
OuterRadius
[in] Outer-radius of the torus. Value should be greater than or equal to 0.0f.
Sides
[in] Number of sides in a cross-section. Value must be greater than or equal to 3.
Rings
[in] Number of rings making up the torus. Value must be greater than or equal to 3.
ppMesh
[out] Address of a pointer to the output shape, an ID3DXMesh interface.
ppAdjacency
[out] Address of a pointer to an ID3DXBuffer interface. When the method returns, this parameter is filled with an array of three DWORDs per face that specify the three neighbors for each face in the mesh. NULL can be specified.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

The D3DXCreateTorus function draws a doughnut, centered at (0, 0, 0) whose axis is aligned with the z-axis. The inner-radius of the torus is the radius of the cross-section (the minor-radius), and the outer-radius of the torus is the radius of the central hole.

This function returns a mesh that can be used later for drawing or manipulation by the application.

Requirements

Header: Declared in D3dx8shape.h.
Import Library: Use D3dx8.lib.


Texturing Functions

Direct3DX supplies the following texturing functions.

  • D3DXCheckCubeTextureRequirements
  • D3DXCheckTextureRequirements
  • D3DXCheckVolumeTextureRequirements
  • D3DXCreateCubeTexture
  • D3DXCreateCubeTextureFromFileA
  • D3DXCreateCubeTextureFromFileExA
  • D3DXCreateCubeTextureFromFileExW
  • D3DXCreateCubeTextureFromFileInMemory
  • D3DXCreateCubeTextureFromFileInMemoryEx
  • D3DXCreateCubeTextureFromFileW
  • D3DXCreateTexture
  • D3DXCreateTextureFromFileA
  • D3DXCreateTextureFromFileExA
  • D3DXCreateTextureFromFileExW
  • D3DXCreateTextureFromFileInMemory
  • D3DXCreateTextureFromFileInMemoryEx
  • D3DXCreateTextureFromFileW
  • D3DXCreateTextureFromResourceA
  • D3DXCreateTextureFromResourceExA
  • D3DXCreateTextureFromResourceExW
  • D3DXCreateTextureFromResourceW
  • D3DXCreateVolumeTexture
  • D3DXFilterCubeTexture
  • D3DXFilterTexture
  • D3DXFilterVolumeTexture
  • D3DXLoadSurfaceFromFileA
  • D3DXLoadSurfaceFromFileInMemory
  • D3DXLoadSurfaceFromFileW
  • D3DXLoadSurfaceFromMemory
  • D3DXLoadSurfaceFromResourceA
  • D3DXLoadSurfaceFromResourceW
  • D3DXLoadSurfaceFromSurface
  • D3DXLoadVolumeFromMemory
  • D3DXLoadVolumeFromVolume


D3DXCheckCubeTextureRequirements

Checks cube-texture-creation parameters.

HRESULT D3DXCheckCubeTextureRequirements(
  LPDIRECT3DDEVICE8 pDevice,
  UINT* pSize,
  UINT* pNumMipLevels,
  DWORD Usage,
  D3DFORMAT* pFormat,
  D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the cube texture.
pSize
[in, out] Pointer to the requested width and height in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to the number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_INVALIDCALL

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

Cube textures differ from other surfaces in that they are collections of surfaces. To call SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture8::GetCubeMapSurface and pass the resulting surface to SetRenderTarget.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXCheckTextureRequirements

Checks texture-creation parameters.

HRESULT D3DXCheckTextureRequirements(
  LPDIRECT3DDEVICE8 pDevice,
  UINT* pWidth,
  UINT* pHeight,
  UINT* pNumMipLevels,
  DWORD Usage,
  D3DFORMAT* pFormat,
  D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
pWidth
[in, out] Pointer to the requested width in pixels, or NULL. Returns the corrected size.
pHeight
[in, out] Pointer to the requested height in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_INVALIDCALL

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXCheckVolumeTextureRequirements

Checks volume-texture-creation parameters.

HRESULT D3DXCheckVolumeTextureRequirements(
  LPDIRECT3DDEVICE8 pDevice,
  UINT* pWidth,
  UINT* pHeight,
  UINT* pDepth,
  UINT* pNumMipLevels,
  DWORD Usage,
  D3DFORMAT* pFormat,
  D3DPOOL Pool
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the volume texture.
pWidth
[in, out] Pointer to the requested width in pixels, or NULL. Returns the corrected size.
pHeight
[in, out] Pointer to the requested height in pixels, or NULL. Returns the corrected size.
pDepth
[in, out] Pointer to the requested depth in pixels, or NULL. Returns the corrected size.
pNumMipLevels
[in, out] Pointer to the number of requested mipmap levels, or NULL. Returns the corrected number of mipmap levels.
Usage
[in] Currently not used, set to 0.
pFormat
[in, out] Pointer to a member of the D3DFORMAT enumerated type. Specifies the desired pixel format, or NULL. Returns the corrected format.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_INVALIDCALL

Remarks

If parameters to this function are invalid, this function returns corrected parameters.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXCreateCubeTexture

Creates an empty cube texture, adjusting the calling parameters as needed.

HRESULT D3DXCreateCubeTexture(
  LPDIRECT3DDEVICE8 pDevice,
  UINT Size,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  LPDIRECT3DCUBETEXTURE8* ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture8 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
E_OUTOFMEMORY

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces. To call SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture8::GetCubeMapSurface and pass the resulting surface to SetRenderTarget.

Internally, D3DXCreateCubeTexture uses D3DXCheckCubeTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateCubeTexture will often succeed where calls to IDirect3Ddevice8::CreateCubeTexture would fail.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXCreateCubeTextureFromFileA

Creates a cube texture from a file specified by an ANSI string.

D3DXCreateCubeTextureFromFile maps to either D3DXCreateCubeTextureFromFileA or D3DXCreateCubeTextureFromFileW, depending on the inclusion or exclusion of the #define UNICODE switch, see Remarks.

HRESULT D3DXCreateCubeTextureFromFileA(
  LPDIRECT3DDEVICE8 pDevice,
  LPCSTR pSrcFile,
  LPDIRECT3DCUBETEXTURE8* ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the cube texture.
pSrcFile
[in] Pointer to an ANSI string that specifies the file from which to create the cube texture. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture8 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateCubeTextureFromFile is defined.

#ifdef UNICODE
#define D3DXCreateCubeTextureFromFile D3DXCreateCubeTextureFromFileW
#else
#define D3DXCreateCubeTextureFromFile D3DXCreateCubeTextureFromFileA
#endif

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

D3DXCreateCubeTextureFromFileA uses the DirectDrawSurface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.

Requirements

Header: Declared in D3dx8tex.h.

See Also

D3DXCreateCubeTextureFromFileW


D3DXCreateCubeTextureFromFileExA

Creates a cube texture from a file specified by an ANSI string. This is a more advanced function than D3DXCreateCubeTextureFromFileA.

D3DXCreateCubeTextureFromFileEx maps to either D3DXCreateCubeTextureFromFileExA or D3DXCreateCubeTextureFromFileExW, depending on the inclusion or exclusion of the #define UNICODE switch, see Remarks.

HRESULT D3DXCreateCubeTextureFromFileExA(
  LPDIRECT3DDEVICE8 pDevice,
  LPCSTR pSrcFile,
  UINT Size,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo,
  PALETTEENTRY* pPalette,
  LPDIRECT3DCUBETEXTURE8* ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the cube texture.
pSrcFile
[in] Pointer to an ANSI string that specifies the file from which to create the cube texture. See Remarks.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8. If this value is 0 or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more flags, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter. Internally, the flag D3DX_FILTER_MIRROR is always used.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags. This flag is always used internally for this function.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
MipFilter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter. Internally, the flag D3DX_FILTER_MIRROR is always used.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags. This flag is always used internally for this function.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant, and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture8 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces. To call SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture8::GetCubeMapSurface and pass the resulting surface to SetRenderTarget.

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX 8.0®, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateCubeTextureFromFileEx is defined.

#ifdef UNICODE
#define D3DXCreateCubeTextureFromFileEx D3DXCreateCubeTextureFromFileExW
#else
#define D3DXCreateCubeTextureFromFileEx D3DXCreateCubeTextureFromFileExA
#endif

D3DXCreateCubeTextureFromFileExA uses the DirectDrawSurface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.

Requirements

Header: Declared in D3dx8tex.h.

See Also

D3DXCreateCubeTextureFromFileExW


D3DXCreateCubeTextureFromFileExW

Creates a cube texture from a file specified by Unicode string. This is a more advanced function than D3DXCreateCubeTextureFromFileW.

D3DXCreateCubeTextureFromFileEx maps to either D3DXCreateCubeTextureFromFileExA or D3DXCreateCubeTextureFromFileExW, depending on the inclusion or exclusion of the #define UNICODE switch, see Remarks.

HRESULT D3DXCreateCubeTextureFromFileExW(
  LPDIRECT3DDEVICE8 pDevice,
  LPCWSTR pSrcFile,
  UINT Size,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo,
  PALETTEENTRY* pPalette,
  LPDIRECT3DCUBETEXTURE8* ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the cube texture.
pSrcFile
[in] Pointer to a Unicode string that specifies the file from which to create the cube texture. See Remarks.
Size
[in] Width and height of the cube texture, in pixels. For example, if the cube texture is an 8-pixel by 8-pixel cube, the value for this parameter should be 8. If this value is 0 or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat. See Remarks.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned cube texture might have a different format from that specified by Format. Applications should check the format of the returned cube texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter. Internally, the flag D3DX_FILTER_MIRROR is always used.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags. This flag is always used internally for this function.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
MipFilter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter. Internally, the flag D3DX_FILTER_MIRROR is always used.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags. This flag is always used internally for this function.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture8 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces. To call SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture8::GetCubeMapSurface and pass the resulting surface to SetRenderTarget.

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateCubeTextureFromFileEx is defined.

#ifdef UNICODE
#define D3DXCreateCubeTextureFromFileEx D3DXCreateCubeTextureFromFileExW
#else
#define D3DXCreateCubeTextureFromFileEx D3DXCreateCubeTextureFromFileExA
#endif

D3DXCreateCubeTextureFromFileExW uses the DirectDrawSurface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.

Requirements

Header: Declared in D3dx8tex.h.

See Also

D3DXCreateCubeTextureFromFileExA


D3DXCreateCubeTextureFromFileInMemory

Creates a cube texture from a file in memory.

HRESULT D3DXCreateCubeTextureFromFileInMemory(
  LPDIRECT3DDEVICE8 pDevice,
  LPCVOID pSrcData,
  UINT SrcDataSize,
  LPDIRECT3DCUBETEXTURE8* ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the cube texture.
pSrcData
[in] Pointer to the file in memory from which to create the cubemap. See Remarks.
SrcDataSize
[in] Size of the file in memory, in bytes.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture8 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

This method is designed to be used for loading image files stored as RT_RCDATA, which is an application-defined resource (raw data). Otherwise this method will fail.

D3DXCreateCubeTextureFromFileInMemory uses the DirectDrawSurface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.

Requirements

Header: Declared in D3dx8tex.h.


D3DXCreateCubeTextureFromFileInMemoryEx

Creates a cube texture from a file in memory. This is a more advanced function than D3DXCreateCubeTextureFromFileInMemory.

HRESULT D3DXCreateCubeTextureFromFileInMemoryEx(
  LPDIRECT3DDEVICE8 pDevice,
  LPCVOID pSrcData,
  UINT SrcDataSize,
  UINT Size,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo,
  PALETTEENTRY* pPalette,
  LPDIRECT3DCUBETEXTURE8* ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the cube texture.
pSrcData
[in] Pointer to the file in memory from which to create the cube texture. See Remarks.
SrcDataSize
[in] Size of the file in memory, in bytes.
Size
[in] Width and height in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat. See Remarks.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the cube texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the cube texture should be placed.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter. Internally, the flag D3DX_FILTER_MIRROR is always used.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags. This flag is always used internally for this function.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
MipFilter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter. Internally, the flag D3DX_FILTER_MIRROR is always used.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags. This flag is always used internally for this function.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant, and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture8 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Cube textures differ from other surfaces in that they are collections of surfaces. To call SetRenderTarget with a cube texture, you must select an individual face using IDirect3DCubeTexture8::GetCubeMapSurface and pass the resulting surface to SetRenderTarget.

This method is designed to be used for loading image files stored as RT_RCDATA, which is an application-defined resource (raw data). Otherwise this method will fail.

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXCreateCubeTextureFromFileInMemoryEx uses the DirectDrawSurface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format

Requirements

Header: Declared in D3dx8tex.h.


D3DXCreateCubeTextureFromFileW

Creates a cube texture from a file specified by a Unicode string.

D3DXCreateCubeTextureFromFile maps to either D3DXCreateCubeTextureFromFileA or D3DXCreateCubeTextureFromFileW, depending on the inclusion or exclusion of the #define UNICODE switch, see Remarks.

HRESULT D3DXCreateCubeTextureFromFileW(
  LPDIRECT3DDEVICE8 pDevice,
  LPCWSTR pSrcFile,
  LPDIRECT3DCUBETEXTURE8* ppCubeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the cube texture.
pSrcFile
[in] Pointer to a Unicode string that specifies the file from which to create the cube texture. See Remarks.
ppCubeTexture
[out] Address of a pointer to an IDirect3DCubeTexture8 interface, representing the created cube texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateCubeTextureFromFile is defined.

#ifdef UNICODE
#define D3DXCreateCubeTextureFromFile D3DXCreateCubeTextureFromFileW
#else
#define D3DXCreateCubeTextureFromFile D3DXCreateCubeTextureFromFileA
#endif

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

D3DXCreateCubeTextureFromFileInMemoryW uses the DirectDrawSurface (DDS) file format. The DXTex Tool enables you to generate a cube map from other file formats and save it in the DDS file format.

Requirements

Header: Declared in D3dx8tex.h.

See Also

D3DXCreateCubeTextureFromFileA


D3DXCreateTexture

Creates an empty texture, adjusting the calling parameters as needed.

HRESULT D3DXCreateTexture(
  LPDIRECT3DDEVICE8 pDevice,
  UINT Width,
  UINT Height,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  LPDIRECT3DTEXTURE8* ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
Width
[in] Width in pixels. This value must be non-zero.
Height
[in] Height in pixels. This value must be non-zero.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
ppTexture
[out] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

Internally, D3DXCreateTexture uses D3DXCheckTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateTexture will often succeed where calls to IDirect3Ddevice8::CreateTexture would fail.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXCreateTextureFromFileA

Creates a texture from a file specified by an ANSI string.

HRESULT D3DXCreateTextureFromFileA(
  LPDIRECT3DDEVICE8 pDevice,
  LPCSTR pSrcFile,
  LPDIRECT3DTEXTURE8* ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to an ANSI string that specifies the file from which to create the texture.
ppTexture
[out] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Mipmapped textures automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

D3DXCreateTextureFromFile maps to either D3DXCreateTextureFromFileA or D3DXCreateTextureFromFileW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateTextureFromFile is defined.

#ifdef UNICODE
#define D3DXCreateTextureFromFile D3DXCreateTextureFromFileW
#else
#define D3DXCreateTextureFromFile D3DXCreateTextureFromFileA
#endif

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextureFromFileExA, D3DXCreateTextureFromFileExW, D3DXCreateTextureFromFileW


D3DXCreateTextureFromFileExA

Creates a texture from a file specified by an ANSI string. This is a more advanced function than D3DXCreateTextureFromFileA.

HRESULT D3DXCreateTextureFromFileExA(
  LPDIRECT3DDEVICE8 pDevice,
  LPCSTR pSrcFile,
  UINT Width,
  UINT Height,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo,
  PALETTEENTRY* pPalette,
  LPDIRECT3DTEXTURE8* ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to an ANSI string that specifies the file from which to create the texture.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat.
Format
Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
MipFilter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Mipmapped textures automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXCreateTextureFromFileEx maps to either D3DXCreateTextureFromFileExA or D3DXCreateTextureFromFileExW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateTextureFromFileEx is defined.

#ifdef UNICODE
#define D3DXCreateTextureFromFileEx D3DXCreateTextureFromFileExW
#else
#define D3DXCreateTextureFromFileEx D3DXCreateTextureFromFileExA
#endif

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextureFromFileA, D3DXCreateTextureFromFileExW, D3DXCreateTextureFromFileW


D3DXCreateTextureFromFileExW

Creates a texture from a file specified by Unicode string. This is a more advanced function than D3DXCreateTextureFromFileW.

HRESULT D3DXCreateTextureFromFileExW(
  LPDIRECT3DDEVICE8 pDevice,
  LPCWSTR pSrcFile,
  UINT Width,
  UINT Height,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo,
  PALETTEENTRY* pPalette,
  LPDIRECT3DTEXTURE8* ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a Unicode string that specifies the file from which to create the texture.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one ore more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
MipFilter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Mipmapped textures automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXCreateTextureFromFileEx maps to either D3DXCreateTextureFromFileExA or D3DXCreateTextureFromFileExW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateTextureFromFileEx is defined.

#ifdef UNICODE
#define D3DXCreateTextureFromFileEx D3DXCreateTextureFromFileExW
#else
#define D3DXCreateTextureFromFileEx D3DXCreateTextureFromFileExA
#endif

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextureFromFileA, D3DXCreateTextureFromFileExA, D3DXCreateTextureFromFileW


D3DXCreateTextureFromFileInMemory

Creates a texture from a file in memory.

HRESULT D3DXCreateTextureFromFileInMemory(
  LPDIRECT3DDEVICE8 pDevice,
  LPCVOID pSrcData,
  UINT SrcData,
  LPDIRECT3DTEXTURE8* ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
pSrcData
[in] Pointer to the file in memory from which to create the texture.
SrcData
[in] Size of the file in memory, in bytes.
ppTexture
[out] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

This method is designed to be used for loading image files stored as RT_RCDATA, which is an application-defined resource (raw data). Otherwise this method will fail.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextureFromFileInMemoryEx


D3DXCreateTextureFromFileInMemoryEx

Creates a texture from a file in memory. This is a more advanced function than D3DXCreateTextureFromFileInMemory.

HRESULT D3DXCreateTextureFromFileInMemoryEx(
  LPDIRECT3DDEVICE8 pDevice,
  LPCVOID pSrcData,
  UINT SrcData,
  UINT Width,
  UINT Height,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo
  PALETTEENTRY* pPalette,
  LPDIRECT3DTEXTURE8* ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
pSrcData
[in] Pointer to the file in memory from which to create the texture.
SrcData
[in] Size of the file in memory, in bytes.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat.
Format
[in] A member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
MipFilter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

This method is designed to be used for loading image files stored as RT_RCDATA, which is an application-defined resource (raw data). Otherwise, this method will fail.

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextureFromFileInMemory


D3DXCreateTextureFromFileW

Creates a texture from a file specified by a Unicode string.

HRESULT D3DXCreateTextureFromFileW(
  LPDIRECT3DDEVICE8 pDevice,
  LPCWSTR pSrcFile,
  LPDIRECT3DTEXTURE8* ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a Unicode string that specifies the file from which to create the texture.
ppTexture
[out] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

Mipmapped textures automatically have each level filled with the loaded texture.

When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

D3DXCreateTextureFromFile maps to either D3DXCreateTextureFromFileA or D3DXCreateTextureFromFileW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateTextureFromFile is defined.

#ifdef UNICODE
#define D3DXCreateTextureFromFile D3DXCreateTextureFromFileW
#else
#define D3DXCreateTextureFromFile D3DXCreateTextureFromFileA
#endif

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextureFromFileA, D3DXCreateTextureFromFileExA, D3DXCreateTextureFromFileExW


D3DXCreateTextureFromResourceA

Creates a texture from a resource specified by an ANSI string.

HRESULT D3DXCreateTextureFromResourceA(
  LPDIRECT3DDEVICE8 pDevice,
  HMODULE hSrcModule,
  LPCSTR pSrcResource,
  LPDIRECT3DTEXTURE8* ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to an ANSI string that specifies the resource from which to create the texture.
ppTexture
[out] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

The resource being loaded must be a bitmap resource(RT_BITMAP).

D3DXCreateTextureFromResource maps to either D3DXCreateTextureFromResourceA or D3DXCreateTextureFromResourceW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateTextureFromResource is defined.

#ifdef UNICODE
#define D3DXCreateTextureFromResource D3DXCreateTextureFromResourceW
#else
#define D3DXCreateTextureFromResource D3DXCreateTextureFromResourceA
#endif

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextureFromResourceExA, D3DXCreateTextureFromResourceExW, D3DXCreateTextureFromResourceW


D3DXCreateTextureFromResourceExA

Creates a texture from a resource specified by an ANSI string. This is a more advanced function than D3DXCreateTextureFromResourceA.

HRESULT D3DXCreateTextureFromResourceExA(
  LPDIRECT3DDEVICE8 pDevice,
  HMODULE hSrcModule,
  LPCSTR pSrcResource,
  UINT Width,
  UINT Height,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo,
  PALETTEENTRY* pPalette,
  LPDIRECT3DTEXTURE8* ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to an ANSI string that specifies the resource from which to create the texture.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat.
Format
[in] A member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
MipFilter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.
D3DX_FILTER_BOX

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

The resource being loaded must be a bitmap resource(RT_BITMAP).

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXCreateTextureFromResourceEx maps to either D3DXCreateTextureFromResourceExA or D3DXCreateTextureFromResourceExW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateTextureFromResourceEx is defined.

#ifdef UNICODE
#define D3DXCreateTextureFromResourceEx D3DXCreateTextureFromResourceExW
#else
#define D3DXCreateTextureFromResourceEx D3DXCreateTextureFromResourceExA
#endif

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextureFromResourceA, D3DXCreateTextureFromResourceW, D3DXCreateTextureFromResourceExW


D3DXCreateTextureFromResourceExW

Creates a texture from a resource specified by a Unicode string. This is a more advanced function than D3DXCreateTextureFromResourceW.

HRESULT D3DXCreateTextureFromResourceExW(
  LPDIRECT3DDEVICE8 pDevice,
  HMODULE hSrcModule,
  LPCWSTR pSrcResource,
  UINT Width,
  UINT Height,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  DWORD Filter,
  DWORD MipFilter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo,
  PALETTEENTRY* pPalette,
  LPDIRECT3DTEXTURE8* ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a Unicode string that specifies the resource from which to create the texture.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] 0 or D3DUSAGE_RENDERTARGET. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the SetRenderTarget method. If D3DUSAGE_RENDERTARGET is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D8::CheckDeviceFormat.
Format
[in] A member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If Format is D3DFMT_UNKNOWN, the format is taken from the file.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
MipFilter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. See Remarks.
ppTexture
[out] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

The resource being loaded must be a bitmap resource(RT_BITMAP).

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXCreateTextureFromResourceEx maps to either D3DXCreateTextureFromResourceExA or D3DXCreateTextureFromResourceExW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateTextureFromResourceEx is defined.

#ifdef UNICODE
#define D3DXCreateTextureFromResourceEx D3DXCreateTextureFromResourceExW
#else
#define D3DXCreateTextureFromResourceEx D3DXCreateTextureFromResourceExA
#endif

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextureFromResourceA, D3DXCreateTextureFromResourceExA, D3DXCreateTextureFromResourceW


D3DXCreateTextureFromResourceW

Creates a texture from a resource specified by a Unicode string.

HRESULT D3DXCreateTextureFromResourceW(
  LPDIRECT3DDEVICE8 pDevice,
  HMODULE hSrcModule,
  LPCWSTR pSrcResource,
  LPDIRECT3DTEXTURE8* ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the texture.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a Unicode string that specifies the resource from which to create the texture.
ppTexture
[out] Address of a pointer to an IDirect3DTexture8 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA
E_OUTOFMEMORY

Remarks

The resource being loaded must be a bitmap resource(RT_BITMAP).

D3DXCreateTextureFromResource maps to either D3DXCreateTextureFromResourceA or D3DXCreateTextureFromResourceW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXCreateTextureFromResource is defined.

#ifdef UNICODE
#define D3DXCreateTextureFromResource D3DXCreateTextureFromResourceW
#else
#define D3DXCreateTextureFromResource D3DXCreateTextureFromResourceA
#endif

Note that a resource created with this function will be placed in the memory class denoted by D3DPOOL_MANAGED.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXCreateTextureFromResourceA, D3DXCreateTextureFromResourceExA, D3DXCreateTextureFromResourceExW


D3DXCreateVolumeTexture

Creates an empty volume texture, adjusting the calling parameters as needed.

HRESULT D3DXCreateVolumeTexture(
  LPDIRECT3DDEVICE8 pDevice,
  UINT Width,
  UINT Height,
  UINT Depth,
  UINT MipLevels,
  DWORD Usage,
  D3DFORMAT Format,
  D3DPOOL Pool,
  LPDIRECT3DVOLUMETEXTURE8* ppVolumeTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice8 interface, representing the device to be associated with the volume texture.
Width
[in] Width in pixels. This value must be non-zero.
Height
[in] Height in pixels. This value must be non-zero.
Depth
[in] Depth in pixels. This value must be non-zero.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created.
Usage
[in] Currently not used, set to 0.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the volume texture. The returned volume texture might have a different format from that specified by Format. Applications should check the format of the returned volume texture.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the volume texture should be placed.
ppVolumeTexture
[out] Address of a pointer to an IDirect3DVolumeTexture8 interface, representing the created volume texture object.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_NOTAVAILABLE
D3DERR_OUTOFVIDEOMEMORY
D3DERR_INVALIDCALL
E_OUTOFMEMORY

Remarks

Internally, D3DXCreateVolumeTexture uses D3DXCheckVolumeTextureRequirements to adjust the calling parameters. Therefore, calls to D3DXCreateVolumeTexture will often succeed where calls to IDirect3Ddevice8::CreateVolumeTexture would fail.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXFilterCubeTexture

Filters mipmap levels of a cube texture map.

HRESULT D3DXFilterCubeTexture(
  LPDIRECT3DCUBETEXTURE8 pCubeTexture,
  CONST PALETTEENTRY* pPalette,
  UINT SrcLevel,
  DWORD MipFilter
);

Parameters

pCubeTexture
[in] Pointer to an IDirect3DCubeTexture8 interface, representing the cube texture object to filter.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL. If a palette is not specified, the default Microsoft® Direct3D® palette (an all opaque white palette) is provided. See Remarks.
SrcLevel
[in] The level whose image is used to generate the subsequent levels. Specifying D3DX_DEFAULT for this parameter is equivalent to specifying 0.
MipFilter
[in] A combination of one or more flags controlling how the mipmap is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

For each side of the cube texture, a box-filter is recursively applied to each level to generate the next level.

Cube textures created in the default pool (D3DPOOL_DEFAULT) cannot be used with D3DXFilterCubeTexture because a lock operation is needed on the object. Note that locks are prohibited on textures in the default pool.

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXFilterTexture

Filters mipmap levels of a texture.

HRESULT D3DXFilterTexture(
  LPDIRECT3DTEXTURE8 pTexture,
  CONST PALETTEENTRY* pPalette,
  UINT SrcLevel,
  DWORD MipFilter
);

Parameters

pTexture
[in] Pointer to an IDirect3DTexture8 interface, representing the texture object to filter.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL for nonpalletized formats. If a palette is not specified, the default Microsoft® Direct3D® palette (an all opaque white palette) is provided. See Remarks.
SrcLevel
[in] The level whose image is used to generate the subsequent levels. Specifying D3DX_DEFAULT for this parameter is equivalent to specifying 0.
MipFilter
[in] A combination of one or more flags controlling how the mipmap is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
This flag indicates that the resulting image be dithered using a 4x4 ordered dither algorithm.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

A box-filter is recursively applied to each texture level to generate the next texture level.

Textures created in the default pool (D3DPOOL_DEFAULT) cannot be used with D3DXFilterTexture because a lock operation is needed on the object. Note that locks are prohibited on textures in the default pool.

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXFilterVolumeTexture

Filters mipmap levels of a volume texture.

HRESULT D3DXFilterVolumeTexture(
  LPDIRECT3DVOLUMETEXTURE8 pVolumeTexture,
  CONST PALETTEENTRY* pPalette,
  UINT SrcLevel,
  DWORD MipFilter
);

Parameters

pVolumeTexture
[in] Pointer to an IDirect3DVolumeTexture8 interface, representing the volume texture object to filter.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL for nonpalletized formats. If a palette is not specified, the default Microsoft® Direct3D® palette (an all opaque white palette) is provided. See Remarks.
SrcLevel
[in] The level whose image is used to generate the subsequent levels. Specifying D3DX_DEFAULT for this parameter is equivalent to specifying 0.
MipFilter
[in] A combination of one or more flags controlling how the mipmap is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX | D3D_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be D3DERR_INVALIDCALL.

Remarks

A box-filter is recursively applied to each texture level to generate the next texture level.

Volume textures created in the default pool (D3DPOOL_DEFAULT) cannot be used with D3DXFilterVolumeTexture because a lock operation is needed on the object. Note that locks are prohibited on textures in the default pool.

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXLoadSurfaceFromFileA

Loads a surface from a file specified by an ANSI string.

HRESULT D3DXLoadSurfaceFromFileA(
  LPDIRECT3DSURFACE8 pDestSurface,
  CONST PALETTEENTRY* pDestPalette,
  CONST RECT* pDestRect,
  LPCSTR pSrcFile,
  CONST RECT* pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface8 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL. See Remarks.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcFile
[in] Pointer to an ANSI string that specifies the file name of the source image.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXLoadSurfaceFromFile maps to either D3DXLoadSurfaceFromFileA or D3DXLoadSurfaceFromFileW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXLoadSurfaceFromFile is defined.

#ifdef UNICODE
#define D3DXLoadSurfaceFromFile D3DXLoadSurfaceFromFileW
#else
#define D3DXLoadSurfaceFromFile D3DXLoadSurfaceFromFileA
#endif

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXLoadSurfaceFromFileW


D3DXLoadSurfaceFromFileInMemory

Loads a surface from a file in memory.

HRESULT D3DXLoadSurfaceFromFileInMemory(
  LPDIRECT3DSURFACE8 pDestSurface,
  CONST PALETTEENTRY* pDestPalette,
  CONST RECT* pDestRect,
  LPCVOID pSrcData,
  UINT SrcData,
  CONST RECT* pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface8 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL. See Remarks.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcData
[in] Pointer to the file in memory from which to load the surface.
SrcData
[in] Size of the file in memory, in bytes.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXLoadSurfaceFromFileW

Loads a surface from a file specified by a Unicode string.

HRESULT D3DXLoadSurfaceFromFileW(
  LPDIRECT3DSURFACE8 pDestSurface,
  CONST PALETTEENTRY* pDestPalette,
  CONST RECT* pDestRect,
  LPCWSTR pSrcFile,
  CONST RECT* pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface8 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL. See Remarks.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcFile
[in] Pointer to a Unicode string that specifies the file name of the source image.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire image.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXLoadSurfaceFromFile maps to either D3DXLoadSurfaceFromFileA or D3DXLoadSurfaceFromFileW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXLoadSurfaceFromFile is defined.

#ifdef UNICODE
#define D3DXLoadSurfaceFromFile D3DXLoadSurfaceFromFileW
#else
#define D3DXLoadSurfaceFromFile D3DXLoadSurfaceFromFileA
#endif

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXLoadSurfaceFromFileA


D3DXLoadSurfaceFromMemory

Loads a surface from memory.

HRESULT D3DXLoadSurfaceFromMemory(
  LPDIRECT3DSURFACE8 pDestSurface,
  CONST PALETTEENTRY* pDestPalette,
  CONST RECT* pDestRect,
  LPCVOID pSrcMemory,
  D3DFORMAT SrcFormat,
  UINT SrcPitch,
  CONST PALETTEENTRY* pSrcPalette,
  CONST RECT* pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface8 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL. See Remarks.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcMemory
[in] Pointer to the top-left corner of the source image in memory.
SrcFormat
[in] Member of the D3DFORMAT enumerated type, the pixel format of the source image.
SrcPitch
[in] Pitch of source image, in bytes. For DXT formats, this number should represent the width of one row of cells, in bytes.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL. See Remarks.
pSrcRect
[in] Pointer to a RECT structure. Specifies the dimensions of the source image in memory. This value cannot be NULL.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXLoadSurfaceFromResourceA

Loads a surface from a resource specified by an ANSI string.

HRESULT D3DXLoadSurfaceFromResourceA(
  LPDIRECT3DSURFACE8 pDestSurface,
  CONST PALETTEENTRY* pDestPalette,
  CONST RECT* pDestRect,
  HMODULE hSrcModule,
  LPCSTR pSrcResource,
  CONST RECT* pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface8 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL. See Remarks.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to an ANSI string that specifies the resource name of the source image.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire surface.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

The resource being loaded must be a bitmap resource(RT_BITMAP).

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXLoadSurfaceFromResource maps to either D3DXLoadSurfaceFromResourceA or D3DXLoadSurfaceFromResourceW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXLoadSurfaceFromResource is defined.

#ifdef UNICODE
#define D3DXLoadSurfaceFromResource D3DXLoadSurfaceFromResourceW
#else
#define D3DXLoadSurfaceFromResource D3DXLoadSurfaceFromResourceA
#endif

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXLoadSurfaceFromResourceW


D3DXLoadSurfaceFromResourceW

Loads a surface from a resource specified by a Unicode string.

HRESULT D3DXLoadSurfaceFromResourceW(
  LPDIRECT3DSURFACE8 pDestSurface,
  CONST PALETTEENTRY* pDestPalette,
  CONST RECT* pDestRect,
  HMODULE hSrcModule,
  LPCWSTR pSrcResource,
  CONST RECT* pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey,
  D3DXIMAGE_INFO* pSrcInfo
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface8 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL. See Remarks.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
hSrcModule
[in] Handle to the module where the resource is located, or NULL for module associated with the image the operating system used to create the current process.
pSrcResource
[in] Pointer to a Unicode string that specifies the resource name of the source image.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire surface.
Filter
[in] A combination of one or more flags controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled with a description of the data in the source image file, or NULL.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

The resource being loaded must be a bitmap resource(RT_BITMAP).

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

D3DXLoadSurfaceFromResource maps to either D3DXLoadSurfaceFromResourceA or D3DXLoadSurfaceFromResourceW, depending on the inclusion or exclusion of the #define UNICODE switch. Include or exclude the #define UNICODE switch to specify whether your application expects Unicode or ANSI strings. The following code fragment shows how D3DXLoadSurfaceFromResource is defined.

#ifdef UNICODE
#define D3DXLoadSurfaceFromResource D3DXLoadSurfaceFromResourceW
#else
#define D3DXLoadSurfaceFromResource D3DXLoadSurfaceFromResourceA
#endif

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.

See Also

D3DXLoadSurfaceFromResourceA


D3DXLoadSurfaceFromSurface

Loads a surface from another surface with color conversion.

HRESULT D3DXLoadSurfaceFromSurface(
  LPDIRECT3DSURFACE8 pDestSurface,
  CONST PALETTEENTRY* pDestPalette,
  CONST RECT* pDestRect,
  LPDIRECT3DSURFACE8 pSrcSurface,
  CONST PALETTEENTRY* pSrcPalette,
  CONST RECT* pSrcRect,
  DWORD Filter,
  D3DCOLOR ColorKey
);

Parameters

pDestSurface
[in] Pointer to an IDirect3DSurface8 interface. Specifies the destination surface, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL. See Remarks.
pDestRect
[in] Pointer to a RECT structure. Specifies the destination rectangle. Set this parameter to NULL to specify the entire surface.
pSrcSurface
[in] Pointer to an IDirect3DSurface8 interface, representing the source surface.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL. See Remarks.
pSrcRect
[in] Pointer to a RECT structure. Specifies the source rectangle. Set this parameter to NULL to specify the entire surface.
Filter
[in] A combination of one or more flags, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXLoadVolumeFromMemory

Loads a volume from memory.

HRESULT D3DXLoadVolumeFromMemory(
  LPDIRECT3DVOLUME8 pDestVolume,
  CONST PALETTEENTRY* pDestPalette,
  CONST D3DBOX* pDestBox,
  LPCVOID pSrcMemory,
  D3DFORMAT SrcFormat,
  UINT SrcRowPitch,
  UINT SrcSlicePitch,
  CONST PALETTEENTRY* pSrcPalette,
  CONST D3DBOX* pSrcBox,
  DWORD Filter,
  D3DCOLOR ColorKey
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume8 interface. Specifies the destination volume, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL. See Remarks.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcMemory
[in] Pointer to the top-left corner of the source volume in memory.
SrcFormat
[in] Member of the D3DFORMAT enumerated type, the pixel format of the source volume.
SrcRowPitch
[in] Pitch of source image, in bytes. For DXT formats (compressed texture formats), this number should represent the size of one row of cells, in bytes.
SrcSlicePitch
[in] Pitch of source image, in bytes. For DXT formats (compressed texture formats), this number should represent the size of one slice of cells, in bytes.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL. See Remarks.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. NULL is not a valid value for this parameter.
Filter
[in] A combination of one or more flags, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


D3DXLoadVolumeFromVolume

Loads a volume from another volume.

HRESULT D3DXLoadVolumeFromVolume(
  LPDIRECT3DVOLUME8 pDestVolume,
  CONST PALETTEENTRY* pDestPalette,
  CONST D3DBOX* pDestBox,
  LPDIRECT3DVOLUME8 pSrcVolume,
  CONST PALETTEENTRY* pSrcPalette,
  CONST D3DBOX* pSrcBox,
  DWORD Filter,
  D3DCOLOR ColorKey
);

Parameters

pDestVolume
[in] Pointer to an IDirect3DVolume8 interface. Specifies the destination volume, which receives the image.
pDestPalette
[in] Pointer to a PALETTEENTRY structure, the destination palette of 256 colors or NULL. See Remarks.
pDestBox
[in] Pointer to a D3DBOX structure. Specifies the destination box. Set this parameter to NULL to specify the entire volume.
pSrcVolume
[in] A Pointer to an IDirect3DVolume8 interface. Specifies the source volume.
pSrcPalette
[in] Pointer to a PALETTEENTRY structure, the source palette of 256 colors or NULL. See Remarks.
pSrcBox
[in] Pointer to a D3DBOX structure. Specifies the source box. Set this parameter to NULL to specify the entire volume.
Filter
[in] A combination of one or more flags, controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.

Each valid filter must contain exactly one of the following flags.

D3DX_FILTER_BOX
Each pixel is computed by averaging a 2×2(×2) box of pixels from the source image. This filter works only when the dimensions of the destination are half those of the source, as is the case with mipmaps.
D3DX_FILTER_LINEAR
Each destination pixel is computed by sampling the four nearest pixels from the source image. This filter works best when the scale on both axes is less than two.
D3DX_FILTER_NONE
No scaling or filtering will take place. Pixels outside the bounds of the source image are assumed to be transparent black.
D3DX_FILTER_POINT
Each destination pixel is computed by sampling the nearest pixel from the source image.
D3DX_FILTER_TRIANGLE
Every pixel in the source image contributes equally to the destination image. This is the slowest of the filters.

In addition, you can use the OR operator to specify zero or more of the following optional flags with a valid filter.

D3DX_FILTER_MIRROR
Specifying this flag is the same as specifying the D3DX_FILTER_MIRROR_U, D3DX_FILTER_MIRROR_V, and D3DX_FILTER_MIRROR_W flags.
D3DX_FILTER_MIRROR_U
Pixels off the edge of the texture on the u-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_V
Pixels off the edge of the texture on the v-axis should be mirrored, not wrapped.
D3DX_FILTER_MIRROR_W
Pixels off the edge of the texture on the w-axis should be mirrored, not wrapped.
D3DX_FILTER_DITHER
The resulting image must be dithered using a 4x4 ordered dither algorithm.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the colorkey. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque colorkeys. Thus, for opaque black, the value would be equal to 0xFF000000.

Return Values

If the function succeeds, the return value is D3D_OK.

If the function fails, the return value can be one of the following values.

D3DERR_INVALIDCALL
D3DXERR_INVALIDDATA

Remarks

For details on PALETTEENTRY, see the Microsoft® Platform Software Development Kit (SDK). Note that as of Microsoft DirectX® 8.0, the peFlags member of the PALLETTEENTRY structure does not function as documented in the Platform SDK. The peFlags member is now the alpha channel for 8-bit palletized formats.

Requirements

Header: Declared in D3dx8tex.h.
Import Library: Use D3dx8.lib.


Macros

This section contains reference information for the macros provided by the Direct3DX utility library.

  • D3DXToDegree
  • D3DXToRadian


D3DXToDegree

Converts radians into degrees.

D3DXToDegree( radian ) ((radian) * (180.0f / D3DX_PI))

Parameters

radian
The value, in radians, to convert to degrees.

Return Values

The macro returns the radian value in degrees.

Remarks

The CONSTant D3DX_PI is declared with the following define.

#define D3DX_PI    ((FLOAT)  3.141592654f)

Requirements

Header: Declared in D3dx8math.h.

See Also

D3DXToRadian


D3DXToRadian

Converts degrees into radians.

D3DXToRadian( degree ) ((degree) * (D3DX_PI / 180.0f))

Parameters

degree
The value, in degrees, to convert to radians.

Return Values

The macro returns the degree value in radians.

Remarks

The CONSTant D3DX_PI is declared with the following define.

#define D3DX_PI    ((FLOAT)  3.141592654f)

Requirements

Header: Declared in D3dx8math.H.

See Also

D3DXToDegree


Structures

This section contains information about the structures included in the Direct3DX utility library.

  • D3DXATTRIBUTERANGE
  • D3DXATTRIBUTEWEIGHTS
  • D3DXBONECOMBINATION
  • D3DXCOLOR
  • D3DXEFFECT_DESC
  • D3DXIMAGE_INFO
  • D3DXMATERIAL
  • D3DXMATRIX
  • D3DXPASS_DESC
  • D3DXPARAMETER_DESC
  • D3DXPLANE
  • D3DXQUATERNION
  • D3DXTECHNIQUE_DESC
  • D3DXVECTOR2
  • D3DXVECTOR3
  • D3DXVECTOR4
  • D3DXRTS_DESC


D3DXATTRIBUTERANGE

Stores an attribute table entry.

typedef struct _D3DXATTRIBUTERANGE {
    DWORD AttribId;
    DWORD FaceStart;
    DWORD FaceCount;
    DWORD VertexStart;
    DWORD VertexCount;
} D3DXATTRIBUTERANGE;

Members

AttribId
Attribute table identifier.
FaceStart
Starting face.
FaceCount
Face count.
VertexStart
Starting vertex.
VertexCount
Vertex count.

Remarks

An attribute table is used to identify areas of the mesh that need to be drawn with different textures, render states, materials, and so on. In addition, the application can use the attribute table to hide portions of a mesh by not drawing a given attribute identifier (AttribId) when drawing the frame.

The LPD3DXATTRIBUTERANGE type is defined as a pointer to the D3DXATTRIBUTERANGE structure.

typedef D3DXATTRIBUTERANGE* LPD3DXATTRIBUTERANGE;

Requirements

Header: Declared in D3dx8mesh.h.

See Also

ID3DXBaseMesh::DrawSubset


D3DXATTRIBUTEWEIGHTS

Specifies how to weigh vertex components.

typedef struct _D3DXATTRIBUTEWEIGHTS {
    FLOAT Position;
    FLOAT Boundary;
    FLOAT Normal;
    FLOAT Diffuse;
    FLOAT Specular;
    FLOAT Tex[8];
} D3DXATTRIBUTEWEIGHTS;

Members

Position
Position component weight.
Boundary
Boundary component weight.
Normal
Normal component weight.
Diffuse
Diffuse component weight.
Specular
Specular component weight.
Tex
Texture coordinate weights.

Remarks

This structure describes how a simplification operation will consider vertex data when calculating relative costs between collapsing edges. For example, if the Normal field is 0.0, then the simplification operation will ignore the vertex normal component when calculating the error for the collapse. However, if the Normal field is 1.0, then the simplification operation will use the vertex normal component. if the Normal field is 2.0, then double the amount of errors; if the Normal field is 4.0, then quadruple the number of errors, and so on.

The LPD3DXATTRIBUTEWEIGHTS type is defined as a pointer to the D3DXATTRIBUTEWEIGHTS structure.

typedef D3DXATTRIBUTEWEIGHTS* LPD3DXATTRIBUTEWEIGHTS;

Requirements

Header: Declared in D3dx8mesh.h.

See Also

D3DXCreateSPMesh, D3DXGeneratePMesh, D3DXSimplifyMesh


D3DXBONECOMBINATION

Describes a subset of the mesh that has the same attribute and bone combination.

typedef struct _D3DXBONECOMBINATION {
    DWORD AttribId;
    DWORD FaceStart;
    DWORD FaceCount;
    DWORD VertexStart;
    DWORD VertexCount;
    DWORD* BoneId;
} D3DXBONECOMBINATION, *LPD3DXBONECOMBINATION;

Members

AttribId
Attribute table identifier.
FaceStart
Starting face.
FaceCount
Face count.
VertexStart
Starting vertex.
VertexCount
Vertex count.
BoneId
Pointer to an array of values that identify each of the bones that can be drawn in a single drawing call. Note that the array can be of variable length to accommodate variable length bone combinations of ID3DXSkinMesh::ConvertToIndexedBlendedMesh.

Remarks

The subset of the mesh described by D3DXBONECOMBINATION can be rendered in a single drawing call.

Requirements

Header: Declared in D3dx8mesh.h.


D3DXCOLOR

Describes color values.

typedef struct D3DXCOLOR {
  FLOAT r, g, b, a;
} D3DXCOLOR;

Members

r
Red component of the color.
g
Green component of the color.
b
Blue component of the color.
a
Alpha component of the color.

Remarks

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXCOLOR structure implements overloaded constructors and overloaded assignment, unary, and binary (including equality) operators. For more information, see C++ Specific Features.

Requirements

Header: Declared in D3dx8math.h.


D3DXEFFECT_DESC

Describes an effect object.

typedef struct _D3DXEFFECT_DESC
{
    UINT  Parameters;
    UINT  Techniques;
    DWORD Usage;

} D3DXEFFECT_DESC;

Members

Parameters
Number of parameters used for effect.
Techniques
Number of techniques that can render the effect.
Usage
Usage control for this effect. This member can have the following flag set:
D3DUSAGE_SOFTWAREPROCESSING
Set to indicate that the effect will use software processing.

Remarks

An effect object can contain multiple rendering techniques and parameters for the same effect.

Requirements

Header: Declared in D3dx8effect.h.

See Also

ID3DXEffect::GetDesc


D3DXIMAGE_INFO

Returns a description of the original contents of an image file.

typedef struct _D3DXIMAGE_INFO {
    UINT Width;
    UINT Height;
    UINT Depth;
    UINT MipLevels;
    D3DFORMAT Format;
} D3DXIMAGE_INFO;

Members

Width
Width of original image in pixels.
Height
Height of original image in pixels.
Depth
Depth of original image in pixels.
MipLevels
Number of mip levels in original image.
Format
A value from the D3DFORMAT enumerated type that most closely describes the data in the original image.

Requirements

Header: Declared in D3dx8tex.h.


D3DXMATERIAL

Returns material information saved in Microsoft® DirectX® (.x) files.

struct D3DXMATERIAL {
    D3DMATERIAL8  MatD3D;
    LPSTR         pTextureFilename;
};

Members

MatD3D
D3DMATERIAL8 structure that describes the material properties.
pTextureFilename
Pointer to a string that specifies the file name of the texture.

Remarks

The D3DXLoadMeshFromX and D3DXLoadMeshFromXof functions return an array of D3DXMATERIAL structures that specify the material color and name of the texture for each material in the mesh. The application is then required to load the texture.

The LPD3DXMATERIAL type is defined as a pointer to the D3DXMATERIAL structure.

typedef struct D3DXMATERIAL *LPD3DXMATERIAL;

Requirements

Header: Declared in D3dx8mesh.h.

See Also

D3DXLoadMeshFromX, D3DXLoadMeshFromXof


D3DXMATRIX

Describes a matrix.

typedef struct D3DXMATRIX : public D3DMATRIX {
public:
    D3DXMATRIX() {};
    D3DXMATRIX( CONST FLOAT * );
    D3DXMATRIX( CONST D3DMATRIX& );
    D3DXMATRIX( FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
                FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
                FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
                FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );

    // access grants
    FLOAT& operator () ( UINT Row, UINT Col );
    FLOAT  operator () ( UINT Row, UINT Col ) const;

    // casting operators
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXMATRIX& operator *= ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator += ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator -= ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator *= ( FLOAT );
    D3DXMATRIX& operator /= ( FLOAT );

    // unary operators
    D3DXMATRIX operator + () const;
    D3DXMATRIX operator - () const;

    // binary operators
    D3DXMATRIX operator * ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator + ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator - ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator * ( FLOAT ) const;
    D3DXMATRIX operator / ( FLOAT ) const;

    friend D3DXMATRIX operator * ( FLOAT, CONST D3DXMATRIX& );

    BOOL operator == ( CONST D3DXMATRIX& ) const;
    BOOL operator != ( CONST D3DXMATRIX& ) const;

} D3DXMATRIX, *LPD3DXMATRIX;

Remarks

This structure inherits members from the D3DMATRIX structure. C programmers cannot use the D3DXMATRIX structure. They must use the D3DMATRIX structure.

In Direct3DX, the _34 element of a projection matrix cannot be a negative number. If your application needs to use a negative value in this location, it should scale the entire projection matrix by -1, instead.

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXMATRIX structure implements overloaded constructors and overloaded assignment, unary, and binary (including equality) operators. For more information, see C++ Specific Features.

Requirements

Header: Declared in D3dx8math.h.


D3DXPARAMETER_DESC

Describes a parameter used for an effect object.

typedef struct _D3DXPARAMETER_DESC
{
    DWORD             Name;
    D3DXPARAMETERTYPE Type;

} D3DXPARAMETER_DESC;

Members

Name
Four-character code that is the name of parameter.
Type
Describes the type of variable used for this parameter. This member is one of the following constants:
D3DXPT_DWORD
Parameter is a DWORD value.
D3DXPT_FLOAT
Parameter is a floating-point value.
D3DXPT_VECTOR
Parameter is a vector.
D3DXPT_MATRIX
Parameter is a 4x4 matrix.
D3DXPT_TEXTURE
Parameter is a texture.
D3DXPT_VERTEXSHADER
Parameter is a vertex shader.
D3DXPT_PIXELSHADER
Parameter is a pixel shader.
D3DXPT_CONSTANT
Parameter is a constant value.
D3DXPT_FORCE_DWORD
Forces this enumeration to compile to 32 bits in size. This value is not used.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.

See Also

ID3DXEffect::GetParameterDesc


D3DXPASS_DESC

Describes a pass for an effect object.

typedef struct _D3DXPASS_DESC
{
    DWORD Name;

} D3DXPASS_DESC;

Members

Name
Four-character code used for the name of the pass.

Remarks

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.

See Also

ID3DXTechnique::GetPassDesc


D3DXPLANE

Describes a plane.

typedef struct D3DXPLANE {
  FLOAT a, b, c, d;
} D3DXPLANE;

Members

a, b, c, and d
The a, b, c, and d coefficients, respectively, of the clipping plane in the general plane equation. See Remarks.

Remarks

The members of the D3DXPLANE structure take the form of the general plane equation. They fit into the general plane equation so that ax + by + cz + dw = 0.

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXPLANE structure implements overloaded constructors and overloaded unary and binary operators. For more information, see C++ Specific Features.

Requirements

Header: Declared in D3dx8math.h.


D3DXQUATERNION

Describes a quaternion.

typedef struct D3DXQUATERNION {
  FLOAT x, y, z, w;
} D3DXQUATERNION;

Members

x
The x component.
y
The y component.
z
The z component.
w
The w component.

Remarks

Quaternions add a fourth element to the [x, y, z] values that define a vector, resulting in arbitrary 4-D vectors. However, the following illustrates how each element of a unit quaternion relates to an axis-angle rotation (where q represents a unit quaternion (x, y, z, w), axis is normalized, and theta is the desired CCW rotation about the axis):

q.x = sin(theta/2) * axis.x
q.y = sin(theta/2) * axis.y
q.z = sin(theta/2) * axis.z
q.w = cos(theta/2)

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXQUATERNION structure implements overloaded constructors and overloaded assignment, unary and binary (including equality) operators. For more information, see C++ Specific Features.

Requirements

Header: Declared in D3dx8math.h.


D3DXTECHNIQUE_DESC

Describes a technique object.

typedef struct _D3DXTECHNIQUE_DESC
{
    DWORD Name;
    UINT  Passes;
} D3DXTECHNIQUE_DESC;

Members

Name
Four-character code used for the name of this technique object.
Passes
Number of rendering passes the technique requires. See Remarks.

Remarks

Some video cards can render two textures in a single pass. However, if a card does not have this capability, it is often possible to render the same effect in two passes using one texture for each pass.

A four-character code (FOURCC) is a string that is four characters in length. For more information, see Four-Character Codes (FOURCC).

Requirements

Header: Declared in D3dx8effect.h.

See Also

ID3DXTechnique::GetDesc


D3DXVECTOR2

Describes a vector in two-dimensional (2-D) space.

typedef struct D3DXVECTOR2 {
  FLOAT x, y;
} D3DXVECTOR2;

Members

x
The x component.
y
The y component.

Remarks

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXVECTOR2 structure implements overloaded constructors and overloaded assignment, unary and binary (including equality) operators. For more information, see C++ Specific Features.

Requirements

Header: Declared in D3dx8math.h.


D3DXVECTOR3

Describes a vector in three-dimensional (3-D) space.

typedef struct D3DXVECTOR3 : public D3DVECTOR {
public:
    D3DXVECTOR3() {};
    D3DXVECTOR3( CONST FLOAT * );
    D3DXVECTOR3( CONST D3DVECTOR& );
    D3DXVECTOR3( FLOAT x, FLOAT y, FLOAT z );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR3& operator += ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator -= ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator *= ( FLOAT );
    D3DXVECTOR3& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR3 operator + () const;
    D3DXVECTOR3 operator - () const;

    // binary operators
    D3DXVECTOR3 operator + ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator - ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator * ( FLOAT ) const;
    D3DXVECTOR3 operator / ( FLOAT ) const;

    friend D3DXVECTOR3 operator * ( FLOAT, CONST struct D3DXVECTOR3& );

    BOOL operator == ( CONST D3DXVECTOR3& ) const;
    BOOL operator != ( CONST D3DXVECTOR3& ) const;

} D3DXVECTOR3, *LPD3DXVECTOR3;

Members

x
The x component.
y
The y component.
z
The z component.

Remarks

This structure inherits the x, y and z members from the D3DVECTOR structure. C programmers cannot use the D3DXVECTOR3 structure. They must use the D3DVECTOR structure.

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXVECTOR3 structure implements overloaded constructors and overloaded assignment, unary and binary (including equality) operators. For more information, see C++ Specific Features.

Requirements

Header: Declared in D3dx8math.h.


D3DXVECTOR4

Describes a vector in four-dimensional (4-D) space.

typedef struct D3DXVECTOR4 {
  FLOAT x, y, z, w;
} D3DXVECTOR4;

Members

x
The x component.
y
The y component.
z
The z component.
w
The w component.

Remarks

C++ programmers can take advantage of operator overloading and type casting. The C++ implementation of the D3DXVECTOR4 structure implements overloaded constructors and overloaded assignment, unary and binary (including equality) operators. For more information, see C++ Specific Features.

Requirements

Header: Declared in D3dx8math.h.


D3DXRTS_DESC

Describes a render surface.

typedef struct _D3DXRTS_DESC {
    UINT                Width;
    UINT                Height;
    D3DFORMAT           Format;
    BOOL                DepthStencil;
    D3DFORMAT           DepthStencilFormat;

} D3DXRTS_DESC;

Members

Width
Width of the render surface, in pixels.
Height
Height of the render surface, in pixels.
Format
Member of the D3DFORMAT enumerated type, describing the pixel format of the render surface.
DepthStencil
If TRUE, the render surface supports a depth-stencil surface; otherwise this member is set to FALSE.
DepthStencilFormat
If DepthStencil is set to TRUE, this parameter is a member of the D3DFORMAT enumerated type, describing the depth-stencil format of the render surface.

Requirements

Header: Declared in D3dx8core.h.

See Also

ID3DXRenderToSurface::GetDesc


C++ Specific Features

C++ programmers can take advantage of the constructor overloading, operator overloading, and type casting extensions offered by the Direct3DX utility library. The extensions are implemented in the following structures.

  • D3DXCOLOR Extensions
  • D3DXMATRIX Extensions
  • D3DXPLANE Extensions
  • D3DXQUATERNION Extensions
  • D3DXVECTOR2 Extensions
  • D3DXVECTOR3 Extensions
  • D3DXVECTOR4 Extensions


D3DXCOLOR Extensions

Supplies the following operator overloads and type casts for D3DXCOLOR structures.

#ifdef __cplusplus
public:
    D3DXCOLOR() {}
    D3DXCOLOR( DWORD argb );
    D3DXCOLOR( CONST FLOAT * );
    D3DXCOLOR( CONST D3DCOLORVALUE& );
    D3DXCOLOR( FLOAT r, FLOAT g, FLOAT b, FLOAT a );

    // casting
    operator DWORD () const;

    operator FLOAT* ();
    operator CONST FLOAT* () const;

    operator D3DCOLORVALUE* ();
    operator CONST D3DCOLORVALUE* () const;

    operator D3DCOLORVALUE& ();
    operator CONST D3DCOLORVALUE& () const;

    // assignment operators
    D3DXCOLOR& operator += ( CONST D3DXCOLOR& );
    D3DXCOLOR& operator -= ( CONST D3DXCOLOR& );
    D3DXCOLOR& operator *= ( FLOAT );
    D3DXCOLOR& operator /= ( FLOAT );

    // unary operators
    D3DXCOLOR operator + () const;
    D3DXCOLOR operator - () const;

    // binary operators
    D3DXCOLOR operator + ( CONST D3DXCOLOR& ) const;
    D3DXCOLOR operator - ( CONST D3DXCOLOR& ) const;
    D3DXCOLOR operator * ( FLOAT ) const;
    D3DXCOLOR operator / ( FLOAT ) const;

    friend D3DXCOLOR operator * (FLOAT, CONST D3DXCOLOR& );

    BOOL operator == ( CONST D3DXCOLOR& ) const;
    BOOL operator != ( CONST D3DXCOLOR& ) const;

#endif //__cplusplus

Requirements

Header: Declared in D3dx8mesh.h.


D3DXMATRIX Extensions

Supplies the following operator overloads and type casts for D3DXMATRIX structures.

#ifdef __cplusplus
typedef struct D3DXMATRIX : public D3DMATRIX
{
public:
    D3DXMATRIX() {};
    D3DXMATRIX( CONST FLOAT * );
    D3DXMATRIX( CONST D3DMATRIX& );
    D3DXMATRIX( FLOAT _11, FLOAT _12, FLOAT _13, FLOAT _14,
                FLOAT _21, FLOAT _22, FLOAT _23, FLOAT _24,
                FLOAT _31, FLOAT _32, FLOAT _33, FLOAT _34,
                FLOAT _41, FLOAT _42, FLOAT _43, FLOAT _44 );

    // access grants
    FLOAT& operator () ( UINT Row, UINT Col );
    FLOAT  operator () ( UINT Row, UINT Col ) const;

    // casting operators
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXMATRIX& operator *= ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator += ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator -= ( CONST D3DXMATRIX& );
    D3DXMATRIX& operator *= ( FLOAT );
    D3DXMATRIX& operator /= ( FLOAT );

    // unary operators
    D3DXMATRIX operator + () const;
    D3DXMATRIX operator - () const;

    // binary operators
    D3DXMATRIX operator * ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator + ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator - ( CONST D3DXMATRIX& ) const;
    D3DXMATRIX operator * ( FLOAT ) const;
    D3DXMATRIX operator / ( FLOAT ) const;

    friend D3DXMATRIX operator * ( FLOAT, CONST D3DXMATRIX& );

    BOOL operator == ( CONST D3DXMATRIX& ) const;
    BOOL operator != ( CONST D3DXMATRIX& ) const;

} D3DXMATRIX, *LPD3DXMATRIX;

#else //!__cplusplus

Requirements

Header: Declared in D3dx8mesh.h.


D3DXPLANE Extensions

Supplies the following operator overloads and type casts for D3DXPLANE structures.

#ifdef __cplusplus
public:
    D3DXPLANE() {}
    D3DXPLANE( CONST FLOAT* );
    D3DXPLANE( FLOAT a, FLOAT b, FLOAT c, FLOAT d );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // unary operators
    D3DXPLANE operator + () const;
    D3DXPLANE operator - () const;

    // binary operators
    BOOL operator == ( CONST D3DXPLANE& ) const;
    BOOL operator != ( CONST D3DXPLANE& ) const;

#endif //__cplusplus

Requirements

Header: Declared in D3dx8mesh.h.


D3DXQUATERNION Extensions

Supplies the following operator overloads and type casts for D3DXQUATERNION structures.

#ifdef __cplusplus
public:
    D3DXQUATERNION() {}
    D3DXQUATERNION( CONST FLOAT * );
    D3DXQUATERNION( FLOAT x, FLOAT y, FLOAT z, FLOAT w );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXQUATERNION& operator += ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator -= ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator *= ( CONST D3DXQUATERNION& );
    D3DXQUATERNION& operator *= ( FLOAT );
    D3DXQUATERNION& operator /= ( FLOAT );

    // unary operators
    D3DXQUATERNION  operator + () const;
    D3DXQUATERNION  operator - () const;

    // binary operators
    D3DXQUATERNION operator + ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator - ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator * ( CONST D3DXQUATERNION& ) const;
    D3DXQUATERNION operator * ( FLOAT ) const;
    D3DXQUATERNION operator / ( FLOAT ) const;

    friend D3DXQUATERNION operator * (FLOAT, CONST D3DXQUATERNION& );

    BOOL operator == ( CONST D3DXQUATERNION& ) const;
    BOOL operator != ( CONST D3DXQUATERNION& ) const;

#endif //__cplusplus

Requirements

Header: Declared in D3dx8mesh.h.


D3DXVECTOR2 Extensions

Supplies the following operator overloads and type casts for D3DXVECTOR2 structures.

#ifdef __cplusplus
public:
    D3DXVECTOR2() {};
    D3DXVECTOR2( CONST FLOAT * );
    D3DXVECTOR2( FLOAT x, FLOAT y );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR2& operator += ( CONST D3DXVECTOR2& );
    D3DXVECTOR2& operator -= ( CONST D3DXVECTOR2& );
    D3DXVECTOR2& operator *= ( FLOAT );
    D3DXVECTOR2& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR2 operator + () const;
    D3DXVECTOR2 operator - () const;

    // binary operators
    D3DXVECTOR2 operator + ( CONST D3DXVECTOR2& ) const;
    D3DXVECTOR2 operator - ( CONST D3DXVECTOR2& ) const;
    D3DXVECTOR2 operator * ( FLOAT ) const;
    D3DXVECTOR2 operator / ( FLOAT ) const;

    friend D3DXVECTOR2 operator * ( FLOAT, CONST D3DXVECTOR2& );

    BOOL operator == ( CONST D3DXVECTOR2& ) const;
    BOOL operator != ( CONST D3DXVECTOR2& ) const;

public:
#endif //__cplusplus

Requirements

Header: Declared in D3dx8mesh.h.


D3DXVECTOR3 Extensions

Supplies the following operator overloads and type casts for D3DXVECTOR3 structures.

#ifdef __cplusplus
typedef struct D3DXVECTOR3 : public D3DVECTOR
{
public:
    D3DXVECTOR3() {};
    D3DXVECTOR3( CONST FLOAT * );
    D3DXVECTOR3( CONST D3DVECTOR& );
    D3DXVECTOR3( FLOAT x, FLOAT y, FLOAT z );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR3& operator += ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator -= ( CONST D3DXVECTOR3& );
    D3DXVECTOR3& operator *= ( FLOAT );
    D3DXVECTOR3& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR3 operator + () const;
    D3DXVECTOR3 operator - () const;

    // binary operators
    D3DXVECTOR3 operator + ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator - ( CONST D3DXVECTOR3& ) const;
    D3DXVECTOR3 operator * ( FLOAT ) const;
    D3DXVECTOR3 operator / ( FLOAT ) const;

    friend D3DXVECTOR3 operator * ( FLOAT, CONST struct D3DXVECTOR3& );

    BOOL operator == ( CONST D3DXVECTOR3& ) const;
    BOOL operator != ( CONST D3DXVECTOR3& ) const;

} D3DXVECTOR3, *LPD3DXVECTOR3;

#else //!__cplusplus

Requirements

Header: Declared in D3dx8mesh.h.


D3DXVECTOR4 Extensions

Supplies the following operator overloads and type casts for D3DXVECTOR4 structures.

#ifdef __cplusplus
public:
    D3DXVECTOR4() {};
    D3DXVECTOR4( CONST FLOAT* );
    D3DXVECTOR4( FLOAT x, FLOAT y, FLOAT z, FLOAT w );

    // casting
    operator FLOAT* ();
    operator CONST FLOAT* () const;

    // assignment operators
    D3DXVECTOR4& operator += ( CONST D3DXVECTOR4& );
    D3DXVECTOR4& operator -= ( CONST D3DXVECTOR4& );
    D3DXVECTOR4& operator *= ( FLOAT );
    D3DXVECTOR4& operator /= ( FLOAT );

    // unary operators
    D3DXVECTOR4 operator + () const;
    D3DXVECTOR4 operator - () const;

    // binary operators
    D3DXVECTOR4 operator + ( CONST D3DXVECTOR4& ) const;
    D3DXVECTOR4 operator - ( CONST D3DXVECTOR4& ) const;
    D3DXVECTOR4 operator * ( FLOAT ) const;
    D3DXVECTOR4 operator / ( FLOAT ) const;

    friend D3DXVECTOR4 operator * ( FLOAT, CONST D3DXVECTOR4& );

    BOOL operator == ( CONST D3DXVECTOR4& ) const;
    BOOL operator != ( CONST D3DXVECTOR4& ) const;

public:
#endif //__cplusplus

Requirements

Header: Declared in D3dx8mesh.h.


Return Values

Errors are represented by negative values and cannot be combined. The following lists the values that can be returned by methods included with the Direct3DX utility library. See the individual method descriptions for lists of the values that each can return. These lists are not necessarily comprehensive.

D3DXERR_CANNOTATTRSORT
Attribute sort (D3DXMESHOPT_ATTRSORT) is not supported as an optimization technique.
D3DXERR_CANNOTMODIFYINDEXBUFFER
The index buffer cannot be modified.
D3DXERR_INVALIDMESH
The mesh is invalid.
D3DXERR_SKINNINGNOTSUPPORTED
Skinning is not supported.
D3DXERR_TOOMANYINFLUENCES
Too many influences specified.
D3DXERR_INVALIDDATA
The data is invalid.


Direct3DX Shader Assemblers Reference

This section contains reference information for the vertex and pixel shader assemblers provided by the Direct3DX utility library.

  • Vertex Shader Assembler Reference
  • Pixel Shader Assembler Reference

All of the example syntax used in this documentation is intended to demonstrate how to write shaders when using the Direct3DX vertex and pixel shader assemblers.


Vertex Shader Assembler Reference

This section contains reference information for the vertex shader assembler. Reference material is divided into the following categories.

  • Registers
  • Instructions
  • Modifiers

The vertex shader assembler is comprised of a set of registers defined along with a set of operations that can be performed on the registers. Operations are expressed as instructions comprised of an operator and one or more arguments (operands).


Registers

This section contains reference information for the input and output registers implemented by the Direct3DX vertex shader assembler. Information is divided into the following topics.

  • Input Registers
  • Output Registers

All registers are four-component floating-point vectors. Vector elements are designated as x, y, z and w in this documentation, but no semantics are implied.


Input Registers

The following table lists the minimum available input registers for use by a Microsoft® DirectX® 8.0 vertex shader. Note that this table applies to version 1.0 pixel shaders.

Name | Count | I/O Permissions | Number Allowed per Instruction
an | 1 scalar | write/use only | 0 in version 1.0; 1 in version 1.1
c[n] | 96 vectors | read-only | 1
rn | 12 vectors | read/write | 3
vn | 16 vectors | read-only | 1


an

These are the address registers. These registers are not available in vertex shader version 1.0 of Microsoft® DirectX® 8.0, and only a single register is available in version 1.1. The address register, designated as a0.x, may be used as signed integer offset in relative addressing into the constant register file.

c[a0.x + n]

Reads from out of the legal range will return (0.0, 0.0, 0.0, 0.0). Address registers may be a destination only for the mov instruction. Address registers cannot be read by the vertex shader, just used in relative addressing of the constant register file. Addresses read from outside the range of constant registers supported will return unpredictable results.

Version 1.0 vertex shaders that make any use of the address register will fail the Microsoft Direct3D® API call to create the vertex shader. Version 1.1 vertex shaders that attempt to use the address register before setting it will also fail.


c[n]

These are the constant registers. There are at least 96 four-component floating-point vectors comprising the constant register file. The constant registers are designated as either absolute or relative.

    c[n]            ; absolute
    c[a0.x + n]     ; relative - supported only in version 1.1

Therefore, the constant register may be read by using an absolute address, or addressed relative to an address register. Reads from out-of-range registers return (0.0, 0.0, 0.0, 0.0).

The constant register file is read-only from the perspective of the vertex shader. Any single instruction may access only one constant register. However, each source in that instruction may independently swizzle and negate that vector as it is read.

The MaxVertexShaderConst member of D3DCAPS8 indicates the number of available constant registers. Microsoft® DirectX® 8.0 shaders support at least 96 constants.

The constant register file has its data loaded by calling the Microsoft Direct3D® API function to set the vertex shader constant register. Alternatively, when creating a shader, the user can specify what constants should be loaded for a C++ application by an IDirect3DDevice8::SetVertexShader call.


rn

These are the temporary registers. The temporary registers are grouped into a file of 12 4-D floating point vectors. Each temporary register has single-write and triple-read access. Therefore, an instruction can have as many as three temporary registers in its set of input source operands.

No values in a temporary register that remain from preceding invocations of the vertex shader can be used. Vertex shaders that read a value from a temporary register before writing to it will fail the Microsoft® Direct3D® API call to create the vertex shader.


vn

These are the input vertex registers. Each vertex from one or more input vertex streams is loaded into the vertex input registers before the vertex shader is executed. The vertex input registers are a register file consisting of 16 four-component floating-point vectors, designated as v0 through v15. These registers are read only.

Any single instruction may access only one vertex input register. However, each source in the instruction may independently swizzle and negate that vector as it is read.

A declaration passed to the Microsoft® Direct3D® API call to create the vertex shader defines the mapping between the source vertex stream and the vertex input registers. For the fixed function pipeline, the input registers have the fixed mapping shown in the following table.

Vector Component | Register
Position | 0
Blend Weight | 1
Blend Indices | 2
Normal | 3
Point Size | 4
Diffuse | 5
Specular | 6
Texture Coordinate 0 | 7
Texture Coordinate 1 | 8
Texture Coordinate 2 | 9
Texture Coordinate 3 | 10
Texture Coordinate 4 | 11
Texture Coordinate 5 | 12
Texture Coordinate 6 | 13
Texture Coordinate 7 | 14
Position 2 | 15
Normal 2 | 16


Output Registers

Output registers are defined as the inputs to the rasterizer. Generated data is written into the output register file, which has write-only access.

The output registers are defined by the register model of the raster shader, which must support the following minimum counts.

Name | I/O Permissions | Count
oDn | write-only | 2 4-D vectors
oFog | write-only | 1 scalar float
oPos | write-only | 1 4-D vector
oPts | write-only | 1 scalar float
oTn | write-only | 4 4-D vectors

Write operations to destination registers not indicated above are ignored.

Register names are preceded by a lower case 'o,' indicating that the output registers are write-only.

When using vertex shaders with an implementation supporting only the Microsoft® DirectX® 6.0 or 7.0 pixel processing model—that is, an implementation without pixels shaders—the following output registers are available.

Name | I/0 Permissions | Count | Description
oDn | write-only | 2 vectors | Output color data. Required for diffuse color and specular color.
oPos | write-only | 1 vector | Output position. Required for clipping.
oTn | write-only | 2 vectors | Output texture coordinates. Required for maximum number of textures that can be simultaneously bound to the texture blending stages.


oDn

The output data registers, which are used to output vertex color data. Specifically, these are an array of output data registers that are iterated and directly routed to the pixel shader. Typically, these registers are used for colors.


oFog

The output fog value registers. The value is the fog factor to be interpolated and then routed to the fog table. Only the scalar x-component of the fog is used.


oPos

The output position registers. The value is the position in homogeneous clipping space. This value must be written by the vertex shader.


oPts

The output point-size registers. Only the scalar x-component of the point size is used.


oTn

The output texture coordinates registers. Specifically, these are an array of output data registers that are iterated and used as texture coordinate by the sampling stages routing data to the pixel shader.


Instructions

This section contains reference information for the instructions implemented by the Direct3DX vertex shader assembler. Information is divided into the following topics.

  • General Instructions
  • Version and Constant Definition Instructions
  • Macro Instructions
  • Modifiers

The vertex shader program can consist of up to 128 instructions, and instructions can have a maximum of three input arguments (source register operands).


General Instructions

The Direct3DX vertex shader assembler supports the following general instructions.

add | Sum
dp3 | Three-components dot-product
dp4 | Four-component dot-product
dst | Distance vector
expp | Exponential 10-bit precision
lit | Lighting coefficients
logp | Logarithm 10-bit precision
mad | Multiply and add
max | Maximum
min | Minimum
mov | Move
mul | Multiply
rcp | Reciprocal
rsq | Reciprocal square root
sge | Set on greater or equal than
slt | Set on less than
sub | Subtract

Each source operand may be arbitrarily swizzled on read, including broadcast/replicate. Each source operand may be negated.

Writes to the destination registers can include masking of individual components; that is, only the specified components (x,y,z,or w) are updated. No swizzling or negation is supported on writes. Therefore, the output masks must be in the x, y, z, and w order.

The software emulated front end will use the masks on the output register writes to detect what parts of the output vertex a shader modifies and compute an output flexible vertex format (FVF) accordingly for submission to the hardware for rasterization-only use.

Note that unlike the pixel shader language, no linear interpolation blend instruction is supported in the vertex shader language, and that the dp3 operator does not automatically clamp negative results to 0.0.

See Also

Macro Instructions


add

Adds sources.

add   vDest, vSrc0, vSrc1

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
vSrc1
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the add instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1);

    m_TmpReg.x = m_Source[0].x + m_Source[1].x;
    m_TmpReg.y = m_Source[0].y + m_Source[1].y;
    m_TmpReg.z = m_Source[0].z + m_Source[1].z;
    m_TmpReg.w = m_Source[0].w + m_Source[1].w;

    WriteResult();

Remarks

The following examples illustrate how the add instruction might be used.

add r0, v0,c2
add r1.xyz, r0.xyz, v1.xyz


dp3

Computes the three-component dot product of the sources.

dp3   vDest, vSrc0, vSrc1

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
vSrc1
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the dp3 instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1);

    m_TmpReg.x =
    m_TmpReg.y =
    m_TmpReg.z =
    m_TmpReg.w = m_Source[0].x * m_Source[1].x +
                 m_Source[0].y * m_Source[1].y +
                 m_Source[0].z * m_Source[1].z;

    WriteResult();

Remarks

The following example illustrates how the dp3 instruction might be used.

dp3 r2, r0, r1
dp3 r2.x, r0, r1


dp4

Computes the four-component dot product of the sources.

dp4   vDest, vSrc0, vSrc1

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
vSrc1
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the dp4 instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1);

    m_TmpReg.x =
    m_TmpReg.y =
    m_TmpReg.z =
    m_TmpReg.w = m_Source[0].x * m_Source[1].x +
                 m_Source[0].y * m_Source[1].y +
                 m_Source[0].z * m_Source[1].z +
                 m_Source[0].w * m_Source[1].w;

    WriteResult();

Remarks

The following example illustrates how the dp4 instruction might be used.

dp4 r2, r0, r1
dp4 r2.w, r0, r1


dst

Calculates the distance vector.

dst   vDest, vSrc0, vSrc1

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
vSrc1
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the dst instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1);

    m_TmpReg.x = 1;
    m_TmpReg.y = m_Source[0].y * m_Source[1].y;
    m_TmpReg.z = m_Source[0].z;
    m_TmpReg.w = m_Source[1].w;

    WriteResult();

Remarks

The first source operand is assumed to be the vector (ignored, d*d, d*d, ignored) and the second source operand is assumed to be the vector (ignored, 1/d, ignored, 1/d). The destination is the result vector (1, d, d*d, 1/d).

The following example illustrates how the dst instruction might be used.

dst r4, r0, r1


expp

Provides exponential 2x partial support.

expp   vDest, vSrc0

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the expp instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);

    float w = m_Source[0].w;
    float v = (float)floor(m_Source[0].w);

    m_TmpReg.x = (float)pow(2, v);
    m_TmpReg.y = w - v;
    // Reduced precision exponent
    float tmp = (float)pow(2, w);
    DWORD tmpd = *(DWORD*)&tmp & 0xffffff00;
    m_TmpReg.z = *(float*)&tmpd;
    m_TmpReg.w = 1;

    WriteResult();

Remarks

The expp instruction produces undefined results if fed a negative value for the exponent.

This instruction provides exponential base 2 partial precision. It generates an approximate answer in vDest.z and allows for a more accurate determination of vDest.x*function(vDest.y), where function is a user approximation to 2*vDest.y over the limited range (0.0 <= vDest.y < 1.0).

This instruction accepts a scalar source, and reduced precision arithmetic is acceptable in evaluating vDest.z. However, the approximation error must be less than 1/(211) the absolute error (10-bit precision) and over the range (0.0 <= t.y < 1.0). Also, expp returns 1.0 in w.

The following example illustrates how the expp instruction might be used.

expp r5, r0


lit

Provides lighting partial support.

lit   vDest, vSrc0

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the lit instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);

    m_TmpReg.x = 1;
    m_TmpReg.y = 0;
    m_TmpReg.z = 0;
    m_TmpReg.w = 1;
    float power = m_Source[0].w;
    const float MAXPOWER = 127.9961f;
    if (power < -MAXPOWER)
        power = -MAXPOWER;          // Fits into 8.8 fixed point format
    else
    if (power > MAXPOWER)
        power = -MAXPOWER;          // Fits into 8.8 fixed point format

    if (m_Source[0].x > 0)
    {
        m_TmpReg.y = m_Source[0].x;
        if (m_Source[0].y > 0)
        {
            // Allowed approximation is EXP(power * LOG(m_Source[0].y))
            m_TmpReg.z = (float)(pow(m_Source[0].y, power));
        }
    }

    WriteResult();

Remarks

The lit instruction produces undefined results if fed a negative value for the exponent.

This instruction calculates lighting coefficients from two dot products and a power. The source vector is assumed to contain the values shown in the following pseudocode.

vSrc0.x = N*L        ; The dot product between normal and direction to light.
vSrc0.y = N*H        ; The dot product between normal and half vector.
vSrc0.z = ignored    ; This value is ignored.
vSrc0.w = power      ; The power, this value must be in the range from –128.0 through 128.0.

Reduced precision arithmetic is acceptable in evaluating vDest.z. An implementation must support at least 8 fraction bits in the power argument. Dot products are calculated with normalized vectors, and clamp limits are -128 to 128.

Error should correspond to a logp and expp combination, or no more than approximately 1 least significant bit (LSB) for an 8-bit color component.

The following example illustrates how the lit instruction might be used.

lit r0, r1


logp

Provides log2(x) partial support.

logp   vDest, vSrc0

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the logp instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);

    float v = ABSF(m_Source[0].w);
    if (v != 0)
    {
        m_TmpReg.x = m_TmpReg.y = m_TmpReg.z = m_TmpReg.w =
            (float)(log(v)/log(2));
    }
    else
    {
        m_TmpReg.x = m_TmpReg.y = m_TmpReg.z = m_TmpReg.w = MINUS_INFINITY();
    }

    WriteResult();

Remarks

This instruction provides logarithm base 2 partial precision. It generates an approximate answer in vDest.z and allows for a more accurate determination of vDest.x + function(vDest.y), where function is a user approximation to log2(vDest.y) over the limited range (1.0 <= vDest.y < 2.0).

The logp instruction accepts a scalar source of which the sign bit is ignored, and reduced precision arithmetic is acceptable in evaluating vDest.z. The approximation error must be less than 1/(211) in absolute error (10-bit precision), and over the range (1.0 <= t.y < 2.0). A zero source argument generates the result vector (-infinity, 0.0, -infinity, 1.0).

The following example illustrates how the logp instruction might be used.

logp r0,r1


mad

Multiplies and adds sources.

mad   vDest, vSrc0, vSrc1, vSrc2

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
vSrc1
Source register, specifying the input argument.
vSrc2
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the mad instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1);
    SetSrcReg(2);

    m_TmpReg.x = m_Source[0].x * m_Source[1].x + m_Source[2].x;
    m_TmpReg.y = m_Source[0].y * m_Source[1].y + m_Source[2].y;
    m_TmpReg.z = m_Source[0].z * m_Source[1].z + m_Source[2].z;
    m_TmpReg.w = m_Source[0].w * m_Source[1].w + m_Source[2].w;

    WriteResult();

Remarks

The following examples illustrate how the mad instruction might be used.

mad r0,r1,r2,v3


max

Calculates the maximum of the sources.

max   vDest, vSrc0, vSrc1

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
vSrc1
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the max instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1);

    m_TmpReg.x=(m_Source[0].x >= m_Source[1].x) ? m_Source[0].x : m_Source[1].x;
    m_TmpReg.y=(m_Source[0].y >= m_Source[1].y) ? m_Source[0].y : m_Source[1].y;
    m_TmpReg.z=(m_Source[0].z >= m_Source[1].z) ? m_Source[0].z : m_Source[1].z;
    m_TmpReg.w=(m_Source[0].w >= m_Source[1].w) ? m_Source[0].w : m_Source[1].w;

    WriteResult();

Remarks

The following example illustrates how the max instruction might be used.

max r2, r3, r4


min

Calculates the minimum of the sources.

min   vDest, vSrc0, vSrc1

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
vSrc1
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the min instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1);

    m_TmpReg.x=(m_Source[0].x < m_Source[1].x) ? m_Source[0].x : m_Source[1].x;
    m_TmpReg.y=(m_Source[0].y < m_Source[1].y) ? m_Source[0].y : m_Source[1].y;
    m_TmpReg.z=(m_Source[0].z < m_Source[1].z) ? m_Source[0].z : m_Source[1].z;
    m_TmpReg.w=(m_Source[0].w < m_Source[1].w) ? m_Source[0].w : m_Source[1].w;

    WriteResult();

Remarks

The following example illustrates how the min instruction might be used.

min   r2, r3, r4


mov

Move contents of the source into the destination.

mov   vDest, vSrc0

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the mov instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);

    if( m_pDest == m_reg.m_a )
    {
        float p = (float)floor(m_Source[0].x);
        *(int*)&m_pDest->x = FTOI(p);
    }
    else
    {
        m_TmpReg = m_Source[0];
        WriteResult();
    }

Remarks

The following examples illustrate how the mov instruction might be used.

mov r1, v2
mov r1.xy, r2.zw


mul

Multiply sources into the destination.

mul   vDest, vSrc0, vSrc1

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
vSrc1
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the mul instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1);

    m_TmpReg.x = m_Source[0].x * m_Source[1].x;
    m_TmpReg.y = m_Source[0].y * m_Source[1].y;
    m_TmpReg.z = m_Source[0].z * m_Source[1].z;
    m_TmpReg.w = m_Source[0].w * m_Source[1].w;

    WriteResult();

Remarks

The following example illustrates how the mul instruction might be used.

mul r4, v0, r1


rcp

Computes the reciprocal of the source scalar.

rcp   vDest, vSrc0

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the rcp instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);

    if( m_Source[0].w == 1.0f )
    {
        // Must be exactly 1.0
        m_TmpReg.x = m_TmpReg.y = m_TmpReg.z = m_TmpReg.w = 1.0f;
    }
    else if( m_Source[0].w == 0 )
    {
        m_TmpReg.x = m_TmpReg.y = m_TmpReg.z = m_TmpReg.w = PLUS_INFINITY();
    }
    else
    {
        m_TmpReg.x = m_TmpReg.y = m_TmpReg.z = m_TmpReg.w = 1.0f/m_Source[0].w;
    }

    WriteResult();

Remarks

If the source has no subscripts, the x-component is used. The output must be exactly 1.0 if the input is exactly 1.0.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 2.0) because common implementations will separate mantissa and exponent. A source of 0.0 yields infinity.

The following example illustrates how the rcp instruction might be used.

rcp r1, r2
rcp r1, r2.y


rsq

Computes the reciprocal square root of the source scalar.

rsq   vDest, vSrc0

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the rsq instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);

    float v = ABSF(m_Source[0].w);
    if( v == 1.0f )
    {
        m_TmpReg.x = m_TmpReg.y = m_TmpReg.z = m_TmpReg.w = 1.0f;
    }
    else if( v == 0 )
    {
        m_TmpReg.x = m_TmpReg.y = m_TmpReg.z = m_TmpReg.w = PLUS_INFINITY();
    }
    else
    {
        v = (float)(1.0f / sqrt(v));
        m_TmpReg.x = m_TmpReg.y = m_TmpReg.z = m_TmpReg.w = v;
    }

    WriteResult();

Remarks

If source has no subscripts, the x-component is used. The output must be exactly 1.0 if the input is exactly 1.0.

Absolute value is taken before processing; that is, the sign bit is ignored.

Precision should be at least 1.0/(222) absolute error over the range (1.0, 4.0) because common implementations will separate mantissa and exponent. A source of 0.0 yields infinity.

The following example illustrates how the rsq instruction might be used.

rsq r1, r2
rsq r1, r2.y


sge

Sets the destination to 1.0 if the first source operand is greater than or equal to the second source operand; otherwise, the destination is set to 0.0.

sge   vDest, vSrc0, vSrc1

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
vSrc1
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the sge instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1);

    m_TmpReg.x = (m_Source[0].x >= m_Source[1].x) ? 1.0f : 0.0f;
    m_TmpReg.y = (m_Source[0].y >= m_Source[1].y) ? 1.0f : 0.0f;
    m_TmpReg.z = (m_Source[0].z >= m_Source[1].z) ? 1.0f : 0.0f;
    m_TmpReg.w = (m_Source[0].w >= m_Source[1].w) ? 1.0f : 0.0f;

    WriteResult();

Remarks

The following example illustrates how the sge instruction might be used.

sge   r1, r2, v1


slt

Sets the destination to 1.0 if the first source operand is less than the second source operand; otherwise, the destination is set to 0.0.

slt   vDest, vSrc0, vSrc1

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
vSrc1
Source register, specifying the input argument.

Operation

The following code fragment shows the operations performed by the slt instruction to write a result to the destination.

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1);

    m_TmpReg.x = (m_Source[0].x < m_Source[1].x) ? 1.0f : 0.0f;
    m_TmpReg.y = (m_Source[0].y < m_Source[1].y) ? 1.0f : 0.0f;
    m_TmpReg.z = (m_Source[0].z < m_Source[1].z) ? 1.0f : 0.0f;
    m_TmpReg.w = (m_Source[0].w < m_Source[1].w) ? 1.0f : 0.0f;

    WriteResult();

Remarks

The following example illustrates how the slt instruction might be used.

slt   r1, r2, v1


sub

Subtracts sources.

sub   tDest, tSrc0, tSrc1

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Source register, specifying the input argument.
tSrc1
Source register, specifying the input argument.

Remarks

This instruction performs the subtraction based on the following formula.

tDest = tSrc0 - tSrc1

The following example shows how this instruction might be used.

sub   r2, v2, r2    ; difference


Version and Constant Definition Instructions

The Direct3DX vertex shader assembler provides instructions to identify the type and version of the shader and to define constants to use with the vertex shader.

def | Define Constants
vs | Version and Type

A version instruction is required to be at the beginning of each shader.

Note that constant definition instructions must occur after version instructions and before all other instructions.


def

Provides a method to define constants to be used with the vertex shader.

def   vDest, fVal0, fVal1, fVal2, fVal3

Registers

vDest
Destination register, holding the result of the operation.
fVal0
Source register, specifying the input argument.
fVal1
Source register, specifying the input argument.
fVal2
Source register, specifying the input argument.
fVal3
Source register, specifying the input argument.

Remarks

The following example illustrates how the def instruction might be used.

def c0, 0.0f, 0.0f, 0.0f, 1.0f
def c8, 1.0f, 2.0f, 3.0f, 4.0f

These constants are returned as a declaration fragment to be included in the declaration upon shader creation.


vs

Provides a method to specify the type and version of the shader code.

vs.mainVer.subVer

Registers

mainVer
Main version number of the vertex shader.
subVer
Sub version number of the vertex shader.

Remarks

The following example illustrates how the vs instruction might be used.

vs.1.0  ; Vertex shader version 1.0.

This instruction is required to be at the beginning of all vertex shaders.


Macro Instructions

The Direct3DX vertex shader assembler provides macro instructions for application convenience in performing common simple operations. These macros are expanded by the driver into some of the standard vertex shader instructions, for details see the reference topic for each macro instruction.

exp | Exponential base 2 full precision
frc | Fraction
log | Logarithm base 2 full precision
m3x2 | 3×2 vector matrix multiply
m3x3 | 3×3 vector matrix multiply
m3x4 | 3×4 vector matrix multiply
m4x3 | 4×3 vector matrix multiply
m4x4 | 4×4 vector matrix multiply

For the purpose of determining if you exceed the maximum instruction count limit of 128, the macro instructions are guaranteed to expand to no more than the number of actual instructions listed.

Because these are passed to the implementation in the same manner as true instructions, the implementation is free to optimize them. Therefore, no assumptions can be made about timing cycle counts required.

See Also

General Instructions


exp

Provides exponential 2x with full precision to at least 1/220.

exp   vDest, vSrc0

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.

Operation

    SetDestReg();
    SetSrcReg(0);

    float v = m_Source[0].w;

    m_TmpReg.x = m_TmpReg.y = m_TmpReg.z = m_TmpReg.w = (float)pow(2, v);

    WriteResult();

Expansion

This macro takes twelve instruction slots.

Remarks

This is a scalar operation and takes its input from the .w channel, which must be specified. It always replicates the result into all four output channels.


frc

Returns fractional portion of each input component.

frc   vDest, vSrc0

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.

Operation

    SetDestReg();
    SetSrcReg(0);

    m_TmpReg.x = m_Source[0].x - (float)floor(m_Source[0].x);
    m_TmpReg.y = m_Source[0].y - (float)floor(m_Source[0].y);
    m_TmpReg.z = m_Source[0].z - (float)floor(m_Source[0].z);
    m_TmpReg.w = m_Source[0].w - (float)floor(m_Source[0].w);

    WriteResult();

Expansion

This macro takes three instruction slots.

Remarks

Each component of the result is in the range from 0.0 through 1.0.

This macro only writes x and y components.


log

Provides log2(x) support with full float precision of at least 1/220.

log   vDest, vSrc0

Registers

vDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.

Operation

    SetDestReg();
    SetSrcReg(0);

    float v = ABSF(m_Source[0].w);
    if (v != 0)
    {
        m_TmpReg.x = m_TmpReg.y = m_TmpReg.z = m_TmpReg.w =
            (float)(log(v)/log(2));
    }
    else
    {
        m_TmpReg.x = m_TmpReg.y = m_TmpReg.z = m_TmpReg.w = minUS_INFINITY();
    }

    WriteResult();

Expansion

This macro takes twelve instruction slots.

Remarks

This instruction accepts a scalar source .w of which the sign bit is ignored. The result is replicated to all four channels.

The input exponent must be in the range –128 to 128. The approximation error must be less than 1/220 in absolute error, and over the range 1.0 less than or equal to t.y less than 2.0. A zero source generates (-infinity,-infinity,-infinity,-infinity).


m3x2

Computes the product of the input vector and a 3x2 matrix.

m3x2   rDest, vSrc0, mSrc1

Registers

rDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
mSrc1
Source register, specifying the input argument.

Operation

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1, 2);
    m_TmpReg.x = m_Source[0].x * m_Source[1].x +
                 m_Source[0].y * m_Source[1].y +
                 m_Source[0].z * m_Source[1].z;
    m_TmpReg.y = m_Source[0].x * m_Source[2].x +
                 m_Source[0].y * m_Source[2].y +
                 m_Source[0].z * m_Source[2].z;

    WriteResult();

Expansion

The following m3x2 instruction

m3x2   r5, v0, c[3]

expands to

dp3   r5.x, v0, c[3]
dp3   r5.y, v0, c[4]

Therefore, this macro instruction consumes two instruction slots from the instruction count. Note that the last w-component in c[3] and c[4] is ignored in this computation.

Remarks

The input vector is at vSrc0, the input 3x2 matrix is at mSrc1, and the next higher register in the same register file. A 2-D result is produced, leaving the other elements of rDest (z and w) unaffected.

This operation is commonly used for 2-D transforms. This macro instruction is implemented as a pair of dot products.


m3x3

Computes the product of the input vector and a 3x3 matrix.

m3x3   rDest, vSrc0, mSrc1

Registers

rDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
mSrc1
Source register, specifying the input argument.

Operation

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1, 3);
    m_TmpReg.x = m_Source[0].x * m_Source[1].x +
                 m_Source[0].y * m_Source[1].y +
                 m_Source[0].z * m_Source[1].z;
    m_TmpReg.y = m_Source[0].x * m_Source[2].x +
                 m_Source[0].y * m_Source[2].y +
                 m_Source[0].z * m_Source[2].z;
    m_TmpReg.z = m_Source[0].x * m_Source[3].x +
                 m_Source[0].y * m_Source[3].y +
                 m_Source[0].z * m_Source[3].z;

    WriteResult();

Expansion

The following m3x3 instruction

m3x3   r5, v0, c[3]

expands to

dp3   r5.x, v0, c[3]
dp3   r5.y, v0, c[4]
dp3   r5.z, v0, c[5]

Therefore, this macro instruction consumes three instruction slots from the instruction count. Note that the last w-component in c[3], c[4], and c[5] is ignored in this computation.

Remarks

The input vector is at vSrc0 and the input 3x3 matrix is at mSrc1 and the two subsequent registers in the same register file.

This operation is commonly used for transforming normal vectors during lighting computations. This macro instruction is implemented as a series of dot products.


m3x4

Computes the product of the input vector and a 3x4 matrix.

m3x4   rDest, vSrc0, mSrc1

Registers

rDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
mSrc1
Source register, specifying the input argument.

Operation

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1, 4);
    m_TmpReg.x = m_Source[0].x * m_Source[1].x +
                 m_Source[0].y * m_Source[1].y +
                 m_Source[0].z * m_Source[1].z;
    m_TmpReg.y = m_Source[0].x * m_Source[2].x +
                 m_Source[0].y * m_Source[2].y +
                 m_Source[0].z * m_Source[2].z;
    m_TmpReg.z = m_Source[0].x * m_Source[3].x +
                 m_Source[0].y * m_Source[3].y +
                 m_Source[0].z * m_Source[3].z;
    m_TmpReg.w = m_Source[0].x * m_Source[4].x +
                 m_Source[0].y * m_Source[4].y +
                 m_Source[0].z * m_Source[4].z;

    WriteResult();

Expansion

The following m3x4 instruction

m3x4   r5, v[0], c[3]

expands to

dp3 r5.x, v[0], c[3]
dp3 r5.y, v[0], c[4]
dp3 r5.z, v[0], c[5]
dp3 r5.w, v[0], c[6]

Therefore, this macro instruction consumes four instruction slots from the instruction count. Note that the last w-component in c[3], c[4], and c[5] is ignored in this computation.

Remarks

The input vector is at vSrc0 and the input 3x4 matrix is at mSrc1 and the two subsequent registers in the same register file.

This operation is commonly used for transforming a position vector by a matrix that has a projective effect, but applies no translation. This macro instruction is implemented as a series of dot products.


m4x3

Computes the product of the input vector and a 4x3 matrix.

m4x3   rDest, vSrc0, mSrc1

Registers

rDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
mSrc1
Source register, specifying the input argument.

Operation

    SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1, 3);
    m_TmpReg.x = m_Source[0].x * m_Source[1].x +
                 m_Source[0].y * m_Source[1].y +
                 m_Source[0].z * m_Source[1].z +
                 m_Source[0].w * m_Source[1].w;
    m_TmpReg.y = m_Source[0].x * m_Source[2].x +
                 m_Source[0].y * m_Source[2].y +
                 m_Source[0].z * m_Source[2].z +
                 m_Source[0].w * m_Source[2].w;
    m_TmpReg.z = m_Source[0].x * m_Source[3].x +
                 m_Source[0].y * m_Source[3].y +
                 m_Source[0].z * m_Source[3].z +
                 m_Source[0].w * m_Source[3].w;

    WriteResult();

Expansion

The following m4x3 instruction

m4x3   r5, v[0], c[3]

expands to

dp4   r5.x, v[0], c[3]
dp4   r5.y, v[0], c[4]
dp4   r5.z, v[0], c[5]

Therefore, this macro instruction consumes three instruction slots from the instruction count. Note that the last w-component in c[3], c[4], and c[5] is ignored in this computation unless the input vector has a w-value of 1.0. If this w-value is 0.0, then no translation of the input vector will occur; that is, the translation elements of the matrix will not be applied.

Remarks

The input vector is at vSrc0 and the input 4x3 matrix is at mSrc1 and the two next higher registers in the same register file.

This operation is commonly used for transforming a position vector by a matrix that has no projective effect, such as occurs in model-space transformations. This macro instruction is implemented as a series of dot products.


m4x4

Computes the product of the input vector and a 4x4 matrix.

m4x4   rDest, vSrc0, mSrc1

Registers

rDest
Destination register, holding the result of the operation.
vSrc0
Source register, specifying the input argument.
mSrc1
Source register, specifying the input argument.

Operation

   SetDestReg();
    SetSrcReg(0);
    SetSrcReg(1, 4);
    m_TmpReg.x = m_Source[0].x * m_Source[1].x +
                 m_Source[0].y * m_Source[1].y +
                 m_Source[0].z * m_Source[1].z +
                 m_Source[0].w * m_Source[1].w;
    m_TmpReg.y = m_Source[0].x * m_Source[2].x +
                 m_Source[0].y * m_Source[2].y +
                 m_Source[0].z * m_Source[2].z +
                 m_Source[0].w * m_Source[2].w;
    m_TmpReg.z = m_Source[0].x * m_Source[3].x +
                 m_Source[0].y * m_Source[3].y +
                 m_Source[0].z * m_Source[3].z +
                 m_Source[0].w * m_Source[3].w;
    m_TmpReg.w = m_Source[0].x * m_Source[4].x +
                 m_Source[0].y * m_Source[4].y +
                 m_Source[0].z * m_Source[4].z +
                 m_Source[0].w * m_Source[4].w;

    WriteResult();

Expansion

The following m4x4 instruction

m4x4   r5, v[0], c[3]

expands to

dp4   r5.x, v[0], c[3]
dp4   r5.y, v[0], c[4]
dp4   r5.z, v[0], c[5]
dp4   r5.w, v[0], c[6]

Therefore, this macro consumes four instruction slots from the instruction count.

Remarks

The input vector is at vSrc0 and the input 4x4 matrix is at mSrc1 and the three subsequent registers in the same file.

This operation is commonly used to transform an position by a projection matrix. This macro instruction is implemented as a series of dot products.


Modifiers

This section contains reference information for the component modifiers implemented by the Direct3DX vertex shader assembler.

As shown in the following table, component modifiers (where r is a valid register, either an, c[n], rn, vn, or any of the output registers) can be applied to the individual components of the vector data.

Component Modifier | Description
r.{x}{y}{z}{w} | Destination mask
r.[xyzw][xyzw][xyzw][xywz] | Source swizzle
-r | Source negation


Pixel Shader Assembler Reference

This section contains reference information for the Direct3DX pixel shader assembler. Reference material is divided into the following categories.

  • Registers
  • Instructions
  • Modifiers
  • Output Write Masks

The pixel shader assembler is comprised of a set of registers defined along with a set of operations that can be performed on the registers. Operations are expressed as instructions comprised of an operator and one or more arguments (operands).

Microsoft® DirectX® 8.0 requires intermediate computations to maintain at least 8-bit precision for all surface formats. Both higher precision (12-bit) for in-stage math and saturation to 8-bits between texture stages are recommended. No modifiable rounding modes or exceptions are supported. Multiplication should be supported with a round-to-nearest precision to minimize precision loss.


Registers

This section contains reference information for the registers implemented by the Direct3DX pixel shader assembler.

Name | I/0 Permissions | Minimum Count | Maximum Count per Instruction | Source
cn | read-only | 8 | 2 | API call
rn | read/write | 2 | 2 | Written
tn | read/write | 4 | 1 | Textures
vn | read-only | 2 | 1 | Vertex Colors

The minimum count column indicates the minimum number of registers that the implementation must support in order to be able to expose Microsoft® DirectX® 8.0 shading capability.

The maximum count per instruction column indicates the maximum number of registers supported in any one instruction. This includes source parameter read ports for an instruction. The destination parameter of an instruction does not apply towards the limit.

Each register is a four-component vector, whose components range from –1.0 to 1.0, with at least 8 bits of precision per component. Unlike the vertex shader assembler, the pixel shader assembler does not have any output registers; rather, the pixel shader just emits r0.


cn

These are the constant registers. Derived from the D3DRS_TEXTUREFACTOR constant, the constant factor registers are loaded by the application through the IDirect3DDevice8::SetPixelShaderConstant method.

The constant factor registers are read-only. There are at least eight constant factor registers defined for use by a pixel shader, but a maximum of two may be used in any one instruction.


rn

These are the temporary registers. The temporary registers are available for use in storing intermediate results. They are read-write and a maximum of two temporary registers can appear in any single shader instruction. Shader preprocessing in the debug runtime will fail IDirect3DDevice8::CreatePixelShader on any shader that attempts to read from a temporary register that has not been written to by a previous instruction.

Note that all pixel shaders must write r0 as the final result, so the simplest decal pixel shader consists of two instructions.

ps.1.0       // DirectX8 Version.
tex   t0
mov   r0, t0


tn

These are the texture registers. There are as many texture registers as there are simultaneous textures supported. The texture registers are initialized to contain texture colors from the texture sampling units including filtering modes defined by that stage's texture stage state. The colors come from their corresponding textures as defined by IDirect3DDevice8::SetTexture and sampled at the corresponding texture coordinates.

Any texture register that does not have a texture set will be sampled as opaque black (0,0,0,1). A maximum of two texture registers can appear in any single shader instruction. Texture registers may also be used as temporary registers. Specifically, after the texture addressing instructions, these registers can be used as read/write temporary registers.

In most cases, a texture register is only valid as a destination of a texture command; however, note that the arithmetic instructions can read from texture registers.


vn

These are the vertex color registers. The input vertex color registers contain color values obtained by per-pixel Gouraud iteration of the color values emitted by the vertex shader (which may in turn receive them from the vertex stream). A compliant Microsoft® DirectX® 8.0 implementation must support at least two of the input color registers.

Input color registers are read-only, and a maximum of one of these colors can be used in any one instruction.

To simulate flat shading, a constant color is more efficient. However, when the shade mode is D3DSHADE_FLAT, applications iteration of both colors is disabled. Note that fog should continue to be iterated. Ideally, all color iteration should be perspective correct in the same manner as the texture coordinate iteration.


Instructions

There are two main categories of operations understood by the Direct3DX compiler for the pixel shader: pixel color and alpha blending operations and texture addressing operations. The assembler represents these operations using instructions. Pixel color and alpha blending operations modify color data, and texture addressing operations affect and process texture coordinate data. All of the pixel shader instructions are performed on a per-pixel basis—that is, they have no knowledge of other pixels in the pipeline.

  • Color and Alpha Blending Instructions
  • Version and Constant Definition Instructions
  • Texture Addressing Instructions

The blending operations can be used for independent processing of RGB color and scalar alpha. In most cases, pixel blending (color or alpha) operations can support both a color and an alpha instruction in one slot.

Implementations must support programs of at least eight blending instructions and four addressing instructions to be compliant.

Texture addressing operations each consume one slot, but pixel blending (color and alpha) operations can be paired to enable both a color and a alpha instruction in a single slot. In Microsoft® DirectX® 8.0, the texture addressing instructions must precede the color blending instructions.

The syntax for texture address perturbation operation is included within the shader program itself in the form of texture declarations. These control how address perturbation operations are applied to the color values sampled from the textures during their pre-loading into the temporary register file for use in the body of the pixel shader.


Color and Alpha Blending Instructions

This section contains reference information for the color and alpha blending instructions implemented by the Direct3DX pixel shader assembler.

The color and alpha blending instructions are listed in the following table. All of these operations are performed component-wise.

Instruction | Description
add | Add
cnd | Conditional
dp3 | Three-Component Vector Dot-Product
lrp | Linear Interpolation Blend
mad | Multiply and Add
mov | Copy Source Into Destination
mul | Modulate
sub | Loads the difference of the two colors in the source operands.


add

Loads the sum of the two colors in the source operands.

add   tDest, tSrc0, tSrc1

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Source register, specifying the input argument.
tSrc1
Source register, specifying the input argument.

Remarks

The following example shows how this instruction might be used.

add d, s1, s2    ; sum d = s1 + s2


cnd

Performs a conditional operation, comparing the value in r0.a with 0.5.

cnd   tDest, tSrc0, tSrc1, tSrc2

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Source register, specifying the input argument.
tSrc1
Source register, specifying the input argument.
tSrc2
Source register, specifying the input argument.

Remarks

This instruction can only be used to compare the value in r0.a with 0.5. If the alpha (r0.a) is greater than 0.5, then the first source is returned as the result; otherwise, the second source is returned.

The following example shows how this instruction might be used.

cnd d, r0.a, s1, s2    ; d = ( r0.a >0.5 ? s1 : s2 )

To compare two values you can use the following pixel shader code because a - (b - 0.5) = a - b + 0.5.

sub r0, v0,   v1_bias
cnd r0, r0.a, c0, c1

As mentioned above, r0.a is the only value that can be placed in the first source argument and the compare value must be "greater than 0.5."


dp3

Loads the three-component vector dot-product of the two colors in the source operand registers.

dp3   tDest, tSrc0, tSrc1

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Source register, specifying the input argument.
tSrc1
Source register, specifying the input argument.

Remarks

This instruction generates a scalar result, but replicates it to all specified output channels.

dp3 r, s1, s2    ; s1 dot s2 replicated to all channels

Note that the dp3 instruction is a fundamentally a vector operation, and is therefore always performed in the vector pipeline. Using it with the Alpha Replicate input argument modifier (.a) input argument modifier just indicates that its result should be propagated to the alpha channel as well. In other words, dp3 can be specified as an alpha operation only when it is also the color operation, and must also use the same arguments.

dp3 r0.rgb, t0, v0
dp3 r0.a,   t0, v0

Or equivalently,

dp3 r0, t0, v0

will cause the grayscale result of the dp3 operation to be copied into both the color and alpha channels of r0.

A different instruction can be specified in the alpha channel of the result.

dp3 r0.rgb, t0, v0
mul r0.a,   t0, v0

The dp3 instruction usually benefits from the Signed Scaling input argument modifier (_bx2) applied to its input arguments if they have not already been expanded to signed dynamic range. When used for lighting, the saturate instruction modifier (_sat) instruction modifier is often used to clamp the negative values to black, as shown in the following example.

dp3_sat r0, t0_bx2, v0_bx2    ; t0 is bump, v0 is light direction


lrp

Linearly interpolates between the 2nd and 3rd source registers by a proportion specified in the 1st source register.

lrp   tDest, tSrc0, tSrc1, tSrc2

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Source register, specifying the input argument.
tSrc1
Source register, specifying the input argument.
tSrc2
Source register, specifying the input argument.

Remarks

This instruction performs the linear interpolation based on the following formula.

tSrc0 * tSrc1 + (1-tSrc0) * tSrc2 = tSrc2 + tSrc0 * (tSrc1 - tSrc2)

The following example shows how this instruction might be used.

lrp d, s0, s1, s2    ; d = s0*s1 + (1-s0)*s2 = s2 + s0*(s1-s2)


mad

Loads the first source register added to the product of the two colors in the last two source operand registers.

mad   tDest, tSrc0, tSrc1, tSrc2

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Source register, specifying the input argument.
tSrc1
Source register, specifying the input argument.
tSrc2
Source register, specifying the input argument.

Remarks

This instruction performs a multiply-accumulate operation. It takes the last two arguments, multiplies them together, and adds them to the remaining input/source argument, and places that into the result register.

This instruction performs the multiply-add based on the following formula.

tSrc0 + tSrc1 * tSrc2

The following example shows how this instruction might be used.

mad  d, s0, s1, s2    ; d = s0 + s1*s2


mov

Loads with the value in the source register.

mov   tDest, tSrc0

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Source register, specifying the input argument.

Remarks

The following example shows how this instruction might be used.

mov   d, s    ; copy s to d ( d = s )


mul

Loads the destination register with the component-wise product of the two colors in the source operand registers

mul   tDest, tSrc0, tSrc1

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Source register, specifying the input argument.
tSrc1
Source register, specifying the input argument.

Remarks

This instruction performs a modulate operation.

The following example shows how this instruction might be used.

mul  d, s1, s2    ; modulate d = s1*s2


sub

Loads the difference of the two colors in the source operands.

sub   tDest, tSrc0, tSrc1

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Source register, specifying the input argument.
tSrc1
Source register, specifying the input argument.

Remarks

This instruction performs the subtraction based on the following formula.

tDest = tSrc0 - tSrc1

The following example shows how this instruction might be used.

sub   d, s1, s2    ; difference


Version and Constant Definition Instructions

The Direct3DX pixel shader assembler provides instructions to identify the type and version of the shader and to define constants to use with the pixel shader.

def | Define Constants
ps | Version and Type

A version instruction is required to be at the beginning of each shader.

Note that constant definition instructions must occur after version instructions and before all other instructions.


def

Provides a method to define constants to be used with the pixel shader.

def   vDest, fVal0, fVal1, fVal2, fVal3

Registers

vDest
Destination register, holding the result of the operation.
fVal0
Source register, specifying the input argument.
fVal1
Source register, specifying the input argument.
fVal2
Source register, specifying the input argument.
fVal3
Source register, specifying the input argument.

Remarks

The following example illustrates how the def instruction might be used. Note that the def instruction must come before other shader instructions.

Ps.1.0
def c0, 0.0f, 0.0f, 0.0f, 1.0f
def c7, 1.0f, 2.0f, 3.0f, 4.0f
tex t0
mov r0, t0

These constants are defined in the instruction stream.


ps

Provides a method to specify the type and version of the shader code.

ps.mainVer.subVer

Registers

mainVer
Main version number of the pixel shader.
subVer
Sub version number of the pixel shader.

Remarks

The following example illustrates how the ps instruction might be used.

ps.1.0  ; Pixel shader version 1.0.

This instruction is required to be at the beginning of all pixel shaders.


Texture Addressing Instructions

This section contains reference information for the texture addressing instructions implemented by the Direct3DX pixel shader assembler. The texture addressing instructions are provided to enable manipulations of texture address data (as opposed to texture color contents).

The textures set at the sampling stages are sampled from the corresponding textures using the sampling, filtering, and wrapping modes selected by the Microsoft® Direct3D® application programming interface (API) texture stage states. When these textures are sampled, some operations may be applied to the address used to sample them. These operations are referred to as texture addressing operations.

A subset of the texture addressing instructions and the texture perturbation operations are listed in the following table.

Instruction | Description
tex | No Modification
texbem | Bump Environment Map
texbeml | Bump Environment Map with Luminance
texcoord | Texture Coordinate
texkill | Mask Out Pixel
texm3x2pad | Input to 3×2 Matrix Multiply
texm3x2tex | 3×2 Matrix Multiply Result
texreg2ar | Remapping Alpha and Red Components
texreg2gb | Remapping Green and Blue Components

In addition, the pixel shader API supports a number of methods to perform a per-pixel 3×3 matrix multiply on the vector sampled from a texture. The 3×3 matrix is comprised of the texture coordinates from three consecutive texture declaration stages. These matrix multiply operations are constructed from multiple texture address operations.

The following table lists the remaining texture addressing instructions, those that are concerned with per-pixel 3×3 matrix multiplies.

Instruction | Description
texm3x3pad | Input to 3×3 Matrix Multiply
texm3x3spec | Specular Reflection and Environment Mapping
texm3x3tex | 3×3 Matrix Multiply Result
texm3x3vspec | Specular Reflection/Environment Mapping without Constant Eye Vector

Texture address instructions define an output argument (result) being the texture register that they declare/define. Some instructions require an input operand to be specified. This input operand must be a previously defined texture. These can also be thought of as declarations of the texture colors emitted by the texture sampling units into the color operation/alpha operation/blending shader. These texture registers can be declared in terms of previously declared textures, but not in terms of later textures, or other pixel color registers.

All texture address operations must be declared in the order of the texture they define. No texture address operation can refer to another texture that is after it —that is, of a higher stage number.

Performance Note Texture addressing operations need to support sufficient precision for representing texture addresses. For example, precision should be sufficient enough to represent perturbations in the elements of the bump environment mapping matrix that can perturb to a fraction of a texel in an environment map of the maximum texture dimensions supported by the device. Furthermore, all iterated quantities in these operations must be iterated with perspective correction.


tex

Samples a color from the texture and copies it into the corresponding register with no modification applied to the addresses used for sampling.

tex   tDest

Registers

tDest
Destination register, holding the result of the operation.

Remarks

Because this instruction is the default, the tex instruction is assumed for any textures whose sampling is not specified by other statements.

The following example shows how this instruction might be used.

tex r0    ; Declare register 0 as color from the
          ; texture currently set at stage 0.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.


texbem

Takes the color defined by the input argument as DuDv perturbation data.

texbem   tDest, tSrc0

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Temporary source register, specifying the input argument.

Remarks

The texbem instruction transforms the u and v components by the 2-D bump environment mapping matrix, adds them to the current stage's texture coordinates, and samples the current stage's texture.

tex    t0        ; Define t0 as being sampled from the texture.
texbem t1, t0    ; Compute u = u1 + mat00*r0.r + mat01*r0.g, and
                 ;         v = v1 + mat10*r0.r + mat11*r0.g.
                 ; Then sample at u,v; r0.b is ignored.
mov r0, t1       ; Copy final result to output color.

This operation always interprets du and dv as signed quantities, so that the Signed Scaling input modifier (_bx2) is not required to be specified on the input argument. The texture is set at the second stage, the texture set on the first stage is ignored.

This can be used for a variety of techniques based on address perturbation, including per-pixel environment mapping and diffuse lighting (bump mapping), environment matting, and so on.

This operation is a macro of two instructions (consuming 2 stages/slots): u' = u + du*M00 + dv*M01 and v' = v + du*M10 + dv*M11 where M00, M01, M10, and M11 are D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, and D3DTSS_BUMPENVMAT11.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.


texbeml

Takes the color sampled by the preceding stage as DuDvL perturbation data with luminance information.

texbeml   tDest, tSrc0

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Temporary source register, specifying the input argument.

Remarks

The texbeml instruction transforms the color's red and green components by the 2-D bump environment mapping matrix, adds the components to the current stage's texture coordinates, and samples this texture at the resulting 2-D address. Then it applies a luminance correction using the luminance value (L), and the Microsoft® Direct3D® API-specified luminance and bias texture stage values.

The following pixel shader defines the color in the destination register as the color taken from the texture map set at stage 1, indexed by an address perturbed by the values of the red and green channels, and sampled from the map set on stage 0.

tex     t0        ; Define t0 to get a 3-tuple DuDvL.
texbeml t1, t0    ; Compute u = u1 + mat00*r0.r + mat01*r0.g, and
                  ;         v = v1 + mat10*r0.r + mat11*r0.g.
                  ; Then apply luminance correction.
mov r0, t1        ; Copy final result to output color.

The texture is set at the second stage, the texture set on the first stage is ignored.

This operation is a macro of two instructions (consuming 2 stages/slots): u' = u + du*M00 + dv*M01 and v' = v + du*M10 + dv*M11 where M00, M01, M10, and M11 are D3DTSS_BUMPENVMAT00, D3DTSS_BUMPENVMAT01, D3DTSS_BUMPENVMAT10, and D3DTSS_BUMPENVMAT11.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.


texcoord

Converts the iterated texture coordinate assigned to this stage to a color for use in blending.

texcoord   tDest

Registers

tDest
Destination register, holding the result of the operation.

Remarks

This instruction allows the use of the texture coordinate as an additional Gouraud iterated (guaranteed perspective correct) color.

texcoord  t0    ; Declare register t0 as a color from its texture coordinates.

Because any quantity can be mapped by the vertex shader into a texture coordinate, the texcoord instruction can be used to stream arbitrary data such as position, normal, and light source direction to the pixel shader.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.


texkill

Masks out the pixel, if any texture coordinates are less than 0.

texkill   tDest

Registers

tDest
Destination register, holding the result of the operation.

This instruction can be used to implement arbitrary clip planes in the rasterizer.

When using vertex shaders, the application is responsible for applying the perspective transform. This can cause problems for the arbitrary clipping planes because if it contains anisomorphic scale factors, the clip planes would need to be transformed as well. Therefore, it is best to provide an unprojected vertex position for use in the arbitrary clipper, which is the texture coordinate set identified by the texkill operator.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.


texm3x2pad

Used in combination with other texture address operations to perform 2×3 matrix multiplies.

texm3x2pad   tDest, tSrc0

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Temporary source register, specifying the input argument.

Remarks

This instruction is used to represent stages where only the texture coordinate is used. These corresponding stages have not textures bound, and no sampling will occur. The input argument, t0, should still be specified.

The following example shows how the texm3x2pad instruction might be used.

tex t0             ; Define t0 as a standard 3-vector.
texm3x2pad t1, t0  ; Perform fist row of matrix multiply.
texm3x2tex t2, t0  ; Perform second row of matrix multiply to get a
                   ; 2-vector with which to sample texture 2.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.


texm3x2tex

Performs a 3×2 matrix multiply on the input color vector.

texm3x2tex   tDest, tSrc0

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Temporary source register, specifying the input argument.

Remarks

The texm3x2tex instruction takes the specified input color and calculates the dot product of the input color and that stage's texture coordinates (u, v, and w) to produce a u coordinate. Then, it takes that same input color and calculates the dot product of the input color and the texture coordinates of this stage to compute the v coordinate. Lastly, this stage's texture is sampled at (u, v) to produce the final color. No texture is sampled or needs to be set at the preceding stage, and any operator assigned to it is overridden by this one.

The following example shows how the texm3x2tex instruction might be used.

tex t0             ; Define t0 as a standard 3-vector.
texm3x2pad t1, t0  ; Perform first row of matrix multiply.
texm3x2tex t2, t0  ; Perform second row of matrix multiply to get a
                   ; 2-vector with which to sample texture 2.
mov r0, t2

A bump (normal) map should be set on stage 0, and a standard 2-D texture should be set on stage 2. Any texture set at stage 1 is ignored. For example, in the following shader, a base texture is lit by modulating with a diffuse bump map and adding an exponential specular. Stage 0 sets the base texture, stage 1 sets the normal map, and stage 2 sets the normal map again.

ps.1.0                 ; DirectX8 Version
tex t0                 ; sample normal map
texm3x2pad t1, t0_bx2  ; dot with light vector
texm3x2tex t2, t0_bx2  ; dot with halfway vector and sample
mov r0, t2

Texture coordinate set 0 positions the bump map. Texture coordinate sets 1 and 2 are the rows of the matrix.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.


texm3x3pad

Represents operations that are consumed by rows of the 3×3 matrix multiply that have no textures bound.

texm3x3pad   tDest, tSrc0

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Temporary source register, specifying the input argument.

Remarks

This instruction is a part of a 3×3 matrix multiply operation performed in a pixel shader's texture declaration stage. Texture coordinates corresponding to the declared texture are used as a row of the matrix. No texture should be bound at this stage.

The input argument to this declaration, t0, should be the input argument to the matrix multiply, tSrc0, as shown in the following example pixel shader.

tex t0             ; Define t0 as a standard 3-vector.
texm3x3pad t1, t0  ; Perform first row of matrix multiply.
texm3x3pad t2, t1  ; Perform second row of matrix multiply.
texm3x3tex t3, t2  ; Perform third row of matrix multiply to get a
                   ; 3-vector with which to sample texture 2.
mov r0, t3

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.


texm3x3spec

Performs specular reflection and environment mapping.

texm3x3spec   tDest, tSrc0, tSrc1

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Source register, specifying the input argument.
tSrc1
Source register, specifying the input argument.

Remarks

This operation takes the resulting post-transformed vector, and uses it as the normal to reflect an eye-ray vector. This eye-ray vector is always the constant color c0. Then, the instruction uses the result as an address to look up in a cube texture set at that stage. A specular environment map would be preloaded.

tex t0                  ; Define t0 as a standard 3-vector.
texm3x3pad t1, t0       ; Perform first row of matrix multiply.
texm3x3pad t2, t0       ; Perform second row of matrix multiply.
texm3x3spec t3, t0, c0  ; Perform third row of matrix multiply, do
                        ; reflection calculation, and sample texture 3.
mov r0, t3              ; Copy final result to output color.

A bump (normal) map should be set on stage 0, and cube texture should be set on stage 3. Any textures set at stages 1 or 2 are ignored.

Texture coordinate set 0 positions the bump map. Texture coordinate sets 1, 2, and 3 are the rows of the 3×3 matrix.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.

See Also

texm3x3vspec


texm3x3tex

Returns the result of the final 3×3 matrix multiply.

texm3x3tex   tDest, tSrc0
tDest
Destination register, holding the result of the operation.
tSrc0
Temporary source register, specifying the input argument.

Remarks

The texm3x3tex instruction is used as the final of three instructions representing a 3×3 matrix multiply operation performed in a pixel shader's texture declaration. The result of this instruction will contain the resulting transformed vector. The input argument to this declaration should be the input to the matrix multiply. Texture coordinates assigned to this stage are used as a row of the matrix.

The 3×3 matrix is comprised of the texture coordinates of this and the two preceding stages. The resulting three-component-vector is then used to index into the texture assigned at this stage, (which can be either a cube texture or a volume texture) to produce the final color. No texture colors are sampled from the preceding two stages, and any operator assigned to them is overridden by this one.

tex t0             ; Define t0 as a standard 3-vector.
texm3x3pad t1, t0  ; Perform first row of matrix multiply.
texm3x3pad t2, t0  ; Perform second row of matrix multiply.
texm3x3tex t3, t0  ; Perform third row of matrix multiply.

dp3 r0, t0, v0     ; Compute lighting intensity for diffuse
                   ; using v0.

A bump (normal) map should be set on stage 0, and cube texture should be set on stage 3. Any textures set at stages 1 or 2 are ignored.

Texture coordinate set 0 positions the bump map. Texture coordinate sets 1, 2, and 3 are the rows of the 3×3 matrix.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.


texm3x3vspec

Performs specular reflection and environment mapping where the eye-vector is not constant.

texm3x3vspec   tDest, tSrc0

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Source register, specifying the input argument.

Remarks

This instruction is used for texture addressing. It works just as texm3x3spec, except that the eye-ray is taken from the w-components of the three sets of texture coordinates used as rows of the matrix.

tex t0               ; Define t0 as a standard 3-vector.
texm3x3pad t1, t0    ; Perform first row of matrix multiply.
texm3x3pad t2, t0    ; Perform second row of matrix multiply.
texm3x3vspec t3, t0  ; Perform third row of matrix multiply, sample
                     ; texture 2, do reflection calculation
                     ; using eye ray, and sample texture 3
                     ; specular map.
mov r0.rgb, t3       ; Put specular color into the result.
mov r0.a,   t3       ; Put diffuse color into the alpha channel.

A bump (normal) map should be set on stage 0, and cube texture should be set on stage 3. Any textures set at stages 1 or 2 are ignored.

Texture coordinate set 0 positions the bump map. Texture coordinate sets 1, 2, and 3 are the rows of the 3×3 matrix.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.

See Also

texm3x3spec


texreg2ar

Samples this stage's texture at the 2-D coordinates specified by the alpha and red components of the specified input color vector.

texreg2ar tDest, tSrc0

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Temporary source register, specifying the input argument.

Remarks

This instruction is useful for color space re-mapping operations.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.


texreg2gb

Samples this stage's texture at the 2-D coordinates specified by the green and blue components of the specified input color vector.

texreg2gb tDest, tSrc0

Registers

tDest
Destination register, holding the result of the operation.
tSrc0
Temporary source register, specifying the input argument.

Remarks

This instruction is useful for color space re-mapping operations.

Note that this instruction has an unnamed input which is the assigned texture that corresponds to this texture stage.


Modifiers

The Direct3DX pixel shader assembler supports the following types of modifiers.

  • Argument Modifiers
  • Instruction Modifiers


Argument Modifiers

The Direct3DX pixel shader assembler can take instruction arguments (operands) with modifier flags that affect the input argument before it is processed in the instruction. There are two types of input argument modifiers: color and alpha blending input argument modifiers and texture addressing input argument modifiers.

The input argument modifiers are defined by the following table, where rn is an input argument (register).

Instruction | Syntax | Description
Alpha Replicate | rn.a | Replicates the alpha channel to all colors.
Invert | 1-rn | Complements y = 1.0 - x. Unsigned x is required.
Negate | -rn | Negates the value y = -x. Signed x is required.
Bias | rn_bias | Shifts value down by ½, y = (x-0.5).
Signed Scaling | rn_bx2 | Shifts value down and scales data by 2, y = 2*(x-0.5).

For example, the lrp instruction can be implemented using input argument modifiers.

; Using diffuse alpha to blend between r0 and t0
lrp r0, v0.a, r0, t0
; can be written (using more clocks) as:
sub r0, r0, t0
mad r0, t0, v0.a, r0

Unlike vertex shaders, component swizzles are not supported by the pixel shader. The x, y, and z components are treated together as an RGB color component, and the w component is treated as alpha which can be routed separately.


Alpha Replicate

rn.a

Replicates the alpha channel of the affected register to all of its color channels before processing the instruction.

The following example shows how to use this modifier.

mul r0, r0, r1.a    ; Modulate by the alpha channel (grayscale),
                  ; varies only the intensity of color.

Note that this operator can be used in conjunction with the Invert or Negate operators. Its functionality is analogous to the D3DTA_ALPHAREPLICATE flag in the Microsoft® DirectX® 6.0 and 7.0 multitexture syntax.

This modifier is for use with the color and alpha blending instructions.


Invert

1-rn

Compliments the colors in each channel of the specified register.

The following example shows how to use this modifier.

mul r0, r0, 1-r1    ; Multiply by (1.0 – r1).

This modifier only produces defined results when the input data is unsigned, meaning that it is in the range of 0 to 1. This operation is performed after any other modifiers present on the same argument.

Note that this modifier only works with unsigned data. The use of this instruction is inconsistent with the Bias, Signed Scaling, and Negate modifiers, so it cannot appear on the same register with any of these modifiers.

This modifier is for use with the color and alpha blending instructions.


Negate

-rn

Performs a signed inverse (y = -x), or negates the value before it is used in the instruction.

The following example shows how to use this modifier.

mul r0, r0, -v1    ; Multiply by –specular color.

This operation is performed after any other modifiers present on the same argument.

Note that Invert (1-rn)and Negate (-rn) are mutually exclusive and cannot be applied to the same register.

This modifier is for use with the color and alpha blending instructions.


Bias

rn_bias

Shift each channel down by ½. So, it performs y = (x-0.5) before the register is operated on.

The following example shows how to use this modifier.

add r0, r0, t0_bias    ; Shift down by 0.5.

This example shows how to use add to perform the same operation as D3DTOP_ADDSIGNED in Microsoft® DirectX® 6.0 and 7.0 multitexture syntax.

This modifier has the effect of modifying data that was in the range 0 to 1 to be in the range -0.5 to 0.5. This is commonly used for applying detail textures. It can also enable the input data to be processed as a signed quantity while reserving dynamic range before overflow clamping that can occur on implementations limited to the range -1 to1.

Note that this modifier is mutually exclusive with Invert, so it cannot be applied to the same register.

This modifier is for use with the color and alpha blending instructions.


Signed Scaling

rn_bx2

When used with a color and alpha blending instruction, this modifier subtracts 0.5 from each channel and scales the result by 2.0 before the instruction is executed. So it performs y = (x-0.5)*2.

The following example shows how to use this modifier.

dp3_sat r0, t1_bx2, v0_bx2    ; Per-pixel lighting/bump mapping which assumes bump normals
                              ; assumes bump normals in t1 and light direction in diffuse
                              ; color v0.

This modifier has the effect of remapping data that was in the range 0 to 1 to be in the signed range -1 to 1. This enables subsequent processing of the data to use the full signed dynamic range of the implementation.

This modifier is commonly used on inputs to the dot product instruction (dp3).

Note that this modifier is mutually exclusive with Invert, so it cannot be applied to the same register.

The input arguments to texture register declarations can support the _bx2 modifier to indicate additional processing to be performed during the execution of the declaration/instruction for the dp3, texm3x2tex, and texm3x3tex operations. The other texture addressing operators do not support the _bx2 input argument modifiers.

To indicate that the input register argument should be biased and scaled before use, append _bx2 to the input register argument.

tex t0            ; Read a texture color.
dp3 t1, t0_bx2    ; Calculate a dotproduct with this stage's texture coordinates.

This performs the operation y = 2(x - 0.5) on the input register before using it in the specified operator. This operation is commonly used to translate data that is intended to contain signed values in the range -1 to 1, but does not do this because the source it comes from cannot support it. Such data sources include textures (tn), iterated colors (vn), texture coordinates, or constant factor registers (cn).

This modifier is for use with both the color and alpha blending instructions and the texture addressing instructions.


Instruction Modifiers

The Direct3DX pixel shader assembler support shift/scale modifier flags and a saturation modifier flag that affects the generated output result. Instruction modifiers integrate with the instruction processing in the following order.

  1. Perform inversion.
  2. Apply biasing.
  3. Apply scaling to the result.
  4. Perform clamping.

The shift/scale modifiers can vary the magnitude of the result within a certain range.

Name | Modifier
_x2 | Multiply result by 2
_x4 | Multiply result by 4
_d2 | Divide result by 2

In addition, a saturation modifier (_sat) is provided for both color and alpha blending instructions and texture addressing instructions.

For color and alpha blending instruction, the saturation modifier clamps the result of this instruction into the range 0.0 to 1.0 for each component. The following example shows how to use this instruction modifier.

dp3_sat r0, t0_bx2, v0_bx2    ; t0 is bump, v0 is light direction

This operation occurs after the scaling instruction modifier. This is most often used to clamp dot product results. However, it also enables consistent emulation of multipass methods where the frame buffer is always in the range 0 to 1, and of Microsoft® DirectX 6.0 and 7.0 multitexture syntax, in which saturation is defined to occur at every stage.

For texture addressing instructions, the saturation modifier can be appended to the operation to indicate that the result of the operation should be clamped into the color range 0 .0 to 1.0 upon completion of the operation. This is commonly required for use in lighting operations. The following example shows how to use this instruction modifier.

ps.1.0                       ; DirectX8 Version
tex t0                       ; Read a texture color.
dp3_sat t1, t0_bx2, v0_bx2   ; Calculate a dotproduct with the texture coordinates and clamp.

The following add instruction loads the destination register (d) with the sum of the two colors in the source operands (s0 and s1), and multiplies the result by 2.

add_x2   d, s0, s1

The following add instruction loads the destination register (d) with the sum of the two colors in the source operands (s0 and s1), and clamps the result into the range 0.0 to 1.0 for each component.

add_sat   d, s0, s1

The following add instruction loads the destination register (d) with the sum of the two colors in the source operands (s0 and s1), multiplies the result by 2, and clamps the result into the range 0.0 to 1.0 for each component.

add_2x_sat   d, s0, s1


Output Write Masks

The output masks supported by the Direct3DX pixel shader compiler are used to indicate whether this result should update either the color or the alpha component of the result, and therefore whether to use the color or alpha pipelines for its processing. These output masks are analogous to the separate color and alpha operations in Microsoft® DirectX 6.0 and 7.0 multitexture blending.

These flags are not as general as those supported by vertex shaders because the rgb components are always grouped into a single flag, resulting in only two different masks, .a and .rgb.

The following output write masks are supported.

  • Color/Vector Write Mask
  • Alpha/Scalar Write Mask
  • Full Write Mask

Note that none of the output write masks are supported for the texture addressing instruction. These operations always update all four components of the destination register, you cannot separate r, g, and b individually.

The pixel shader does not support arbitrary swizzles, only color and alpha operations.


Color/Vector Write Mask

.rgb

When specified on the output register, this flag indicates that the operation will update only the three color channels of the destination register, and therefore should be performed in the color (vector) pipeline for the instruction.

The following example shows how to use this output write mask.

mul r0.rgb,  t0, v0
add r0.a,    t1, v1


Alpha/Scalar Write Mask

.a

When specified on the destination register, this flag indicates that the operation will update only the alpha channel of the destination register, and therefore should be performed in the alpha (scalar) pipeline for this instruction.

The following example shows how to use this output write mask.

mul r0.rgb,  t0, v0
add r0.a,    t1, v1


Full Write Mask

.rgba

Requests that the same instruction be applied in both the color and alpha channels. This is the default, so no output mask needs to be specified to achieve the same result.

For example, the following instruction

mul r0, t0, v0

is equivalent to

mul r0.rgba, t0, v0

which is also equivalent to the following instruction.

  mul r0.rgb, t0, v0
+ mul r0.a,   t0, v0

Note that even this last syntax takes only one clock due to pairing between the scalar and vector pipelines. For more information, see Pixel Shader Instruction Pairing.


Effect File Format

This section contains reference information for the effect file format. An effect file consists of a set of parameter declarations, followed by descriptions of various techniques.

  • Parameter Types
  • Constant Value Syntax
  • Vertex Shader Declaration Syntax
  • List of Valid States
  • Sample of an Effect File

Technique descriptions have the following syntax. Remember that id must be a valid FourCC code. For information on FourCC codes, see Four-Character Codes (FOURCC).

  • Variable declarations go before the body of the technique.
  • The body of the technique contains one or more pass descriptions.
  • A pass contains one or more state assignments.
  • States can be assigned to either a constant value or to a parameter.
{type} {id};
{type} {id} = {const};

TECHNIQUE {id}
{
    PASS {id}
    {
        {state}      = {const};
        {state}[{n}] = {const};
        {state}      = <{id}>;
        {state}[{n}] = <{id}>;
    }
}


Parameter Types

Parameter declarations have the following syntax, where type is a valid type, and id is a valid Four-Character Codes (FOURCC). If a const value is provided as an initial value for the parameter, its type must match type.

{type} {id};
{type} {id} = {const};

The following table lists all of the valid parameter types that are used for effect file parameter declarations along with a sample.

Type Sample
DWORD
DWORD minVertices;
FLOAT
FLOAT fRotationAdvances;
VECTOR
VECTOR vecPoint;
MATRIX
MATRIX matIndentity;
TEXTURE
TEXTURE tex1;
VERTEXSHADER
VERTEXSHADER v1;
PIXELSHADER
PIXELSHADER p1;


Constant Value Syntax

The following table list shows the proper syntax for constant values and a sample.

Type Syntax
DWORD
#

0x#

54573153

0xff12a1fa
FLOAT
#f

#.f
.#f
#.#f

5f

5.f
.4f
4.5f
VECTOR
(float)

(float, float)
(float, float, float)
(float, float, float, float)

( 4.5f )

( 4.5f, 1.0f )
( 4.5f, 1.0f, 2.0f )
( 4.5f, 1.0f, 2.0f, 3.4f )
MATRIX
[ float, float, float, float,

  float, float, float, float,
  float, float, float, float,
  float, float, float, float ]

[ 1.0f, 0.0f, 0.0f, 0.0f,

  0.0f, 1.0f, 0.0f, 0.0f,
  0.0f, 0.0f, 1.0f, 0.0f,
  0.0f, 0.0f, 0.0f, 1.0f ]
VERTEXSHADER
DECL { ... }

DECL { ... }, ASM { ... }

decl

{
   stream 0;
   float v0[3];
   float v3[3];
   ubyte v5[4];
   float v7[2];
}

decl
{
   stream 0;
   float v0[3];
   float v3[3];
   ubyte v5[4];
   float v7[2];
}
asm
{
   vs.1.0
   mov oPos, v0
}
PIXELSHADER
ASM { ... }

asm

{
   vs.1.0
   mov oPos, v0
}

For information on the layout of the DECL syntax, see Vertex Shader Declaration Syntax.

For information on the layout of the ASM syntax, see Pixel Shader Assembler Reference.


Vertex Shader Declaration Syntax

DECL
{
    STREAM n;
    SKIP n;
    FVF a|b|c;

    type v#;
    type v#[n];
}

The following table describes the type of values used for the above syntax.

Syntax | Description
a|b|c | DWORD expression which can consist of DWORDs and flexible vector format flags. To use a FVF, just strip off the D3DFVF_ prefix.
Type | One of the following types: UBYTE, SHORT, FLOAT, D3DCOLOR.
v# | A valid vertex shader input register. See the table below for the list of FVF flags and their corresponding vertex shader input register.
n | A number between 1 and 4

The following table lists the FVF codes and the corresponding vertex shader input registers.

FVF | Name | Register Number
D3DFVF_XYZ | D3DVSDE_POSITION | 0
D3DFVF_XYZRHW | D3DVSDE_BLENDWEIGHT | 1
D3DFVF_XYZB1 through D3DFVF_XYZB5 | D3DVSDE_BLENDINDICES | 2
D3DFVF_NORMAL | D3DVSDE_NORMAL | 3
D3DFVF_PSIZE | D3DVSDE_PSIZE | 4
D3DFVF_DIFFUSE | D3DVSDE_DIFFUSE | 5
D3DFVF_SPECULAR | D3DVSDE_SPECULAR | 6
D3DFVF_TEX0 | D3DVSDE_TEXCOORD0 | 7
D3DFVF_TEX1 | D3DVSDE_TEXCOORD1 | 8
D3DFVF_TEX2 | D3DVSDE_TEXCOORD2 | 9
D3DFVF_TEX3 | D3DVSDE_TEXCOORD3 | 10
D3DFVF_TEX4 | D3DVSDE_TEXCOORD4 | 11
D3DFVF_TEX5 | D3DVSDE_TEXCOORD5 | 12
D3DFVF_TEX6 | D3DVSDE_TEXCOORD6 | 13
D3DFVF_TEX7 | D3DVSDE_TEXCOORD7 | 14
 | D3DVSDE_POSITION2 | 15
 | D3DVSDE_NORMAL2 | 16


List of Valid States

The following topic covers the entire list of valid states that can be used when creating an effect file.

When setting states of type DWORD, you can use enumerated values. For example, SrcBlend is typically set using D3DBLEND_xxx enumerated types. Therefore, you can use any of these enumeration types in your assignment. Just strip off the D3DBLEND_ prefix as shown in the code fragment below.

SrcBlend = One;

You can also string these together in an "OR" expression.

TextureTransformFlags[0] = Count3 | Projected;

The following table lists the valid render states used in an effect file.

Type | Render State | Valid Values
DWORD | ZEnable | D3DZB
DWORD | FillMode | D3DFILL
DWORD | ShadeMode | D3DSHADE
DWORD | LinePattern |
DWORD | ZWriteEnable | TRUE/FALSE
DWORD | AlphaTestEnable | TRUE/FALSE
DWORD | LastPixel | TRUE/FALSE
DWORD | SrcBlend | D3DBLEND
DWORD | DestBlend | D3DBLEND
DWORD | CullMode | D3DCULL
DWORD | ZFunc | D3DCMP
DWORD | AlphaRef |
DWORD | AlphaFunc | D3DCMP
DWORD | DitherEnable | TRUE/FALSE
DWORD | AlphaBlendEnable | TRUE/FALSE
DWORD | FogEnable | TRUE/FALSE
DWORD | SpecularEnable | TRUE/FALSE
DWORD | ZVisible | TRUE/FALSE
DWORD | FogColor |
DWORD | FogTableMode | D3DFOG
FLOAT | FogStart |
FLOAT | FogEnd |
FLOAT | FogDensity |
DWORD | EdgeAntialias | TRUE/FALSE
DWORD | Zbias |
DWORD | RangeFogEnable |
DWORD | StencilEnable | TRUE/FALSE
DWORD | StencilFail | D3DSTENCILOP
DWORD | StencilZFail | D3DSTENCILOP
DWORD | StencilPass | D3DSTENCILOP
DWORD | StencilFunc | D3DCMP
DWORD | StencilRef |
DWORD | StencilMask |
DWORD | StencilWriteMask |
DWORD | TextureFactor |
DWORD | Wrap0 | D3DWRAP
DWORD | Wrap1 | D3DWRAP
DWORD | Wrap2 | D3DWRAP
DWORD | Wrap3 | D3DWRAP
DWORD | Wrap4 | D3DWRAP
DWORD | Wrap5 | D3DWRAP
DWORD | Wrap6 | D3DWRAP
DWORD | Wrap7 | D3DWRAP
DWORD | Clipping | TRUE/FALSE
DWORD | Lighting | TRUE/FALSE
DWORD | Ambient |
DWORD | FogVertexMode |
DWORD | ColorVertex | TRUE/FALSE
DWORD | LocalViewer | TRUE/FALSE
DWORD | NormalizeNormals | TRUE/FALSE
DWORD | DiffuseMaterialSource | D3DMCS
DWORD | SpecularMaterialSource | D3DMCS
DWORD | AmbientMaterialSource | D3DMCS
DWORD | EmissiveMaterialSource | D3DMCS
DWORD | VertexBlend | D3DVBF
DWORD | ClipPlaneEnable | TRUE/FALSE
DWORD | SoftwareVertexProcessing | TRUE/FALSE
FLOAT | PointSize |
FLOAT | PointSize_Min |
FLOAT | PointSize_Max |
DWORD | PointSpriteEnable | TRUE/FALSE
DWORD | PointScaleEnable | TRUE/FALSE
FLOAT | PointScale_A |
FLOAT | PointScale_B |
FLOAT | PointScale_C |
DWORD | MultiSampleAntialias | TRUE/FALSE
DWORD | MultiSampleMask |
DWORD | PatchSegments |
DWORD | IndexedVertexBlendEnable | TRUE/FALSE
DWORD | ColorWriteEnable | TRUE/FALSE
FLOAT | TweenFactor |
DWORD | BlendOp | D3DBLENDOP

The following table lists the valid texture stage states used in an effect file.

Type | Texture Stage State | Valid Values
DWORD | ColorOp[8] | D3DTOP
DWORD | ColorArg0[8] | D3DTA
DWORD | ColorArg1[8] | D3DTA
DWORD | ColorArg2[8] | D3DTA
DWORD | AlphaOp[8] | D3DTOP
DWORD | AlphaArg0[8] | D3DTA
DWORD | AlphaArg1[8] | D3DTA
DWORD | AlphaArg2[8] | D3DTA
DWORD | ResultArg[8] | D3DTA
DWORD | BumpEnvMat00[8] |
DWORD | BumpEnvMat01[8] |
DWORD | BumpEnvMat10[8] |
DWORD | BumpEnvMat11[8] |
DWORD | TexCoordIndex[8] | D3DTSS_TCI
DWORD | AddressU[8] | D3DTADDRESS
DWORD | AddressV[8] | D3DTADDRESS
DWORD | AddressW[8] | D3DTADDRESS
DWORD | BorderColor[8] |
DWORD | MagFilter[8] | D3DTEXF
DWORD | MinFilter[8] | D3DTEXF
DWORD | MipFilter[8] | D3DTEXF
DWORD | MipMapLodBias[8] |
DWORD | MaxMipLevel[8] |
DWORD | MaxAnsiotropy[8] |
FLOAT | BumpEnvLScale[8] |
FLOAT | BumpEnvLOffset[8] |
DWORD | TextureTransformFlags[8] | D3DTTFF

The following table lists the valid light states used in an effect file. If you set light states in your effect, you should set all states that you need to completely describe the light. States that you fail to declare will be set to some default value because there is no way for D3DX to set light states individually.

Type | Light State | Valid Values
DWORD | LightType[n] | D3DLT
VECTOR | LightDiffuse[n] |
VECTOR | LightSpecular[n] |
VECTOR | LightAmbient[n] |
VECTOR | LightPosition[n] |
VECTOR | LightDirection[n] |
FLOAT | LightRange[n] |
FLOAT | LightFalloff[n] |
FLOAT | LightAttenuation0[n] |
FLOAT | LightAttenuation1[n] |
FLOAT | LightAttenuation2[n] |
FLOAT | LightTheta[n] |
FLOAT | LightPhi[n] |
DWORD | LightEnable[n] | TRUE/FALSE

The following table lists the valid material states used in an effect file. If you set material states in your effect, you should set all states that you need to completely describe the material. States that you fail to declare will be set to some default value because there is no way for D3DX to set material states individually.

Type | Material State
VECTOR | MaterialDiffuse
VECTOR | MaterialAmbient
VECTOR | MaterialSpecular
VECTOR | MaterialEmissive
FLOAT | MaterialPower

The following table lists other valid states used in an effect file.

Type | State
VERTEXSHADER | VertexShader
PIXELSHADER | PixelShader
CONSTANT | VertexShaderConstant[n]
CONSTANT | PixelShaderConstant[n]
TEXTURE | Texture[8]
MATRIX | ProjectionTransform
MATRIX | ViewTransform
MATRIX | WorldTransform[256]
MATRIX | TextureTransform[8]


Sample of an Effect File

The following shows the basic syntax and layout of a typical effect file.

//
// Sample Effect
// This effect adds two textures, using single pass or multipass technique.
//

texture tex0;
texture tex1;

// Single pass

technique t0
{
    pass p0
    {
        Texture[0] = <tex0>;
        Texture[1] = <tex1>;

        ColorOp[0] = SelectArg1;
        ColorArg1[0] = Texture;

        ColorOp[1] = Add;
        ColorArg1[0] = Texture;
        ColorArg2[0] = Current;

        ColorOp[2] = Disable;
    }
}

// Multipass

technique t1
{
    pass p0
    {
        Texture[0] = <tex0>;

        ColorOp[0] = SelectArg1;
        ColorArg1[0] = Texture;
        ColorOp[1] = Disable;
    }

    pass p1
    {
        AlphaBlendEnable = True;
        SrcBlend = One;
        DestBlend = One;

        Texture[0] = <tex1>;

        ColorOp[0] = SelectArg1;
        ColorArg1[0] = Texture;
        ColorOp[1] = Disable;
    }
}


X File C/C++ Reference

This section contains reference information for the API elements used to work with Microsoft® DirectX® (.x) files.

  • Interfaces
  • Functions
  • Structures
  • Return Values


Interfaces

This section contains reference information for the COM interfaces used to read to and write from Microsoft® DirectX® (.x) files.

  • IDirectXFile
  • IDirectXFileBinary
  • IDirectXFileData
  • IDirectXFileDataReference
  • IDirectXFileEnumObject
  • IDirectXFileObject
  • IDirectXFileSaveObject


IDirectXFile

Applications use the methods of the IDirectXFile interface to create instances of the IDirectXFileEnumObject and IDirectXFileSaveObject interfaces, and to register templates.

The IDirectXFile interface is obtained by calling the DirectXFileCreate function.

The methods of the IDirectXFile interface can be organized into the following groups.

Creation | CreateEnumObject
 | CreateSaveObject
Templates | RegisterTemplates

The IDirectXFile interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The globally unique identifier (GUID) for the IDirectXFile interface is IID_IDirectXFile.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFile::CreateEnumObject

Creates an enumerator object.

HRESULT CreateEnumObject(
  LPVOID pvSource,
  DXFILELOADOPTIONS dwLoadOptions,
  LPDIRECTXFILEENUMOBJECT* ppEnumObj
);

Parameters

pvSource
[out] Pointer to data whose contents depend on the value of dwLoadOptions
dwLoadOptions
[in] Value that specifies the source of the data. This value can be one of the following flags.
DXFILELOAD_FROMFILE
Indicates data read from a file, so the value in pvSource is the name of the file.
DXFILELOAD_FROMRESOURCE
Indicates data read from a resource, so the value in pvSource is a DXFILELOADRESOURCE structure.
DXFILELOAD_FROMMEMORY
Indicates data read from memory, so the value in pvSource is a DXFILELOADMEMORY structure.
DXFILELOAD_FROMSTREAM
Indicates data read from a stream. Not currently supported.
DXFILELOAD_FROMURL
Indicates data read from a URL, so the value in pvSource is the name of the URL.
ppEnumObj
[out] Address of a pointer to an IDirectXFileEnumObject interface, representing the created enumerator object.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADFILEFLOATSIZE
DXFILEERR_BADFILETYPE
DXFILEERR_BADFILEVERSION
DXFILEERR_BADRESOURCE
DXFILEERR_BADVALUE
DXFILEERR_FILENOTFOUND
DXFILEERR_RESOURCENOTFOUND
DXFILEERR_URLNOTFOUND

Remarks

After using this method, use one of the IDirectXFileEnumObject methods to retrieve a data object.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.

See Also

IDirectXFileEnumObject


IDirectXFile::CreateSaveObject

Creates a save object.

HRESULT CreateSaveObject(
  LPCSTR szFileName,
  DXFILEFORMAT dwFileFormat,
  LPDIRECTXFILESAVEOBJECT* ppSaveObj
);

Parameters

szFileName
[in] Pointer to the name of the file to use for saving data.
dwFileFormat
[in] Indicates the format to use when saving the Microsoft® DirectX® file. For more information, see Remarks.
DXFILEFORMAT_BINARY
Indicates a binary file.
DXFILEFORMAT_COMPRESSED
Indicates a compressed file.
DXFILEFORMAT_TEXT
Indicates a text file.
ppSaveObj
[out, retval] Address of a pointer to an IDirectXFileSaveObject interface, representing the created save object.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADFILE
DXFILEERR_BADVALUE

Remarks

After using this method, use methods of the IDirectXFileSaveObject interface to create data objects and to save templates or data.

The default value for the file format is DXFILEFORMAT_BINARY. The file format values can be combined in a logical OR to create compressed text or compressed binary files. If a file is specified as both binary (0) and text (1), it will be saved as a text file because the value will be indistinguishable from the text file format value (0 + 1 = 1). If you indicate that the file format should be text and compressed, the file will first be written out as text and then compressed. However, compressed text files are not as efficient as binary text files, so in most cases you will want to indicate binary and compressed. Setting a file to be compressed without specifying a format will result in a binary, compressed file.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.

See Also

IDirectXFileSaveObject


IDirectXFile::RegisterTemplates

Registers custom templates.

HRESULT RegisterTemplates(
  LPVOID pvData,
  DWORD cbSize
);

Parameters

pvData
[in] Pointer to a buffer consisting of a Microsoft® DirectX® file in text or binary format that contains templates.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADFILEFLOATSIZE
DXFILEERR_BADFILETYPE
DXFILEERR_BADFILEVERSION
DXFILEERR_BADVALUE
DXFILEERR_PARSEERROR

Remarks

The following code fragment provides an example call to RegisterTemplates and example contents for the buffer to which pvData points.

TIDirectXFile * pDXFile;

char *szTemplates = "xof 0303txt 0032\
    template SimpleData { \
        <2b934580-9e9a-11cf-ab39-0020af71e433> \
        DWORD item1;DWORD item2;DWORD item3;} \
    template ArrayData { \
        <2b934581-9e9a-11cf-ab39-0020af71e433> \
        DWORD cItems; array DWORD aItem[2][cItems]; [...] } \
    template RestrictedData { \
        <2b934582-9e9a-11cf-ab39-0020af71e433> \
        DWORD item; [SimpleData]}";

hr = pDXFile->RegisterTemplates(szTemplates, strlen(szTemplates));

All templates must specify a name and a Universally Unique Identifier (UUID).

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileBinary

Applications use the methods of the IDirectXFileBinary interface to read and retrieve information about binary data.

The IDirectXFileBinary interface inherits the following IDirectXFileObject methods, which can be organized into this group.

Information | GetId
 | GetName

The methods of the IDirectXFileBinary interface can be organized into the following groups.

Information | GetMimeType
 | GetSize
Reading Data | Read

The IDirectXFileBinary interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The globally unique identifier (GUID) for the IDirectXFileBinary interface is IID_IDirectXFileBinary.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileBinary::GetMimeType

Retrieves the Multipurpose Internet Mail Extensions (MIME) type for the binary data.

HRESULT GetMimeType(
  LPCSTR* pszMimeType
);

Parameters

pszMimeType
[out, retval] Address of a pointer to receive the MIME type string.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

Remarks

When there is no MIME type specified in a Microsoft® DirectX® file for a binary object, the function will set pszMimeType to NULL.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileBinary::GetSize

Retrieves the size of the binary data.

HRESULT GetSize(
  DWORD* pcbSize
);

Parameters

pcbSize
[out, retval] Pointer to the returned size of the binary data, in bytes.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileBinary::Read

Reads the binary data.

HRESULT Read(
  LPVOID pvData,
  DWORD cbSize,
  LPDWORD pcbRead
);

Parameters

pvData
[out] Pointer to the buffer that receives the data that has been read.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.
pcbRead
[out, retval] Pointer to the number of bytes actually read.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOMOREDATA

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileData

Applications use the methods of the IDirectXFileData interface to build or to access the immediate hierarchy of the data object. Template restrictions determine the hierarchy. Data types allowed by the template are called optional members. The optional members are not required, but an object might miss important information without them. These optional members are saved as children of the data object. The children can be another data object, a reference to an earlier data object, or a binary object.

The IDirectXFileData interface inherits the following IDirectXFileObject methods, which can be organized into this group.

Information | GetId
 | GetName

The methods of the IDirectXFileData interface can be organized into the following groups.

Add Data | AddBinaryObject
 | AddDataObject
 | AddDataReference
Retrieve Data | GetData
 | GetNextObject
 | GetType

The IDirectXFileData interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The globally unique identifier (GUID) for the IDirectXFileData interface is IID_IDirectXFileData.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileData::AddBinaryObject

Creates a binary object and adds it as a child object.

HRESULT AddBinaryObject(
  LPCSTR szName,
  const GUID* pguid,
  LPCSTR szMimeType,
  LPVOID pvData,
  DWORD cbSize
);

Parameters

szName
[in] Pointer to the name of the object. Specify NULL if the object does not need a name.
pguid
[in] Pointer to the globally unique identifier (GUID) representing the object. Specify NULL if the object does not need a GUID.
szMimeType
[in] Pointer to the object's MIME type.
pvData
[in] Pointer to the object's data.
cbSize
[in] Size of the buffer pointed to by pvData, in bytes.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.

See Also

IDirectXFileBinary::GetMimeType


IDirectXFileData::AddDataObject

Adds a data object as a child object.

HRESULT AddDataObject(
  LPDIRECTXFILEDATA pDataObj
);

Parameters

pDataObj
[in] Pointer to an IDirectXFileData interface, representing the file data object to add as a child object.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

Remarks

Use the IDirectXFileSaveObject::CreateDataObject method to create the IDirectXFileData object before calling this method.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.

See Also

IDirectXFileSaveObject::CreateDataObject


IDirectXFileData::AddDataReference

Creates and adds a data reference object as a child object.

HRESULT AddDataReference(
  LPCSTR szRef,
  const GUID* pguidRef
);

Parameters

szRef
[in] Pointer to the name of the referenced data object. This parameter can be NULL if pguidRef provides a reference to the globally unique identifier (GUID).
pguidRef
[in] Pointer to the GUID representing the data. This parameter can be NULL if szRef provides a reference to the name.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

Remarks

For this method to succeed, either the szRef or pguidRef parameter must be non-NULL.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileData::GetData

Retrieves the data for one of the object's members or the data for all members.

HRESULT GetData(
  LPCSTR szMember,
  DWORD* pcbSize,
  void** ppvData
);

Parameters

szMember
[in] Pointer to the name of the member for which to retrieve data. Specify NULL to retrieve all required members' data.
pcbSize
[out] Pointer to receive the ppvData buffer size, in bytes.
ppvData
[out] Address of a pointer to the buffer to receive the data associated with szMember. If szMember is NULL, ppvData is set to point to a buffer containing all required members' data in a contiguous block of memory.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADARRAYSIZE
DXFILEERR_BADDATAREFERENCE
DXFILEERR_BADVALUE

Remarks

This method retrieves the data for required members of a data object but no data for optional (child) members. Use IDirectXFileData::GetNextObject to retrieve child objects.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.

See Also

IDirectXFileData::GetNextObject


IDirectXFileData::GetNextObject

Retrieves the next child data object, data reference object, or binary object in the Microsoft® DirectX® file.

HRESULT GetNextObject(
  LPDIRECTXFILEOBJECT* ppChildObj
);

Parameters

ppChildObj
[out, retval] Address of a pointer to an IDirectXFileObject interface, representing the returned child object's file object interface.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOMOREOBJECTS

Remarks

To determine the type of object retrieved, use QueryInterface to query the retrieved object for support of IDirectXFileData, IDirectXFileDataReference, or IDirectXFileBinary interfaces. The interface supported indicates the type of object (data, data reference, or binary).

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.

See Also

IDirectXFileBinary, IDirectXFileData, IDirectXFileDataReference


IDirectXFileData::GetType

Retrieves the globally unique identifier (GUID) of the object's template.

HRESULT GetType(
  const GUID** ppguid
);

Parameters

ppguid
[out, retval] Address of a pointer to receive the GUID of the object's template.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileDataReference

Applications use the methods of the IDirectXFileDataReference interface to support data reference objects. A data reference object refers to a data object that is defined earlier in the file. This enables you to use the same object multiple times without repeating it in the file.

The IDirectXFileDataReference interface inherits the following IDirectXFileObject methods, which can be organized into this group.

Information | GetId
 | GetName

The IDirectXFileDataReference interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

After you have determined that an object is a data reference object, use the IDirectXFileDataReference::Resolve method to retrieve the referenced object defined earlier in the file.

For information on how to identify a data reference object, see the IDirectXFileData interface.

The globally unique identifier (GUID) for the IDirectXFileDataReference interface is IID_IDirectXFileDataReference.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileDataReference::Resolve

Resolves data references.

HRESULT Resolve(
  LPDIRECTXFILEDATA* ppDataObj
);

Parameters

ppDataObj
[out, retval] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOTFOUND

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileEnumObject

Applications use the methods of the IDirectXFileEnumObject interface to cycle through the data objects in the file and to retrieve a data object by its globally unique identifier (GUID) or by its name.

The methods of the IDirectXFileEnumObject interface can be organized into the following groups.

Object Retrieval | GetDataObjectById
 | GetDataObjectByName
Enumeration | GetNextDataObject

The IDirectXFileEnumObject interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The GUID for the IDirectXFileEnumObject interface is IID_IDirectXFileEnumObject.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileEnumObject::GetDataObjectById

Retrieves the data object that has the specified globally unique identifier (GUID).

HRESULT GetDataObjectById(
  REFGUID rguid,
  LPDIRECTXFILEDATA* ppDataObj
);

Parameters

rguid
[in] Reference to the requested globally unique identifier (GUID).
ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOTFOUND

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileEnumObject::GetDataObjectByName

Retrieves the data object that has the specified name.

HRESULT GetDataObjectByName(
  LPCSTR szName,
  LPDIRECTXFILEDATA* ppDataObj
);

Parameters

szName
[in] Pointer to the requested name.
ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOTFOUND

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileEnumObject::GetNextDataObject

Retrieves the next top-level object in the Microsoft® DirectX® file.

HRESULT GetNextDataObject(
  LPDIRECTXFILEDATA* ppDataObj
);

Parameters

ppDataObj
[out] Address of a pointer to an IDirectXFileData interface, representing the returned file data object.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADVALUE
DXFILEERR_NOMOREOBJECTS

Remarks

Top-level objects are always data objects. Data reference objects and binary objects can only be children of data objects.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileObject

Applications use the methods of the IDirectXFileObject interface to retrieve information about Microsoft® DirectX® file objects.

The methods of the IDirectXFileObject interface can be organized into the following group.

Information | GetId
 | GetName

The IDirectXFileObject interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The globally unique identifier (GUID) for the IDirectXFileObject interface is IID_IDirectXFileObject.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileObject::GetId

Retrieves a pointer to the globally unique identifier (GUID) that identifies a Microsoft® DirectX® file object.

HRESULT GetId(
  LPGUID pGuid
);

Parameters

pGuid
[out, retval] Pointer to a globally unique identifier (GUID) to receive the object's ID. The function will set the GUID to a NULL GUID if the object does not have an ID.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

Applies To

This method applies to the following interfaces, which inherit from IDirectXFileObject.

  • IDirectXFileBinary
  • IDirectXFileData

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileObject::GetName

Retrieves a pointer to a Microsoft® DirectX® file object's name.

HRESULT GetName(
  LPSTR pstrNameBuf,
  LPDWORD pdwBufLen
);

Parameters

pstrNameBuf
[out] Pointer to the buffer in which the Microsoft® DirectX® file object's name will be copied. Set to NULL if only the buffer length is needed.
pdwBufLen
[in, out] Pointer to a DWORD specifying the length of the buffer pointed to by pstrNameBuf. The pdwBufLen parameter value will be modified to the buffer length needed to hold the object's name even if pstrNameBuf is NULL. In either case, the function will return DXFILEERR_BADVALUE if the original value of pdwBufLen is not as large as or larger than the length needed to hold the object's name.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

Applies To

This method applies to the following interfaces, which inherit from IDirectXFileObject.

  • IDirectXFileBinary
  • IDirectXFileData

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileSaveObject

Applications use the methods of the IDirectXFileSaveObject interface to create data objects and to save templates and data objects. Note that templates are not required in every file. For example, you could put all templates into a single Microsoft® DirectX® file rather than duplicating them in every DirectX file.

The IDirectXFileSaveObject interface is obtained by calling the IDirectXFile::CreateSaveObject method.

The methods of the IDirectXFileSaveObject interface can be organized into the following group.

Creation | CreateDataObject
Saving | SaveData
 | SaveTemplates

The IDirectXFileSaveObject interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The globally unique identifier (GUID) for the IDirectXFileSaveObject interface is IID_IDirectXFileSaveObject.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileSaveObject::CreateDataObject

Creates a data object.

HRESULT CreateDataObject(
  REFGUID rguidTemplate,
  LPCSTR szName,
  const GUID* pguid,
  DWORD cbSize,
  LPVOID pvData,
  LPDIRECTXFILEDATA* ppDataObj
);

Parameters

rguidTemplate
[in] Globally unique identifier (GUID) representing the data object's template.
szName
[in] Pointer to the name of the data object. Specify NULL if the object does not have a name.
pguid
[in] Pointer to a GUID representing the data object. Specify NULL if the object does not have a GUID.
cbSize
[in] Size of the data object, in bytes.
pvData
[in] Pointer to a buffer containing all required member's data.
ppDataObj
[out, retval] Address of a pointer to an IDirectXFileData interface, representing the created file data object.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

Remarks

If a data reference object will reference the data object, either the szName or pguid parameter must be non-NULL.

Save any templates by using the IDirectXFileSaveObject::SaveTemplates method before saving the data created by this method. Save the created data by using the IDirectXFileSaveObject::SaveData method.

If you need to save optional data, use the IDirectXFileData::AddDataObject method after using this method and before using SaveData. If the object has child objects, add them before calling SaveData.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.

See Also

IDirectXFileData::AddDataObject, IDirectXFileSaveObject::SaveData, IDirectXFileSaveObject::SaveTemplates


IDirectXFileSaveObject::SaveData

Saves a data object and its children to a Microsoft® DirectX® file.

HRESULT SaveData(
  LPDIRECTXFILEDATA pDataObj
);

Parameters

pDataObj
[in] Pointer to an IDirectXFileData interface, representing the file data object to save.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be one of the following values.

DXFILEERR_BADARRAYSIZE
DXFILEERR_BADVALUE

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.


IDirectXFileSaveObject::SaveTemplates

Saves templates to a Microsoft® DirectX® file.

HRESULT SaveTemplates(
  DWORD cTemplates,
  const GUID** ppguidTemplates
);

Parameters

cTemplates
[in] Total number of templates to save.
ppguidTemplates
[in] Address of a pointer to an array of the globally unique identifiers (GUIDs) for all templates to save.

Return Values

If the method succeeds, the return value is DXFILE_OK.

If the method fails, the return value can be DXFILEERR_BADVALUE.

Remarks

The following code fragment provides an example call to SaveTemplates and example contents for the array to which ppguidTemplates points.

IDirectXFileSaveObject * pDXFileSaveObject;

const GUID *aIds[] = {
    &DXFILEOBJ_SimpleData,
    &DXFILEOBJ_ArrayData,
    &DXFILEOBJ_RestrictedData};

hr = pDXFileSaveObject->SaveTemplates(3, aIds);

After using this method to save the templates, use the IDirectXFileSaveObject::CreateDataObject method to create a data object.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.

See Also

IDirectXFileSaveObject::CreateDataObject


Functions

This section contains reference information for the functions that you need to implement when you work with Microsoft® DirectX® files. The following function is implemented.

  • DirectXFileCreate


DirectXFileCreate

Creates an instance of a DirectXFile object.

STDAPI DirectXFileCreate(
  LPDIRECTXFILE* lplpDirectXFile
);

Parameters

lplpDirectXFile
Address of a pointer to an IDirectXFile interface, representing the created DirectXFile object.

Return Values

If the function succeeds, the return value is DXFILE_OK.

If the function fails, the return value can be one of the following values.

DXFILEERR_BADALLOC
DXFILEERR_BADVALUE

Remarks

After using this function, use IDirectXFile::RegisterTemplates to register templates, IDirectXFile::CreateEnumObject to create an enumerator object, or IDirectXFile::CreateSaveObject to create a save object.

Requirements

Header: Declared in Dxfile.h.
Import Library: Use D3dxof.lib.

See Also

IDirectXFile::CreateEnumObject, IDirectXFile::CreateSaveObject, IDirectXFile::RegisterTemplates


Structures

This section contains information about the structures used with Microsoft® DirectX® files.

  • DXFILELOADMEMORY
  • DXFILELOADRESOURCE


DXFILELOADMEMORY

Identifies memory data.

typedef struct _DXFILELOADMEMORY {
    LPVOID lpMemory;
    DWORD dSize;
} DXFILELOADMEMORY, *LPDXFILELOADMEMORY;

Members

lpMemory
Pointer to a block of memory to be loaded.
dSize
Size of the block of memory to be loaded, in bytes.

Remarks

This structure identifies a resource to be loaded when an application uses the IDirectXFile::CreateEnumObject method and specifies DXFILELOAD_FROMMEMORY.

Requirements

Header: Declared in Dxfile.h.

See Also

IDirectXFile::CreateEnumObject


DXFILELOADRESOURCE

Identifies resource data.

typedef struct _DXFILELOADRESOURCE {
    HMODULE hModule;
    LPCTSTR lpName;
    LPCTSTR lpType;
} DXFILELOADRESOURCE, *LPDXFILELOADRESOURCE;

Members

hModule
Handle of the module containing the resource to be loaded. If this member is NULL, the resource must be attached to the executable file that will use it.
lpName
Pointer to a string specifying the name of the resource to be loaded. For example, if the resource is a mesh, this member should specify the name of the mesh file.
lpType
Pointer to a string specifying the user-defined type identifying the resource.

Remarks

This structure identifies a resource to be loaded when an application uses the IDirectXFile::CreateEnumObject method and specifies DXFILELOAD_FROMRESOURCE.

Requirements

Header: Declared in Dxfile.h.

See Also

IDirectXFile::CreateEnumObject


Return Values

The methods used to work with Microsoft® DirectX® (.x) files can return the following values in addition to the standard COM return values.

DXFILE_OK
Command completed successfully.
DXFILEERR_BADALLOC
Memory allocation failed.
DXFILEERR_BADARRAYSIZE
Array size is invalid.
DXFILEERR_BADCACHEFILE
The cache file containing the .x file date is invalid. A cache file contains data retrieved from the network, cached on the hard disk, and retrieved in subsequent requests.
DXFILEERR_BADDATAREFERENCE
Data reference is invalid.
DXFILEERR_BADFILE
File is invalid.
DXFILEERR_BADFILECOMPRESSIONTYPE
File compression type is invalid.
DXFILEERR_BADFILEFLOATSIZE
Floating-point size is invalid.
DXFILEERR_BADFILETYPE
File is not a DirectX (.x) file.
DXFILEERR_BADFILEVERSION
File version is not valid.
DXFILEERR_BADINTRINSICS
Intrinsics are invalid.
DXFILEERR_BADOBJECT
Object is invalid.
DXFILEERR_BADRESOURCE
Resource is invalid.
DXFILEERR_BADTYPE
Object type is invalid.
DXFILEERR_BADVALUE
Parameter is invalid.
DXFILEERR_FILENOTFOUND
File could not be found.
DXFILEERR_INTERNALERROR
Internal error occurred.
DXFILEERR_NOINTERNET
Internet connection not found.
DXFILEERR_NOMOREDATA
No further data is available.
DXFILEERR_NOMOREOBJECTS
All objects have been enumerated.
DXFILEERR_NOMORESTREAMHANDLES
No stream handles are available.
DXFILEERR_NOTDONEYET
Operation has not completed.
DXFILEERR_NOTFOUND
Object could not be found.
DXFILEERR_PARSEERROR
File could not be parsed.
DXFILEERR_RESOURCENOTFOUND
Resource could not be found.
DXFILEERR_NOTEMPLATE
No template available.
DXFILEERR_URLNOTFOUND
URL could not be found.


X File Format Reference

This section contains reference information for the Microsoft® DirectX® (.x) file format.

  • X File Templates
  • Binary Format


X File Templates

This section lists and details the following .x file templates.

  • Header
  • Vector
  • Coords2d
  • Quaternion
  • Matrix4x4
  • ColorRGBA
  • ColorRGB
  • IndexedColor
  • Boolean
  • Boolean2d
  • Material
  • TextureFilename
  • MeshFace
  • MeshFaceWraps
  • MeshTextureCoords
  • MeshNormals
  • MeshVertexColors
  • MeshMaterialList
  • Mesh
  • FrameTransformMatrix
  • Frame
  • FloatKeys
  • TimedFloatKeys
  • AnimationKey
  • AnimationOptions
  • Animation
  • AnimationSet
  • Patch
  • PatchMesh
  • VertexDuplicationIndices
  • XSkinMeshHeader
  • SkinWeights


Header

Defines the application-specific header.

UUID

<3D82AB43-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
major | WORD |  | None
minor | WORD |  |
flags | DWORD |  |


Vector

Defines a vector.

UUID

<3D82AB5E-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
x | FLOAT |  | None
y | FLOAT |  |
z | FLOAT |  |


Coords2d

A two dimensional vector used to define a mesh's texture coordinates.

UUID

<F6F23F44-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
u | FLOAT |  | None
v | FLOAT |  |


Quaternion

Currently unused.

UUID

<10DD46A3-775B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
s | FLOAT |  | None
v | Vector |  |


Matrix4x4

Defines a 4×4 matrix. This is used as a frame transformation matrix.

UUID

<F6F23F45-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
matrix | array FLOAT | 16 | None


ColorRGBA

Defines a color object with an alpha component. This is used for the face color in the material template definition.

UUID

<35FF44E0-6C7C-11cf-8F52-0040333594A3>

Member name | Type | Optional array Size | Optional data objects
red | FLOAT |  | None
green | FLOAT |  |
blue | FLOAT |  |
alpha | FLOAT |  |


ColorRGB

Defines the basic RGB color object.

UUID

<D3E16E81-7835-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
red | FLOAT |  | None
green | FLOAT |  |
blue | FLOAT |  |


IndexedColor

Consists of an index parameter and an RGBA color and is used for defining mesh vertex colors. The index defines the vertex to which the color is applied.

UUID

<1630B820-7842-11cf-8F52-0040333594A3>

Member name | Type | Optional array size
index | DWORD |
indexColor | ColorRGBA |


Boolean

Defines a simple Boolean type. This template should be set to 0 or 1.

UUID

<4885AE61-78E8-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
truefalse | DWORD |  | None


Boolean2d

Defines a set of two Boolean values used in the MeshFaceWraps template to define the texture topology of an individual face.

UUID

<4885AE63-78E8-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
u | Boolean |  | None
v | Boolean |  |


Material

Defines a basic material color that can be applied to either a complete mesh or a mesh's individual faces. The power is the specular exponent of the material. Note that the ambient color requires an alpha component.

TextureFilename is an optional data object. If this object is not present, the face is untextured.

UUID

<3D82AB4D-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
faceColor | ColorRGBA |  | Any
power | FLOAT |  |
specularColor | ColorRGB |  |
emissiveColor | ColorRGB |  |


TextureFilename

Enables you to specify the file name of a texture to apply to a mesh or a face. This template should appear within a material object.

UUID

<A42790E1-7810-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
filename | STRING |  | None


MeshFace

Used by the Mesh template to define a mesh's faces. Each element of the nFaceVertexIndices array references a mesh vertex used to build the face.

UUID

<3D82AB5F-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
nFaceVertexIndices | DWORD |  | None
faceVertexIndices | array DWORD | nFaceVertexIndicies |


MeshFaceWraps

Used to define the texture topology of each face in a wrap. The value of the nFaceWrapValues member should be equal to the number of faces in a mesh.

UUID

<4885AE62-78E8-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nFaceWrapValues | DWORD |  | None
faceWrapValues | Boolean2d |  |


MeshTextureCoords

Defines a mesh's texture coordinates.

UUID

<F6F23F40-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nTextureCoords | DWORD |  | None
textureCoords | array Coords2d | nTextureCoords |


MeshNormals

Defines normals for a mesh. The first array of vectors is the normal vectors themselves, and the second array is an array of indexes specifying which normals should be applied to a given face. The value of the nFaceNormals member should be equal to the number of faces in a mesh.

UUID

<F6F23F43-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nNormals | DWORD |  | None
normals | array Vector | nNormals |
nFaceNormals | DWORD |  |
faceNormals | array MeshFace | nFaceNormals |


MeshVertexColors

Specifies vertex colors for a mesh, instead of applying a material per face or per mesh.

UUID

<1630B821-7842-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nVertexColors | DWORD |  | None
vertexColors | array IndexedColor | nVertexColors |


MeshMaterialList

Used in a mesh object to specify which material applies to which faces. The nMaterials member specifies how many materials are present, and materials specify which material to apply.

UUID

<F6F23F42-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nMaterials | DWORD |  | Material
nFaceIndexes | DWORD |  |
FaceIndexes | array DWORD | nFaceIndexes |


Mesh

Defines a simple mesh. The first array is a list of vertices, and the second array defines the faces of the mesh by indexing into the vertex array.

UUID

<3D82AB44-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
nVertices | DWORD |  | Any
vertices | array Vector | nVertices |
nFaces | DWORD |  |
faces | array MeshFace | nFaces |

Optional Data Elements

The following optional data elements can be used.

Data element | Description
MeshFaceWraps | If this is not present, wrapping for both u and v defaults to false.
MeshTextureCoords | If this is not present, there are no texture coordinates.
MeshNormals | If this is not present, normals are generated using the GenerateNormals method of the API.
MeshVertexColors | If this is not present, the colors default to white.
MeshMaterialList | If this is not present, the material defaults to white.


FrameTransformMatrix

Defines a local transform for a frame (and all its child objects).

UUID

<F6F23F41-7686-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
frameMatrix | Matrix4x4 |  | None


Frame

Defines a frame. Currently, the frame can contain objects of the type Mesh and a FrameTransformMatrix.

UUID

<3D82AB46-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
None |  |  | Any

Optional Data Elements

The following optional elements can be used.

Data element | Description
FrameTransformMatrix | If this element is not present, no local transform is applied to the frame.
Mesh | Any number of mesh objects that become children of the frame. These objects can be specified inline or by reference.


FloatKeys

Defines an array of floating-point numbers (floats) and the number of floats in that array. This is used for defining sets of animation keys.

UUID

<10DD46A9-775B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
nValues | DWORD |  | None
values | array FLOAT | nValues |


TimedFloatKeys

Defines a set of floats and a positive time used in animations.

UUID

<F406B180-7B3B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
time | DWORD |  | None
tfkeys | FloatKeys |  |


AnimationKey

Defines a set of animation keys. The keyType member specifies whether the keys are rotation, scale position, or matrix keys (using the integers 0, 1, 2, or 3 respectively). A matrix key is useful for sets of animation data that need to be represented as transformation matrices.

UUID

<10DD46A8-775B-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
keyType | DWORD |  | None
nKeys | DWORD |  |
keys | array TimedFloatKeys | nKeys |


AnimationOptions

Enables you to set the animation options. The openclosed member can be either 0 for a closed or 1 for an open animation. The positionquality member is used to set the position quality for any position keys specified and can either be 0 for spline positions or 1 for linear positions. By default, an animation is closed.

UUID

<E2BF56C0-840F-11cf-8F52-0040333594A3>

Member name | Type | Optional array size | Optional data objects
openclosed | DWORD |  | None
positionquality | DWORD |  |


Animation

Contains animations referencing a previous frame. It should contain one reference to a frame and at least one set of AnimationKey templates. It also can contain an AnimationOptions data object.

UUID

<3D82AB4F-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
None |  |  | Any

Optional Data Elements

The following optional data elements are used.

Data element | Description
AnimationKey | All animations require AnimationKeys.
AnimationOptions | If this element is not present, an animation is closed.


AnimationSet

Contains one or more Animation objects. Each animation within an animation set has the same time at any given point. Increasing the animation set's time increases the time for all the animations it contains.

UUID

<3D82AB50-62DA-11cf-AB39-0020AF71E433>

Member name | Type | Optional array size | Optional data objects
None |  |  | Animation


Patch

Defines a bézier control patch. The array defines the control points for the patch.

UUID

<A3EB5D44-FC22-429D-9AFB-3221CB9719A6>

Member name | Type | Optional array size | Optional data objects
nControlIndices | DWORD |  | None
controlIndices | array DWORD | nControlIndices |

The type of patch is defined by the number of control points, as shown in the following table.

Number of control points | Type
10 | Cubic Bézier Triangular Patch
15 | Quartic Bézier Triangular Patch
16 | Cubic Bézier Quad (Rectangular) Patch

The order of the control points are given in a spiral pattern, as shown in the following diagrams for triangular and rectangular patches.

Triangular patches used the following pattern.

Rectangular patches use the following pattern.


PatchMesh

Defines a mesh defined by bézier patches. The first array is a list of vertices, and the second array defines the patches for the mesh by indexing into the vertex array.

UUID

<D02C95CC-EDBA-4305-9B5D-1820D7704BBF>

Member name | Type | Optional array size | Optional data objects
nVertices | DWORD |  | None
vertices | array Vector | nVertices |
nPatches | DWORD |  |
patches | array Patch | nPatches |

The patches use the vertices in the array of vertices as the control points for each patch.


VertexDuplicationIndices

This template is instantiated on a per-mesh basis, holding information about which vertices in the mesh are duplicates of each other. Duplicates result when a vertex sits on a smoothing group or material boundary. The purpose of this template is to allow the loader to determine which vertices exhibiting different peripheral parameters are actually the same vertexes in the model. Certain applications (mesh simplification for example) can make use of this information.

UUID

<B8D65549-D7C9-4995-89CF-53A9A8B031E3>

Member name | Type | Optional array size | Optional data objects
nIndices | DWORD |  | None
nOriginalVertices | DWORD |  |
indices | array DWORD | nIndices |

The number of vertices in the mesh before any duplication occurred is nOriginalVertices. The value indices[n] holds the vertex index that vertex[n] in the vertex array for the mesh would have had if no duplication had occurred. So any indices in this array that are the same indicate duplicate vertices.


XSkinMeshHeader

This template is instantiated on a per-mesh basis only in meshes that contain exported skinning information. The purpose of this template is to provide information about the nature of the skinning information that was exported.

UUID

<3CF169CE-FF7C-44ab-93C0-F78F62D172E2>

Member name | Type | Optional array size | Optional data objects
nMaxSkinWeightsPerVertex | WORD |  | None
nMaxSkinWeightsPerFace | WORD |  |
nBones | WORD |  |

The maximum number of transforms that affect a vertex in the mesh is nMaxSkinWeightsPerVertex. The maximum number of unique transforms that affect the three vertices of any face is nMaxSkinWeightsPerFace. The number of bones that affect vertices in this mesh is nBones.


SkinWeights

This template is instantiated on a per-mesh basis. Within a mesh, a sequence of n instances of this template will appear, where n is the number of bones (X file frames) that influence the vertices in the mesh. Each instance of the template basically defines the influence of a particular bone on the mesh. There is a list of vertex indices, and a corresponding list of weights.

UUID

<6F0D123B-BAD2-4167-A0D0-80224F25FABB>

Member name | Type | Optional array size | Optional data objects
transformNodeName | STRING |  | None
nWeights | DWORD |  |
vertexIndices | array DWORD | nWeights |
weights | array float | nWeights |
matrixOffset | Matrix4x4 |  |

The name of the bone whose influence is being defined is transformNodeName, and nWeights is the number of vertices affected by this bone. The vertices influenced by this bone are contained in vertexIndices, and the weights for each of the vertices influenced by this bone are contained in weights.

The matrix matrixOffset transforms the mesh vertices to the space of the bone. When concatenated to the bone's transform, this provides the world space coordinates of the mesh as affected by the bone.


Binary Format

This section details the binary version of the Microsoft® DirectX® (.x) file format as introduced with the release of DirectX 3.0. The information presented in this section should be read in conjunction with the X File Architecture section.

The binary format is a tokenized representation of the text format. Tokens can be stand-alone or accompanied by primitive data records. Stand-alone tokens give grammatical structure, and record-bearing tokens supply the necessary data.

Note that all data is stored in little-endian format. A valid binary data stream consists of a header followed by templates and/or data objects.

This section discusses the following components of the binary file format and provides an example template and binary data object.

  • Header
  • Tokens
  • Token Records
  • Templates
  • Data
  • Examples


Header

The following definitions should be used when directly reading and writing the binary header. Note that compressed data streams are not currently supported and are therefore not detailed here.

#define XOFFILE_FORMAT_MAGIC \
  ((long)'x' + ((long)'o' << 8) + ((long)'f' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_VERSION \
  ((long)'0' + ((long)'3' << 8) + ((long)'0' << 16) + ((long)'2' << 24))

#define XOFFILE_FORMAT_BINARY \
  ((long)'b' + ((long)'i' << 8) + ((long)'n' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_TEXT   \
  ((long)'t' + ((long)'x' << 8) + ((long)'t' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_COMPRESSED \
  ((long)'c' + ((long)'m' << 8) + ((long)'p' << 16) + ((long)' ' << 24))

#define XOFFILE_FORMAT_FLOAT_BITS_32 \
  ((long)'0' + ((long)'0' << 8) + ((long)'3' << 16) + ((long)'2' << 24))

#define XOFFILE_FORMAT_FLOAT_BITS_64 \
  ((long)'0' + ((long)'0' << 8) + ((long)'6' << 16) + ((long)'4' << 24))


Tokens

Tokens are written as little-endian WORDs. The following list of token values is divided into record-bearing and stand-alone tokens.

The record-bearing tokens are defined as follows.

#define TOKEN_NAME 1
#define TOKEN_STRING 2
#define TOKEN_INTEGER 3
#define TOKEN_GUID 5
#define TOKEN_INTEGER_LIST 6
#define TOKEN_FLOAT_LIST 7

The stand-alone tokens are defined as follows.

#define TOKEN_OBRACE 10
#define TOKEN_CBRACE 11
#define TOKEN_OPAREN 12
#define TOKEN_CPAREN 13
#define TOKEN_OBRACKET 14
#define TOKEN_CBRACKET 15
#define TOKEN_OANGLE 16
#define TOKEN_CANGLE 17
#define TOKEN_DOT 18
#define TOKEN_COMMA 19
#define TOKEN_SEMICOLON 20
#define TOKEN_TEMPLATE 31
#define TOKEN_WORD 40
#define TOKEN_DWORD 41
#define TOKEN_FLOAT 42
#define TOKEN_DOUBLE 43
#define TOKEN_CHAR 44
#define TOKEN_UCHAR 45
#define TOKEN_SWORD 46
#define TOKEN_SDWORD 47
#define TOKEN_VOID 48
#define TOKEN_LPSTR 49
#define TOKEN_UNICODE 50
#define TOKEN_CSTRING 51
#define TOKEN_ARRAY 52


Token Records

This section describes the format of the records for each of the record-bearing tokens. Information is divided into the following sections.

  • TOKEN_NAME
  • TOKEN_STRING
  • TOKEN_INTEGER
  • TOKEN_GUID
  • TOKEN_INTEGER_LIST
  • TOKEN_FLOAT_LIST


TOKEN_NAME

A variable-length record. The token is followed by a count value that specifies the number of bytes that follow in the name field. An ASCII name of length count completes the record.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_NAME
count | DWORD | 4 | Length of name field, in bytes
name | BYTE array | count | ASCII name


TOKEN_STRING

A variable-length record. The token is followed by a count value that specifies the number of bytes that follow in the string field. An ASCII string of length count continues the record, which is completed by a terminating token. The choice of terminator is determined by syntax issues discussed elsewhere.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_STRING
count | DWORD | 4 | Length of string field in bytes
string | BYTE array | count | ASCII string
terminator | DWORD | 4 | TOKEN_SEMICOLON or TOKEN_COMMA


TOKEN_INTEGER

A fixed length record. The token is followed by the integer value required.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_INTEGER
value | DWORD | 4 | Single integer


TOKEN_GUID

A fixed-length record. The token is followed by the four data fields as defined by the OSF DCE standard.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_GUID
data1 | DWORD | 4 | UUID data field 1
data2 | WORD | 2 | UUID data field 2
data3 | WORD | 2 | UUID data field 3
data4 | BYTE array | 8 | UUID data field 4


TOKEN_INTEGER_LIST

A variable-length record. The token is followed by a count value that specifies the number of integers that follow in the list field. For efficiency, consecutive integer lists should be compounded into a single list.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_INTEGER_LIST
count | DWORD | 4 | Number of integers in list field
list | DWORD | 4 × count | Integer list


TOKEN_FLOAT_LIST

A variable-length record. The token is followed by a count value that specifies the number of floats or doubles that follow in the list field. The size of the floating point value (float or double) is determined by the value of float size specified in the file header. For efficiency, consecutive TOKEN_FLOAT_LISTs should be compounded into a single list.

Field | Type | Size (bytes) | Contents
token | WORD | 2 | TOKEN_FLOAT_LIST
count | DWORD | 4 | Number of floats or doubles in list field
list | float/double array | 4 or 8 × count | Float or double list


Templates

A template has the following syntax definition.

template              : TOKEN_TEMPLATE name TOKEN_OBRACE
                            class_id
                            template_parts
                            TOKEN_CBRACE

template_parts        : template_members_part TOKEN_OBRACKET
                        template_option_info
                        TOKEN_CBRACKET
                      | template_members_list

template_members_part : /* Empty */
                      | template_members_list

template_option_info  : ellipsis
                      | template_option_list

template_members_list :    template_members
                      | template_members_list template_members

template_members      : primitive
                      | array
                      | template_reference

primitive             : primitive_type optional_name TOKEN_SEMICOLON

array                 : TOKEN_ARRAY array_data_type name dimension_list
                        TOKEN_SEMICOLON

template_reference    : name optional_name YT_SEMICOLON

primitive_type        : TOKEN_WORD
                      | TOKEN_DWORD
                      | TOKEN_FLOAT
                      | TOKEN_DOUBLE
                      | TOKEN_CHAR
                      | TOKEN_UCHAR
                      | TOKEN_SWORD
                      | TOKEN_SDWORD
                      | TOKEN_LPSTR
                      | TOKEN_UNICODE
                      | TOKEN_CSTRING

array_data_type       : primitive_type
                      | name

dimension_list        : dimension
                      | dimension_list dimension

dimension             : TOKEN_OBRACKET dimension_size TOKEN_CBRACKET

dimension_size        : TOKEN_INTEGER
                      | name

template_option_list  : template_option_part
                      | template_option_list template_option_part

template_option_part  : name optional_class_id

name                  : TOKEN_NAME

optional_name         : /* Empty */
                      | name

class_id              : TOKEN_GUID

optional_class_id     : /* Empty */
                      | class_id

ellipsis              : TOKEN_DOT TOKEN_DOT TOKEN_DOT


Data

A data object has the following syntax definition.

object                : identifier optional_name TOKEN_OBRACE
                            optional_class_id
                            data_parts_list
                            TOKEN_CBRACE
data_parts_list       : data_part
                      | data_parts_list data_part

data_part             : data_reference
                      | object
                      | number_list
                      | float_list
                      | string_list

number_list           : TOKEN_INTEGER_LIST

float_list            : TOKEN_FLOAT_LIST

string_list           : string_list_1 list_separator

string_list_1         : string
                      | string_list_1 list_separator string

list_separator        : comma
                      | semicolon

string                : TOKEN_STRING

identifier            : name
                      | primitive_type

data_reference        : TOKEN_OBRACE name optional_class_id TOKEN_CBRACE

Note that in number_list and float_list data in binary files, TOKEN_COMMA and TOKEN_SEMICOLON are not used. The comma and semicolon are used in string_list data. Also note that you can only use data_reference for optional data members.


Examples

Two example binary template definitions and an example of a binary data object follow. Note that data is stored in little-endian format, which is not shown in these examples.

The closed template RGB is identified by the UUID {55b6d780-37ec-11d0-ab39-0020af71e433} and has three members r, g, and b each of type float.

TOKEN_TEMPLATE, TOKEN_NAME, 3, 'R', 'G', 'B', TOKEN_OBRACE,
TOKEN_GUID, 55b6d780, 37ec, 11d0, ab, 39, 00, 20, af, 71, e4, 33,
TOKEN_FLOAT, TOKEN_NAME, 1, 'r', TOKEN_SEMICOLON,
TOKEN_FLOAT, TOKEN_NAME, 1, 'g', TOKEN_SEMICOLON,
TOKEN_FLOAT, TOKEN_NAME, 1, 'b', TOKEN_SEMICOLON,
TOKEN_CBRACE

The closed template Matrix4x4 is identified by the UUID {55b6d781-37ec-11d0-ab39-0020af71e433} and has one member—a two-dimensional array named matrix of type float.

TOKEN_TEMPLATE, TOKEN_NAME, 9, 'M', 'a', 't', 'r', 'i', 'x', '4', 'x', '4', TOKEN_OBRACE,
TOKEN_GUID, 55b6d781, 37ec, 11d0, ab, 39, 00, 20, af, 71, e4, 33,
TOKEN_ARRAY, TOKEN_FLOAT, TOKEN_NAME, 6, 'm', 'a', 't', 'r', 'i', 'x',
TOKEN_OBRACKET, TOKEN_INTEGER, 4, TOKEN_CBRACKET,
TOKEN_OBRACKET, TOKEN_INTEGER, 4, TOKEN_CBRACKET,
TOKEN_CBRACE

The binary data object that follows shows an instance of the RGB template defined earlier. The example object is named blue, and its three members r, g, and b have the values 0.0, 0.0 and 1.0, respectively. Note that data is stored in little-endian format, which is not shown in this example.

TOKEN_NAME, 3, 'R', 'G', 'B', TOKEN_NAME, 4, 'b', 'l', 'u', 'e', TOKEN_OBRACE,
TOKEN_FLOAT_LIST, 3, 0.0, 0.0, 1.0, TOKEN_CBRACE


DirectX Audio

This section provides information about using Microsoft® DirectX® to play and capture sounds in applications.

Like other components of DirectX, DirectX Audio can be used with C, C++, and Microsoft® Visual Basic®. This Help file is specific to C and C++. The sample code uses C++ syntax.

For an overview of the organization of the DirectX Audio Help, see Roadmap.


Roadmap

Information on DirectX Audio is presented in the following sections:

  • What's New in DirectX Audio. New features and functionality of this component in DirectX 8.0. If you've used Microsoft® DirectSound® or Microsoft® DirectMusic® before, read this section first, because much has changed since DirectX 7.0.
  • Introduction to DirectX Audio. An overview of what DirectX Audio is and what it can do for your application, together with a first look at some important objects and the steps involved in playing audio.
  • Understanding DirectX Audio. A deeper look at the underlying mechanisms. This section won't teach you how to implement audio playback or capture in your application, but it will help you understand the application programming interface (API).
  • Using DirectX Audio. A guide to using the API. You'll probably want to familiarize yourself with the table of contents for this section, and then refer to parts of it as you need specific information. Use it in conjunction with the reference section.
  • Advanced Topics in DirectX Audio. Information of interest mostly for developing specialized applications or applications that need highly optimized performance.
  • Programming Tips and Tools. Miscellaneous information about compiling and debugging DirectX Audio applications.
  • DirectX Audio C++ Tutorials. Step-by-step implementation of basic functionality. If you're the kind of person who learns best by doing, this is a good place to start.
  • DirectX Audio C++ Samples. A guide to the sample applications in the SDK, to point you to the sample code you need. As well as showing how to implement basic functionality, each sample demonstrates one or more particular features of DirectX Audio.
  • DirectMusic C/C++ Reference. Detailed information about all the API elements declared in the DirectMusic header files. This section includes information about the file format used by DirectMusic and DirectMusic Producer.
  • DirectSound C/C++ Reference. Detailed information about all the API elements declared in Dsound.h.

DirectMusic Producer

DirectMusic Producer is a powerful authoring application included with the DirectX SDK. It enables composers to create dynamic musical elements that can be incorporated in an application.

If your focus is more on sound design than on application development, you might want to start with DirectMusic Producer Help, which is installed with that application.

If you're an application developer and just want an overview of the material you'll be working with, see Compositional Music Elements.

Audio Scripting

DirectX Audio scripting is used by composers and sound designers to have more direct control over the soundtrack in an application. Documentation for the script API is included in the DirectMusic Producer Help.

For an overview, see Audio Scripts. To learn how to incorporate scripts in an application, see Using Audio Scripts.


What's New in DirectX Audio?

Microsoft DirectX 8.0 (C++)

What's New in DirectX Audio

The audio components of DirectX have undergone a major revision. DirectMusic and DirectSound are now a more unified API for playing sounds of all kinds, and many new capabilities have been added.

The following list describes some of the new features:

Integration of waves and message-based sounds in a single playback mechanism
Wave files and resources can now be loaded by the DirectMusic loader and played by the DirectMusic performance. The application no longer needs to parse the wave and copy or stream it to a DirectSound buffer. The timing of wave playback is based on the DirectMusic master clock, and waves can be synchronized to musical events and processed by tools just like any other segment.

The DirectSound API continues to be supported, and you can still play waves directly through DirectSound buffers. DirectSound continues to be the API for wave capture and full duplex.

More flexible and powerful audiopath model
In previous versions of DirectMusic, performance channels were mapped to ports, and each port sent its output to a single DirectSound buffer. Under the new model, channels in a segment are mapped to audiopaths that control the data flow from the performance to the final output. Output from the synthesizer can be sent to multiple playback buffers, each with its own 3-D positioning and effects. Audiopaths can be created dynamically by the application or authored into segments.
Individual control over segment states
Each playing instance of a segment can have its own audiopath, so parameters such as volume, pan, and pitch bend can be modified for each segment state individually.
DLS2 Synthesis
The DirectMusic synthesizer is now based on the Downloadable Sounds (DLS) Level 2 standard, providing higher-quality sound synthesis. New features of the DLS2 synthesizer include six-stage envelopes, layering of voices, release waveforms, and additional low-frequency oscillators (LFOs). Each voice has an optional low-pass resonant filter.
Special effects
DirectX Media Objects can be attached to sound buffers to add effects. Standard effects such as musical reverb, I3DL2 (Interactive 3-D Audio Level 2) environmental reverb, distortion, and echo are provided by DirectX Audio, and third-party effects can be added.
Greater control over cueing
A composer can set points in a segment that specify where the segment can begin playback, so that the segment can maintain its relationship to the time signature. Primary segments can contain arbitrary points where other segments can be cued, allowing greater control than cueing to the nearest measure, beat, or grid. A new segment cue flag, DMUS_SEGF_SEGMENTEND, causes the segment to play when the current primary segment finishes playing.
Notification of impending silence
The performance notification event has a new notification type, DMUS_NOTIFICATION_MUSICALMOSTEND, which indicates that the last primary segment in the queue is about to end. This notification gives the application a chance to schedule a new segment.
Enhanced MIDI controller support
Curve messages now support RPN (registered parameter number) and NRPN (nonregistered parameter number) controller changes.
Infinite repetition of segments
The new DMUS_SEG_REPEAT_INFINITE flag allows a segment to play for an indefinite time.
Simplified downloading and unloading of bands
Bands can be downloaded and unloaded with a simple method call on the segment object.
Dynamic track data generation
New track configuration and play flags allow tracks to be recomposed each time the segment is played or looped. For example, a chordmap track can be configured to establish a new chord progression each time the segment plays.
Audio scripting
Music composers and sound designers can gain greater control over the performance by using scripts. The application does not handle the details of playback but instead calls into the script. For example, a game event might trigger a script function. The script author can easily modify the soundtrack's response to the game event by modifying the function.
Improved run-time control over tracks
Applications can set individual track configurations to disable playback and parameter control. Tracks can be configured to operate in clock time rather than music time. Tracks in self-controlling segments can be configured to override parameter tracks in controlling or primary segments.
Container object
All components of a DirectMusic Producer project can be kept in a single file, making it easier to find and load all objects. Containers can also be embedded in segments, so that everything necessary to play a segment is kept within the segment.
Lyrics track
Time-stamped text is sent to the performance by a segment containing a lyrics track.
Improved cache management
Applications can more easily release unused objects that were loaded by other objects.


Introduction to DirectX Audio

  • The Power of DirectX Audio
  • Getting Started with DirectX Audio


The Power of DirectX Audio

DirectX Audio does much more than simply play sounds. It provides a complete system for implementing a dynamic soundtrack that takes advantage of hardware acceleration, Downloadable Sounds (DLS), DirectX Media Objects (DMOs), and advanced 3-D positioning effects.

By using the DirectMusic and DirectSound interfaces in your application, you can do the following:

  • Load and play sounds from files or resources in MIDI, wave, or DirectMusic Producer run time format.
  • Play from multiple sources simultaneously.
  • Schedule the timing of musical events with high precision.
  • Send tempo changes, patch changes, and other MIDI events programmatically.
  • Use Downloadable Sounds. By using the DLS synthesizer, an application can be sure that message-based music sounds the same on all computers. An application can also play an unlimited variety of instruments and even produce unique sounds for individual notes and velocities.
  • Locate sounds in a 3-D environment.
  • Easily apply pitch changes, reverb, and other effects to sounds.
  • Use more than 16 MIDI channels. DirectX Audio breaks through the 16-channel limitation and makes it possible for any number of voices to be played simultaneously, up to the limits of the synthesizer.
  • Play segments on different audiopaths, so that effects or spatialization can be applied individually to each sound.
  • Capture MIDI data or stream ("thru") it from one port to another.
  • Capture wave sounds from a microphone or other input.

If you use source files from DirectMusic Producer or a similar application, you can do much more:

  • Control many more aspects of playback at run time, for example by choosing a different set of musical variations or altering the chord progression.
  • Play music that varies subtly each time it repeats.
  • Play waves with variations.
  • Map performance channels to audiopaths, so that different parts within the same segment can have different effects.
  • Compose wholly new pieces of music at run time, not generated algorithmically but based on components supplied by a human composer.
  • Dynamically compose transitions between existing pieces of music.
  • Cue transitions, motifs, and sound effects to occur at specified rhythmic points in the performance.

These capabilities are the ones most often used by mainstream applications. DirectX Audio is designed to be used easily for the basic tasks, but it also allows low-level access to those who need it. It is also extensible. Specialized applications can implement new objects at virtually every stage on the audiopath, such as the following:

  • Loaders to parse data in new or proprietary formats.
  • Tracks containing any kind of sequenced data.
  • Tools to process messages—for example, to intercept notes and apply transpositions, or to display lyrics embedded in a segment file.
  • Custom sequencer.
  • Custom synthesizer.
  • Effects filters.

Also part of DirectX Audio is DirectMusic Producer, an application that enables composers to create DLS collections, chordmaps, styles, and segments—the pieces that let you take full advantage of the power of DirectMusic. DirectMusic Producer also makes it possible to create playable segments that contain multiple time-stamped waves. These waves can be in compressed or uncompressed format and can be either streamed at run time or wholly contained in memory.

As an application developer, you might never use DirectMusic Producer yourself, but it is a good idea to have a broad understanding of what it does so that you can work effectively with your sound design team. For an introduction from the application designer's perspective, see Compositional Music Elements. For more detail, see the DirectMusic Producer documentation.

DirectX Audio delivers full functionality on Microsoft® Windows® 95, Microsoft® Windows® 98, and Microsoft® Windows® 2000. However, support for hardware synthesizers is available only on Windows 2000 and Windows 98 Second Edition.


Getting Started with DirectX Audio

Creating your first DirectX Audio application does not require a lot of setup. Presumably you have already installed the current version of DirectX and have the paths to the header files set up in your development environment. You must also be able to link to the DirectX library files in the \lib folder. The necessary DLLs and the default DLS collection (used by the software synthesizer) were placed in your system directory as part of the SDK installation.

Apart from that, all you need are a sound card, speakers or headphones, and some sounds. Any of the following will do:

  • MIDI (.mid) files.
  • Wave (.wav) files.
  • Segment (.sgt) files from DirectMusic Producer. Sample files are installed along with that application, and others are included with the DirectX sample applications.

For now, you can ignore the other kinds of files you'll find with DirectMusic Producer. Chordmaps, styles, bands, and DLS files are building blocks for playable segments but aren't playable themselves. Segments can also be obtained from container files, but it requires a bit of extra work to extract them.

More information on getting started is included in the following topics:

  • Basic Concepts of DirectX Audio
  • Basic Steps in Playing Sounds
  • Building DirectX Audio Projects


Basic Concepts of DirectX Audio

This section is an introduction to some of the key concepts of DirectX Audio and the objects that implement them.

DirectX is based on the Component Object Model (COM), so all functionality is performed by objects. In addition, source data is encapsulated in objects.

The objects discussed in this section are exposed in every DirectX Audio application, other than those using only DirectSound. Many other objects are at work behind the scenes and can be accessed by more advanced applications, but they are not discussed here.

The following topics are discussed:

  • Loader
  • Segments and Segment States
  • Performance
  • Messages
  • Performance Channels
  • DLS Synthesizer
  • Instruments and Downloading
  • Audiopaths and Buffers


Loader

The loader (IDirectMusicLoader8) is an object that gets other objects. It is generally one of the first objects created in a DirectX Audio application. The loader is used to load all audio content, including DirectMusic segment files, DLS collections, MIDI files, and both mono and stereo wave files. It can also load data stored in resources.

Any object that encapsulates data from a file or resource supports the IDirectMusicObject8 interface. The loader gets this interface and then uses it to initiate the process of streaming the data into an object in your application. Data objects parse themselves through their implementations of IPersistStream, and the entire loading process is carried out automatically. All you need to do is pass a description of the object to the loader, along with a request for the desired interface, such as IDirectMusicSegment8.


Segments and Segment States

Segments are objects encapsulating sequenced sound data. The data might be a MIDI sequence, a wave, a collection of information originating in a segment file from DirectMusic Producer, or a piece of music composed at run time from different components. In general, a segment is a piece of music or other sound that is played as a unit.

A segment can be played as a primary segment or secondary segment. Only one primary segment can be played at a time. Secondary segments are typically short musical motifs or sound effects played over the primary segment.

Segments originating as MIDI or wave files sound the same each time they are played, unless the application performs some special processing on them. A segment authored in DirectMusic Producer, on the other hand, can contain different musical patterns and other information that allows variation each time the segment is played.

Segments can combine different kinds of data such as waves, patterns, chord changes, band changes, and tempo changes. Each type of data is encapsulated in a track object. Applications written in C++ can access individual tracks, but most do not need to. Segments can also contain information about the audiopath on which they should be played, including special effects.

DirectMusic Producer segments can also contain references to other loadable musical components. For example, it is possible to obtain a band object from a segment authored with that band.

Each time a segment is played, a segment state object is created. The application can use this object to get information about the state of playback and the audiopath for that instance of the playing segment.


Performance

The performance object manages the flow of data from the source to the synthesizer. Typically an application has only a single performance.

The performance handles timing, the mapping of data channels to audiopaths, the routing of messages, tool management, notifications, and other important tasks.


Messages

Audio data flows through the performance in the form of messages. Performance messages are similar to MIDI messages but contain more information and a greater variety of information. A message could contain information about a musical note, a wave, or a controller change. It might even contain text for a display of lyrics.

Most applications don't deal directly with messages, which are generated by tracks when a segment is playing. However, it is possible for an application to insert messages into the performance or to intercept messages by implementing tools.

Messages are also used for notifications. Applications can request that an event be signaled whenever certain points in the performance are reached—for example, on every beat of the music. Information about the event is contained in a performance message.


Performance Channels

Every playing sound consists of one or more parts. A part might be a MIDI channel, a part in a DirectMusic Producer segment, or a wave. Often a part corresponds to a single musical instrument.

A performance channel is the route between a part and an audiopath. Every message that contains information about a part also specifies the part's performance channel, so that it can be routed correctly.

Performance channels are similar to MIDI channels, but whereas traditional MIDI playback is limited to 16 channels, the number of performance channels is virtually unlimited.


DLS Synthesizer

Data that is not already in the form of a wave—a MIDI note, for example—has to be converted to a wave form before it can be played by the sound card. This conversion is done by a synthesizer.

Although DirectX Audio supports basic MIDI synthesis on some operating systems, most applications use a synthesizer that implements the Downloadable Sounds (DLS) Level 2 standard. In the absence of a suitable hardware synthesizer, the Microsoft software synthesizer is used.

The synthesizer produces sounds based on wave samples and is capable of producing highly sophisticated musical timbres as well as any other kind of sound.

Note The DLS Level 1 synthesizer used with the DirectX 7 interfaces contains reverbation capabilities, which are on by default. The Waves TrueVerb reverberation technology is licensed to Microsoft Corporation as the SimpleVerb implementation.

The DLS Level 2 synthesizer used with the DirectX 8.0 interfaces does not contain built-in reverberation capabilities. Reverberation is instead implemented as a DMO. Waves MaxxVerb is licenced to Microsoft Corporation for this purpose.


Instruments and Downloading

To play an instrument, the synthesizer needs information about how the instrument should sound. This information, consisting of wave samples and articulation data, is stored in DLS collections. Instrument data is made available to the synthesizer by being downloaded.

Typically a range of notes for one instrument is based on one sample that is appropriately pitched for each note. However, DLS Level 2 enables each note to be based on a different sample or combination of samples. Even the velocity of a note can trigger the use of different samples for that instrument.

By default, the Microsoft software synthesizer takes its DLS data from the Roland GM/GS collection. The default collection contains DLS data for the 128 instruments defined by the General MIDI standard. Custom collections can include instruments of any kind. The wave samples for an instrument do not have to be based on a musical instrument but can be any recorded sound such as a sound effect, a fragment of speech, or even a fully formed measure of music.

Most applications do not need to access collections directly, as the necessary data is either contained in the default collection or referenced by a band object associated with a segment. A band is a set of instruments and settings mapped to performance channels. Several techniques are available for ensuring that band instruments are downloaded before use.

Note The Roland GM/GS Sound Set cannot be modified. See the Copyright Warning for the legal restrictions.

Wave files and resources also have to be downloaded to the synthesizer before they can be played.


Audiopaths and Buffers

Each DirectMusic segment plays on an audiopath that controls the flow of sounds from the performance to the synthesizer, then through DirectSound buffers where effects can be applied, and finally into the primary buffer, where the final output is mixed.

Note The buffers referred to here are used for streaming and processing PCM data after it has left the synthesizer, and support the IDirectSoundBuffer8 interface. Another kind of buffer, represented by the IDirectMusicBuffer8 interface, is used for sequencing message data to the synthesizer. Most applications do not need access to the second kind of buffer, which is managed by the DirectMusic performance.

Applications can create standard audiopaths and then play segments on them. For example, an application could create one audiopath for playing MIDI files to a buffer with musical reverb and another for playing wave files to a buffer with 3-D control.

More sophisticated audiopath configurations can be authored into a segment in DirectMusic Producer. For example, a nonstandard configuration might direct parts in a segment through different DirectSound buffers in order to apply different effects to them.

An audiopath can be seen as a chain of objects through which data is streamed. An application can gain access to any of these objects. For example, you might retrieve a buffer object to set 3-D properties of a sound source, or an effect DMO to change the parameters of the effect.


Basic Steps in Playing Sounds

If you understand the fundamentals outlined in Basic Concepts of DirectX Audio, you're ready to implement a rudimentary soundtrack in an application. After learning these few simple steps, you can go on to explore other parts of the API that will give you as much control over the soundtrack as you need.

This topic gives an overview of the necessary steps, without getting into the coding details. For sample code, see Tutorial 1: Playing Audio Files.

To produce a sound, an application needs to do the following:

1. Initialize COM

There are no helper functions for creating DirectMusic objects, so you need to call CoInitializeEx to initialize COM.

2. Create and initialize the performance

Most applications have a single performance object. You create it by calling CoCreateInstance and obtaining the IDirectMusicPerformance8 interface. Then call IDirectMusicPerformance8::InitAudio. This method can set up a default audiopath.

3. Create the loader

Using CoCreateInstance, obtain an IDirectMusicLoader8 interface. You need to do this only once, and you should keep the same loader object for the life of the application.

4. Load a segment

Call IDirectMusicLoader8::SetSearchDirectory so the loader can find the data files. Then call IDirectMusicLoader8::GetObject to load a segment from a file or resource and obtain its IDirectMusicSegment8 interface.

5. Download the band

Download DLS data to the synthesizer so that instruments can play. Wave files also must be downloaded. The simplest way to do this is by calling IDirectMusicSegment8::Download.

6. Play the segment

Pass the segment pointer to IDirectMusicPerformance8::PlaySegmentEx.

For a more detailed look at this process, see the following topics:

  • Loading Audio Data
  • Playing Sounds

Note It is also possible to play wave sounds using only the DirectSound interfaces. However, doing so requires you to parse the data source yourself and handle the streaming of data to buffers. For more information, see Wave Playback in DirectSound.


Building DirectX Audio Projects

Projects need to include the Dmusici.h header file, which contains declarations for the DirectMusic performance layer. Including this file will bring in three other essential headers:

  • Dmusicc.h: declarations for the core layer of DirectMusic
  • Dmerr.h: DirectMusic return values
  • Dsound.h: the DirectSound API

Dmusicf.h contains file structures and defines, and is needed only for applications such as music-authoring tools that work directly with files and don't rely solely on the loaders built into DirectMusic.

Dmksctrl.h contains declarations for the IKsControl interface used for port property sets. You do not need this file if you have the Ksproxy.h and Ks.h files.

Dmplugin.h contains declarations for the IDirectMusicTool8 and IDirectMusicTrack8 interfaces, which are implemented by add-ons for advanced applications that need specialized message-processing tools and track types. Most applications do not use this part of the DirectMusic API.

If you are using the DirectSound API directly and want to be able to use helper functions such as DirectSoundCreate8, be sure to link to Dsound.lib and include the appropriate folder in the library search path.

You must also ensure that your application has access to the GUIDs used by DirectX Audio. For more information, see Compiling DirectX Samples and Other DirectX Applications.

DirectX Audio uses the multithreading capabilities of the Windows 32-bit operating system. Multithreading allows DirectX to generate, process, and synthesize music in the background while your application is accomplishing other tasks. You should develop your project with multithreading in mind. If nothing else, be sure to link with the multithreaded libraries.


Understanding DirectX Audio

This section describes the underlying workings of DirectX Audio without going into the details of the DirectMusic and DirectSound APIs. It is intended to give you a deeper understanding of concepts than that presented in Basic Concepts of DirectX Audio. For information on how to use the APIs, see Using DirectX Audio.

The following topics are covered:

  • DirectSound and DirectMusic
  • Overview of Audio Data Flow
  • Compositional Music Elements
  • How Music Varies During Playback
  • Music Values and MIDI Notes
  • Downloadable Sounds
  • Audio Scripts


DirectSound and DirectMusic

Previous versions of DirectX presented audio features as two discrete components: DirectSound and DirectMusic. DirectSound was for playing and capturing prerecorded digital samples (waves), and DirectMusic was for playing message-based data ranging from simple MIDI files to musical segments authored in DirectMusic Producer. Although DirectMusic has always been capable of playing nonmusical sound effects through the use of DLS, the emphasis in the past was on its ability to play music.

With DirectX 8, the DirectMusic interfaces are the primary mechanism for loading and playing all sounds, whether they originate as files or resources in wave format, MIDI format, DirectMusic Producer format, or indeed any format for which an add-on loader and tools are available.

Applications can still use the DirectSound interfaces for wave playback, and DirectSoundCapture remains the API for wave capture. However, in most applications DirectSound does its work downstream from the DirectMusic synthesizer. It takes the output from the synthesizer, routes it through effects filters, applies 3-D effects, and does the final mixing before streaming the data to the output device.

If you've used DirectSound in the past, you'll find that switching to the DirectMusic interfaces for loading and playing waves offers the following advantages:

  • No need to parse the file or resource. The DirectMusic loader does it for you.
  • Automatic use of the Windows audio compression manager (ACM ) for wave formats other than those supported by DirectSound.
  • Automatic streaming of data. No more manual buffer creation and tracking of read and write pointers.
  • Better timing control. Not only can you schedule sounds more precisely using the DirectMusic master clock, but you can easily synchronize sound effects with music.
  • Easier management of multiple instances of a sound.

Waves incorporated in DirectMusic Producer files have additional advantages. DLS articulation effects, such as envelopes, can be added to waves. Segments can contain wave variations, adding a random element to playback.

These advantages don't mean you have to lose the low-level control offered by DirectSound. The DirectMusic API enables you to access any object in the audiopath. If you want to get an interface for an existing buffer, you can easily do so. You can also take advantage of all the new features of the DirectSound API for adding filters and effects.


Overview of Audio Data Flow

Typically, a DirectX Audio application obtains musical data from one or more of the following sources:

  • MIDI files.
  • Wave files.
  • Segment files authored in DirectMusic Producer or a similar application.
  • Component files authored in an application such as DirectMusic Producer and turned into a complete composition by the composer object.

Note Any of these data sources can be stored in the application as a resource rather than in a separate file.

Data from these sources is encapsulated in segment objects. Each segment object represents data from a single source. At any given moment in a performance, one primary segment and any number of secondary segments can be playing. Source files can be mixed—for example, a secondary segment based on a wave file can be played along with a primary segment based on an authored segment file.

A segment comprises one or more tracks, each containing timed data of a particular kind—for example, notes or tempo changes. Most tracks generate time-stamped messages when the segment is played by the performance. Other kinds of tracks supply data only when queried by the performance.

The performance first dispatches the messages to any application-defined tools. Such tools are grouped in segment toolgraphs that process only messages from particular segments, audiopath toolsgraphs for messages from all segments playing on the path, and a performance toolgraph that accepts messages from all segments. A tool can modify a message and pass it on, delete it, or send a new message.

Finally, the messages are delivered to the output tool, which converts the data to MIDI format before passing it to the synthesizer. Channel-specific MIDI messages are directed to the appropriate channel group on the synthesizer. The synthesizer creates sound waves and streams them to a device called a sink, which manages the distribution of data through buses to DirectSound buffers.

There are three kinds of buffers:

  • Sink-in buffers are DirectSound secondary buffers into which the sink streams data. These buffers convert the data format to that of the primary buffer, if necessary, and enable the application to control pan, volume, 3-D spatialization, and other properties. They can also pass their data through effects modules to add effects such as reverberation and echo. The resulting waveform is passed either directly to the primary buffer or to one or more mix-in buffers.
  • Mix-in buffers receive data from other buffers, apply effects, and mix the resulting wave forms. These buffers can be used to apply global effects. An effect achieved by directing data to a mix-in buffer is called a send.
  • The primary buffer performs the final mixing on all data and passes it to the rendering device.

Note Applications are not responsible for streaming the data through secondary buffers that are part of a DirectMusic performance. Although an application can obtain a buffer object for the purpose of adding effects and changing properties, it cannot lock the buffer and write to it, as it must when using the DirectSound API to play wave sounds.

The following diagram is a simplified view of the flow of data from files to the speakers. A single segment is shown, though multiple segments can play at the same time. The segment gets its data from only one of the four possible sources shown: a wave file, a MIDI file, a segment file authored in DirectMusic Producer, or component files combined by the composer object.

Notes In all cases, data can come from a resource rather than a file.

For a closer look at the flow of messages through the performance, see Using DirectMusic Messages.

For information on how to implement the process shown in the illustration, see Loading Audio Data and Playing Sounds.


Compositional Music Elements

If you want to take full advantage of DirectX Audio, you won't play just MIDI and wave files. You'll take musical elements authored in DirectMusic Producer or a similar application and use them to create performances that can be varied or manipulated in countless ways.

Note Throughout this documentation, the human composer of musical elements is referred to as the author, to avoid confusion with the composer object of DirectMusic. Similarly, musical elements are said to be authored rather than composed.

The following brief introduction to these elements and how they are authored is meant to give the application developer an understanding of the material being used in the performance. For a more detailed view, see the documentation for DirectMusic Producer. For information on how to incorporate these elements in an application, see Using Compositional Elements.

The following compositional elements are described:

  • Styles
  • Chordmaps
  • Style-based Segments
  • MIDI-based Segments
  • Templates
  • Bands


Styles

A style is a collection of musical patterns that can be used to create a dynamic score. It also contains a time signature and a tempo, and can contain one or more bands.

A pattern is a musical figure, one or more measures long, consisting of a basic sequence of notes for each instrument, or part. These notes are not fixed but are ultimately mapped to particular pitches according to the current key, chord, and play mode. Patterns also include variations.

A motif is a special type of pattern designed to be played dynamically over the basic score. Motifs are often used in interactive applications to mark an event.

In DirectMusic Producer, patterns are created by the author on a grid analogous to a piano roll. Each part has its own row, corresponding to a performance channel, on which notes are represented by bars of varying length (duration), thickness (velocity), position on a vertical scale (pitch), and position on a horizontal scale (time).

The author can create many variations for each pattern. Typically, this is done by copying the pattern and then making small changes to one or more parts. At run time, variations are chosen by the style playback mechanism. However, the author can disable any variation for any chord—that is, specify that the variation must never be chosen when a certain chord is being played.

The author also assigns a groove range to the pattern, specifying the groove levels at which the pattern can be played.

The pattern can also be designated as an embellishment. Embellishments are of five types—intro, fill, break, end, and custom—and a pattern can be assigned to one or more of these categories. When the music is played and a certain type of embellishment is called for, only patterns of that type are candidates for playback.


Chordmaps

Much modern music, especially music in the popular, rock, folk, and jazz idioms, is based on the concept of chord progression, meaning that all the notes played within a given span of time are associated with a certain chord, and the music moves harmoniously from one chord to another.

The notes within a pattern authored for DirectMusic are derived from or intended to harmonize with a single chord. At run time, however, the pattern is transposed according to the chord progression—that is, each time the underlying chord changes, DirectMusic modifies the pitch of the notes accordingly.

The chordmap is a road map of chord progressions. Within the chordmap designer, the author chooses chords that can express the desired musical feeling or personality. These chords are arranged in a flowchart along a time line. The time line is conceptually circular, so it keeps looping back to the beginning as long as that segment of music is being played.

Certain important chords are designated as signposts. These are chords that must be played at certain points. The music is always moving from one signpost to the next. Between the signposts, however, the chord progression can follow various routes from one chord to another, as mapped out by the author.

The route through the chord chart may be chosen at run time by the composition engine, providing variation in addition to that found in the patterns themselves. Or it may be chosen by the authoring tool when the author is creating a segment.

A chord in the chordmap can actually consist of several different chords, referred to as subchords. In order to achieve polytonality by playing different inversions of the same chord, the author can assign different parts to different subchords. Each subchord is valid for one or more levels, and these are matched up with levels assigned to parts in the style.


Style-based Segments

A style-based segment is a largely prebuilt piece of music that the author constructs from the following elements:

  • Style. A style consists of general information about the music (such as time signature and tempo), as well as patterns. See Styles.
  • Chord progression. This might be derived automatically by the authoring tool from a chordmap (by choosing a path through the chord chart), or entered manually by the author.
  • Command track. This track, known as the groove track in DirectMusic Producer, is a series of commands for selecting appropriate patterns at set times. A characteristic of the patterns in styles is that they can be designated as embellishments (intro, fill, break, and end) and can also be assigned a certain groove range by the author. The command track of the segment might instruct the style playback engine to select an intro pattern and play it for the first measure, then play only patterns with a groove level of 25 for the next four measures, then play a break, and so on.
  • Band. The author can assign instruments and performance channels to all the parts in the various patterns.


MIDI-based Segments

A MIDI-based segment is created in DirectMusic Producer, often by importing a MIDI file to which the author might add tempo, key, and band changes, as well as loop points. Unlike a style-based segment, a MIDI segment has no patterns and no command track. Instead, it has a sequence track that contains MIDI notes and other commands.


Templates

A template is a segment that contains a signpost track and, optionally, a command track. The signpost track can be used to create a new chord progression, either for the segment itself or for another segment that does not have a signpost track. The command track supplies groove levels and embellishments. You can use templates at run time to compose new material.

Note Templates created in versions of DirectMusic Producer prior to DirectX 8.0 are not playable self-contained segments. They can be used only to compose other segments.

The signpost track contains a sequence of signpost markers, which mark the beginning and end of regions in which variations in the chord progression are possible. Each signpost marker is designated as valid for a particular group of signpost chords in a chordmap. The author of the content is responsible for assigning signpost markers and signpost chords to the appropriate groups.

DirectMusic composes a segment by applying the signpost track to a particular style and chordmap. Each time the composer encounters a pair of signpost markers along the time line in the template, it searches the chordmap for a pair of signpost chords that belong to that group. If it finds a pair and the interval between them fits into the time available, it follows the chord progression between those two signpost chords, as defined in the chordmap. If it is unable to find a path that works, or if there is no end signpost marker, the engine plays any chord from the group of the beginning signpost marker.

For information on composing segments from templates in an application, see Using Templates.


Bands

A band is a set of instruments, with their performance parameters, associated with particular parts in a piece of music. This isn't the same as a DLS collection, which represents a set of instruments that can be downloaded to the synthesizer and thus made available to any application.

In a tool such as DirectMusic Producer, the author creates a band by assigning instruments to performance channels. These instruments can be from any DLS collection, and instruments from different sources can be mixed within a band. Each of these instruments is given volume, pan, and transposition settings.

Performance channels map instruments to parts. If a pattern calls for a particular note on channel 1, that note is played by the instrument in the current band that is assigned to channel 1. The sound is modified by the band's settings for the volume, pan, and transposition of that instrument.

Bands can be saved as separate files or included in styles or segments.


How Music Varies During Playback

As DirectMusic plays a style-based segment, changes are made to the basic harmony and rhythm so that the performance does not sound static. Changes are partly scripted and partly random.

  • Choice of pattern. A typical style contains multiple patterns, which are selected in response to commands from the command track. For example, if the command track calls for a break embellishment to be played, the style playback engine selects a break pattern that is compatible with the current groove level. (The author specifies which groove levels are appropriate for each pattern.) If there is more than one suitable pattern, one is chosen according to rules embedded in the segment by the author. The choice might be completely or partly random, or patterns might be selected in a certain sequence.
  • Variations within a pattern. Any part within a pattern can have multiple variations. Variations can play in an order specified by the author; otherwise the style playback engine makes a random choice of variations on each repetition of the pattern.
  • Groove level. The groove level of the segment determines which of the patterns in the style can be selected for playback. The current level is set by the command track, which is normally authored into a segment. The groove level of a segment can also be changed programmatically, and a modifier can be applied to all segments by setting the master groove level for the performance.
  • Transposition. As the segment plays, changes are made to the underlying chord according to the progression in the chord track. The notes in the current pattern are automatically transposed to harmonize with the new chord.
  • Variations in timing. The playback engine can introduce small random changes in the parameters of individual notes—when they begin and when they end.
  • Band. The choice of instruments and instrument settings (volume, pan, and transposition) can be changed as the segment is playing, either by the band track within an authored segment or dynamically by the application. The application can change the band by creating a secondary segment based on a band object and then playing that segment, or by setting a parameter on the band track of the playing segment.

In many cases, applications exert control over the music by playing different segments rather than by manipulating existing segments. For example, to have the music reflect a change in the intensity of a game, you can simply transition to a new segment authored for that intensity level. You can achieve a similar effect with a single style-based segment by having the author create patterns with different groove ranges, and then changing the groove level in response to game events.


Music Values and MIDI Notes

Notes in a pattern within a DirectMusic style are not fixed notes. Rather, they are music values that become actual notes only when they are transposed to the current chord according to the current play mode and subchord level.

A music value is a representation of the note's intended role. For example, a music value can specify that a note is intended to be played as the second position in the chord, up one in the scale. When that music value is applied to a particular chord, it is converted to the appropriate MIDI note—the one in the second position in the chord, up one in the scale.

The play mode determines how to interpret the note against the chord. For example, if the mode is DMUS_PLAYMODE_NORMALCHORD, the note is interpreted against the intervals of the chord and scale, based on the root of the chord. If the mode is DMUS_PLAYMODE_FIXEDTOKEY, the note is interpreted as a linear value.

To allow for complex harmonies with multiple parallel chord progressions, DirectMusic chords can comprise multiple subchords. The subchord level is a value in the range from 0 through 31 that determines which subchords of a chord can be used in establishing the music value. Each subchord is valid for one or more levels, as defined by the author of the music. DirectMusic Producer supports up to four subchords per chord.

When a segment is played, each note is encapsulated in a message structure that specifies the original music value and the final MIDI note along with the play mode and subchord level that were used in transposition. Most applications don't deal directly with note messages, but tools can intercept them and alter the notes. For example, a tool could intercept a note that was transposed in a certain play mode, change the play mode, and calculate a new MIDI value before passing on the message.

More information on music values, play modes, chords, and subchords is contained in the following reference topics:

  • DMUS_NOTE_PMSG
  • DMUS_PLAYMODE_FLAGS
  • DMUS_CHORD_PARAM
  • DMUS_CHORD_KEY
  • DMUS_SUBCHORD
  • IDirectMusicPerformance8::MIDIToMusic
  • IDirectMusicPerformance8::MusicToMIDI


Downloadable Sounds

In the past, most computer audio has been produced in one of two fundamentally different ways, each with its advantages and disadvantages:

  • Waveforms are reproduced from digital samples, typically stored in a .wav file or, in the case of Red Book audio, on a standard CD track. Digital samples can reproduce any sound, and the output is very similar on all sound cards. However, they require large amounts of storage and resources for streaming.
  • Musical instrument sounds are synthesized, usually in hardware, in response to messages, typically from a MIDI file. MIDI files are compact and require few streaming resources, but the output is limited to the number of instruments available in the General MIDI set and in the synthesizer, and may sound very different on different systems.

One way to combine the advantages of digital sampling with the compactness and flexibility of MIDI is wave-table synthesis—the synthesis of instrument sounds from digital samples. These samples are obtained from recordings of real instruments and then stored on the hardware. The samples are looped and adjusted in such a way as to produce sounds of any length at various pitches and volumes.

Wave-table synthesis produces more realistic timbres than algorithmic FM synthesis but is still limited to a fixed set of instruments. Moreover, a particular instrument might sound different on different pieces of hardware, depending on the manufacturer's implementation of that instrument.

Enter the Downloadable Sounds (DLS) standard, published by the MIDI Manufacturers Association. DLS is a way of allowing wave-table synthesis to be based on samples provided at run time rather than hard-wired into the system. The data describing an instrument is downloaded to the synthesizer, and then the instrument can be played like any other MIDI instrument. Because DLS data can be distributed as part of an application, developers can be sure that their soundtracks will be delivered uniformly on all systems. Moreover, they are not limited in their choice of instruments.

A DLS instrument is created from one or more digital samples, typically representing single pitches, which are then modified by the synthesizer to create other pitches. Multiple samples are used to make the instrument sound realistic over a wide range of pitches. When a DLS instrument is downloaded, each sample is assigned to a certain range of pitches, called a region.

DLS Level 2 allows every note to occupy its own region. Moreover, the timbre for each region can be made up of multiple samples, called layers, and different layers can be triggered depending on the velocity of the note. A single instrument can thus be used to produce thousands of different sounds.

In addition, samples can be given an articulation, which defines characteristics that make the sound more like that produced by a real instrument. Articulation includes envelopes for the volume and pitch of the sound and a low-frequency oscillator (LFO) to provide vibrato and tremolo.

Samples can be loopable or single-shot. A loopable sample plays repeatedly for the duration of the note. A single-shot sample plays only once.

DLS data is stored in instrument collections, from which it is downloaded to the synthesizer.

DLS instruments are assigned patch numbers and respond to MIDI messages just like other MIDI instruments. However, a DLS instrument does not have to belong to the General MIDI set. In fact, it doesn't have to represent a musical instrument at all. Any sound, even a fragment of speech or a fully composed measure of music, can be associated with a DLS instrument.

For more information on DLS collections and how instruments are created, see the documentation for DirectMusic Producer. To learn more about the DLS standard, consult the document "Downloadable Sounds Level 2", available from the MIDI Manufacturers Association.

Most applications don't have to deal directly with instruments or DLS data. The opening of collections and downloading of instrument data is handled by the band object. When you download a band, all the instrument data associated with that band is downloaded as well. For more information, see Using Bands.


Audio Scripts

An audio script is a file containing variables and routines that can be accessed from within an application. It is written in a subset of Microsoft® Visual Basic® Scripting Edition called AudioVBScript. DirectMusic Producer includes an authoring environment for scripts and saves them in a special format that includes binary parameters as well as the text of the script.

Scripts implement some of the key DirectX Audio objects and can perform basic functions such as the following:

  • Creating audiopaths
  • Setting audiopath volumes
  • Setting global parameters for the performance
  • Loading, playing, and stopping segments
  • Downloading bands

DirectX Audio scripts are designed to make it easier for application developers and sound designers to coordinate their efforts. Scripts enable sound designers to have greater and more immediate control over the soundtrack. The basic functionality of loading and playing sounds is performed by the script. The application contains generalized code that calls into the script.

Here's an example of how this might be helpful.

The sound effects for a certain game are stored as individual wave files. The game uses these sounds for events such as weapons firing and monsters grunting. Using conventional programming techniques, the developers load the individual sounds by file name and play them as secondary segments at appropriate points in the game.

Suppose the sound designers want to make some changes. They decide, for example, that the boss monster should have a different grunt than his minions. They create the necessary files and hand them off to the developers, who implement the changes in code. Considerable time may pass before the sound designers are able to get a newly compiled version of the game and test it.

Now imagine the same scenario using an audio script. Rather than hard-coding the actual sounds into the application, the developers might write code like the following to respond to a grunt. Assume that that szGrunter has been set to a string constant such as "Player", "Boss" or "Minion", and that pdmScript is an interface to the script object:

pdmScript->SetVariableVariant("Grunter", szGrunter, NULL);
pdmScript->CallRoutine("PlayGrunt", NULL);

This fragment of code sets the value of the Grunter variable in the script and calls the PlayGrunt script routine. The script author—most likely a member of the sound design team—decides what the routine does. For example, it might test the value of "Grunter" before deciding what sound to play.

To change the response to the game situation, all that is required is an alteration in the text of the script, and the new routine can be tested immediately against the existing application.

The scripting API is documented in the DirectMusic Producer Help file. For more information on how to implement a script in your application, see Using Audio Scripts.

Note Audio scripts are not designed to be used on Web pages.


Using DirectX Audio

This section is a guide to using the Microsoft® DirectMusic® and Microsoft® DirectSound® APIs in application development.

Information is presented in the following topics:

  • Loading Audio Data
  • Playing Sounds
  • Performance Parameters
  • Using Audiopaths
  • 3-D Sound
  • Using Effects
  • Buffer Chains
  • Using Compositional Elements
  • Using Audio Scripts
  • Wave Playback in DirectSound
  • Sound Capture

For a more general overview, see Getting Started with DirectX Audio.

For an understanding of the underlying mechanisms of data flow, see Understanding DirectX Audio.

For information on advanced features used mainly by specialized applications, see Advanced Topics in DirectX Audio.


Loading Audio Data

Many DirectMusic objects have to be loaded from a file or resource before they can be incorporated into a performance. The IDirectMusicLoader8 interface is used to manage the enumeration and loading of such objects, as well as to cache them so that they are not loaded more than once.

An application should have only one instance of the loader in existence at a time. You should create a single global loader object and not free it until there is no more loading to be done. This strategy ensures that objects are found and cached efficiently.

The DirectMusic implementation of IStream streams the data from the source. The parsing of the data is handled by the various objects themselves through their implementations of IPersistStream. As long as you are dealing only with standard DirectMusic data, you don't need to use these interfaces directly.

Loading of objects referenced by other objects is handled transparently. For example, suppose a style being loaded from a DirectMusic Producer file contains a reference to a band whose data is in another file. When the style's IPersistStream finds the reference, it obtains the IDirectMusicGetLoader8 interface from the IStream that passed it the data stream. Using this interface, it obtains a pointer to the loader object. Then it calls IDirectMusicLoader8::GetObject to load the band.

More information on using the loader is contained in the following topics:

  • Setting the Loader's Search Directory
  • Scanning a Directory for Objects
  • Enumerating Objects
  • Loading an Object from a File
  • Loading an Object from a Resource
  • Containers
  • Getting Object Descriptors
  • Cache Management
  • Garbage Collection
  • Setting Objects

See also Custom Loading in the Advanced Topics in DirectX Audio section.


Setting the Loader's Search Directory

By default, the loader looks for objects in the current directory unless a full path is specified in the wszFileName member of the DMUS_OBJECTDESC structure describing the object being sought. By using the IDirectMusicLoader8::SetSearchDirectory method, you can set a different default path for the IDirectMusicLoader8::GetObject, IDirectMusicLoader8::LoadObjectFromFile, and IDirectMusicLoader8::EnumObject methods. This default path can apply to all objects, or only to objects of a certain class.

The following code example sets the search path for style files:

HRESULT mySetLoaderPath (
    IDirectMusicLoader8 *pILoader)    // Previously created.
{
    return pILoader->SetSearchDirectory(
            CLSID_DirectMusicStyle,
            L"c:\\mymusic\\funky",
            FALSE);
}

After calling this function, the application can load a style by file name, without including the full path.


Scanning a Directory for Objects

The IDirectMusicLoader8::ScanDirectory method scans the current search directory for objects of a given class. You can further narrow the search by providing a subclass and a file extension other than "*".

The method compiles a list of all matching files and uses the IDirectMusicObject8::ParseDescriptor method to extract the GUID and the name of the object. These identifiers are retained in an internal database so that the application can subsequently load objects by GUID or name rather than by file name. See Loading an Object from a File.

Note If you are working with DirectMusic Producer content, it is always a good idea to call IDirectMusicLoader8::ScanDirectory before loading any objects. Even though you may be loading objects explicitly by file name, those objects might contain references to other objects not identified by file name, and the loader will not be able to find these referenced objects if ScanDirectory has not been called on every directory in which the objects might be.

If you include a pointer to a string in the pwszScanFileName parameter of the ScanDirectory method, the results of the scan are cached in a file by that name to speed up subsequent scans. When a cache file is available, the method updates object information only for files whose time stamps or sizes have changed.

Note In the current version of DirectMusic, ScanDirectory does not use the cache file. Nevertheless, you can implement a cache file now, and it will speed up performance under future versions.

For an example, see Enumerating Objects.


Enumerating Objects

Use the IDirectMusicLoader8::EnumObject method to iterate through all objects of a given class, or of all classes, that have previously been listed in the internal database through a call to IDirectMusicLoader8::ScanDirectory or calls to IDirectMusicLoader8::GetObject. A description of each object found is returned in a DMUS_OBJECTDESC structure.

Note To be sure of finding all objects, call ScanDirectory first. EnumObject works by checking the internal database of objects, not by parsing disk files.

The following example enumerates all listed style objects in the current search directory and displays information about each one by using the TRACE debugging macro. The loop continues until there are no more objects of that class to enumerate.

void myListStyles(
        IDirectMusicLoader *pILoader)

{
    HRESULT hr = pILoader->SetSearchDirectory(
            CLSID_DirectMusicStyle,
            L"c:\\mymusic\\wassup",
            TRUE);
    if (SUCCEEDED(hr))
    {
        hr = pILoader->ScanDirectory(
                CLSID_DirectMusicStyle,
                L"sty",
                L"stylecache");
        if (hr == S_OK)    // Only if files were found.
        {
            DWORD dwIndex;
            DMUS_OBJECTDESC Desc;
            Desc.dwSize = sizeof(DMUS_OBJECTDESC);
            for (dwIndex = 0; ;dwIndex++)
            {
                if (S_OK ==(pILoader->EnumObject(
                        CLSID_DirectMusicStyle,
                        dwIndex, &Desc)))
                {
                    TRACE("Name: %S, Category: %S, Path: %S\n",
                            Desc.wszName,
                            Desc.wszCategory,
                            Desc.wszFileName);
                }
                else break;
            }
        }
    }
}

Notice that the example does not use the SUCCEEDED macro to test the result of the method call, because EnumObject returns a success code, S_FALSE, for an invalid index number.


Loading an Object from a File

To load an object, first obtain the IDirectMusicLoader8 interface, as in the following example:

IDirectMusicLoader8* m_pLoader;

CoInitializeEx(NULL, 0);
HRESULT hr = CoCreateInstance(
    CLSID_DirectMusicLoader,
    NULL,
    CLSCTX_INPROC,
    IID_IDirectMusicLoader8,
    (void**)&m_pLoader);

You can then load an object from file by using either IDirectMusicLoader8::LoadObjectFromFile or IDirectMusicLoader8::GetObject. The first of these methods is more convenient because it does not require you to describe the object by filling out a DMUS_OBJECTDESC structure.

The following sample code loads four segments from a directory previously set by IDirectMusicLoader8::SetSearchDirectory:

IDirectMusicSegment8 * m_pSegments[4];

static WCHAR  wszNames[4][MAX_PATH] = {
    L"AudioPath1.sgt",
    L"AudioPath2.sgt",
    L"AudioPath3.wav",
    L"AudioPath4.sgt"
};

for (DWORD dwIndex = 0; dwIndex < 4; dwIndex++)
{
    hr = m_pLoader->LoadObjectFromFile(
            CLSID_DirectMusicSegment,
            IID_IDirectMusicSegment8,
            wszNames[dwIndex],
            (void**) &m_pSegments[dwIndex]);
}

The following example function uses IDirectMusicLoader8::GetObject to load a style object from a file. The first parameter receives a pointer to the style.

void myLoadStyle(
    IDirectMusicStyle8 **ppStyle, IDirectMusicLoader8 *pLoader)
{
    if (pLoader)
    {
        DMUS_OBJECTDESC Desc;

        // Start by initializing Desc with the file name and
        // class GUID for the style object.

        wcscpy(Desc.wszFileName,L"c:\\mymusic\\funky\\polka.sty");
        Desc.guidClass = CLSID_DirectMusicStyle;
        Desc.dwSize = sizeof (DMUS_OBJECTDESC);
        Desc.dwValidData = DMUS_OBJ_CLASS |
                           DMUS_OBJ_FILENAME |
                           DMUS_OBJ_FULLPATH;

        pLoader->GetObject(&Desc, IID_IDirectMusicStyle8,
                (void **) ppStyle);
    }
}

The example identifies the file by a full path name and indicates this by setting the DMUS_OBJ_FULLPATH flag.

To identify the particular file object being sought, fill in at least one of the wszName, guidObject, and wszFileName members of the DMUS_OBJECTDESC structure, and set the corresponding flag or flags in the dwValidData member. If you identify the file by wszName or guidObject, but not by wszFileName, you must first call the IDirectMusicLoader8::ScanDirectory method to make the GUIDs and names in the current directory available. For more information, see Scanning a Directory for Objects.

See also Loading an Object from a Resource.


Loading an Object from a Resource

Objects stored as resources or at some other location in memory are loaded in much the same way as file objects. See Loading an Object from a File.

With memory objects, however, the wszName, guidObject, and wszFileName members of the DMUS_OBJECTDESC structure are irrelevant. Instead, you must obtain a pointer to the block of memory occupied by the object, and its size, and put these in the pbMemData and llMemLength members respectively. You must also set the DMUS_OBJ_MEMORY flag in the dwFlags member.

The memory cannot be released once IDirectMusicLoader8::GetObject has been called, because the loader keeps an internal pointer to the memory to facilitate caching data. If you want to clear it out, call IDirectMusicLoader8::SetObject with the same DMUS_OBJECTDESC descriptor, but with NULL in pbMemData. This is not an issue when loading from a resource, because resource memory is not freed.

The following function loads a MIDI file from a resource into a segment:

// m_pLoader is a valid IDirectMusicLoader8 pointer.

IDirectMusicSegment8* m_pSegment;

HRESULT LoadMidi(HMODULE hMod, WORD ResourceID)
{
    HRESULT              hr;
    DMUS_OBJECTDESC      ObjDesc;

    HRSRC hFound = FindResource(hMod,
            MAKEINTRESOURCE(ResourceID), RT_RCDATA);
    HGLOBAL hRes = LoadResource(hMod, hFound);

    ObjDesc.dwSize = sizeof(DMUS_OBJECTDESC);
    ObjDesc.guidClass = CLSID_DirectMusicSegment;
    ObjDesc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_MEMORY;
    ObjDesc.pbMemData = (BYTE *) LockResource(hRes);
    ObjDesc.llMemLength = SizeofResource(hMod, hFound);

    hr = m_pLoader->GetObject(
            &ObjDesc, IID_IDirectMusicSegment8,
            (void**) &m_pSegment );

    return hr;
}

Objects referenced by other objects must be loaded first. For example, if you load a segment that contains a reference to a style, the style must already be loaded in order for the segment to play correctly. Alternatively, you can call IDirectMusicLoader8::SetObject on the style so that the segment can find it.


Containers

Containers are objects representing files that contain various objects. A container file might hold all the data necessary for a performance, including segments, styles, and DLS collections. Container files are typically created in DirectMusic Producer. Containers can also exist within segment and script files.

You load a container like any other object, using IDirectMusicLoader8::GetObject. This method makes all objects in the container known to the loader, so that you can then use GetObject to retrieve them by name or GUID.

After you have obtained the IDirectMusicContainer8 interface, you can enumerate the objects in the container by using IDirectMusicContainer8::EnumObject.

The following sample function loads a container, retrieves a segment from it by name, and returns an IDirectMusicSegment interface. For purposes of demonstration, the container object is created and released within the function; in practice, this should be done only once during the life of the application, to prevent duplication of objects.

IDirectMusicSegment* LoadSegmentFromContainer (
        IDirectMusicLoader8* pLoader,
        WCHAR* wszFileName,
        WCHAR* wszSegmentName )

{
  DMUS_OBJECTDESC ObjDesc;
  IDirectMusicSegment* pSegment = NULL;
  IDirectMusicContainer8* pContainer = NULL;

// Load the container.

  HRESULT hr = pLoader->LoadObjectFromFile(CLSID_DirectMusicContainer,
      IID_IDirectMusicContainer8, wszFileName, (void**)&pContainer);
  if (FAILED(hr))
        return NULL;

// Describe the segment.

  ZeroMemory(&objDesc, sizeof(objDesc));
  objDesc.dwSize = sizeof(objDesc);
  objDesc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_NAME;
  objDesc.guidClass = CLSID_DirectMusicSegment;
  wcsncpy (objDesc.wszName, wszSegmentName,
      sizeof(objDesc.wszName) - 1);
  objDesc.wszName[sizeof(objDesc.wszName) - 1] = 0;

// Load the segment.

  hr = pLoader->GetObject(&ObjDesc, IID_IDirectMusicSegment,
      (void**) &pSegment);

// Release the container from the cache and destroy the object.

  if (pContainer)
  {
    IDirectMusicObject *pObject = NULL;
    pContainer->QueryInterface(IID_IDirectMusicObject,
            (void **)&pObject);
    if (pObject)
    {
      pLoader->ReleaseObject(pObject);
      pObject->Release();
    }
  pContainer->Release();
  }
  if (S_OK != hr) return NULL;
  return pSegment;
}


Getting Object Descriptors

Once you have loaded an object, you can use its IDirectMusicObject8 interface to retrieve information about it in a DMUS_OBJECTDESC structure.

The following code example uses the IDirectMusicObject8::GetDescriptor method to obtain the name of a style:

//  pStyle is a valid pointer to an IDirectMusicStyle8 interface.

IDirectMusicObject8 *pIObject;
DMUS_OBJECTDESC Desc;

if (SUCCEEDED(pStyle->QueryInterface(IID_IDirectMusicObject8,
        (void **) &pIObject)))
{
    if (SUCCEEDED(pIObject->GetDescriptor(&Desc)))
    {
        if (Desc.dwValidData & DMUS_OBJ_NAME)
        {
            // Desc.wszName contains the name of the style.
        }
    }
    pIObject->Release();
}


Cache Management

When an object is cached, the same instance of the object is always returned by the IDirectMusicLoader8::GetObject method.

The cache stores a pointer to the object. The memory for the object itself is managed by COM, and is not released until the reference count reaches zero. It is important to remember that releasing an object from the cache is not the same as releasing your application's COM reference to it.

Caching is used extensively in the file-loading process to resolve links to objects. For example, two segments could reference the same style. When the first segment loads, it calls the loader to get the style. The loader creates a style object, loads the data from disk, caches a pointer to the style object, and returns this pointer to the segment. If caching is enabled, when the second segment loads, it asks for the style, and the loader immediately returns the same pointer. Now both segments point to the same style. If caching is disabled, the second segment's request for the style causes a duplicate style object to be loaded from the file, at a cost in time and memory.

Here's another example. A band object counts on the loader to keep the General MIDI DLS collection cached. Every time a band has to download a GM instrument, it gets the collection from the loader. If caching for CLSID_DirectMusicCollection is disabled, every patch change in a MIDI file causes a separate copy of the entire GM collection to be created. This is obviously undesirable.

By default, caching is enabled for all object classes. You can disable caching for an object class, or for all objects, by using the IDirectMusicLoader8::EnableCache method. This method can also be used to re-enable caching for any or all object classes.

If you want to clear the cache without disabling future caching, use the IDirectMusicLoader8::ClearCache method. It's not necessary to call this method before terminating your application, because the cache is automatically cleared when the loader is released. ClearCache is only useful if the application soundtrack is changing completely, with all new instruments and source files.

To cache a single object when general caching is disabled, pass it to the IDirectMusicLoader8::CacheObject method.

You can remove an object from the cache, ensuring that it will be loaded again on the next call to GetObject, by using the IDirectMusicLoader8::ReleaseObject or IDirectMusicLoader8::ReleaseObjectByUnknown method. It is a good idea to call one of these methods before calling Release on an object, especially a segment. If you don't, a reference to the object remains in the cache, so the object continues to exist. As well as taking up memory, the object might retain certain state information. In the case of a segment, any instance that you load later will be taken from the cache, and the start point and loop points will be the same as they were when the previous instance was destroyed.

For more information on cache management, see Garbage Collection.


Garbage Collection

Caching of loaded objects can lead to wasted memory when an application loads many objects, particularly objects that reference other objects.

When automatic caching is enabled, as it is by default, every object loaded by IDirectMusicLoader8::GetObject is cached, including objects that are loaded by reference. For example, if you call GetObject on a segment, and that segment contains a reference to a script, the script is loaded and cached as well.

When you call IDirectMusicLoader8::ReleaseObject or IDirectMusicLoader8::ReleaseObjectByUnknown, however, only the primary object that was loaded by GetObject is removed from the cache. Referenced objects are not released, regardless of whether they are still in use by other objects.

In order to clean up objects that are not in use, call IDirectMusicLoader8::CollectGarbage. This method releases all objects from the cache except objects directly loaded by GetObject and objects referenced by them. CollectGarbage clears an object from the cache by releasing the loader's COM reference to the object. If the object's reference count drops to zero as a result, the object destroys itself, thus making its memory available again.

In summary, to ensure that loaded objects do not remain in memory when no longer needed, you need to do the following:

  • Call ReleaseObject or ReleaseObjectByUnknown on any object for which GetObject has been called.
  • Call CollectGarbage to release the loader's reference to any objects that were loaded indirectly.
  • Call Release on any pointers held by your application.

A complication arises when objects have circular references to one another. Suppose a segment contains a reference, by way of its script track, to a script object, and the script contains a reference to the segment. You load the segment directly by calling GetObject, and the script is loaded indirectly. Then you release the segment from the cache by using ReleaseObject, and call Release on your application's reference to it. The segment continues to exist because there is still one COM reference to it, which is held by the script object. The script is now garbage, because it is not referenced by any other object in the cache. Without taking special measures, however, CollectGarbage could only release the loader's reference to the script; therefore its reference count would not drop to zero. The segment and script would continue to be referenced by one another, and although both were removed from the cache, they would both continue to exist in memory.

To avoid this problem, CollectGarbage calls an internal method on an object that forces the object to release its references to other objects. In the example above, it causes the script to release its reference to the segment. The segment's reference count drops to zero, and in the course of destroying itself, the segment releases its reference to the script, thus allowing the script to destroy itself when the loader releases its reference.

There is one more complication, however. Suppose the application has obtained an interface to the script that the loader knows nothing about, and neglects to call Release on this pointer. The script continues to exist, but it might not be able to behave as it should, because it no longer has a reference to the segment. Calling a method on the script could lead to a fatal error. To prevent this, CollectGarbage ensures that all methods on the script return DMUS_S_GARBAGE_COLLECTED.

This scenario does not affect most applications. However, you should be aware that calling a method on an object that has been cleared from the cache by CollectGarbage might not yield the desired result.

The following sample code, where m_pLoader is an IDirectMusicLoader8 interface and m_pPerformance is an IDirectMusicPerformance8 interface, loads a script that contains a reference to a segment. After calling a routine in the script, the example removes the script object from the cache and then calls CollectGarbage to free the segment object. If the segment contains a reference to the script, this is released so that the script can be destroyed, in turn releasing the segment and allowing it to be destroyed.

// Load script and call routine.

IDirectMusicScript8 *pScript;

m_pLoader->GetObject(scriptdesc, IID_IDirectMusicScript8, &pScript);
pScript->Init(m_pPerformance, NULL);
pScript->CallRoutine(L"DoorSlam", NULL);

// Release script object and collect garbage.

pLoader->ReleaseObjectByUnknown(pScript);
pLoader->CollectGarbage();
pScript->Release();


Setting Objects

Sometimes it is desirable to tell the loader where to get an object, without actually loading that object, so that the loader can retrieve it if the object is later referenced by other objects as they are being loaded. You might also want to give an object a new attribute so that the loader can find it by that attribute.

The IDirectMusicLoader8::SetObject method takes as a parameter a DMUS_OBJECTDESC structure that contains two key pieces of information:

  • A pointer to the data. This can be either a file path or a pointer to a block of memory. See Loading an Object from a File and Loading an Object from a Resource.
  • An identifier for the object when it is referenced later. This could be a GUID or a name. Later, the call to IDirectMusicLoader8::GetObject will find the stored object by using the same name or GUID. Note that you cannot change a GUID or name that already exists in the object.

On return, the DMUS_OBJECTDESC structure may contain additional information about the object gathered by the loader.

The following function assigns a name to an unnamed object (such as a MIDI file) in a resource:

// m_pLoader is a valid IDirectMusicLoader8 interface pointer.

HRESULT SetObjectFromResource(const GUID* guid, int ID,
        char* type, WCHAR* name)
{
  HRSRC hResource = NULL;
  HGLOBAL hData = NULL;
  hResource = FindResource(g_hInstance, MAKEINTRESOURCE(ID), type);
  if (hResource != NULL)
  {
    hData = LoadResource(g_hInstance, hResource);
    if (hData != NULL)
    {
      DMUS_OBJECTDESC desc;
      if(m_pLoader && (hResource != NULL) && (hData != NULL))
      {
        ZeroMemory(&desc,sizeof(desc));
        desc.pbMemData = (BYTE*) LockResource(*hData);
        desc.llMemLength = SizeofResource(g_hInstance, (*hResource));
        desc.guidClass = (*guid);
        desc.dwSize = sizeof(desc);
        desc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_MEMORY;
        if (name)
        {
            wcscpy(desc.wszName, name);
            desc.dwValidData |= DMUS_OBJ_NAME;
        }
        return m_pLoader->SetObject(&desc);
      }
    }
  }
  return E_FAIL;
}

The sample function could be used to assign a name to a MIDI file stored as a resource of type "MIDI", as in the following function call:

SetObjectFromResource(CLSID_DirectMusicSegment, 101,
        "MIDI", "canyon");

The object can now be loaded at any time by name.


Playing Sounds

This section introduces the basic elements of a DirectMusic performance and the key methods that you need to get data from source to output.

The following topics are discussed:

  • Creating the Performance
  • Using Segments
  • Using Bands
  • Timing
  • Notification and Event Handling


Creating the Performance

The performance object is the overall manager of playback. Among the tasks it performs are the following:

  • Managing ports and audiopaths
  • Mapping channels to audiopaths
  • Playing and stopping segments
  • Dispatching messages
  • Managing tools and timing

Most applications have a single performance object, but it is possible to have more than one performance with different parameters, such as master tempo or volume.

The following code example creates a performance and obtains a pointer to the IDirectMusicPerformance8 interface:

IDirectMusicPerformance8* pPerf;

if (FAILED(CoCreateInstance(
        CLSID_DirectMusicPerformance,
        NULL,
        CLSCTX_INPROC,
        IID_IDirectMusicPerformance8,
        (void**)&pPerf
    )))
{
    pPerf = NULL;
}

After the performance is created, it must be initialized. If your application is using audiopaths, as is recommended, you must call the IDirectMusicPerformance8::InitAudio method. Applications using the earlier channel-to-port mapping model call IDirectMusicPerformance8::Init instead. For more information, see Migrating from Ports to Audiopaths.

An important part of initialization is the creation of a DirectMusic object. You can pass an existing IDirectMusic8 interface pointer to IDirectMusicPerformance8::InitAudio, but in most cases it is more convenient to have InitAudio create the DirectMusic object. You can also choose whether or not to retrieve a pointer to the IDirectMusic8 interface, depending on how much control you need over ports and the master clock. Most applications don't need access to the methods of IDirectMusic8 and can pass NULL as the ppDirectMusic parameter of InitAudio.

InitAudio can also take an existing DirectSound object. DirectSound manages the sound data after it leaves the synthesizer. In most cases you can let InitAudio create this object. You don't need an interface to it unless you intend to use DirectSound for other purposes such as creating a DirectSoundCapture object or for playing waves directly into buffers rather than through the DirectMusic performance.

By passing a DMUS_AUDIOPARAMS structure to InitAudio, the application can request synthesizer capabilities or set a synthesizer other than the default one. Most applications don't need to do this.

The following code example initializes the performance without retrieving pointers to the DirectMusic and DirectSound objects. It creates a standard default audiopath with 16 performance channels and all available features on the port.

// hWnd is the application window handle

if (SUCCEEDED(pPerf->InitAudio(NULL, NULL, hWnd,
        DMUS_APATH_SHARED_STEREOPLUSREVERB, 16,
        DMUS_AUDIOF_ALL, NULL)))
{
    // Performance initialized.
}


Using Segments

Segments are the basic units of playable data in the DirectMusic performance. A segment is represented by an IDirectMusicSegment8 interface.

You can create a segment object in an application by any of the following means:

  • Load a file or resource object that supports the IDirectMusicSegment8 interface. For more information, see Loading Audio Data.
  • Get a motif from a style by using the IDirectMusicStyle8::GetMotif method.
  • Use methods of the IDirectMusicComposer8 interface to create a composition or transition at run time. See Overview of Programming for Composition and Using Transitions.
  • Make a copy of an existing segment by using the IDirectMusicSegment8::Clone method.
  • Use the IDirectMusicBand8::CreateSegment method. This creates a special type of secondary segment that is used only for making band changes. See Making Band Changes Programmatically.
  • Use the IDirectMusicPatternTrack8::CreateSegment method to create a segment from a pattern track object. Most applications don't do this, because pattern track objects usually come from segments in the first place.
  • Construct a segment from existing tracks. Create a segment object by calling CoCreateInstance, and then add tracks by calling IDirectMusicSegment8::InsertTrack. This technique is not used by most applications.

Each segment consists of one or more tracks, each represented by an IDirectMusicTrack8 interface. Tracks contain most of the data for the segment, whether that data consists of note events, band changes, tempo changes, or other timed events. Applications generally don't need to use this interface, because the tracks are managed through the segment object. For more information, see DirectMusic Tracks.

Segments can perform different roles in the performance. There must always be a primary segment, which provides the main content of the soundtrack and normally serves as the control segment. Secondary segments play along with the primary segment and might provide sound effects or short musical themes. A special type of secondary segment is the motif, which is always obtained from a DirectMusic style object.

In addition there are three kinds of segments with special roles:

  • Transition segment. A short musical transition created at run time by the DirectMusic composer object and normally played as a primary segment leading from one segment to another, or from a segment to silence.
  • Band segment. A set of instruments and instrument settings for the various channels in the performance. The application can play a band segment as a secondary segment to execute changes in the band performing the music.
  • Template segment. A guide to chord progressions, groove levels, and embellishments, used in conjunction with a style and chordmap to compose music at run time.

The playback of segments is controlled by the performance object and begins with a call to IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx.

Only one primary segment can play inside a performance. When you cue a primary segment for playback, you can specify that it is to be played after the currently playing segment is finished, or you can use it to replace the current primary segment.

Secondary segments, on the other hand, play over the current primary segment, and any number of secondary segments can be playing simultaneously.

Secondary segments do not normally alter the performance of the primary segment. For example, a secondary segment can be based on a different style without affecting the style of the primary segment. However, a secondary segment can be designated as the control segment, in which case it takes over certain tasks normally handled by the primary segment.

More information on segments is contained in the following topics:

  • Segment States
  • Control Segments
  • Self-Controlling Segments
  • Wave Segments

See also Segment Timing.


Segment States

When you play a segment, parameters for that segment such as the audiopath, repetitions, and start point are stored in a segment state, represented by an IDirectMusicSegmentState8 interface. The parameters are valid only for that instance of the segment. Changes subsequently made to the segment by using methods of IDirectMusicSegment8 are reflected in new segment states created by calls to IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx.

When different instances of a segment are being played on different audiopaths, you can use the segment state to retrieve a 3-D sound buffer or an effect, and make changes that apply only to that instance. For example, you might use the same engine sound for different cars in a race game, playing the sound for each car on its own audiopath. You can use either IDirectMusicAudioPath8::GetObjectInPath or IDirectMusicSegmentState8::GetObjectInPath to retrieve an IDirectSound3DBuffer8 interface from each audiopath, allowing you to set the 3-D parameters for each car individually.


Control Segments

The control segment is the source of any data that is shared across tracks. The following tracks give their data to the performance not by sending messages, as most other tracks do, but by responding to parameter calls.

  • Chord
  • Command
  • Mute
  • Tempo
  • Time signature

The chord track, for example, answers parameter calls from the style track. To determine the MIDI value for a note before sending that note, the style track must determine the current chord. It does so by calling IDirectMusicPerformance8::GetParam, and this call is relayed to the chord track in the control segment.

To function as a control segment, a segment must have at least one controlling track. The mute, command, tempo, and chord tracks are controlling tracks.

The control segment does not affect any aspect of playback that is controlled by messages. The time signature comes from the control segment only when there is no time signature track, as is normally the case in segments not based on MIDI files.

By default, the primary segment is the control segment. However, a secondary segment can be designated the control segment by passing the DMUS_SEGF_CONTROL flag to IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx.

When a secondary segment is the control segment, the primary segment continues to function as a fallback source of control data. For example, if a secondary control segment does not contain a tempo track, but the primary segment does, the tempo comes from the primary segment.

For more information, see the following topics:

  • DMUS_SEGF_FLAGS
  • Track Configuration


Self-Controlling Segments

A self-controlling segment ignores any control information from the control segment that duplicates control information in the self-controlling segment. For example, if the segment has a command track, it can use its own groove levels rather than the groove levels set by the control segment.

Segments can define for each track where it gets its controlling information, as follows:

  • From tracks in the control segment. This is the default behavior.
  • From tracks in the primary segment, regardless of whether it is the control segment.
  • From tracks in the same segment.

Segments are usually configured to be self-controlling by the author. However, applications can configure individual tracks within segments by setting or clearing the following flags, using the IDirectMusicSegment8::SetTrackConfig or IDirectMusicSegmentState8::SetTrackConfig method:

DMUS_TRACKCONFIG_OVERRIDE_ALL
The track should get parameters from this segment before control and primary tracks.
DMUS_TRACKCONFIG_OVERRIDE_PRIMARY
The track should get parameters from this segment before the primary segment tracks.
DMUS_TRACKCONFIG_FALLBACK
The track should get parameters from this segment if the primary and control segments don't return the needed information.

The following example code, where pSegment is an IDirectMusicSegment8 interface pointer, instructs the style track to get all its parameters from other tracks in the same segment, ensuring that chords, groove levels, and mute commands do not come from the control segment.

HRESULT hr = pSegment ->SetTrackConfig(CLSID_DirectMusicStyleTrack,
        -1, DMUS_SEG_ALLTRACKS, DMUS_TRACKCONFIG_OVERRIDE_ALL, 0);

For more information, see Track Configuration.


Wave Segments

The DirectMusic loader can load compressed wave-form audio files in any format supported by the audio compression manager (ACM), as well as uncompressed wave files.

Segments based on wave files are played just like any other segment. They pass through the performance as DMUS_WAVE_PMSG messages and are always played on channel 0 of the audiopath. Although waves are not synthesized in the same sense as musical notes, they do pass through the synthesizer and can be manipulated by MIDI controllers.

Waves can also be embedded in DirectMusic Producer files, where they can behave somewhat like styles with variations. For an example, see the AudioScripts sample application, where the ScriptDemoBaseball.spt script plays variations on the vendor's cry each time a button is clicked.

Waves in segment (.sgt) files must be downloaded to the synthesizer before being played. They are downloaded when the segment's bands are downloaded. For more information, see Downloading and Unloading Bands.


Using Bands

A band is a choice of instruments assigned to particular parts in a segment or style. At performance time, each instrument track is mapped to a performance channel, which stores the following information:

  • MIDI volume.
  • MIDI pan.
  • Transposition. If this value is nonzero, music notes on the channel are automatically transposed for the instrument.
  • The instrument's MIDI patch number, including MSB and LSB bank selects.
  • A reference to the DLS collection from which to load the instrument. By default, the DLS collection is the standard General MIDI collection.

Segments and styles always contain at least one band, called the default band. Styles can contain additional bands. When you load a segment or style, the default band and any other bands are automatically loaded as well. However, you must still download the DLS data for the instruments in any band that you intend to use.

You can retrieve a pointer to the default band by using the IDirectMusicStyle8::GetDefaultBand method.

Other bands might be authored into the style, and can be found and retrieved by using the IDirectMusicStyle8::EnumBand and IDirectMusicStyle8::GetBand methods. Bands can also be obtained from other style files or from band files. Once you have obtained an IDirectMusicBand8 interface, you have access to that band and can substitute it for the default band.

Bands are loaded like other objects. For more information, see Loading Audio Data.

More information about bands is contained in the following topics:

  • Downloading and Unloading Bands
  • Making Band Changes Programmatically
  • Ensuring Timely Band Changes
  • Playing a MIDI File with Custom Instruments


Downloading and Unloading Bands

Before a band can be used, the instruments it references must be downloaded to the performance. This step maps the instruments to performance channels and downloads the DLS data to the synthesizer.

By default, the application is responsible for downloading any band it uses. However, you can turn on automatic downloading of bands.

Downloading a band makes the band available to the performance but does not perform any program changes. Program changes take place in response to messages generated by the segment's band track, which is typically authored into a segment file. For information on how to make program changes at run time, see Making Band Changes Programmatically.

Information about how to implement downloading and unloading of bands is contained in the following topics:

  • Automatically Downloading Bands
  • Manually Downloading Bands
  • Patch Collisions
  • Unloading Bands


Automatically Downloading Bands

When automatic downloading is on, the instruments in the band are downloaded when the segment containing the band is cued. The instruments are automatically unloaded when the segment is stopped, unless another segment using the same instruments is cued to play immediately or is currently playing.

Automatic downloading should be used only when the timing of segment starts is not critical. Repeated loading and unloading of instruments takes time and can cause serious degradation of performance in complex audio environments.

Automatic unloading, which is part of the automatic downloading mechanism, can also lead to undesired results. For example, suppose you play a short secondary segment that changes the instrument on a channel. The instrument is automatically downloaded when the secondary segment starts, replacing the existing instrument. When the secondary segment ends, the instrument is automatically unloaded, with the result that there is no instrument on that channel, and the channel plays silence.

You can turn on automatic downloading of bands in one of the following ways:

  • Call the IDirectMusicPerformance8::SetGlobalParam method for the GUID_PerfAutoDownload parameter. See Setting and Retrieving Global Parameters and the following example.
  • Enable automatic downloading for a single segment by calling the IDirectMusicSegment8::SetParam method for the GUID_Enable_Auto_Download parameter. See Setting and Retrieving Track Parameters.

In the following code example, the global parameter for the performance pPerf is set to enable automatic downloading of bands:

BOOL fAuto = TRUE;
pPerf->SetGlobalParam(GUID_PerfAutoDownload, &fAuto, sizeof(BOOL));


Manually Downloading Bands

You can manually download a band in one of the following ways:

  • Call IDirectMusicSegment8::Download to download the bands and waves in a segment to either an audiopath or a performance.
  • Obtain an IDirectMusicBand8 interface from a loaded object, and call the IDirectMusicBand8::Download method.
  • Call the IDirectMusicSegment8::SetParam method with the GUID_Download or GUID_DownloadToAudioPath parameter to download the band in the segment's first band track. You can also use IDirectMusicPerformance8::SetParam to set this parameter on the primary segment, or IDirectMusicTrack8::SetParamEx to set it directly on a band track. See Setting and Retrieving Track Parameters.

If your application creates audiopaths that use more than one synthesizer, or port, you must download bands to the individual audiopaths, not to the performance. However, most applications use only a single synthesizer, and it is safe to download all instrument data to the performance.

Multiple audiopaths usually share the same synthesizer. When a band is downloaded to an audiopath, the instrument data is downloaded to the port on that audiopath and is then available to any audiopath using the same port. The data does not have to be downloaded to each audiopath.

For example, suppose you have a segment that uses a DLS instrument for the sound of a car engine in a race game. To manipulate the 3-D parameters independently for each car in the race, you play the sound on multiple audiopaths. The instrument has to be downloaded only once.

There is no danger in downloading the same instrument multiple times. If an instrument appears in one band multiple times or if it appears in multiple bands that are all opened and downloaded at the same time, only one copy of the instrument is sent to the synthesizer.

The following function loads a band from disk and downloads it to the performance:

HRESULT myDownloadBand(
    IDirectMusicLoader8 *pILoader,      // Loader interface.
    IDirectMusicBand8 **ppBand,         // To retrieve pointer.
    IDirectMusicPerformance8 *pPerf,    // Performance to use band.
    WCHAR *pwszFile)                    // File to load.
{
    HRESULT hr;
    DMUS_OBJECTDESC Desc;

    // Start by initializing Desc with the file name
    // and GUID for the band object.

    wcscpy(Desc.wszFileName,pwszFile);
    Desc.dwSize = sizeof(Desc);
    Desc.guidClass = CLSID_DirectMusicBand;
    Desc.dwValidData = DMUS_OBJ_CLASS |
            DMUS_OBJ_FILENAME | DMUS_OBJ_FULLPATH;

    hr = pILoader->GetObject(&Desc, IID_IDirectMusicBand8,
            (void **) ppBand);
    if (SUCCEEDED(hr))
    {
        hr = (*ppBand)->Download(pPerf);
    }
    return hr;
}


Patch Collisions

When bands from different segments are downloaded to the same port, instruments in band can overwrite data from a previously downloaded band.

For example, suppose segment A uses a band that assigns a piano to patch number 1, and segment B uses a band that assigns a banjo to the same patch. The application calls IDirectMusicSegment8::Download first for segment A and then for segment B. Even though the bands might be downloaded to different audiopaths, the instrument data is downloaded to the same synthesizer, so any note on a performance channel mapped to patch number 1 will be played by the banjo.

This potential for patch collisions must be taken into account when the content is authored. Different segments should not use different instruments with the same patch number.


Unloading Bands

Bands take up memory, so they should be unloaded when they are no longer in use. If you have enabled automatic downloading of bands, the bands associated with a segment are unloaded automatically when the segment stops. Otherwise, you can manually unload a band in one of the following ways:

  • Call the IDirectMusicSegment8::Unload or IDirectMusicBand8::Unload method for instruments downloaded by the corresponding Download method.
  • Call the IDirectMusicSegment8::SetParam method for the GUID_Unload or GUID_UnloadFromAudioPath parameter to unload the band in the segment's band track. You can also use IDirectMusicPerformance8::SetParam to set this parameter on the primary segment, or IDirectMusicTrack8::SetParamEx to set it directly on a band track. See Setting and Retrieving Track Parameters.

The IDirectMusicPerformance8::CloseDown method also unloads any remaining downloaded instruments.


Making Band Changes Programmatically

Usually, the band track in a loaded segment will perform program changes. However, you can also do so manually.

First create a secondary segment with a call to the IDirectMusicBand8::CreateSegment method, and then play that segment by calling IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx. Typically, you would use DMUS_SEGF_MEASURE or DMUS_SEGF_GRID in the dwFlags parameter to ensure that the band change takes effect on an appropriate boundary.

The following sample function creates a segment from a band and plays it. It is presumed that the instruments have been downloaded or that automatic downloading has been enabled.

HRESULT myPlayBand(
    IDirectMusicBand8 *pBand,          // Pointer to a band object.
    IDirectMusicPerformance8 *pPerf,   // Performance to use the band.
    REFERENCE_TIME rfTime,             // Time to play at.
    DWORD dwFlags)                     // Performance flags.
{
    IDirectMusicSegment *pSegment;

// We don't need IDirectMusicSegment8, which we'd have to QI for.

    HRESULT hr = pBand->CreateSegment(&pSegment);
    if (SUCCEEDED(hr))
    {
        hr = pPerf->PlaySegment(pSegment,
                dwFlags | DMUS_SEGF_SECONDARY,
                rfTime,
                NULL);
        pSegment->Release();
    }
    return hr;
}

A performance can be playing instruments from more than one band at a time. For example, suppose your application is playing a primary segment using one band, and then plays a motif from a style that has a different band. As long as the instruments in the two bands are mapped to different performance channels, no conflict arises. Note, though, that motif segments don't always have their own band tracks, so you might get silence from the motif's channels unless you first create a band segment and play it.


Ensuring Timely Band Changes

A consideration in playing band segments is the randomness in the timing of notes played by a style track. For instance, a note that is on measure 1, beat 1 might actually play somewhat earlier or later than the actual beat boundary. The band segment isn't aware of this, with the result that some of the notes might play with the incorrect instrument.

To prevent this problem, an application should cue the band segment early. Suppose, for example, that you have a style segment pStyleSeg and a band segment pBandSeg. You want to play both the style segment and the band segment on the next measure boundary of the performance (pPerf). You know that the style contains notes that could go out up to 30 ticks earlier, in music time, than the start time of the segment. The following code example ensures that the band segment is played 31 ticks before the style segment, so all instruments are in place before any note is played:

// First get the time of the next measure, and convert it to
// music time.

REFERENCE_TIME rtResolved;
MUSIC_TIME mtResolved;

pPerf->GetResolvedTime( 0, &rtResolved, DMUS_TIME_RESOLVE_MEASURE );
pPerf->ReferenceToMusicTime( rtResolved, &mtResolved );

// Now play the band segment 31 ticks before the measure boundary.

mtResolved -= 31;
pPerf->PlaySegment(pBandSeg, 0, mtResolved, NULL);

// Play the style segment on the measure boundary.

pPerf->PlaySegment(pStyleSeg, DMUS_TIME_RESOLVE_MEASURE, 0, NULL);

Note If there is no randomness in the notes played by a segment (for example, one loaded from a MIDI file), you don't need to worry about the timeliness of a band segment played at the same time. By default, all band segments start 1 tick early.


Playing a MIDI File with Custom Instruments

By default, when you play a MIDI file the instruments used are those in the Roland GM/GS Sound Set, contained in the Gm.dls file. However, you can use instruments from any DLS collection when playing a MIDI file.

First load the collection and retrieve a pointer to the IDirectMusicCollection8 interface.

The following example function loads a collection by file name:

HRESULT LoadCollectionByName(
        IDirectMusicLoader8 *pILoader,
        char *pszFileName,
        IDirectMusicCollection8 **ppICollection)
{
    HRESULT hr;
    DMUS_OBJECTDESC Desc;             // Descriptor.

    // Start by initializing Desc with the file name
    // and GUIDfor the collection object.
    // The file name starts as a char string, so convert
    // to Unicode.

    mbstowcs(Desc.wszFileName,pszFileName,DMUS_MAX_FILENAME);
    Desc.dwSize = sizeof(DMUS_OBJECTDESC);
    Desc.guidClass = CLSID_DirectMusicCollection;
    Desc.dwValidData = DMUS_OBJ_CLASS
            | DMUS_OBJ_FILENAME
            | DMUS_OBJ_FULLPATH;

    hr = pILoader->GetObject(&Desc,
            IID_IDirectMusicCollection8,
            (void **) ppICollection);
    return hr;
}

Next you must connect the DLS data to the segment by calling IDirectMusicSegment8::SetParam.The following code example shows how to make a connection between a segment and a collection returned by the LoadCollectionByName function.

// Assume that pSegment was created from a MIDI file and that
// pLoadedCollection is a valid IDirectMusicCollection8 pointer.

HRESULT hr = pSegment->SetParam(GUID_ConnectToDLSCollection,
        0xFFFFFFFF, 0, 0,
        (void*)pLoadedCollection);

Finally, download the instruments in the collection to the performance or audiopath by calling IDirectMusicSegment8::Download.

When a custom collection is attached to a MIDI segment, the connection to the GM collection is not broken. For example, suppose you load a collection containing a single instrument that has a patch number of 12 and connect this to the segment. MIDI channels with any patch number other than 12 continue to be played by the appropriate instruments in the GM collection.

For more information on collections, see Using Instrument Collections.


Timing

This section is an overview of various timing issues in DirectMusic. The following topics are discussed:

  • Master Clock
  • Clock Time vs. Music Time
  • Changing the Tempo
  • Prepare Time
  • Latency and Bumper Time
  • Segment Timing


Master Clock

To guarantee accurate timing with an acceptably low latency, DirectMusic incorporates a master clock in kernel mode. This clock is based on a hardware timer. DirectMusic automatically selects the system clock as the master clock, but an application can select a different one, such as the wave-out crystal on a sound card.

The master clock is a high-resolution timer that is shared by all processes, devices, and applications that are using DirectMusic. The clock is used to synchronize all audio playback in the system. It is a standard IReferenceClock interface. The IReferenceClock::GetTime method returns the current time as a 64-bit integer (defined as the REFERENCE_TIME type) in increments of 100 nanoseconds.

To obtain an interface to the master clock, call the IDirectMusic8::GetMasterClock method.

You can choose a different master clock for your application, but only if there are no other DirectMusic applications running. First you get descriptions of all devices that can serve as the master clock by using the IDirectMusic8::EnumMasterClock method. Once you have obtained the GUID of the device that you want to use as the master clock, you pass this to the IDirectMusic8::SetMasterClock method.


Clock Time vs. Music Time

In DirectX for C++, the time returned by the master clock is a 64-bit value defined as type REFERENCE_TIME. Reference time is measured in units of approximately 100 nanoseconds, so the clock ticks about 10 million times each second. The value returned by the IReferenceClock::GetTime method is relative to an arbitrary start time.

Music time is a 32-bit value defined as type MUSIC_TIME. It is not an absolute measure of time but is relative to the tempo. The clock is started when the performance is initialized and ticks DMUS_PPQ times for each quarter-note. DMUS_PPQ is defined as 768.

When a performance is initialized, it starts keeping an internal clock. You can retrieve the current performance time in both reference time and music time by using the IDirectMusicPerformance8::GetTime method.

The IDirectMusicPerformance8::AdjustTime method can be used to make small changes to the performance time. Most applications don't need to do this, but it can be useful when synchronizing to another source.

To convert between the two kinds of time in a performance, you can use the IDirectMusicPerformance8::MusicToReferenceTime and IDirectMusicPerformance8::ReferenceToMusicTime methods. These methods convert between time offsets within the performance, taking into account all tempo changes that have taken place since the performance started.

When a segment is cued to play by a call to IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx and the start time is given in reference time, DirectMusic must convert the start time to music time. If no primary segment is currently playing, the conversion is made immediately, based on the current tempo. Otherwise, if another segment is playing, the start time of the cued segment is not converted to music time until the start time has been reached.

If the tempo is changed before the segment starts playing, the actual start time can be affected, or the segment might not start on the desired boundary. In the first case, in which the conversion to music time is done immediately, the start time (in reference time) is advanced if the tempo speeds up and delayed if the tempo slows down. In the second case, in which conversion is made at start time, a change in tempo can mean that the segment does not start at correct resolution boundaries. For example, if the segment is supposed to start on a measure boundary (as indicated in the dwFlags parameter of PlaySegment or PlaySegmentEx), the actual start time (in reference time) is calculated when the segment is cued. However, if the tempo then changes, a measure boundary might not fall at that time.

When a primary segment is played with the DMUS_SEGF_QUEUE flag (see DMUS_SEGF_FLAGS), the i64StartTime parameter is ignored, and the segment is cued to play after any primary segments whose start times have already been converted. If a previously cued segment is still stamped in reference time, that segment will play at its designated time, perhaps interrupting another segment.

For example, say you have three segments, each 10 seconds in length. You cue segment A to play 5 seconds from now. Because no primary segment is currently playing, the start time is immediately converted to music time. At 6 seconds, you cue segment B to play at 20 seconds. In this case, because music is already playing and the tempo might change, the conversion to music time is not made immediately. Then you cue segment C with the DMUS_SEGF_QUEUE flag so that it starts immediately after segment A finishes, at 15 seconds. At 20 seconds, segment B starts playing and interrupts segment C.


Changing the Tempo

The tempo of a performance dictates the conversion between the two types of time used in DirectMusic, which in turn controls the resolution of events to musical boundaries. (See Clock Time vs. Music Time.) The tempo track of the control segment usually manages the tempo, but it is also possible for an application to set the tempo dynamically.

There are two ways to change the tempo: by sending a message and by setting a track parameter on the control segment.

The following code example sends a message to change the tempo:

// Assume that pIDMSegment is a valid IDirectMusicSegment8 and
// IDMPerformance is a valid IDirectMusicPerformance8.

// Disable tempo track in segment so that it does not reset the tempo.

pIDMSegment->SetParam( GUID_DisableTempo, 0xFFFF,0,0, NULL );

DMUS_TEMPO_PMSG* pTempo;

if( SUCCEEDED(pIDMPerformance->AllocPMsg(
        sizeof(DMUS_TEMPO_PMSG), (DMUS_PMSG**)&pTempo)))
{
    // Cue the tempo event.
    ZeroMemory(pTempo, sizeof(DMUS_TEMPO_PMSG));
    pTempo->dwSize = sizeof(DMUS_TEMPO_PMSG);
    pTempo->dblTempo = 100;
    pTempo->dwFlags = DMUS_PMSGF_REFTIME;
    pTempo->dwType = DMUS_PMSGT_TEMPO;
    pIDMPerformance->SendPMsg((DMUS_PMSG*)pTempo);
}

The following example shows how to change the tempo parameter. For more information, see Setting and Retrieving Track Parameters.

DMUS_TEMPO_PARAM Tempo;
Tempo.dblTempo = 100;
pIDMSegment->SetParam(GUID_TempoParam, 0xFFFF, 0, 0, &Tempo);

You can also change the master tempo, which adjusts the tempo set by any control segment. See Setting and Retrieving Global Parameters


Prepare Time

As a segment is played, the performance makes repeated calls to the segment's tracks, causing them to generate messages for the supplied time range, which is some fraction of a second. These messages are then placed in the queue behind those that were generated in previous calls. By default, about a second's worth of messages are in the queue at any given time.

Each time the performance calls on a track to play messages, it calculates the end time for that call by adding the prepare time to the current time. If the current time is 10,000 milliseconds (or the equivalent in REFERENCE_TIME units) and the prepare time is the default 1000 ms, the end time is 11,000—that is, all new messages that are to play up to time 11,000 must be prepared and placed in the queue.

The size of the queue can be changed by calling the IDirectMusicPerformance8::SetPrepareTime method, and the current size can be retrieved by using IDirectMusicPerformance8::GetPrepareTime.

Most applications don't need to change the default prepare time, and the process just described is not visible to the application. However, it is helpful to understand the concept of prepare time because of the DMUS_SEGF_AFTERPREPARETIME flag, which the application can pass to IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx.

Without this flag, if you set a start time of "now" for the segment, the performance invalidates any messages currently in the queue. Any tracks that are still valid at this point—for example, tracks of secondary segments that continue to play despite the introduction of a new primary segment—then have to resend their messages, taking into account any changes made to the environment by the new segment. This causes extra processing and might also lead to undesired results.

You can use the DMUS_SEGF_AFTERPREPARETIME flag to specify that the segment isn't to start playing until all messages currently in the queue have been processed and passed to the port buffer. If messages up to time 10,000 milliseconds (ms) are in the queue and the current time is 9,000 ms, a segment cued to play immediately, but flagged DMUS_SEGF_AFTERPREPARETIME, starts playing just after the 10,000 ms mark.

For more information, see Segment Timing. For an illustration, see Latency and Bumper Time.


Latency and Bumper Time

Latency is the delay between the time at which the port receives a message and the time at which it has synthesized enough of a wave to play. The IDirectMusicPerformance8::GetLatencyTime method retrieves the current time plus the latency for the performance as a whole. This is the largest value returned by any of the ports' latency clocks.

The bumper is an extra amount of time allotted for code to run between the time that an event is put into the port buffer and the time that the port starts to process it. By default, the bumper length is 50 milliseconds. An application can change this value by using the IDirectMusicPerformance8::SetBumperLength method, and retrieve the current value by calling IDirectMusicPerformance8::GetBumperLength.

Here's an example of how latency time and bumper time are combined. Suppose an event is supposed to play at 10,000 milliseconds (ms). The latency of the port is known to be 100 ms, and the bumper length is at its default value of 50 ms. The performance therefore places the message into the port buffer at 9,850 ms.

Any tools that alter the time of messages must take latency and bumper time into account. If a tool stamps a message with a time that is already past the latency time, the note or other event will not play at the correct time.

Once a message has been placed in the port buffer, it no longer belongs to the performance and cannot be stopped from playing by using the IDirectMusicPerformance8::Invalidate method or by stopping the segment. The first message that can be invalidated has a time stamp equal to or greater than the current time plus the latency time and the bumper time. This value can be retrieved by using the IDirectMusicPerformance8::GetQueueTime method.

The following diagram, not to scale, illustrates the relationship of the times and durations retrieved by various methods. The current time is at the left, and the last time for which messages have been prepared is at the right. Remember that prepare time is only an approximation of the total timespan of messages in the queue at any given moment.


Segment Timing

This section covers various aspects of timing in the playing of segments.

To clarify the relationship between times within segments and times within the performance, the following terms are used throughout this section:

Start point
The first point in the segment that can be a segment start time. By default this value is 0, indicating the beginning of the segment. However, it can be changed by the application.
Segment start time
The point in a segment where it begins producing sounds. This time is usually the same as the start point, but can be later if the start point is deliberately aligned to a play time that is in the past.
Play time
The point in the performance where a new segment's start point is cued. In the DirectMusic API, this time is sometimes called start time.
Start marker
A marker indicating a valid start time in a segment.
Play marker
A marker indicating a point in a control segment where another segment's start point can be cued.

Note Start markers and play markers are placed in the segment's marker track by the author and cannot be changed by the application. They can, however, be retrieved by using the GUID_Valid_Start_Time and GUID_Play_Marker parameters.

Segments normally play from the beginning. You can make a segment start from another point by using the IDirectMusicSegment8::SetStartPoint method. The new start point remains valid until changed.

If a repeat count is set by using IDirectMusicSegment8::SetRepeats, the entire segment repeats that number of times, unless a loop has been defined by a call to IDirectMusicSegment8::SetLoopPoints, in which case only the part of the segment between the loop points repeats.

The play time is determined by two parameters of the IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx methods:

  • The i64StartTime parameter sets the earliest time at which the segment can start playing. If i64StartTime is 0, this time is as soon as possible. The actual time at which the segment will start depends on the type of segment. If it is a primary segment or a secondary control segment, the earliest play time is at queue (or flush) time. If it is a noncontrol secondary segment, the earliest play time is at latency time. For more information on queue time and latency time, see Latency and Bumper Time.
  • The dwFlags parameter specifies how soon after the earliest possible play time the segment will actually start playing. Usually, you will want to wait for an appropriate point in the rhythm before introducing a new primary segment, transition, or motif. You control the delay by setting one or more flags from the DMUS_SEGF_FLAGS enumeration.

Aligning a Segment to a Past Time

Rather than forcing the segment start time to the next grid, beat, or measure in the control segment, you might want the segment to start playing sooner, yet still match the rhythm of the current segment. You can make the segment do so by cuing its start point to a rhythmic boundary that has already passed. The rhythm in the cued segment is thus aligned with that in the current segment, and the new segment can start playing immediately.

To cue the segment in the past, use the DMUS_SEGF_ALIGN flag. Add one of DMUS_SEGF_GRID, DMUS_SEGF_BEAT, or DMUS_SEGF_MEASURE to cue the start point of the segment at the appropriate rhythmic boundary. Alternatively, you can use DMUS_SEGF_MARKER to align the start point to the most recently played play marker in the control segment.

Of course, when the start point is in the past, the segment start time has to be adjusted to fall in the present or the future. The performance uses the following rules to determine the segment start time. In all cases, "next" means "next possible"—that is, within the part of the segment that does not fall in the past.

  • If a start marker appears in the cued segment before the next resolution boundary of the specified type, the segment start time falls at that point.
  • If there is no valid start marker, the segment start time is at the next start resolution boundary of the cued segment, as specified by one of the following flags:
    DMUS_SEGF_VALID_START_BEAT
    Put the segment start time on the next beat.
    DMUS_SEGF_VALID_START_GRID
    Put the segment start time on the next grid.
    DMUS_SEGF_VALID_START_TICK
    Put the segment start time at the earliest possible point.
  • If there is no valid start marker and no start resolution flag is supplied, the segment start time is at the next play resolution boundary as specified by the DMUS_SEGF_GRID, DMUS_SEGF_BEAT, or DMUS_SEGF_MEASURE flag. If none of these flags is present, the segment start time is immediate.

Play markers and start markers allow greater flexibility in the cuing of segments, especially motifs. Suppose a motif is designed to sound best when it starts playing at the beginning of a measure in the primary segment. If the motif is cued with the DMUS_SEGF_MEASURE flag, there might be a significant delay before the next measure boundary is reached and the motif plays. But if the DMUS_SEGF_ALIGN flag is added, the motif can start playing sooner without violating the rhythm. Adding the DMUS_SEGF_MARKER flag ensures that the motif plays at an appropriate boundary within the control segment, rather than on just any measure, beat, or grid.

For information on how tempo changes can affect segment start times, see Clock Time vs. Music Time.

The following diagram shows how the timing is determined for a segment cued with the DMUS_SEGF_MEASURE, DMUS_SEGF_ALIGN, and DMUS_SEGF_VALID_START_BEAT flags. The solid vertical lines are measure boundaries, and the dotted lines are beat boundaries. The start point of the segment is aligned with the previous measure boundary in the current primary segment. The segment start time falls at the first beat in the cued segment after the unresolved play time.

Logical Time vs. Actual Time

Some events have both a logical time and an actual time. The actual time is when the event will take place, and the logical time represents the musical position where it belongs.

For example, a segment might contain a program change that belongs to the start of a beat. The logical time is the start of the beat. However, you want to make sure the program change takes place before the note on the beat is played, so you assign it a physical time that's a little earlier.

If the segment loops to the logical time (the start of that same beat), the program change will still go out.


Notification and Event Handling

From time to time, your application may need to respond to a performance event. For example, you might need to know when the end of a segment has been reached, or you might want to synchronize graphics with the beat of the music. You get the desired information by asking DirectMusic to notify you when a certain type of event has taken place.

Note Performance notifications are not to be confused with DirectSound buffer notifications, which are used only by applications that are streaming wave data directly to or from buffers. See Play Buffer Notification and Capture Buffer Notification.

Specify what types of events you want to be notified of by calling the IDirectMusicPerformance8::AddNotificationType method once for each desired type of event. The following code example tells DirectMusic to set segment-related events. The actual type of event, such as a segment start or a segment end, will be derived later from the notification message.

// pPerformance is a valid IDirectMusicPerformance8 pointer.

GUID guid = GUID_NOTIFICATION_SEGMENT;

pPerformance->AddNotificationType(guid);

You can also add notification types for a particular segment by using the IDirectMusicSegment8::AddNotificationType method. You could do this, for example, to receive notification of when a particular segment stops playing. You cannot use this method to request GUID_NOTIFICATION_PERFORMANCE types, because these must come from the performance object.

Note Most applications do not directly call the IDirectMusicTrack8::AddNotificationType method.

Information about notifications is sent in DMUS_NOTIFICATION_PMSG message structures. You can poll for any pending notification messages within the Windows message loop by calling the IDirectMusicPerformance8::GetNotificationPMsg method, or you can have DirectMusic signal an event object in a separate thread when a message is pending.

If you want to be alerted of pending DirectMusic notification messages by a Windows event object, you must first obtain an event handle by calling the Microsoft® Win32® CreateEvent function. Typically, you would create an autoreset event with a call such as the following:

HANDLE g_hNotify = CreateEvent(NULL, FALSE, FALSE, NULL);

After creating the event, assign the handle to the performance by passing it to the IDirectMusicPerformance8::SetNotificationHandle method. You can use the second parameter of this method to specify how long DirectMusic should hold onto the event if it is not retrieved. A value of 0 in this parameter indicates that the default time of 2 seconds is to be used.

In the following example, g_pPerf is a valid pointer to the IDirectMusicPerformance8 interface:

g_pPerf->SetNotificationHandle(g_hNotify, 0);

The following sample function executes repeatedly in its own thread, checking for signaled events and retrieving notification messages:

void WaitForEvent( LPVOID lpv)
{
    DWORD dwResult;
    DMUS_NOTIFICATION_PMSG* pPmsg;
    char szCount[4];

    while (TRUE)
    {
        dwResult = WaitForSingleObject(g_hNotify, 100);
        while (S_OK == g_pPerf->GetNotificationPMsg(&pPmsg))
        {
            // Check notification type and do something in response.
            .
            .
            .
            g_pPerf->FreePMsg((DMUS_PMSG*)pPmsg);
        }
    }
}

This thread is executed as follows:

_beginthread(WaitForEvent, 0, NULL);

When notifications are no longer needed, the following code shuts down the thread, removes the notification handle from the performance, and destroys the event object:

_endthread();
g_pPerf->SetNotificationHandle(0, 0);
CloseHandle(g_hNotify);

It isn't necessary to create an event in order to retrieve notification messages in your application's message loop. As long as you have requested notifications by calling one of the AddNotificationType methods, the performance sends messages that can be retrieved by calling IDirectMusicPerformance8::GetNotificationPMsg.

More than one message might be waiting when an event is signaled or when you call GetNotificationPMsg in the message loop. To be sure of catching all notifications, call GetNotificationPMsg repeatedly until it returns S_FALSE.

Multiple messages with the same time stamp are not queued in any particular order.

It is the application's responsibility to free any messages it retrieves, by calling the IDirectMusicPerformance8::FreePMsg method.


Performance Parameters

DirectMusic lets you control many aspects of track behavior by changing parameters during playback, using one of the following SetParam methods:

  • IDirectMusicPerformance8::SetParam sets data on a specific track within the current control segment of the performance. The control segment is normally the primary segment, but a secondary segment can be designated as the control segment when it is played. See Control Segments.
  • IDirectMusicSegment8::SetParam sets data on a specific track within the segment.
  • IDirectMusicTrack8::SetParam and IDirectMusicTrack8::SetParamEx set data on the track represented by the interface. Applications do not normally have interfaces to individual tracks.

The IDirectMusicPerformance8::SetGlobalParam method enables you to set values that apply across the entire performance.

The equivalent GetParam and GetGlobalParam methods retrieve current values for a track or the performance.

To have the music respond immediately to a changed parameter, an application can flush messages from the queue by using the IDirectMusicPerformance8::Invalidate method. This method causes all tracks to resend messages from the specified point forward.

More information about parameters is contained in the following topics:

  • Setting and Retrieving Track Parameters
  • Disabling and Enabling Track Parameters
  • Setting and Retrieving Global Parameters


Setting and Retrieving Track Parameters

The following methods are used for setting and retrieving track parameters:

  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParam
  • IDirectMusicTrack8::SetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParamEx

When calling one of these methods on the performance or segment, you can identify the track by setting the dwGroupBits and dwIndex parameters. Usually, however, you can let DirectMusic find the appropriate track for you. For more information, see Identifying the Track.

The track parameter that is being set or retrieved is identified by a GUID in the rguidType parameter of the method. Each parameter that requires data is associated with a particular data type, and pParam must point to a variable or structure of this type. In some cases, part of the data structure must be initialized even when retrieving the parameter. For some parameters, you must also specify the time within the track at which the change is to take effect or for which the parameter is to be retrieved.

For reference information on the data associated with the standard parameter types, see Standard Track Parameters.

Some parameter changes might not appear to take effect immediately. For example, changing the groove level does not make a difference until the current pattern is about to finish playing and the next pattern is chosen. If you want the change to take effect sooner, you can force the current pattern to be discarded by calling the IDirectMusicPerformance8::Invalidate method.

To determine whether a particular parameter is supported by a track, use the IDirectMusicTrack8::IsParamSupported method and check for an S_OK result.

More information is given in the following topic:

  • Identifying the Track


Identifying the Track

When you set or retrieve a parameter by using IDirectMusicTrack8::SetParamEx or IDirectMusicTrack8::GetParamEx, the parameter is associated with the track on which the method is called. However, when you call IDirectMusicPerformance8::SetParam, IDirectMusicPerformance8::GetParam, IDirectMusicSegment8::SetParam, or IDirectMusicSegment8::GetParam, DirectMusic needs to find the appropriate track.

Normally, you can let DirectMusic determine which track contains the desired parameter. To do this, set dwGroupBits to 0xFFFFFFFF and dwIndex to DMUS_SEG_ANYTRACK or DMUS_SEG_ALLTRACKS. For example, the following call to IDirectMusicSegment8::SetParam turns off the tempo track so that looping a segment does not reset the tempo:

pIDMSegment->SetParam(GUID_DisableTempo, 0xFFFFFFFF,
    DMUS_SEG_ALLTRACKS, 0, NULL);

There are times, however, when you need to identify a track. Typically, this would be the case when a segment contains multiple tracks of the same type. To set or retrieve the parameter on the desired track, you must identify it by group and index value.

Every track belongs to one or more groups, each group being represented by a bit in the dwGroupBits parameter of one of the methods under discussion. The track is assigned to a group or groups when it is inserted in the performance. See IDirectMusicSegment8::InsertTrack. In the case of segments loaded from a file, track groups are assigned by the author of the segment.

A track is identified by a zero-based index value within each of the groups it belongs to. The index value is determined by the order in which the tracks were inserted.

Suppose a segment contains the tracks shown in the following table.

Track | Group Bits
A | 0x1
B | 0x2
C | 0x1
D | 0x3

Group 1 contains tracks A, C, and D, and group 2 contains tracks B and D. If you call the set or get method with a value of 1 in dwGroupBits and a value of 0 in dwIndex, the parameter is retrieved from track A, which is the first track in group 1. If dwIndex is 1, the parameter is retrieved from track C, the second track in the group. Track D belongs to two groups, 1 and 2, so it can be identified as either dwGroupBits = 1 and dwIndex =2, or dwGroupBits = 2 and dwIndex = 1.

If you set more than 1 bit in dwGroupBits, the parameter is retrieved from the nth track containing any of those bits, where n is the value in dwIndex.


Disabling and Enabling Track Parameters

By setting the GUID_DisableTempo and GUID_DisableTimeSig parameters on a track, you can disable the setting of tempo and time signature by a control segment. You might want to do this, for example, when you have set the tempo dynamically and don't want the primary segment to send tempo messages.

To re-enable the parameter, call one of the set-parameter methods with GUID_EnableTempo or GUID_EnableTimeSig as the rguidType parameter. You can also set these parameters to force a segment to send tempo messages even though it isn't the control segment, or to cause a secondary segment to send time signature messages. For more information, see Control Segments.

For more information on how to set a parameter, see Setting and Retrieving Track Parameters.

See also the Remarks for IDirectMusicTrack8::IsParamSupported.

It is also possible to disable and enable any track parameter by setting the configuration flags on the track. For more information, see Track Configuration.


Setting and Retrieving Global Parameters

By using the IDirectMusicPerformance8::SetGlobalParam and IDirectMusicPerformance8::GetGlobalParam methods, you can set and retrieve parameters that affect the entire performance rather than a single track.

The parameter to be set or retrieved is identified by a GUID in the rguidType parameter of the method. Each parameter is associated with a particular data type, whose size is given in the dwSize parameter. The predefined GUIDs and their data types are shown in the following table.

Parameter type GUID (rguidType) and Data (*pParam) | Description
GUID_PerfAutoDownload BOOL | This parameter controls whether instruments are automatically downloaded when a segment is played. By default, it is off. See Downloading and Unloading Bands.
GUID_PerfMasterGrooveLevel char | The master groove level is a value that is always added to the groove level established by the command track. The resulting value is adjusted, if necessary, to fall within the range from 1 through 100.
GUID_PerfMasterTempo float | The master tempo is a scaling factor applied to the tempo by the final output tool. By default, it is 1. A value of 0.5 would halve the tempo, and a value of 2.0 would double it. This value can be set in the range from DMUS_MASTERTEMPO_MIN through DMUS_MASTERTEMPO_MAX.
GUID_PerfMasterVolume long | The master volume is an amplification or attenuation factor, in hundredths of a decibel, applied to the default volume of the entire performance and any other performances using the same synthesizer. The range of permitted values is determined by the port. For the default software synthesizer, the allowed range is +20db to -200dB, but the useful range is +10db to -100db. Hardware MIDI ports do not support changing master volume.

Applications can also use custom types of global parameters. To create a new type, establish a GUID and a data type for it.

When a parameter is set, the performance allocates memory for the data in a linked list of items identified by GUID. The data can be retrieved by a call to IDirectMusicPerformance8::GetGlobalParam.

Note Even predefined parameters have to be set before they can be retrieved. GetGlobalParam fails if SetGlobalParam has never been called on the parameter.


Using Audiopaths

A DirectMusic performance contains one or more audiopaths, which manage the flow of sound data through various objects. An audiopath might include the performance itself, a segment, toolgraphs, the synthesizer, DirectSound buffers, effects DMOs, and the primary DirectSound buffer where the final mixing is done.

If your application does nothing more complicated than playing 2-D sound effects or MIDI files, you can set up a standard default audiopath and play everything on it. But to take advantage of the full power of DirectX Audio you must be able to take control of the audiopath.

This section is a guide to creating audiopaths, playing segments on them, and accessing objects within them. The following topics are covered:

  • Migrating from Ports to Audiopaths
  • Creating Audiopaths
  • Default Audiopath
  • Standard Audiopaths
  • Playing Sounds on Audiopaths
  • Retrieving Objects from an Audiopath


Migrating from Ports to Audiopaths

If you have written applications using versions of DirectMusic prior to DirectX 8.0, you will find that the recommended way of creating a route for audio output has changed. You can still use DirectMusic the old way, but in order to take advantage of features such as effects processing, individual control of segment states, and custom audiopath configurations in DirectMusic Producer segments, you must do things in a new way.

Important differences between the old and new models for audio output include the following:

  • Applications no longer deal directly with ports. DirectMusic handles the creation of the port and the mapping of performance channels. The IDirectMusicPerformance8::Init, IDirectMusicPerformance8::AddPort, IDirectMusicPerformance8::AssignPChannel and IDirectMusicPerformance8::AssignPChannelBlock methods are not used in the audiopath model.
  • To play sounds through a 3-D buffer, an application no longer needs to create the buffer explicitly and assign it to a port by using IDirectMusicPort8::SetDirectSound. The buffer is now created as part of the audiopath, and the application obtains access to it by using one of the GetObjectInPath methods.
  • Deactivating an audiopath has a different effect than deactivating a port. When an port is deactivated, it no longer produces sound, but the performance can continue playing segments. When an audiopath is deactivated, all playback on that audiopath stops and any attempt to play a segment on it will fail.


Creating Audiopaths

Applications can set up audiopaths in the following ways:

  • Create one or more standard audiopaths by using IDirectMusicPerformance8::CreateStandardAudioPath. See Standard Audiopaths.
  • Create a default standard audiopath for the performance in the call to IDirectMusicPerformance8::InitAudio. See Default Audiopath.
  • Obtain an audiopath configuration from a file authored in DirectMusic Producer and pass the configuration object to IDirectMusicPerformance8::CreateAudioPath.
  • Have DirectMusic create an audiopath from the segment's audiopath configuration when the segment is played. Audiopaths created in this way are temporary and not visible to the application.

An audiopath configuration object can be loaded just like any other object, by using IDirectMusicLoader8::GetObject or IDirectMusicLoader8::LoadObjectFromFile. A configuration embedded in a segment can be retrieved by using IDirectMusicSegment8::GetAudioPathConfig.

The audiopath configuration object does not have a unique interface or methods, and your application cannot change the configuration in any way. All you can do with the object is pass it, by its IUnknown interface, to IDirectMusicPerformance8::CreateAudioPath. For sample code, see Playing Sounds on Audiopaths.

Audiopath configurations are the only means of creating nonstandard audiopaths. For instance, if different performance channels are to be routed to different buffers, this mapping must be specified in the audiopath configuration of a segment.


Default Audiopath

The default audiopath is the one used when a segment is played by using IDirectMusicPerformance8::PlaySegment, or when no audiopath is specified in a call to IDirectMusicPerformance8::PlaySegmentEx.

You can create an audiopath and make it the default by specifying a standard type in the dwDefaultPathType parameter of IDirectMusicPerformance8::InitAudio.

Any existing audiopath can be made the default audiopath by passing it to IDirectMusicPerformance8::SetDefaultAudioPath. Retrieve the default audiopath by using IDirectMusicPerformance8::GetDefaultAudioPath.


Standard Audiopaths

If your application does not play exclusively on audiopaths created from audiopath configuration objects, you must create one or more standard audiopaths.

Standard audiopaths are identified by the values passed in the dwType parameter of IDirectMusicPerformance8::CreateStandardAudioPath or in the dwDefaultPathType parameter of IDirectMusicPerformance8::InitAudio.

The audiopaths defined by DirectMusic manage the flow of synthesizer output through combinations of standard buffers, some of which have effect DMOs attached to them. The following table shows the standard audiopaths and which standard buffers they contain. Shared buffers can be used by more than one audiopath.

Audiopath Type | Standard Buffers | Buffer Shared?
DMUS_APATH_DYNAMIC_3D | 3-D Dry | No
DMUS_APATH_DYNAMIC_MONO | Mono | No
DMUS_APATH_DYNAMIC_STEREO | Stereo | No
DMUS_APATH_SHARED_STEREOPLUSREVERB | Stereo Reverb | Yes Yes

Characteristics of the standard buffers are shown in the following table, where the Capabilities column lists values returned in the dwFlags member of the DSBCAPS structure passed to IDirectSoundBuffer8::GetCaps. The last column shows interfaces that can always be obtained from the buffer object. In addition, applications can add effects to buffers by using IDirectSoundBuffer8::SetFX, in which case other interfaces will be available. IDirectSoundBuffer8 is available for all buffers. For more information on obtaining interfaces, see Retrieving Objects from an Audiopath.

Standard Buffer | Description | Capabilities | Interfaces
3-D Dry | Mono 3-D buffer | DSBCAPS_CTRL3D DSBCAPS_CTRLFX DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS DSBCAPS_MUTE3DATMAXDISTANCE | IDirectSound3DBuffer8
Mono | Mono buffer with no effects | DSBCAPS_CTRLFX DSBCAPS_CTRLPAN DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS | None.
Reverb | Stereo buffer with music reverberation effect | DSBCAPS_CTRLFX DSBCAPS_CTRLPAN DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS | IDirectSoundFXWavesReverb8
Stereo | Stereo buffer with no effects | DSBCAPS_CTRLFX DSBCAPS_CTRLPAN DSBCAPS_CTRLVOLUME DSBCAPS_GLOBALFOCUS | None.

More information about the standard audiopaths is available in the following topics:

  • DMUS_APATH_DYNAMIC_3D
  • DMUS_APATH_DYNAMIC_MONO
  • DMUS_APATH_DYNAMIC_STEREO
  • DMUS_APATH_SHARED_STEREOPLUSREVERB


DMUS_APATH_DYNAMIC_3D

Sets up a nonshared buffer of type 3-D Dry.

Applications can obtain an interface to the 3-D Dry buffer by calling one of the GetObjectInPath methods with dwStage set to DMUS_PATH_BUFFER and dwBuffer set to 0.


DMUS_APATH_DYNAMIC_MONO

Sets up a nonshared buffer of type Mono that has no 3-D parameters or special effects.

Applications can obtain an interface to the buffer by calling one of the GetObjectInPath methods with dwStage set to DMUS_PATH_BUFFER and dwBuffer set to 0.


DMUS_APATH_DYNAMIC_STEREO

Sets up a nonshared buffer of type Stereo. This audiopath is intended for sound effects on stereo buffers. No reverberation is available.

Applications can obtain an interface to the buffer by calling one of the GetObjectInPath methods with dwStage set to DMUS_PATH_BUFFER and dwBuffer set to 0.


DMUS_APATH_SHARED_STEREOPLUSREVERB

Sets up buffers of type Reverb and Stereo.

The Stereo buffer is shared among multiple audiopaths. It is a sink-in buffer, meaning that it accepts data directly from the synthesizer, not from other buffers.

Applications can obtain an interface to the Stereo buffer by calling one of the GetObjectInPath methods with dwStage set to DMUS_PATH_BUFFER and dwBuffer set to 0.

The Reverb buffer is also a shared sink-in buffer. Unlike the Stereo buffer, it accepts a mono input from the synthesizer and converts the data to stereo format.

Applications can obtain an interface to the Reverb buffer by calling one of the GetObjectInPath methods with dwStage set to DMUS_PATH_BUFFER and dwBuffer set to 1.

The following sample code, where g_pPerf is an IDirectMusicPerformance8interface, retrieves an IDirectSoundFXWavesReverb8 interface to the DMO in the Reverb buffer on a default DMUS_APATH_SHARED_STEREOPLUSREVERB audiopath:

IDirectMusicAudioPath8 * pAudioPath;
IDirectSoundFXWavesReverb8 * pEffectDMO;
HRESULT hr;

hr = g_pPerf->GetDefaultAudioPath(&pAudioPath);
if (SUCCEEDED(hr))
{
  HRESULT hr = pAudioPath->GetObjectInPath(DMUS_PCHANNEL_ALL,
        DMUS_PATH_BUFFER_DMO, 1,
        GUID_All_Objects, 0, IID_IDirectSoundFXWavesReverb8,
        (LPVOID*) &pEffectDMO);
}


Playing Sounds on Audiopaths

If your application has created a default audiopath in the call to IDirectMusicPerformance8::InitAudio, you can play a segment on this path by using IDirectMusicPerformance8::PlaySegment. You can also play a segment on the default path by passing NULL in the pAudioPath parameter of IDirectMusicPerformance8::PlaySegmentEx.

If there is no default audiopath, or if you want to play a segment on another path, you must use PlaySegmentEx rather than PlaySegment. You can specify the audiopath in two ways:

  • Supply a pointer in the pAudioPath parameter. Usually this is the IDirectMusicAudioPath8 interface pointer you received when the audiopath was created.
  • Include DMUS_SEGF_USE_AUDIOPATH in dwFlags. This flag causes the segment to create an audiopath from a configuration embedded in the segment object.

Note An audiopath created in response to the DMUS_SEGF_USE_AUDIOPATH flag is automatically released as soon as the segment has stopped playing. If the audiopath contains an effect such as reverberation, the effect is cut short prematurely. To prevent this from happening, the application should create the audiopath manually and release it only after a suitable delay.

Bands are not downloaded for segments played with the DMUS_SEGF_USE_AUDIOPATH flag unless automatic downloading is enabled. For more information, see Automatically Downloading Bands.

The following sample code, where g_pPerf is an IDirectMusicPerformance8 interface pointer and g_pSeg is an IDirectMusicSegment8 interface to any type of sound file, plays the segment on an embedded audiopath configuration if one is available, or on the default audiopath otherwise:

IDirectMusicAudioPath8 * pPath =  NULL;
IUnknown *pConfig;

if (g_pSeg)
{
  if (SUCCEEDED(g_pSeg->GetAudioPathConfig(&pConfig)))
  {
    g_pPerf->CreateAudioPath(pConfig, TRUE, &pPath);
    pConfig->Release();
  }
  g_pPerf->PlaySegmentEx(g_pSeg, NULL, NULL, 0, 0, NULL,
      NULL, pPath);
  if (pPath)
  {
      pPath->Release();
      pPath = NULL;
  }
}

If you have an interface to the audiopath, you can change the volume by using IDirectMusicAudioPath8::SetVolume. Unlike the global parameter GUID_PerfMasterVolume, which affects all sounds playing on the synthesizer, this method sets the volume only on the performance channels playing on this audiopath.


Retrieving Objects from an Audiopath

It is often necessary to retrieve an interface to a particular object within the audiopath. Common reasons to do so include the following:

  • To manipulate the 3-D properties of sounds by obtaining an IDirectSound3DBuffer8 interface.
  • To set global 3-D sound properties by obtaining an IDirectSound3DListener8 interface from the primary buffer.
  • To set effects on a secondary buffer by obtaining the IDirectSoundBuffer8 interface.
  • To set effect parameters by obtaining an interface to a DMO such as IDirectSoundFXI3DL2Reverb8.

Objects can be retrieved from an audiopath by calling IDirectMusicSegmentState8::GetObjectInPath on the segment state that is playing on the audiopath. You can also call IDirectMusicAudioPath8::GetObjectInPath on the audiopath object itself. The following table gives information about the parameters to these two methods.

dwStage | guidObject | dwPChannel used? | dwIndex used? | iidInterface (typical)
DMUS_PATH_AUDIOPATH (*) | Ignored | No | No | IID_IDirectMusicAudioPath8
DMUS_PATH_AUDIOPATH_GRAPH | Ignored | No | No | IID_IDirectMusicGraph8
DMUS_PATH_AUDIOPATH_TOOL | Tool class ID or GUID_All_Objects to enumerate | Yes | Yes | IID_IDirectMusicTool8
DMUS_PATH_BUFFER | Ignored | Yes | No, identify by dwBuffer | IID_IDirectSoundBuffer8
DMUS_PATH_BUFFER_DMO | DMO class ID, such as GUID_DSFX_STANDARD_GARGLE, or GUID_All_Objects to enumerate | Yes | Yes; index of DMO within buffer | GUID for standard DMO interface, such as IID_IDirectSoundFXGargle(**)
DMUS_PATH_MIXIN_BUFFER | Ignored | No | No, identify by dwBuffer | IID_IDirectSoundBuffer8
DMUS_PATH_MIXIN_BUFFER_DMO | DMO class ID, such as GUID_DSFX_STANDARD_I3DL2REVERB, or GUID_All_Objects to enumerate | No | Yes; index of DMO within buffer | GUID for standard DMO interface, such as IID_IDirectSoundFXI3DL2Reverb(**)
DMUS_PATH_PERFORMANCE | Ignored | No | No | IID_IDirectMusicPerformance8
DMUS_PATH_PERFORMANCE_GRAPH | Ignored | No | No | IID_IDirectMusicGraph8
DMUS_PATH_PERFORMANCE_TOOL | Tool class ID or GUID_All_Objects to enumerate | Yes | Yes | IID_IDirectMusicTool8
DMUS_PATH_PORT | Port class ID or GUID_All_Objects to enumerate | Yes | Yes | IID_IDirectMusicPort
DMUS_PATH_PRIMARY_BUFFER | Ignored | No | No | IID_IDirectSound3DListener8
DMUS_PATH_SEGMENT (*) | Ignored | No | No | IID_IDirectMusicSegment8
DMUS_PATH_SEGMENT_GRAPH (*) | Ignored | No | No | IID_IDirectMusicGraph8
DMUS_PATH_SEGMENT_TOOL (*) | Tool class ID or GUID_All_Objects to enumerate | Yes | Yes | IID_IDirectMusicTool8
DMUS_PATH_SEGMENT_TRACK (*) | Track class ID or GUID_All_Objects to enumerate | No | Yes | IID_IDirectMusicTrack8

Notes (*) Objects in this stage cannot be retrieved by IDirectMusicAudioPath8::GetObjectInPath.

(**) The standard DMOs provided with DirectX also support the IMediaObject, IMediaObjectInPlace, and IMediaParams interfaces. For information on these interfaces, see the DirectShow documentation.

For more information on the values for dwIndex when retrieving standard buffers, see Standard Audiopaths.

If you already have an interface to an effects buffer, it is also possible to retrieve a DMO interface by using IDirectSoundBuffer8::GetObjectInPath.

You can retrieve an IDirectSoundBuffer8 interface for any buffer in the audiopath, but some methods are not valid. For more information, see IDirectSoundBuffer8.


3-D Sound

Using DirectX Audio, you can locate sounds in space and can apply Doppler shift to moving sounds.

3-D effects are applied to individual DirectSound buffers. Because you can direct different sounds along different audiopaths, each with its own buffer, it's easy to apply different parameters to different sounds.

The following topics cover some general aspects of 3-D sound:

  • Coordinates of 3-D Space
  • Perception of Sound Positions

Information on how to use 3-D sound in an application is found in the following sections:

  • DirectSound 3-D Buffers
  • DirectSound 3-D Listeners


Coordinates of 3-D Space

The position, velocity, and orientation of sound sources and listeners in 3-D space are represented by Cartesian coordinates, which are values on three axes: the x-axis, the y-axis, and the z-axis. The axes are relative to a viewpoint established by the application. Values on the x-axis increase from left to right, on the y-axis from down to up, and on the z-axis from near to far.

The D3DVECTOR structure contains values describing position, velocity, or orientation on the three axes.

Conventionally, vectors are expressed as three values enclosed in parentheses and separated by commas, in the order (x, y, z).

For position, the values are in meters by default. If your application does not use the meter as its unit of measure for 3-D graphics, you can set a distance factor, which is a floating-point value representing meters per application-specified distance unit. For example, if your application uses feet, it could specify a distance factor of .3048, which is the number of meters in a foot. For more information, see Distance Factor.

For velocity, the vector describes the rate of movement along each axis in units per second. Again, the default unit is meters, but this can be changed by the application.

For orientation, the values are in arbitrary units and are relative to one another. If the base view of the 3-D world is facing north, level to the ground, and the orientation of the listener is (1, 0, 0)—that is, positive on the x-axis and neutral on the other two axes—then the listener is facing due east. If the vector is (1, 0, 1), the listener's orientation is to the northeast. If it is (-1, 0, 1) the listener is facing northwest. Since the values within a vector are not in absolute units, the last example could equally well be expressed as (-5, 0, 5) or (-0.25, 0, 0.25).

You can see how vectors in 2-D space work by drawing them on a sheet of graph paper. Let the values increase from the bottom of the paper to the top and from left to right. A line drawn from (0, 0) to (1, 1) has the same orientation, or direction, as one drawn from (0, 0), to (5, 5). However, the second line indicates a greater distance, or velocity. 3-D vectors work in just the same way, with an additional axis.


Perception of Sound Positions

In the real world, the perception of a sound's position in space is influenced by several factors. Not all of these factors are acoustical; one of the most important is sight. Clues from the sounds themselves include the following:

  • Overall loudness. As a sound source moves away from the listener, its perceived volume decreases at a fixed rate. This phenomenon is known as rolloff.
  • Interaural intensity difference. A sound coming from the listener's right sounds louder in the right ear than in the left.
  • Interaural time difference. A sound emitted by a source to the listener's right will arrive at the right ear slightly before it arrives at the left ear. The duration of this offset is approximately a millisecond.
  • Muffling. The shape and orientation of the ears ensures that sounds coming from behind the listener are slightly muffled compared with sounds coming from in front. In addition, if a sound is coming from the right, the sound reaching the left ear will be muffled by the mass of the listener's head as well as by the orientation of the left ear.

Although these are not the only cues people use to discern the position of sound, they are the main ones, and they are the factors that have been implemented in the positioning system of DirectX Audio. Hardware optimized for 3-D sound can support other cues as well, such as the effect of the earlobes on the pitch and timing of sounds arriving from different directions. The mathematics behind this effect are known as the head-related transfer function (HRTF).

In most cases, DirectSound creates virtual 3-D effects on two speakers or a set of headphones. However, it will also take advantage of four-channel systems with WDM drivers if the user has selected the surround sound speaker configuration in Control Panel. For more information, see DSBUFFERDESC.


DirectSound 3-D Buffers

Each sound source in a 3-D environment is represented by an IDirectSound3DBuffer8 interface. This interface is supported only by sound buffers created with the DSBCAPS_CTRL3D flag. Methods of the interface are used to set and retrieve parameters of a single sound source.

Applications must supply monaural sound sources when using the 3-D capabilities of DirectSound. If you attempt to create a buffer with the DSBCAPS_CTRL3D flag set and a wave format with more than one channel, an error results.

This section describes how your applications can obtain and manage 3-D buffer objects.The following topics are discussed:

  • Obtaining the 3-D Buffer Object
  • Batch Parameters for 3-D Buffers
  • Minimum and Maximum Distances
  • Processing Mode
  • Buffer Position and Velocity
  • Sound Cones


Obtaining the 3-D Buffer Object

The IDirectSound3DBuffer8 interface is obtained from a secondary DirectSound buffer that has been created with the DSBCAPS_CTRL3D flag in the dwFlags member of the DSBUFFERDESC structure.

If your application is using the DirectMusic performance and audiopaths, you can create an audiopath containing a 3-D buffer by passing DMUS_APATH_DYNAMIC_3D as the dwType parameter to IDirectMusicPerformance8::CreateStandardAudioPath.

You can also create a suitable audiopath from a configuration object. An audiopath configuration can specify 3-D parameters for a buffer. When the audiopath is created, the 3-D properties of the buffer are initialized with these parameters.

To obtain an interface to a 3-D buffer in an audiopath, call IDirectMusicAudioPath8::GetObjectInPath or IDirectMusicSegmentState8::GetObjectInPath, with dwStage set to DMUS_PATH_BUFFER.

The following sample code creates a standard audio path and retrieves an IDirectSound3DBuffer8 interface:

HRESULT                  hr;
IDirectMusicAudioPath8*  g_p3DAudioPath;
IDirectSound3DBuffer8*   g_pDS3DBuffer;

if (FAILED(hr = pPerformance->CreateStandardAudioPath(
        DMUS_APATH_DYNAMIC_3D, 64, TRUE, &g_p3DAudioPath)))
    return hr;

if (FAILED(hr = g_p3DAudioPath->GetObjectInPath(
        DMUS_PCHANNEL_ALL, DMUS_PATH_BUFFER, 0,
        GUID_NULL, 0, IID_IDirectSound3DBuffer8,
        (LPVOID*) &g_pDS3DBuffer)))
    return hr;

If your application is creating and managing its own DirectSound secondary buffers without using the DirectMusic performance, you can retrieve the IDirectSound3DBuffer8 interface by calling the IDirectSoundBuffer8::QueryInterface method on the buffer, as in the following sample code:

// Assume that lpDsbSecondary is a valid IDirectSoundBuffer8
// that has been created with DSBCAPS_CTRL3D.

LPDIRECTSOUND3DBUFFER8 lpDs3dBuffer;

HRESULT hr = lpDsbSecondary->QueryInterface(IID_IDirectSound3DBuffer8,
                                            (LPVOID *)&lpDs3dBuffer);


Batch Parameters for 3-D Buffers

Applications can retrieve or set a 3-D sound buffer's parameters individually or in batches. To set individual values, your application can use the applicable IDirectSound3DBuffer8 interface method. However, applications often must set or retrieve all the values at once. You can do this with the IDirectSound3DBuffer8::GetAllParameters and IDirectSound3DBuffer8::SetAllParameters methods.

Parameter changes can also be made more efficiently by flagging them as deferred and then executing them all at once. For more information, see Deferred Settings.


Minimum and Maximum Distances

As a listener approaches a sound source, the sound gets louder; the volume doubles when the distance is halved. Past a certain point, however, it is not reasonable for the volume to continue to increase. This is the minimum distance for the sound source.

The minimum distance is especially useful when an application must compensate for the difference in absolute volume levels of different sounds. Although a jet engine is much louder than a bee, for practical reasons these sounds must be recorded at similar absolute volumes. An application might use a minimum distance of 100 meters for the jet engine and 2 centimeters for the bee. With these settings, the jet engine would be at half volume when the listener was 200 meters away, but the bee would be at half volume when the listener was 4 centimeters away.

The default minimum distance for a sound buffer, DS3D_DEFAULTMINDISTANCE, is defined as 1 unit, or 1 meter at the default distance factor. Unless you change this value, the sound is at full volume when it is 1 meter away from the listener, half as loud at 2 meters, a quarter as loud at 4 meters, and so on. For most sounds you will probably want to set a larger minimum distance so that the sound does not fade so rapidly as it moves away.

The maximum distance for a sound source is the distance beyond which the sound does not get any quieter. The default maximum distance for a DirectSound 3-D buffer (DS3D_DEFAULTMAXDISTANCE) is 1 billion, meaning that in most cases the attenuation will continue to be calculated long after the sound has moved out of hearing range. To avoid unnecessary processing, applications should set a reasonable maximum distance and include the DSBCAPS_MUTE3DATMAXDISTANCE flag when creating the buffer. This flag is automatically set on standard 3-D buffers created as part of an audiopath; see Standard Audiopaths.

The maximum distance can also be used to prevent a sound from becoming inaudible. For example, if you have set the minimum distance for a sound at 100 meters, that sound might become effectively inaudible at 1,000 meters or less. By setting the maximum distance at 800 meters, you ensure that the sound always has at least one-eighth of its maximum volume regardless of the distance. In this case, of course, you would not set the DSBCAPS_MUTE3DATMAXDISTANCE flag.

The following illustration shows how minimum and maximum distance affect the loudness of a jet and a bee at increasing distances.

An application sets and retrieves the minimum distance value by using the IDirectSound3DBuffer8::SetMinDistance and IDirectSound3DBuffer8::GetMinDistance methods. Similarly, it can set and retrieve the maximum distance value by using the IDirectSound3DBuffer8::SetMaxDistance and IDirectSound3DBuffer8::GetMaxDistance methods.

By default, distance values are expressed in meters. See Distance Factor.

To adjust the effect of distance on volume for all sound buffers, you can change the Rolloff Factor.


Processing Mode

Sound buffers have three processing modes: normal, head-relative, and disabled.

In normal mode, the sound source is positioned and oriented absolutely in world space. This is the default mode.

In head-relative mode, the buffer is automatically repositioned in world space as the listener moves and turns. Values set and retrieved through methods such as IDirectSound3DBuffer8::SetPosition, IDirectSound3DBuffer8::SetVelocity, and IDirectSound3DBuffer8::GetConeOrientation are all relative to the current position, velocity, and orientation of the listener.

In disabled mode, 3-D sound processing is disabled and the sound seems to originate from the center of the listener's head.

An application sets the mode for a 3-D sound buffer by using the IDirectSound3DBuffer8::SetMode method.


Buffer Position and Velocity

3-D sounds have position and velocity. It is entirely up to the application to specify values for both.

Position is expressed as a vector, relative to either world space or the listener, depending on the processing mode.

Velocity is measured in distance units per second—by default, meters per second. Velocity is used only in calculating the effects of Doppler shift and does not have to correspond to the actual rate of movement of the sound source.

An application can set and retrieve a sound source's position in 3-D space by using the IDirectSound3DBuffer8::SetPosition and IDirectSound3DBuffer8::GetPosition methods.

To set or retrieve the velocity, use the IDirectSound3DBuffer8::SetVelocity and IDirectSound3DBuffer8::GetVelocity methods.


Sound Cones

A sound with no orientation has the same amplitude at a given distance in all directions. A sound with an orientation is loudest in the direction of orientation. The model that describes the loudness of the oriented sound is called a sound cone. Sound cones are made up of an inside (or inner) cone and an outside (or outer) cone.

At any angle within the inner cone, the volume of the sound is just what it would be if there were no cone, after taking into account the basic volume of the buffer, the distance from the listener, the listener's orientation, and so on.

At any angle outside the outer cone, the normal volume is attenuated by a factor set by the application. The outside cone volume is expressed in hundredths of decibels and is a negative value, because it represents attenuation from the default volume of 0.

Between the inner and outer cones is a zone of transition from the inside volume to the outside volume. The volume decreases as the angle increases.

The following illustration shows the concept of sound cones.

Every 3-D sound buffer has a sound cone, but by default a buffer behaves like an omnidirectional sound source, because the outside volume is not attenuated, and the inside and outside cone angles are 360 degrees. Unless the application changes these values, the sound does not have any apparent orientation.

Designing sound cones properly can add dramatic effects to your application. For example, you could position a sound source in the center of a room, setting its orientation toward an open door in a hallway. Then set the angle of the inside cone so that it extends to the width of the doorway, make the outside cone a bit wider, and set the outside cone volume to inaudible. A listener moving along the hallway will begin to hear the sound only when near the doorway, and the sound will be loudest as the listener passes in front of the open door.

An application sets or retrieves the angles that define sound cones by using the IDirectSound3DBuffer8::SetConeAngles and IDirectSound3DBuffer8::GetConeAngles methods. The outside cone angle must always be equal to or greater than the inside cone angle.

To set or retrieve the orientation of sound cones, an application can use the IDirectSound3DBuffer8::SetConeOrientation and IDirectSound3DBuffer8::GetConeOrientation methods.

An application sets and retrieves the outside cone volume by using the IDirectSound3DBuffer8::SetConeOutsideVolume and IDirectSound3DBuffer8::GetConeOutsideVolume methods.


DirectSound 3-D Listeners

In a virtual 3-D environment as in the real world, sounds exist only in relation to a point of reception. The 3-D sound effects in a DirectX Audio application are affected not only by the position, orientation, and velocity values of the sound sources, but also by the position, orientation, and velocity of the virtual listener.

By default, the listener is stationary at the zero point of all vectors, oriented with the nose toward the positive Z-axis and the top of the head toward the positive Y-axis. By obtaining an object to represent the listener, the application can change all these values to reflect the movement and facing of the user within virtual space. The listener object also controls the general parameters of the acoustic environment, such as the amount of Doppler shift and the rate of volume attenuation over distance.

This section describes how your application can obtain a listener and manage global 3-D sound parameters. The following topics are discussed:

  • Obtaining the 3-D Listener
  • Batch Parameters for 3-D Listeners
  • Deferred Settings
  • Distance Factor
  • Listener Orientation
  • Listener Position and Velocity
  • Doppler Factor
  • Rolloff Factor


Obtaining the 3-D Listener

Global sound parameters are set and retrieved by using the IDirectSound3DListener8 interface, which is an interface to the primary sound buffer. There is only one primary buffer in an application, and only one listener.

If you are using the DirectMusic performance and audiopaths to play your 3-D sounds, you can obtain the listener from any audiopath by using IDirectMusicAudioPath8::GetObjectInPath or IDirectMusicSegmentState8::GetObjectInPath, setting the dwStage parameter to DMUS_PATH_PRIMARY_BUFFER. In the following example, g_p3DAudioPath is a pointer to an IDirectMusicAudioPath8 interface:

IDirectSound3DListener8* g_pDSListener;

HRESULT hr = g_p3DAudioPath->GetObjectInPath(
    DMUS_PCHANNEL_ALL, DMUS_PATH_PRIMARY_BUFFER, 0,
    GUID_NULL, 0, IID_IDirectSound3DListener8,
    (LPVOID*) &g_pDSListener));

If your application is creating and managing its own sound buffers, using only the DirectSound API, you must create a primary buffer object and then obtain the listener interface from that.

Create the primary buffer by using the IDirectSound8::CreateSoundBuffer method, specifying the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags in the dwFlags member of the DSBUFFERDESC structure. Call the IDirectSoundBuffer::QueryInterface method on the resulting buffer to obtain a pointer to an IDirectSound3DListener8 interface for that buffer.

In the following example, lpds is an IDirectSound8 interface pointer:

DSBUFFERDESC           dsbd;
LPDIRECTSOUNDBUFFER    lpdsbPrimary;
LPDIRECTSOUNDLISTENER8 lp3DListener;

ZeroMemory(&dsbd, sizeof(DSBUFFERDESC));
dsbd.dwSize = sizeof(DSBUFFERDESC);
dsbd.dwFlags = DSBCAPS_CTRL3D | DSBCAPS_PRIMARYBUFFER;
if SUCCEEDED(lpds->CreateSoundBuffer(&dsbd, &lpdsbPrimary, NULL))
{
    // Get listener interface.
    if FAILED(lpdsbPrimary->QueryInterface(
            IID_IDirectSound3DListener8,
            (LPVOID *)&lp3DListener))
    {
    lpdsbPrimary->Release();
    }
}

Once the listener has been obtained, the IDirectSoundBuffer interface to the primary buffer is not needed and can be released.


Batch Parameters for 3-D Listeners

Applications can retrieve or set a 3-D listener object's parameters individually or in batches. To set individual values, your application can use the applicable IDirectSound3DListener8 interface method. However, applications often must set or retrieve all the values that describe the listener at once. An application can perform these batch parameter manipulations in a single call by using the IDirectSound3DListener8::GetAllParameters and IDirectSound3DListener8::SetAllParameters methods.

Parameter changes can also be made more efficiently by flagging them as deferred and then executing them all at once. For more information, see Deferred Settings.


Deferred Settings

Every change to 3-D sound buffer and listener settings causes remixing, at the expense of CPU cycles. To minimize the performance impact of changing 3-D settings, use the DS3D_DEFERRED flag in the dwApply parameter of any of the IDirectSound3DListener8 or IDirectSound3DBuffer8 methods that change 3-D settings. Then call the IDirectSound3DListener8::CommitDeferredSettings method to execute all of the deferred commands at once.

Note Deferred settings are overridden by immediate settings. For example, if you set the listener velocity to (1.0, 0.0, 0.0) with the DS3D_DEFERRED flag and then set it to (2.0, 0.0, 0.0) with the DS3D_IMMEDIATE flag, the velocity becomes (2.0, 0.0, 0.0) and does not change when CommitDeferredSettings is called.


Distance Factor

The distance factor is the number of meters in a vector unit. By default, the distance factor is 1.0. If the velocity of a buffer is (2.0, 0.0, 0.0), the sound source is considered to be moving along the x-axis at 2 meters per second. Applications that are using a different unit of measurement for 3-D graphics vectors might want to change the distance factor accordingly.

Suppose, for example, that the basic unit of measurement in your application is the foot, or 0.3048 meters. You call the IDirectSound3DListener8::SetDistanceFactor method, specifying 0.3048 as the flDistanceFactor parameter. From then on, you continue using feet in parameters to method calls, and they are automatically converted to meters.

You can retrieve the current distance factor set for a listener by using the IDirectSound3DListener8::GetDistanceFactor method.

The distance factor mainly affects Doppler shift, by changing the actual velocity represented by n units per second. It does not directly affect rolloff, because the rate of attenuation over distance is based on the minimum distance in units. If you set the minimum distance for a given sound at 2 units, the volume will be halved at a distance of 4 units, whether those units are in feet, meters, or any other measure. For more information, see Minimum and Maximum Distances.


Listener Orientation

Listener orientation is defined by the relationship between two vectors that share an origin at the center of the listener's head: the top and front vectors. The top vector points straight up through the top of the head, and the front vector points forward through the listener's face at right angles to the top vector, as in the following illustration.

An application can set and retrieve the listener's orientation by using the IDirectSound3DListener8::SetOrientation and IDirectSound3DListener8::GetOrientation methods.

By default, the front vector is (0.0, 0.0, 1.0), and the top vector is (0.0, 1.0, 0.0). The two vectors must always be at right angles to one another. If necessary, DirectSound will adjust the front vector so that it is at right angles to the top vector.


Listener Position and Velocity

An application can set and retrieve a listener's position in 3-D space by using the IDirectSound3DListener8::SetPosition and IDirectSound3DListener8::GetPosition methods.

To set or retrieve the velocity value that DirectSound uses to calculate Doppler-shift effects for a moving listener, use the IDirectSound3DListener8::SetVelocity and IDirectSound3DListener8::GetVelocity methods. Velocity is measured in distance units per second—by default, meters per second.

As with buffers, a listener's position and its velocity are completely independent. It is up to the application to set an appropriate velocity for the listener.


Doppler Factor

DirectSound automatically creates Doppler shift effects for any buffer or listener that has a velocity. Effects are cumulative: if the listener and the sound buffer are both moving, the system automatically calculates the relative velocity and adjusts the Doppler effect accordingly.

In order to have realistic Doppler shift effects in your application, you must calculate the speed of any object that is moving and set the appropriate velocity for that sound source or listener. You are free to exaggerate or lessen this value in a particular case in order to create special effects. You can also globally increase or decrease Doppler shift by changing the Doppler factor.

The Doppler factor can range from DS3D_MINDOPPLERFACTOR to DS3D_MAXDOPPLERFACTOR, defined as 0.0 and 10.0 respectively. A value of 0 means no Doppler shift is applied to a sound. Every other value represents a multiple of the real-world Doppler shift. In other words, a value of 1 (or DS3D_DEFAULTDOPPLERFACTOR) means the Doppler shift that would be experienced in the real world is applied to the sound, a value of 2 means twice the real-world Doppler shift, and so on.

The Doppler factor can be set and retrieved by using the IDirectSound3DListener8::SetDopplerFactor and IDirectSound3DListener8::GetDopplerFactor methods.


Rolloff Factor

Rolloff is the amount of attenuation that is applied to sounds, based on the listener's distance from the sound source. DirectSound can ignore rolloff, exaggerate it, or give it the same effect as in the real world, depending on a variable called the rolloff factor.

The rolloff factor can range from DS3D_MINROLLOFFFACTOR to DS3D_MAXROLLOFFFACTOR, defined as 0.0 and 10.0 respectively. A value of DS3D_MINROLLOFFFACTOR means no rolloff is applied to a sound. Every other value represents a multiple of the real-world rolloff. In other words, a value of 1 (DS3D_DEFAULTROLLOFFFACTOR) means the rolloff that would be experienced in the real world is applied to the sound, a value of 2 means twice the real-world rolloff, and so on.

Set and retrieve the rolloff factor for all sounds by using the IDirectSound3DListener8::SetRolloffFactor and IDirectSound3DListener8::GetRolloffFactor methods.

To change the effect of distance for an individual sound buffer, you can set the minimum distance for the buffer. For more information, see Minimum and Maximum Distances.


Using Effects

DirectX Audio provides support for effects processing of sounds by DirectX Media Objects (DMOs). For general information on DMOs, see Introduction to DirectX Media Objects in the DirectShow documentation.

A standard set of effects is available to every DirectX application. Other DMOs can be registered on the system.

All the standard DMOs except Waves reverberation can process 8- or 16-bit PCM wave format data with one or two channels at any sample rate supported by DirectSound. Waves reverberation does not support 8-bit samples.

The following topics contain information on setting up and using effects:

  • Setting Effects on Buffers
  • Effect Parameters
  • Standard Effects

This section focuses on the use of effects in audiopaths, but much of the information is also relevant to applications that manage their own DirectSound buffers. See Using Effects in DirectSound.


Setting Effects on Buffers

If you are playing segments authored in DirectMusic Producer with audiopath configurations, any effects are set up when you create the audiopath from the configuration object. A standard audiopath might also contain effects. However, in some cases you may prefer to implement an effect on a custom audiopath at run time or add an effect to a standard audiopath. For example, you might want to add an effect to a standard audiopath so that you can apply the effect to wave or MIDI files.

To apply an effect to an audiopath, first obtain an IDirectSoundBuffer8 interface to a buffer on the path. Then set one or more effects on that buffer by using IDirectSoundBuffer8::SetFX.

To learn how to obtain a buffer interface, see Retrieving Objects from an Audiopath. For information on how to identify standard audiopath buffers in the call to GetObjectInPath, see the audiopath types under Standard Audiopaths.

The following sample code sets a standard audiopath, retrieves a buffer from the path, and sets an echo effect on the buffer:

// Assume that pPerformance is a valid IDirectMusicPerformance8
// interface pointer.

IDirectMusicAudioPath*  g_p3DAudioPath;
IDirectSoundBuffer8*    g_pDSBuffer;
HRESULT                 hr;

// Create a standard audiopath with a source and
// environment reverb buffers. Don't activate the path;
// SetFX fails if the buffer is running.

if( FAILED(hr = pPerformance->CreateStandardAudioPath(
    DMUS_APATH_DYNAMIC_3D, 64, FALSE, &g_p3DAudioPath)))
    return hr;

// Get the buffer in the audio path.

if( FAILED(hr = g_p3DAudioPath->GetObjectInPath(DMUS_PCHANNEL_ALL,
    DMUS_PATH_BUFFER, 0, GUID_NULL, 0, IID_IDirectSoundBuffer8,
    (LPVOID*) &g_pDSBuffer)))
    return hr;

// Describe the effect.

DSEFFECTDESC dsEffect;
dsEffect.dwSize = sizeof(DSEFFECTDESC);
dsEffect.dwFlags = 0;
dsEffect.guidDSFXClass = GUID_DSFX_STANDARD_ECHO;
dsEffect.dwReserved1 = 0;
dsEffect.dwReserved2 = 0;

DWORD dwResults;

// Set the effect
if (FAILED(hr = g_pDSBuffer->SetFX(1, &dsEffect, &dwResults)))
    return hr;

// You can check the value of dwResults here to see if and how
// the effect was allocated.

// Activate the path.

g_p3DAudioPath->Activate(TRUE);


Effect Parameters

To set or retrieve parameters of sound effects, you must first obtain the appropriate interface to the buffer that contains the effect. The following interfaces give you access to parameters of the DMOs supplied with DirectX Audio.

  • IDirectSoundFXChorus8
  • IDirectSoundFXCompressor8
  • IDirectSoundFXDistortion8
  • IDirectSoundFXEcho8
  • IDirectSoundFXFlanger8
  • IDirectSoundFXGargle8
  • IDirectSoundFXI3DL2Reverb8
  • IDirectSoundFXParamEq8
  • IDirectSoundFXWavesReverb8

To retrieve an effect interface, pass DMUS_PATH_BUFFER_DMO as the dwStage parameter to IDirectMusicAudioPath8::GetObjectInPath or IDirectMusicSegmentState8::GetObjectInPath. If the audiopath contains more than one buffer, dwBuffer must be the index of the buffer. For information on the index numbers of buffers in standard audiopaths, see the audiopath types under Standard Audiopaths.

The following sample code retrieves an interface for the gargle effect on a buffer created from an audiopath configuration. It then uses this interface to change a parameter of the effect.

// g_p3DAudioPath is a valid IDirectMusicAudioPath8 pointer
// obtained from IDirectMusicPerformance8::CreateAudioPath.
// To simplify the example, error-handling is omitted.

HRESULT                  hr;
IDirectSoundFXGargle8*   pEffectDMO;
DSFXGargle               FXParams;

hr = g_p3DAudioPath->GetObjectInPath(DMUS_PCHANNEL_ALL,
        DMUS_PATH_BUFFER_DMO, 0,
        GUID_All_Objects, 0, IID_IDirectSoundFXGargle8,
        (LPVOID*) &pEffectDMO);

hr = pEffectDMO->GetAllParameters(&FXParams);
FXParams.dwRateHz  = DSFXGARGLE_RATEHZ_MIN;
hr = pEffectDMO->SetAllParameters(&FXParams);

If your application is managing its own DirectSound buffers, you need to ensure that changes in effect parameters take place immediately. For efficiency, DirectSound processes 100 milliseconds of sound data in a buffer, starting at the play cursor, before IDirectSoundBuffer8::Play is called. This can happen after any of the following calls:

  • IDirectSoundBuffer8::Unlock
  • IDirectSoundBuffer8::Stop
  • IDirectSoundBuffer8::SetCurrentPosition
  • IDirectSoundBuffer8::SetFX

If you call any of these methods and then change effect parameters, the new parameters will not be heard until the preprocessed data has been played. To avoid this situation, do one of the following:

  • Write data to the buffer after effect parameters have been changed, not before.
  • Call Stop or SetCurrentPosition on the buffer to force preprocessing after you have set the parameters.


Standard Effects

This topic is an introduction to the sound effects provided with DirectX Audio. The following effects are covered:

  • Chorus
  • Compression
  • Distortion
  • Echo
  • Environmental Reverberation
  • Flange
  • Gargle
  • Parametric Equalizer
  • Waves Reverberation


Chorus

Chorus is a voice-doubling effect created by echoing the original sound with a slight delay and slightly modulating the delayof the echo.

This effect is represented by the IDirectSoundFXChorus8 interface. Its parameters are contained in the DSFXChorus structure.


Compression

Compression is a reduction in the fluctuation of a signal above a certain amplitude.

This effect is represented by the IDirectSoundFXCompressor8 interface. Its parameters are contained in the DSFXCompressor structure.


Distortion

Distortion is achieved by adding harmonics to the signal in such a way that, as the level increases, the top of the waveform becomes squared off or clipped.

This effect is represented by the IDirectSoundFXDistortion8 interface. Its parameters are contained in the DSFXDistortion structure.


Echo

An echo effect causes an entire sound to be repeated after a fixed delay.

This effect is represented by the IDirectSoundFXEcho8 interface. Its parameters are contained in the DSFXEcho structure.


Environmental Reverberation

DirectX supports environmental reverberation in accordance with the Interactive 3-D Audio, Level 2 (I3DL2) specification, published by the Interactive Audio Special Interest Group.

The DirectX environmental reverb effect is an implementation of the listener properties in the I3DL2 specification. Source properties are not supported in this release.

Sounds reaching the listener have three temporal components:

  • The direct path is the audio signal that goes straight from the sound source to the listener, without bouncing off any surface. There is therefore only one direct path signal.
  • Early reflections are the audio signals that reach the listener after one or two reflections off surfaces such as the walls, floor, and ceiling. If a signal is the result of the sound hitting only one wall on its way to the listener, it is called a first-order reflection. If it bounces off two walls before reaching the listener, it is called a second-order reflection. Humans can typically perceive individual reflections only of the first or second order.
  • Late reverberation, or simply reverb, consists of the combined lower-order reflections, usually a dense succession of echoes of diminishing intensity.

The combination of early reflections and late reverberation is sometimes called the room effect.

Reverb properties include the following:

  • Attenuation of the early reflections and late reverberation.
  • Rolloff factor, or the rate at which reflected signals become attenuated with distance. The rolloff factor for the direct path is managed by the DirectSound listener.
  • Reflections delay. This is the interval between the arrival of the direct-path signals and the arrival of the first early reflections.
  • Reverb delay. This is the interval between the first of the early reflections and the onset of late reverberation.
  • Decay time. This is the interval between the onset of late reverberation and the time when its intensity has been reduced by 60 dB.
  • Diffusion, which is proportional to the number of echos per second in the late reverberation. Depending on the implementation, the density can change as the reverberation decays. In DirectX, the application can control this property by setting a percentage of the range allowed by the implementation.
  • Density, which is is proportional to the number of resonances per hertz in the late reverberation. Lower densities produce hollower sounds like those found in small rooms. In DirectX, the application can control this property by setting a percentage of the range allowed by the implementation.

Reverb properties are represented by an IDirectSoundFXI3DL2Reverb8 interface, and the parameters of the environment are contained in a DSFXI3DL2Reverb structure.

DirectX supports many sets of default parameters, or presets, that describe the reverb properties of audio environments ranging from mountains to sewer pipes. Most applications can simply choose one of these environments by using IDirectSoundFXI3DL2Reverb8::SetPreset.

To set custom properties, use IDirectSoundFXI3DL2Reverb8::SetAllParameters. You can retrieve the current properties by using IDirectSoundFXI3DL2Reverb8::GetAllParameters.


Flange

Flange is an echo effect in which the delay between the original signal and its echo is very short and varies over time. The result is sometimes referred to as a sweeping sound. The term flange originated with the practice of grabbing the flanges of a tape reel to change the speed.

This effect is represented by the IDirectSoundFXFlanger8 interface. Its parameters are contained in the DSFXFlanger structure.


Gargle

The gargle effect modulates the amplitude of the signal.

This effect is represented by the IDirectSoundFXGargle8 interface. Its parameters are contained in the DSFXGargle structure.


Parametric Equalizer

A parametric equalizer amplifies or attenuates signals of a given frequency.

Parametric equalizer effects for different pitches can be applied in parallel by setting multiple instances of the GUID_DSFX_STANDARD_PARAMEQ effect on the same buffer. In this way, the application can have tone control similar to that provided by a hardware equalizer.

This effect is represented by the IDirectSoundFXParamEq8 interface. Its parameters are contained in the DSFXParamEq structure.


Waves Reverberation

The Waves reverberation effect is intended for use with music. The Waves reverberation DMO is based on the Waves MaxxVerb technology, which is licenced to Microsoft.

This effect is represented by the IDirectSoundFXWavesReverb8 interface. Its parameters are contained in the DSFXWavesReverb structure.


Buffer Chains

A sound does not necessarily go through only a single secondary sound buffer. It is possible for buffers in an audiopath to send data to other secondary buffers. The advantage in doing so is that sounds from multiple buffers can be directed to a shared buffer where common 3-D parameters or special effects can be applied. Shared buffers can also be more efficient.

Buffer chains are set up automatically when an audiopath is created from an audiopath configuration embedded in a DirectMusic Producer file. For more information, see Using Audiopaths.

DirectX 8.0 does not support the creation of buffer chains by using the DirectSound API.


Using Compositional Elements

This section is a guide to incorporating dynamic musical components into a DirectX Audio application. It is presumed that you have a basic understanding of elements such as chordmaps and styles. If not, you should first read Compositional Music Elements.

It's possible to incorporate files from DirectMusic Producer into applications without working with individual compositional elements. Many applications use only fully authored segments. However, using individual components gives greater control over the performance at run time.

The following topics are discussed in this section:

  • Music Files for Composition
  • Overview of Programming for Composition
  • Using Styles
  • Using Motifs
  • Using Chordmaps
  • Using Templates
  • Using Transitions


Music Files for Composition

When programming for DirectMusic composition, you will use a variety of files created in DirectMusic Producer or a similar application. You load these elements into the application as COM objects and obtain interfaces to them. See Loading Audio Data.

The following table summarizes the types of file objects you will encounter. Any of these objects can also be obtained from a container file or from a resource.

The Class GUID is the value that you put in the guidClass member of the DMUS_OBJECTDESC structure when loading the object.

Element | Class GUID | Interface | File type
Band | CLSID_DirectMusicBand | IDirectMusicBand8 | bnd
Chordmap | CLSID_DirectMusicChordMap | IDirectMusicChordMap8 | cdm
DLS collection | CLSID_DirectMusicCollection | IDirectMusicCollection8 | dls
Segment | CLSID_DirectMusicSegment | IDirectMusicSegment8 | sgt
Style | CLSID_DirectMusicStyle | IDirectMusicStyle8 | sty

Note Bands can be authored as part of a style, in which case they are automatically loaded when the style is loaded. Similarly, styles and bands can be authored into a segment, in which case you don't need separate files for those elements.

Files can also contain references to other files. If a style contains a reference to a band file, the band is automatically loaded when the style is, provided the loader can find the band file.


Overview of Programming for Composition

When you implement music composed at run time, you will use previously authored objects as building blocks. In consultation with the author or other content provider, you can choose to get the musical data in the form of small building blocks that offer you the greatest possible flexibility and variation at run time, or you can use larger prefabricated elements that define the form of the music more fully.

Using the largest building blocks, you load highly structured segments based on styles, MIDI files, or waves that contain everything the performance needs in order to play the sound. All you have to do is load the segment and query for the IDirectMusicSegment8 interface. You pass this interface pointer to the IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx method. The style playback engine selects pattern variations from the style and plays them according to a fixed chord progression—or, in the case of a MIDI-based segment, simply plays the MIDI sequence. Band changes are usually contained in the segment as well.

If you want to use smaller building blocks, you obtain the following elements:

  • Chordmaps, which are road maps of chord progressions.
  • Styles, which define a basic melody and rhythm with variations, motifs, and embellishments.
  • Template segments, which are structural plans that control various aspects of playback, including the length of the segment, whether it loops, where groove level changes and embellishment patterns are to be placed, and what types of chords in the chordmap are to serve as signposts.

You can construct a segment by combining any chordmap, style, and template, using the IDirectMusicComposer8::ComposeSegmentFromTemplate method.

To have even more flexibility in music composition at run time, you can create segments based on predefined shapes rather than templates, using the IDirectMusicComposer8::ComposeSegmentFromShape method. The shape is used in creating the command and signpost tracks, which control the choice of embellishment patterns, the chord progression, and the frequency of chord changes.

When playing segments, you can also control the band used to play the parts. Bands are typically authored right into styles and templates, but they can also be supplied as separate files. To make band changes dynamically, create a secondary segment containing only the band, using the IDirectMusicBand8::CreateSegment method, and play this segment when it is time to assign instruments and instrument settings to the primary segment. For more information, see Using Bands.


Using Styles

The DirectMusic style object represents a collection of musical patterns, usually including embellishments and motifs, with a time signature, tempo, and band. It defines the basic rhythm and the notes to be played in each instrument part.

For a conceptual overview, see Styles.

A style by itself does not contain enough information to create a segment of music at run time. For this you need two other components: a chordmap, which is a scheme of chord progressions, and a command track to set the groove level and embellishments as the music plays. The command track can come from a template or be generated at run time from a shape. The chordmap generally comes from a chordmap file or resource.

To create a segment with a command track based on a template, call the IDirectMusicComposer8::ComposeSegmentFromTemplate method. See Using Templates.

To create a segment based on a shape, call the IDirectMusicComposer8::ComposeSegmentFromShape method. You supply pointers to a style and a chordmap. You also supply a rate of harmonic motion, which controls the frequency of chord changes, and a shape constant, which determines the progression of groove levels and embellishments.


Using Motifs

A motif is a special kind of pattern in a style intended to be played over the basic style pattern, typically in response to an interactive event. Although a motif can be as complex as any other pattern, even containing variations and multiple instrument parts, usually it is a short, simple musical figure that sounds good against a variety of background patterns. It might also be a sound effect played by a custom DLS instrument or instruments.

All the motifs authored into a style become available to you as soon as you have loaded that style. To get a particular motif ready for playback, call the IDirectMusicStyle8::GetMotif method, passing in the following parameters:

  • The name of the motif. You might know this from the documentation for the style, or you can obtain it from an index value by using the IDirectMusicStyle8::EnumMotif method.
  • A pointer to receive the IIDirectMusicSegment8 interface to the segment object to be created by the method.

The following example function obtains and plays the motif whose name is passed in as pwszMotifName:

void PlayMotif(IDirectMusicPerformance8* pPerf,
         IDirectMusicStyle8* pStyle,
         WCHAR* pwszMotifName)
{
  IDirectMusicSegment* pSeg;

  // Get the motif segment from the style. Check for S_OK
  // specifically, because GetMotif() returns S_FALSE if it
  // does not find the motif.

  if (S_OK == pStyle->GetMotif(pwszMotifName, &pSeg))
  {
    // Play the segment.

    pPerf->PlaySegment(pSeg,
                       DMUS_SEGF_BEAT | DMUS_SEGF_SECONDARY,
                       0,
                       NULL);
    pSeg->Release();
  }
}

Note that pSeg is played as a secondary segment, because a motif is normally played over a primary segment. You cannot play a motif as a primary segment, because it does not have a chord track or band track. If you do want to play a motif against silence, create a primary segment from a style that has only blank patterns, and keep that segment playing while you play the motif.


Using Chordmaps

A chordmap object represents a collection of chords that provides the foundation of the harmonic structure and the mood of the music. A chordmap contains several pathways with many interconnected chords, providing many possibilities for the composition engine to choose from in determining the chord progression in a piece of music.

For a conceptual overview, see Chordmaps.

For authored segments, applications don't normally need to concern themselves with chordmaps. The chordmap is used at the authoring stage to create a fixed chord progression. However, chordmaps can be used to compose segments at run time and to alter the chord progression of existing segments.

If a chordmap reference has been authored into a style, you can retrieve a pointer to its IDirectMusicChordMap8 interface by passing its name (assigned by the author) to the IDirectMusicStyle8::GetChordMap method. You can also use the IDirectMusicStyle8::EnumChordMap method to search for a particular chordmap, or the IDirectMusicStyle8::GetDefaultChordMap method to obtain a pointer to the default chordmap for the style.

Note DirectMusic Producer does not support authoring chordmap references into style files.

You set the chordmap for a composition when you create a segment by using either IDirectMusicComposer8::ComposeSegmentFromTemplate or IDirectMusicComposer8::ComposeSegmentFromShape. For more information, see Using Styles.

Once a segment has been created, you can change its chordmap by calling the IDirectMusicComposer8::ChangeChordMap method. This has the effect of changing the mood of the music without altering its basic rhythm and melody.

Every chordmap has an underlying scale, consisting of 24 tones. You can determine the tones of the scale by using the IDirectMusicChordMap8::GetScale method. The lower 24 bits of the variable pointed to by the pdwScale parameter of this method are set or cleared depending on whether the corresponding tone is part of the scale. The upper 8 bits give the root of the scale as an integer in the range from 0 through 23 (low C to middle B).


Using Templates

A template is a segment that can be used in composing a playable segment of music at run time. The template sets the length of the segment and any loop points. It can provide the command track, which controls changes in the groove level and the choice of embellishment patterns. It also prescribes how the chordmap is used in composing the segment, by specifying from which signpost group each new chord must come.

For a conceptual overview, see Templates.

A template is represented by a DirectMusic segment object.

There are two ways to obtain a template:

  • Load it from a segment file or resource. You load it as a DirectMusicObject and query for the IDirectMusicSegment8 interface. For more information, see Loading Audio Data.
  • Create it from a shape, using the IDirectMusicComposer8::ComposeTemplateFromShape method. You choose the length, the overall shape, whether intro and end embellishment patterns are to be played, and how long the ending is to be. You get back a pointer to the IDirectMusicSegment interface.

Once you have obtained a template segment object, you can pass it to the IDirectMusicComposer8::ComposeSegmentFromTemplate method, along with pointers to a style and a chordmap. You also supply a rate of harmonic motion, which sets the frequency of chord changes. The ComposeSegmentFromTemplate method creates a segment and returns a pointer to its IDirectMusicSegment8 interface. You pass this pointer to the IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx method.


Using Transitions

In order to avoid a sudden and perhaps discordant break when stopping one segment and beginning another, or when bringing the music to a close, you can have the composer object create an intermediate or closing segment that provides an appropriate transition.

You have your choice of three techniques for composing transitional segments:

  • The IDirectMusicPerformance8::PlaySegmentEx method allows you to specify a segment in the pTransition parameter. This segment is used as a template for a newly composed transition. The transition is played at i64StartTime, and then the segment specified by pSource is played.
  • The IDirectMusicComposer8::AutoTransition method, given a pointer to the performance, creates a transition from the currently playing segment to a second segment of your choice, and then automatically cues the transitional segment and the second segment for playback, returning an IDirectMusicSegmentState interface for both. The transition begins playing immediately or on the next boundary, as specified in the dwFlags parameter. Optionally, the second segment can be NULL so that the transition is to silence.
  • The IDirectMusicComposer8::ComposeTransition method composes a transition from any point in one segment to the beginning of a second segment, or to silence, and returns an IDirectMusicSegment interface so that the application can play the transition.

The AutoTransition and ComposeTransition methods both take a chordmap, a command, and a set of flags as parameters:

  • The chordmap, as usual, is used to create a chord track that defines the chord progression in the segment.
  • The command is one of the DMUS_COMMANDT_TYPES enumeration. It determines which type of pattern—either an ordinary groove pattern or one of the embellishments—is called for in the command track of the transitional segment. When the segment plays, an appropriate pattern is selected from the style.
  • The flags are from DMUS_COMPOSEF_FLAGS and further define the transition, principally its timing. The DMUS_COMPOSEF_MODULATE flag can be used to cause the transition to move smoothly from one tonality to another; it can't be used when there is no second segment, because there can be no modulation to silence.

Transitions created by AutoTransition and ComposeTransition are normally a single measure in length. However, they can be longer if the DMUS_COMPOSEF_LONG flag is included and the embellishment in the style is more than one measure long. They also contain at least two measures if they are of type DMUS_COMMANDT_ENDANDINTRO.


Track Composition

Most tracks in a segment are fixed and generate the same data each time the segment is played. However, tracks can generate their data dynamically each time they start playing or each time they loop, provided they implement the IDirectMusicTrack8::Compose method and are configured to do so.

One standard track, the signpost track, supports composition. The signpost track composes a new chord track from a chordmap.

Normally the track configuration is set by the author, but the application can turn track composition behaviors on and off by passing one or more of the following flags to IDirectMusicSegment8::SetTrackConfig or IDirectMusicSegmentState8::SetTrackConfig.

DMUS_TRACKCONFIG_COMPOSING
The track is composed by the IDirectMusicSegment8::Compose method.
DMUS_TRACKCONFIG_LOOP_COMPOSE
The track is automatically composed each time the segment loops.
DMUS_TRACKCONFIG_PLAY_COMPOSE
The track is automatically composed each time the segment starts.

Automatic composition can take place only when the segment contains a track in which to put the composed content. When the signpost track is composed, it requires a chord track for the new chords. You can ensure that the necessary tracks exist by calling IDirectMusicSegment8::Compose before playing the segment.

If you choose to do all composition manually, the only configuration flag to set is DMUS_TRACKCONFIG_COMPOSING. Provided neither of the other two flags is set, the tracks will be composed only when you call Compose.


Using Audio Scripts

Scripts are objects authored in an application that contains a script editor, such as DirectMusic Producer. Although they consist mainly of text, script objects also contain a few binary parameters.

For a conceptual overview, see Audio Scripts.

Load a script by using the IDirectMusicLoader8::GetObject method. Obtain the IDirectMusicScript8 interface, then call IDirectMusicScript8::Init to associate the script with a performance.

The following code loads and initializes a script. Assume that m_pLoader is an IDirectMusicLoader8 interface, m_PPerformance is an IDirectMusicPerformance8 interface, and wstrFileName contains the name of the file.

IDirectMusicScript8*  pScript = NULL;
DMUS_SCRIPT_ERRORINFO errInfo;
HRESULT               hr;

if (SUCCEEDED(hr = m_pLoader->LoadObjectFromFile(
        CLSID_DirectMusicScript, IID_IDirectMusicScript8,
        wstrFileName, (LPVOID*) &pScript)))
{
    hr = pScript->Init( m_pPerformance, &errInfo);
}

Apart from Init, the methods of IDirectMusicScript8 have three main purposes:

  • Set and retrieve the value of variables declared in the script. Because script routines do not accept parameters, variables are the only way for the script and the application to exchange information.
  • Call routines. A routine must finish executing before the application thread can continue.
  • Enumerate routines and variables. These methods are of interest chiefly to script-editing applications.

All the methods of IDirectMusicScript8, except the enumeration methods, retrieve error information in a DMUS_SCRIPT_ERRORINFO structure. An error can occur if a variable is not found or code within a routine fails to execute.

Scripts can also be used without being directly loaded or called by the application. A segment authored in DirectMusic Producer can contain a script track that triggers calls to routines in one or more scripts.


Wave Playback in DirectSound

This section is a guide to playing waves through DirectSound buffers without making use of the services provided by the DirectMusic loader and performance objects.

For most applications written for DirectX 8.0 and later, the best way to play wave sounds is to load them as segments and play them through the performance. Doing so requires less code, allows tighter integration of sound effects and music, and provides greater functionality such as the ability to mix sounds on an audiopath before they enter a 3-D buffer. However, you can still play wave sounds directly to buffers if you so choose.

Information in this section is contained in the following topics:

  • DirectSound Playback Overview
  • DirectSound Devices
  • DirectSound Buffers
  • Using Wave Data
  • Using Effects in DirectSound


DirectSound Playback Overview

The DirectSound object represents a device and is used to manage that device and create sound buffers.

Multiple applications can create DirectSound objects for the same sound device. When the input focus changes between applications, the audio output automatically switches from one application's streams to the other's. As a result, applications do not have to repeatedly play and stop their buffers when the input focus changes.

The DirectSound buffer object represents a buffer containing sound data. Buffer objects are used to start, stop, and pause sound playback, as well as to set attributes such as frequency and format.

The primary sound buffer holds the audio that the listener will hear. Secondary sound buffers each contain a single sound or stream of audio. DirectSound automatically creates a primary buffer, but it is the application's responsibility to create secondary buffers. When sounds in secondary buffers are played, DirectSound mixes them in the primary buffer and sends them to the output device. Only the available processing time limits the number of buffers that DirectSound can mix.

A short sound can be loaded into a buffer in its entirety and played at any time by a simple method call. Longer sounds have to be streamed. An application can ascertain when it is time to stream more data into the buffer, either by polling the position of the play cursor or by requesting notification when the play cursor reaches certain points.

It is your responsibility to put data in the correct format into the secondary sound buffers. DirectSound does not include methods for parsing a wave file or resource. However, there is code in the SDK sample applications that helps with this task.


DirectSound Devices

The first step in implementing DirectSound in an application is to create a DirectSound object, which represents a sound device.

This section describes how your application can enumerate available sound devices, create the DirectSound object for a device, and use the methods of the object to set the cooperative level, retrieve the capabilities of the device, create sound buffers, set the configuration of the system's speakers, and compact hardware memory.

  • Enumeration of Sound Devices
  • Creating the DirectSound Object
  • Cooperative Levels
  • Device Capabilities
  • Speaker Configuration
  • Compacting Hardware Memory


Enumeration of Sound Devices

For an application that is simply going to play sounds through the user's preferred playback device, you don't need to enumerate the available devices. When you create the DirectSound object by calling the DirectSoundCreate8 function, you can specify a default device. For more information, see Creating the DirectSound Object.

If you are looking for a particular kind of device, wish to offer the user a choice of devices, or need to work with two or more devices, you must enumerate the devices available on the system.

Enumeration serves three purposes:

  • Reports what hardware is available.
  • Supplies a globally unique identifier (GUID) for each device.
  • Enables you to create a temporary DirectSound object for each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices, you must first set up a callback function that will be called each time DirectSound finds a device. You can do anything you want within this function, and you can give it any name, but you must declare it in the same form as the DSEnumCallback prototype. The callback function must return TRUE if enumeration is to continue, or FALSE otherwise—for instance, after finding a device with the capabilities you need.

The following callback function adds information about each enumerated device to a combo box. Values for the first three parameters are supplied by the device driver. The fourth parameter is passed on from the DirectSoundEnumerate function.

BOOL CALLBACK DSEnumProc(LPGUID lpGUID,
                         LPCTSTR lpszDesc,
                         LPCTSTR lpszDrvName,
                         LPVOID lpContext )
{
    HWND   hCombo = *(HWND *)lpContext;
    LPGUID lpTemp = NULL;

    if ( lpGUID != NULL )
    {
        if (( lpTemp = malloc( sizeof(GUID))) == NULL )
        return( TRUE );

        memcpy( lpTemp, lpGUID, sizeof(GUID));
    }

    ComboBox_AddString( hCombo, lpszDesc );
    ComboBox_SetItemData( hCombo,
                ComboBox_FindString( hCombo, 0, lpszDesc ),
                lpTemp );
    return( TRUE );
}

The enumeration is set in motion when the dialog containing the combo box is initialized:

if FAILED(DirectSoundEnumerate((LPDSENUMCALLBACK)DSEnumProc,
        (VOID*)&hCombo))
{
    EndDialog( hDlg, TRUE );
    return( TRUE );
}

In this case, the address of the combo box handle is passed into DirectSoundEnumerate, which in turn passes it to the callback function. This parameter can be any 32-bit value that you want to have access to within the callback.

Note The first device enumerated is always called the Primary Sound Driver, and the lpGUID parameter of the callback is NULL. This device represents the preferred playback device set by the user in Control Panel. It is enumerated separately to make it easy for the application to add "Primary Sound Driver" to a list when presenting the user with a choice of devices. The primary device is also enumerated with its proper name and GUID.


Creating the DirectSound Object

The simplest way to create the DirectSound object is with the DirectSoundCreate8 function. The first parameter of this function specifies the GUID of the device to be associated with the object. You can obtain this GUID by Enumeration of Sound Devices, or you can pass one of the following GUIDs to specify a default device:

DSDEVID_DefaultPlayback
The default system audio device. You can also specify this device by passing a NULL pointer in the device GUID parameter. The default device is the one enumerated as "Primary DirectSound Driver".
DSDEVID_DefaultVoicePlayback
The default voice communications device. Typically this is a secondary device such as a USB headset with microphone.

If no device driver is present, the call to DirectSoundCreate8 fails.

The function returns an error if there is no sound device or, under VXD drivers, if the sound device is under the control of an application using the standard Win32 waveform-audio functions. You should prepare your applications for this call to fail so that they can either continue without sound or prompt the user to close the application that is already using the sound device.

The following code creates a DirectSound object for the default device and obtains the IDirectSound8 interface:

LPDIRECTSOUND8 lpds;
HRESULT hr = DirectSoundCreate8(NULL, &lpds, NULL));

Note DirectSoundCreate8 does not cause CoInitialize to be called. If your application uses effect DMOs, it must call CoInitialize regardless of how the DirectSound object is created.

If your application will capture sounds as well as play them, you can conveniently create both the DirectSound and the DirectSoundCapture object, as well as playback and capture buffers, by using the DirectSoundFullDuplexCreate8 function.

You can also create the DirectSound object by using standard COM functions, as follows:

  1. Initialize COM at the start of your application by calling CoInitializeEx:
    if FAILED(CoInitializeEx(NULL, 0))
    return FALSE;
  2. Create the DirectSound object by using CoCreateInstance and the IDirectSound8::Initialize method, rather than the DirectSoundCreate8 function:
    LPDIRECTSOUND8 lpds;
HRESULT hr = CoCreateInstance(&CLSID_DirectSound8,
                              NULL,
                              CLSCTX_INPROC_SERVER,
                              &IID_IDirectSound8,
                              &lpds);

    CLSID_DirectSound8 is the class identifier of the DirectSound driver object class and IID_IDirectSound8 is the interface identifier. The lpds parameter receives the interface pointer.

  3. Call the IDirectSound8::Initialize method to associate the object with a device. This method takes the same device GUID parameter that DirectSoundCreate8 uses.
    if SUCCEEDED(hr)
    hr = lpds->Initialize(NULL);
  4. Before you close the application, close the COM library by calling the CoUninitialize function, as follows:
    CoUninitialize();


Cooperative Levels

Because Windows is a multitasking environment, more than one application can be working with a device driver at any one time. Through the use of cooperative levels, DirectX makes sure that each application does not gain access to the device in the wrong way or at the wrong time. Each DirectSound application has a cooperative level that determines the extent to which it is allowed to access the device.

After creating a DirectSound object, you must set the cooperative level for the device by using the IDirectSound8::SetCooperativeLevel method before you can play sounds.

The following example sets the cooperative level for the DirectSound device represented by the IDirectSound8 interface at lpDirectSound. The hwnd parameter is the handle to the application window.

HRESULT hr = lpDirectSound->SetCooperativeLevel(hwnd, DSSCL_PRIORITY);

DirectSound defines three cooperative levels for sound devices, represented by the values DSSCL_NORMAL, DSSCL_PRIORITY, and DSSCL_WRITEPRIMARY.

Note The DSSCL_EXCLUSIVE cooperative level available in versions earlier than DirectX 8.0 is obsolete. It is no longer possible for a DirectX application to mute other applications. Applications that request the exclusive level are granted the priority level instead.

Normal Cooperative Level

At the normal cooperative level, the application cannot set the format of the primary sound buffer, write to the primary buffer, or compact the on-board memory of the device. All applications at this cooperative level use a primary buffer format of 22 kHz, stereo sound, and 8-bit samples, so that the device can switch between applications as smoothly as possible.

Priority Cooperative Level

When using a DirectSound device with the priority cooperative level, the application has first rights to hardware resources, such as hardware mixing, and can set the format of the primary sound buffer and compact the on-board memory of the device.

Game applications should use the priority cooperative level in almost all circumstances. This level gives the most robust behavior while allowing the application control over sampling rate and bit depth. The priority cooperative level also allows audio from other applications, such as IP telephony, to be heard along with the audio from the game.

Write-primary Cooperative Level

The highest cooperative level is write-primary. When using a DirectSound device with this cooperative level, your application has direct access to the primary sound buffer. In this mode, the application must write directly to the primary buffer. Secondary buffers cannot be played while this is happening.

An application must be set to the write-primary level in order to obtain direct write access to the audio samples in the primary buffer. If the application is not set to this level, then all calls to the IDirectSoundBuffer8::Lock method will fail.

When your application is set to the write-primary cooperative level and gains the foreground, all secondary buffers for other applications are stopped and marked as lost. When your application in turn moves to the background, its primary buffer is marked as lost and must be restored when the application again moves to the foreground. For more information, see Buffer Management.

You cannot set the write-primary cooperative level if a DirectSound driver is not present on the user's system. To determine whether this is the case, call the IDirectSound8::GetCaps method and check for the DSCAPS_EMULDRIVER flag in the DSCAPS structure.

For more information, see Writing to the Primary Buffer.


Device Capabilities

DirectSound enables your application to retrieve the hardware capabilities of the sound device. Most applications will not need to do this, because DirectSound automatically takes advantage of any available hardware acceleration. However, high-performance applications can use the information to scale their sound requirements to the available hardware. For example, an application might choose to play more sounds if hardware mixing is available than if it is not.

After calling the DirectSoundCreate8 function to create a DirectSound object, your application can retrieve the capabilities of the sound device by calling the IDirectSound8::GetCaps method.

The following example retrieves the capabilities of the device represented by the IDirectSound8 interface pointer lpDirectSound:

DSCAPS dscaps;

dscaps.dwSize = sizeof(DSCAPS);
HRESULT hr = lpDirectSound->GetCaps(&dscaps);

The DSCAPS structure receives information about the performance and resources of the sound device, including the maximum resources of each type and the resources that are currently available. Note that the dwSize member of this structure must be initialized before the method is called.

If your application scales to hardware capabilities, you should call the IDirectSound8::GetCaps method between every buffer allocation to determine if there are enough resources to create the next buffer.


Speaker Configuration

DirectSound uses the speaker configuration—that is, the position of the speakers relative to the listener—to optimize 3-D effects for the user's sound system.

In Windows® 98 and Windows® 2000, the speaker configuration can be set by the user in Control Panel. An application can retrieve this value by using IDirectSound8::GetSpeakerConfig and override it by calling IDirectSound8::SetSpeakerConfig.

There is no guarantee that SetSpeakerConfig will have an immediate effect; it might simply change a registry setting that will not take effect until the computer is restarted. Instead of using this method, applications should advise the user to change the speaker configuration through Control Panel.

In Windows 95, GetSpeakerConfig simply returns a default value or the last value you set with SetSpeakerConfig.


Compacting Hardware Memory

As long as it has at least the priority cooperative level, your application can use the IDirectSound8::Compact method to move any on-board sound memory into a contiguous block to make the largest portion of free memory available.


DirectSound Buffers

DirectSound buffer objects control the delivery of wave data from a source to a destination. The source might be a synthesizer, another buffer, a file, or a resource. For most buffers, the destination is a mixing engine called the primary buffer. From the primary buffer, the data goes to the hardware that converts the PCM samples to sound waves.

The information in this section is of interest mainly for applications originally written for previous versions of DirectSound, or applications that need to have low-level control over buffers. If your application is playing sounds by using the DirectMusic performance object, buffer creation and management is done automatically. You can, however, obtain buffer objects in order to gain access to parameters for 3-D effects and effects in DMOs. For more information, see Using Effects and 3-D Sound.

Information about using DirectSound buffers is contained in the following topics:

  • Buffer Basics
  • Creating Secondary Buffers
  • Duplicating Buffers
  • Buffer Control Options
  • 3-D Algorithms for Buffers
  • Filling and Playing Static Buffers
  • Using Streaming Buffers
  • Playback Controls
  • Play and Write Cursors
  • Play Buffer Notification
  • Mixing Sounds
  • Buffer Management

For information about capture buffers, see Capturing Waves.


Buffer Basics

When DirectSound is initialized, it automatically creates and manages a primary sound buffer for mixing sounds and sending them to the output device.

Your application must create at least one secondary sound buffer for storing and playing individual sounds. For more information on how to do this, see Creating Secondary Buffers.

A secondary buffer can exist throughout the life of an application or it can be destroyed when no longer needed. It can contain a single sound that is to be played repeatedly, such as a sound effect in a game, or it can be filled with new data from time to time. The application can play a sound stored in a secondary buffer as a single event or as a looping sound that plays continuously. Secondary buffers can also be used to stream data, in cases where a sound file contains more data than can conveniently be stored in memory.

Buffers can be located either in hardware or in software. Hardware buffers are mixed by the sound card processor, and software buffers are mixed by the CPU. Software buffer data is always in system memory; hardware buffer data can be in system memory or, if the application requests it and resources are available, in on-board memory. For more information, see Dynamic Voice Management and Hardware Acceleration on ISA and PCI Cards.

You mix sounds from different secondary buffers simply by playing them at the same time. Any number of secondary buffers can be played at one time, up to the limits of available processing power.

Normally, you do not have to concern yourself at all with the primary buffer; DirectSound manages it behind the scenes. However, if your application is to perform its own mixing, DirectSound will let you write directly to the primary buffer. If you do this, you cannot also use secondary buffers. For more information, see Writing to the Primary Buffer.


Creating Secondary Buffers

To create a sound buffer, call the IDirectSound8::CreateSoundBuffer method. This method returns a pointer to an IDirectSoundBuffer8 interface, which the application uses to manipulate and play the buffer.

The following example shows how to create a secondary sound buffer:

BOOL AppCreateBasicBuffer(
        LPDIRECTSOUND8 lpDirectSound,
        LPDIRECTSOUNDBUFFER *lplpDsb)
{
    PCMWAVEFORMAT pcmwf;
    DSBUFFERDESC dsbdesc;
    HRESULT hr;

    // Set up wave format structure.
    memset(&pcmwf, 0, sizeof(PCMWAVEFORMAT));
    pcmwf.wf.wFormatTag = WAVE_FORMAT_PCM;
    pcmwf.wf.nChannels = 2;
    pcmwf.wf.nSamplesPerSec = 22050;
    pcmwf.wf.nBlockAlign = 4;
    pcmwf.wf.nAvgBytesPerSec =
        pcmwf.wf.nSamplesPerSec * pcmwf.wf.nBlockAlign;
    pcmwf.wBitsPerSample = 16;

    // Set up DSBUFFERDESC structure.

    memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
    dsbdesc.dwSize = sizeof(DSBUFFERDESC);
    dsbdesc.dwFlags =
        DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY;

    dsbdesc.dwBufferBytes = 3 * pcmwf.wf.nAvgBytesPerSec;
    dsbdesc.lpwfxFormat = (LPWAVEFORMATEX)&pcmwf;

    // Create buffer.

    hr = lpDirectSound->CreateSoundBuffer(&dsbdesc, lplpDsb, NULL);
    if SUCCEEDED(hr)
    {
        // IDirectSoundBuffer interface is in *lplpDsb.
        // Use QueryInterface to obtain IDirectSoundBuffer8.
        return TRUE;
    }
    else
    {
        // Failed.
        *lplpDsb = NULL;
        return FALSE;
    }
}

The example creates a streaming buffer large enough to hold 3 seconds of streaming data. Nonstreaming buffers should be made just large enough to accommodate the entire sound.

DirectSound allocates hardware resources to the first buffer that can take advantage of them. Because hardware buffers are mixed by the sound card processor, they have much less impact on application performance.

If you wish to specify the location of a buffer rather than letting DirectSound decide where it belongs, set either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag in the DSBUFFERDESC structure. If the DSBCAPS_LOCHARDWARE flag is set and there are insufficient hardware resources, the buffer creation request fails.

To take advantage of the voice management features of DirectSound, specify the DSBCAPS_LOCDEFER flag when creating the buffer. This flag defers the allocation of resources for the buffer until it is played. For more information, see Dynamic Voice Management.

You can ascertain the location of an existing buffer by using the IDirectSoundBuffer8::GetCaps method and checking the dwFlags member of the DSBCAPS structure for either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flags. One or the other is always specified.

Setting the DSBCAPS_STATIC flag lets DirectSound know that the buffer should be created in on-board hardware memory if possible. The IDirectSound::CreateSoundBuffer method does not fail if a hardware buffer is not available. This flag has no effect on most modern sound cards, which use system memory for their buffers. Hardware static buffers should be used only for short sounds that are to be played repeatedly. For more information, see Voice Management on ISA and PCI Cards.

Buffer objects are owned by the DirectSound object that created them. When the DirectSound object is released, all buffers created by that object also will be released and should not be referenced.


Duplicating Buffers

You can create two or more secondary buffers containing the same data by using the IDirectSound8::DuplicateSoundBuffer method. You cannot duplicate the primary sound buffer. There is no guarantee that the duplicate buffer actually shares memory with the original buffer, so it is unwise to make changes to one buffer in the expectation that these changes will be reflected in all duplicate buffers.


Buffer Control Options

When creating a sound buffer, your application must specify the control options needed for that buffer. This is done with the dwFlags member of the DSBUFFERDESC structure, which can contain one or more DSBCAPS_CTRL* flags.

The following controls are available:

  • 3-D properties
  • Effects
  • Frequency
  • Pan
  • Volume
  • Position notification

To obtain the best performance on all sound cards, your application should specify only control options it will use.

DirectSound uses the control options in determining whether hardware resources can be allocated to sound buffers. For example, a device might support hardware buffers but provide no pan control on those buffers. In this case, DirectSound would use hardware acceleration only if the DSBCAPS_CTRLPAN flag was not specified.

Note that certain combinations of controls are not allowed. For example, pan and 3-D are mutually exclusive.

If your application attempts to use a control that a buffer lacks, the method call fails. For example, if you attempt to change the volume by using the IDirectSoundBuffer8::SetVolume method, the method can succeed only if the DSBCAPS_CTRLVOLUME flag was specified when the buffer was created. Otherwise the method fails and returns the DSERR_CONTROLUNAVAIL error code.

See also Playback Controls.


3-D Algorithms for Buffers

When you create a secondary buffer with the DSBCAPS_CTRL3D control flag, you can also specify an algorithm to be used in spatializing the sound if the buffer is in software. By default, no HRTF processing is performed, and the location of the sound relative to the listener is indicated by panning and volume only. You can request two levels of HRTF for the buffer.

For more information, see DSBUFFERDESC.


Filling and Playing Static Buffers

A secondary buffer that contains an entire self-contained sound is called a static buffer. Although it is possible to reuse the same buffer for different sounds, typically data is written to a static buffer only once.

Static buffers are created and managed just like streaming buffers. The only difference is in the way they are used: static buffers are filled once and then played, but streaming buffers are constantly refreshed with data as they are playing.

Note A static buffer is not necessarily one created by setting the DSBCAPS_STATIC flag in the buffer description. This flag requests allocation of memory on the sound card, which not available on most modern hardware. A static buffer can exist in system memory and can be created with either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag. For more information, see Voice Management on ISA and PCI Cards.

Loading data into a static buffer is a three-step process:

  1. Lock the entire buffer by using IDirectSoundBuffer8::Lock. You specify the offset within the buffer where you intend to begin writing (normally 0), and get back the memory address of that point.
  2. Write the audio data to the returned address by using a standard memory-copy routine.
  3. Unlock the buffer using IDirectSoundBuffer8::Unlock.

These steps are shown in the following example, where lpdsbStatic is an IDirectSoundBuffer8 interface pointer and pbData is the address of the data source:

LPVOID lpvWrite;
DWORD  dwLength;

if (DS_OK == lpdsbStatic->Lock(
        0,              // Offset at which to start lock.
        0,              // Size of lock; ignored because of flag.
        &lpvWrite,      // Gets address of first part of lock.
        &dwLength,      // Gets size of first part of lock.
        NULL,           // Address of wraparound not needed.
        NULL,           // Size of wraparound not needed.
        DSBLOCK_ENTIREBUFFER))  // Flag.
{
    memcpy(lpvWrite, pbData, dwLength);
    lpdsbStatic->Unlock(
        lpvWrite,       // Address of lock start.
        dwLength,       // Size of lock.
        NULL,           // No wraparound portion.
        0);             // No wraparound size.
}

To play the buffer, call IDirectSoundBuffer8::Play, as in the following example:

lpdsbStatic->SetCurrentPosition(0);
HRESULT hr = lpdsbStatic->Play(
        0,    // Unused.
        0,    // Priority for voice management.
        0);   // Flags.

Because the DSBPLAY_LOOPING flag is not set in the example, the buffer automatically stops when it reaches the end. You can also stop it prematurely by using IDirectSoundBuffer8::Stop. When you stop a buffer prematurely, the play cursor position remains where it is. Hence the call to IDirectSoundBuffer8::SetCurrentPosition in the example, which ensures that the buffer starts from the beginning.


Using Streaming Buffers

A streaming buffer plays a long sound that cannot all fit into the buffer at once. As the buffer plays, old data is periodically replaced with new data.

To play a streaming buffer, call the IDirectSoundBuffer8::Play method, specifying DSBPLAY_LOOPING in the dwFlags parameter.

To halt playback, call the IDirectSoundBuffer8::Stop method. This method stops the buffer immediately, so you need to be sure that all data has been played. This can be done by polling the play position or by setting a notification position.

Streaming into a buffer requires the following steps:

  1. Lock a portion of the buffer by using IDirectSoundBuffer8::Lock. This method returns one or two addresses where data can now be written.
  2. Write the audio data to the returned address or addresses by using a standard memory-copy routine.
  3. Unlock the buffer using IDirectSoundBuffer8::Unlock.

The reason IDirectSoundBuffer8::Lock might return two addresses is that you can lock any number of bytes, up to the size of the buffer, regardless of the start point. If necessary, the locked portion wraps around to the beginning of the buffer. If it does, you have to perform two separate memory copies.

For example, say you lock 30,000 bytes beginning at offset 20,000 in a 40,000-byte buffer. When you call Lock in this case, it returns four values:

  • The address of offset 20,000.
  • The number of bytes locked from that point to the end of the buffer (20,000). You write this number of bytes to the first address.
  • The address of offset 0.
  • The number of bytes locked from that point (10,000). You write this number of bytes to the second address.

If no wraparound is necessary, the last two values are NULL and 0 respectively.

Although it's possible to lock the entire buffer, you must not do so while it is playing. Refresh only a portion of the buffer each time. For example, you might lock and write to the first quarter of the buffer as soon as the play cursor reaches the second quarter, and so on. You must never write to the part of the buffer that lies between the play cursor and the write cursor. For more information, see Play and Write Cursors.

The following function writes data to a sound buffer, starting at the position passed in dwOffset:

BOOL AppWriteDataToBuffer(
    LPDIRECTSOUNDBUFFER8 lpDsb,  // The buffer.
    DWORD dwOffset,              // Our own write cursor.
    LPBYTE lpbSoundData,         // Start of our data.
    DWORD dwSoundBytes)          // Size of block to copy.
{
    LPVOID  lpvPtr1;
    DWORD   dwBytes1;
    LPVOID  lpvPtr2;
    DWORD   dwBytes2;
    HRESULT hr;

    // Obtain memory address of write block. This will be in two parts
    // if the block wraps around.

    hr = lpDsb->Lock(dwOffset, dwSoundBytes, &lpvPtr1,
        &dwBytes1, &lpvPtr2, &dwBytes2, 0);

    // If the buffer was lost, restore and retry lock.

    if (DSERR_BUFFERLOST == hr)

    {
        lpDsb->Restore();
        hr = lpDsb->Lock(dwOffset, dwSoundBytes,
            &lpvPtr1, &dwBytes1, &lpvPtr2, &dwBytes2, 0);
    }
    if SUCCEEDED(hr)
    {
        // Write to pointers.

        CopyMemory(lpvPtr1, lpbSoundData, dwBytes1);
        if (NULL != lpvPtr2)
        {
            CopyMemory(lpvPtr2, lpbSoundData+dwBytes1, dwBytes2);
        }

        // Release the data back to DirectSound.

        hr = lpDsb->Unlock(lpvPtr1, dwBytes1, lpvPtr2,
            dwBytes2);
        if SUCCEEDED(hr)
        {
            // Success.
            return TRUE;
        }
    }

    // Lock, Unlock, or Restore failed.

    return FALSE;
}

For more information, see the following topics:

  • Play and Write Cursors
  • Play Buffer Notification
  • Reading Wave Files


Playback Controls

To retrieve and set the volume at which a buffer is played, your application can use the IDirectSoundBuffer8::GetVolume and IDirectSoundBuffer8::SetVolume methods. Setting the volume on the primary sound buffer changes the waveform-audio volume of the sound card.

By calling the IDirectSoundBuffer8::GetFrequency and IDirectSoundBuffer8::SetFrequency methods, you can retrieve and set the frequency at which audio samples play. You cannot change the frequency of the primary buffer.

To retrieve and set the pan, you can call the IDirectSoundBuffer8::GetPan and IDirectSoundBuffer8::SetPan methods.

In order to use any of these controls, you must set the appropriate flags when creating the buffer. See Buffer Control Options.


Play and Write Cursors

DirectSound maintains two pointers into the buffer: the play cursor and the write cursor. These positions are byte offsets into the buffer, not absolute memory addresses.

The IDirectSoundBuffer8::Play method always starts playing at the buffer's play cursor. When a buffer is created, the cursor position is set to zero. As a sound is played, the cursor moves and always points to the next byte of data to be output. When the buffer is stopped, the cursor remains at the next byte of data.

The write cursor is the point after which it is safe to write data into the buffer. The block between the current play position and the current write position is already committed to be played, and cannot be changed safely.

You might visualize the buffer as a clock face, with data written to it in a clockwise direction. The play position and the write position are like two hands sweeping around the face at the same speed, the write position always keeping a little ahead of the play position. If the play position points to the 1 and the write position points to the 2, it is only safe to write data after the 2. Data between the 1 and the 2 may already have been queued for playback by DirectSound and should not be touched.

The write position moves with the play position, not with data written to the buffer. If you're streaming data, you are responsible for maintaining your own pointer into the buffer to indicate where the next block of data should be written.

An application can retrieve the play and write cursors by calling the IDirectSoundBuffer8::GetCurrentPosition method. The IDirectSoundBuffer8::SetCurrentPosition method lets you move the play cursor. Applications do not control the position of the write cursor.

To ensure that the play cursor is reported as accurately as possible, always specify the DSBCAPS_GETCURRENTPOSITION2 flag when creating a secondary buffer. For more information, see DSBUFFERDESC.


Play Buffer Notification

When streaming audio, you may want your application to be notified when the play cursor reaches a certain point in the buffer, or when playback is stopped. With the IDirectSoundNotify8::SetNotificationPositions method, you can set any number of points within the buffer where events are to be signaled. You cannot do this while the buffer is playing.

First you have to obtain a pointer to the IDirectSoundNotify8 interface. You can do this by using the buffer object's QueryInterface method, as in the following example, where lpDsbSecondary is an IDirectSoundBuffer8 interface pointer:

LPDIRECTSOUNDNOTIFY8 lpDsNotify;

HRESULT hr = lpDsbSecondary->QueryInterface(IID_IDirectSoundNotify8,
                                            (LPVOID *)&lpDsNotify);
if SUCCEEDED(hr)
{
    // Go ahead and use lpDsNotify->SetNotificationPositions.
}

The IDirectSoundNotify8 interface is associated with the buffer object from which you obtained the pointer. The methods of the interface automatically apply to that buffer.

Now create an event object with the Win32 CreateEvent function. Put the handle to this event in the hEventNotify member of a DSBPOSITIONNOTIFY structure. In the dwOffset member of that structure, specify the offset within the buffer where you want the event to be signaled. Then pass the address of the structure—or of an array of structures, if you want to set more than one notification position—to the IDirectSoundNotify8::SetNotificationPositions method.

The following example sets a single notification position. The event will be signaled when playback stops, either because it was not looping and the end of the buffer has been reached, or because the application called the IDirectSoundBuffer8::Stop method.

DSBPOSITIONNOTIFY PositionNotify;

PositionNotify.Offset = DSBPN_OFFSETSTOP;
PositionNotify.hEventNotify = hMyEvent;
// hMyEvent is the handle returned by CreateEvent().

lpDsNotify->SetNotificationPositions(1, &PositionNotify);

If you are taking advantage of voice management, it's possible that a buffer could be terminated before a notification position is reached. See the Remarks for DSBPOSITIONNOTIFY.


Mixing Sounds

It is easy to mix multiple streams with DirectSound. You simply create secondary sound buffers, obtaining an IDirectSoundBuffer8 interface for each sound. You then play the buffers simultaneously. DirectSound takes care of the mixing in the primary sound buffer and plays the result.

The DirectSound mixer produces the best sound quality if all your application's sounds use the same wave format and the hardware output format is matched to the format of the sounds. If this is done, the mixer does not need to perform any format conversion.

Your application can change the hardware output format by creating a primary sound buffer object and calling the IDirectSoundBuffer8::SetFormat method. This primary buffer object is for control purposes only; creating it is not the same as obtaining write access to the primary buffer as described under Writing to the Primary Buffer, and you do not need the DSSCL_WRITEPRIMARY cooperative level. However, you do need a cooperative level of DSSCL_PRIORITY or higher in order to call the SetFormat method. DirectSound will restore the hardware format to the format specified in the last call every time the application gains the input focus.

You must set the format of the primary buffer before creating any secondary buffers.

Note With WDM drivers, setting the primary buffer format has no effect. The format is determined by the kernel mixer. For more information, see DirectSound Driver Models.


Buffer Management

The IDirectSoundBuffer8::GetCaps method retrieves the capabilities of the DirectSoundBuffer object.

Your application can use the IDirectSoundBuffer8::GetStatus method to determine if the buffer is playing or if it has stopped.

Use the IDirectSoundBuffer8::GetFormat method to retrieve information about the format of the sound data in a buffer. You also can use IDirectSoundBuffer8::SetFormat to set the format of the sound data in the primary buffer. For more information, see Mixing Sounds.

Note The SetFormat method cannot be called on secondary buffers. After a secondary buffer is created, its format is fixed. If you need a secondary buffer that uses another format, you must create a new sound buffer with this format.

Memory for a sound buffer can be lost in certain situations: for example, when buffers are located in sound card memory and another application gains control of the hardware resources. Loss can also occur when an application with the write-primary cooperative level moves to the foreground; in this case, DirectSound makes all other sound buffers lost so that the foreground application can write directly to the primary buffer.

The DSERR_BUFFERLOST error code is returned when the IDirectSoundBuffer8::Lock or IDirectSoundBuffer8::Play method is called for a lost buffer. When the application that caused the loss either lowers its cooperative level from write-primary or moves to the background, other applications can attempt to reallocate the buffer memory by calling the IDirectSoundBuffer8::Restore method. If successful, this method restores the buffer memory and all other settings for the buffer, such as volume and pan settings. However, a restored buffer may not contain valid sound data, so the owning application should rewrite the data to the buffer.


Using Wave Data

DirectSound buffers play only waveform audio data, which consists of digital samples of the sound at a fixed sampling rate. The representation of an analog signal by a sequence of numbers is known as pulse code modulation (PCM).

Wave data is usually stored in files or resources in Resource Interchange File Format (RIFF). The data includes a description of the wave format, including parameters such as the sampling rate and number of output channels.

The particular format of a sound can be described by a WAVEFORMATEX or WAVEFORMATEXTENSIBLE structure.

The wFormatTag member of this structure contains a unique identifier assigned by Microsoft Corporation. The only tags valid with DirectSound are the following:

  • WAVE_FORMAT_PCM. This tag indicates pulse code modulation (PCM), an uncompressed format.
  • WAVE_FORMAT_EXTENSIBLE. Multichannel audio format; valid only with WDM drivers. For more information, see Multichannel Wave Formats.

DirectSound does not support compressed wave formats. Applications should use the audio compression manager (ACM) functions, provided with the Win32 APIs in the Platform SDK, to convert compressed audio to PCM format before writing the data to a sound buffer. Alternatively, use the DirectMusic loader, which automatically enlists the help of ACM when loading compressed waves for playback through the DirectMusic performance.

More information on waves is included in the following topics:

  • Multichannel Wave Formats
  • Reading Wave Files
  • Reading Wave Data from a Resource


Multichannel Wave Formats

On WDM drivers, DirectSound buffers support wave formats that have more than two output channels, for speaker configurations such as 5.1, which has speakers at the front left, front center, front right, back left, and back right, plus a low-frequency enhancer.

The WAVEFORMATEXTENSIBLE structure describes a multichannel wave format. This structure is an extension of WAVEFORMATEX that configures the extra bytes already supported by the cbSize member of WAVEFORMATEX. A WAVEFORMATEXTENSIBLE structure can be cast as WAVEFORMATEX wherever the latter is expected, as for example in the DSBUFFERDESC structure.

If there are fewer physical speakers than the number of channels specified in a multichannel wave file, the audio data is mixed appropriately and output to the existing speakers.

DirectSound does not support effects or 3-D processing on buffers in a multichannel format. An attempt to create a buffer with the DSBCAPS_CTRL3D or DSBCAPS_CTRLFX flag and a multichannel wave format will fail.

For more information on multichannel wave formats, see "Enhanced Audio Formats for Multi-Channel Configurations and High-Bit Resolution", available at http://www.microsoft.com/hwdev/audio/multichaud.htm.


Reading Wave Files

This topic explains how to load data from wave files into DirectSound buffers without the help of the DirectMusic loader and performance. Most applications do not need to work directly with wave data and buffers. For the preferred method of loading and playing waves, see Loading Audio Data and Playing Sounds.

Wave files are in the Resource Interchange File Format (RIFF), which consists of a variable number of chunks containing either header information (for example, the wave format of sound samples) or data (the samples themselves). The Win32 API supplies functions for opening and closing RIFF files, seeking chunks, and so on. The names of these functions all start with "mmio".

The DirectSound API does not include methods for handling wave files. However, the Dsutil.cpp file used by many of the SDK sample applications implements a CWaveFile class that has the following public methods:

  • Open. Opens a file for reading and retrieves the wave format, or opens the file for writing and writes the header chunks.
  • GetSize. Returns the size of the data chunk, after Open has been called.
  • Read. Copies a portion of the data chunk into a buffer and advances the read cursor.
  • Write. Writes from a buffer to the data chunk and advances the write cursor.
  • ResetFile. Sets the read and write cursors to the beginning of the data chunk.
  • Close. Closes the file.

The first step in reading a wave file is to call the CWaveFile::Open method. This verifies that the file is in RIFF format and gets information about the wave format. The parameters are the filename, NULL for the format, and the WAVEFILE_READ flag. The method returns an HRESULT.

The following code opens a wave file:

CWaveFile waveFile;

if (FAILED(waveFile.Open("mywave.wav", NULL, WAVEFILE_READ)))
{
    waveFile.Close();
}

The application can now begin copying data from the file to a secondary sound buffer. Normally you don't create the sound buffer until you have obtained the format of the wave. The following code creates a static buffer just large enough to hold all the data in the file:

LPDIRECTSOUNDBUFFER  lpdsbStatic;
DSBUFFERDESC         dsbdesc;

memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
dsbdesc.dwSize = sizeof(DSBUFFERDESC);
dsbdesc.dwFlags = 0;

/* The wave format and size of the data chunk are stored in
// CWaveFile after CWaveFile::Open has been called.

dsbdesc.dwBufferBytes = waveFile.GetSize();
dsbdesc.lpwfxFormat = waveFile.m_pwfx;

// lpds is a valid IDirectSound8 pointer.

if FAILED(lpds->CreateSoundBuffer(&dsbdesc, &lpdsbStatic, NULL))
{
    // Error handling.
    .
    .
    .
}

Now the buffer can be filled with data. Because in this case the application is not streaming the data, the entire buffer is locked from the beginning. There is no wraparound, so only a single pointer and byte count are required.

LPVOID lpvAudio1;
DWORD  dwBytes1;

if FAILED(lpdsbStatic->Lock(
        0,              // Offset of lock start.
        0,              // Size of lock; ignored in this case.
        &lpvAudio1,     // Address of lock start.
        &dwBytes1,      // Number of bytes locked.
        NULL,           // Wraparound start; not used.
        NULL,           // Wraparound size; not used.
        DSBLOCK_ENTIREBUFFER))
{
    // Error handling.
    .
    .
    .
}

The CWaveFile::Read method can then be used to fill the buffer, as follows:

DWORD dwBytesRead;

waveFile.Read((BYTE*)lpvAudio1, dwBytes1, &dwBytesRead);

Finally, the application unlocks the buffer and closes the wave file:

lpdsbStatic->Unlock(lpvAudio1, dwBytes1, NULL, 0);
waveFile.Close();

For a streaming buffer, you would typically call CWaveFile::Read at regular intervals determined by the movement of the play cursor. If the locked portion of the buffer wraps around, call the method once for each segment of the lock.

For more information on streaming, see Using Streaming Buffers and Play Buffer Notification.

See the sample applications in the DirectX SDK installation for more examples of using the CWaveFile class.


Reading Wave Data from a Resource

The DirectSound API does not include methods for reading a wave from a resource. However, the Dsutil.cpp file used by many of the SDK sample applications implements a CWaveFile class that can read waves stored as resources as well as wave files.

To store wave sounds in an executable, import your wave files as resources and give them string names. Note that CWaveFile expects these resources to be of type "WAVE" or "WAV", and expects to find them in the executable module rather than a DLL.

The following code opens a resource identified as "mywave":

CWaveFile waveFile;

if (FAILED(waveFile.Open("mywave", NULL, WAVEFILE_READ)))
{
    waveFile.Close();
}

Once the resource has been opened, it can be read from just as if it were a file. For more information on how to do this by using the CWaveFile class, see Reading Wave Files.


Using Effects in DirectSound

Playback effects in a pure DirectSound application are handled in fundamentally the same way as in an application that uses the DirectMusic performance and audiopaths. For more information, see Using Effects. Because there are no audiopaths in a DirectSound application, you always work directly with buffers.

To use effects, a DirectSound application must call CoInitialize to initialize COM. Doing so does not preclude creating the DirectSound object by using DirectSoundCreate8.

Effects might not work smoothly on very small buffers. DirectSound does not permit the creation of effects-capable buffers that hold less than DSBSIZE_FX_MIN milliseconds of data.

Create a secondary buffer that is capable of holding a DMO by setting the DSBCAPS_CTRLFX flag in the DSBUFFERDESC structure.

Implement effects on your secondary sound buffers by using IDirectSoundBuffer8::SetFX.

Obtain interfaces for effects by using IDirectSoundBuffer8::GetObjectInPath. Note that this method, unlike IDirectMusicAudioPath8::GetObjectInPath and IDirectMusicSegmentState8::GetObjectInPath, does not take a dwStage parameter, because DMOs are the only objects that can be retrieved from buffers.


Sound Capture

This section is a guide to capturing sounds using DirectMusic and DirectSoundCapture objects. The following topics are discussed:

  • Capturing MIDI
  • Capturing Waves


Capturing MIDI

To capture MIDI messages from a device such as a keyboard, create a port for the capture device and use its IDirectMusicPort8::SetReadNotificationHandle method to cause an event to be signaled whenever messages are available to be read. In response to the event, call the IDirectMusicPort8::Read method repeatedly to place pending events into a buffer, until S_FALSE is returned. Each time Read is called, as many events are put into the buffer as are available, or as fit into the buffer. If at least one event was put into the buffer, S_OK is returned.

To retrieve events from the buffer, call the IDirectMusicBuffer8::GetNextEvent method. Each call retrieves a single event, until no more are available, at which point S_FALSE is returned.

The following code fragment illustrates this process. Assume that hEvent was created with CreateEvent and given to the capture port pPort by a call to SetReadNotificationHandle. Assume also that pBuffer was initialized by IDirectMusic8::CreateMusicBuffer.

REFERENCE_TIME rt;
DWORD          dwGroup;
DWORD          cb;
BYTE          *pb;

DWORD dw = WaitForMultipleObjects(1, hEvent, FALSE, INFINITE);
for (;;)
{
    hr = pPort->Read(pBuffer);
    if (hr == S_FALSE)
      {
          break;  // No more messages to read into the buffer.
      }
    pBuffer->ResetReadPtr();
    for (;;)
    {
        hr = pBuffer->GetNextEvent(&rt, &dwGroup, &cb, &pb);
        if (hr == S_OK)
        {
            // pb points to the data structure for the message, and
            // you can do anything that you want with it.
        }
        else if (hr == S_FALSE)
        {
            break;  // No more messages in the buffer.
        }
    }  // Done with the buffer.
}  // Done reading pending events.

If you don't wish to intercept messages, but simply want to send them from one port to another, you can use the IDirectMusicThru8 interface. See IDirectMusicThru8::ThruChannel for details.


Capturing Waves

The DirectSoundCapture object (IDirectSoundCapture8) is used to query the capabilities of sound capture devices and to create buffers for capturing audio from an input source. DirectSoundCapture allows capturing of data in PCM or compressed formats.

The DirectSound capture buffer object (IDirectSoundCaptureBuffer8) represents a buffer used for receiving data from the input device. Like playback buffers, this buffer is conceptually circular: when input reaches the end of the buffer, it automatically starts again at the beginning.

The methods of IDirectSoundCaptureBuffer8 enable you to retrieve the properties of the buffer, start and stop audio capture, and lock portions of the memory, so that you can safely retrieve data for saving to a file or for some other purpose. On operating systems that support capture effects, it also provides methods for retrieving DMOs and ascertaining the status of effects.

More information about wave capture is found in the following topics:

  • Enumeration of Capture Devices
  • Creating the DirectSoundCapture Object
  • Capture Device Capabilities
  • Creating a Capture Buffer
  • Capture Buffer Information
  • Capture Buffer Notification
  • Capture Buffer Effects
  • Using the Capture Buffer
  • Writing to a Wave File


Enumeration of Capture Devices

For an application that is simply going to capture sounds through the user's preferred capture device, you don't need to enumerate the available devices. By passing NULL or a predefined GUID to DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8,you can create a default device. For more information, see Creating the DirectSoundCapture Object.

If you are looking for a particular kind of device or wish to offer the user a choice of devices, you must enumerate the devices available on the system.

Enumeration serves three purposes:

  • Reports what hardware is available.
  • Supplies a GUID for each device.
  • Enables you to initialize each device as it is enumerated, so that you can check the capabilities of the device.

To enumerate devices, first set up a callback function that will be called each time DirectSound finds a device. You can do anything you want within this function, and you can give it any name, but you must declare it in the same form as the DSEnumCallback prototype. The callback function must return TRUE if enumeration is to continue, or FALSE otherwise—for instance, after finding a device with the capabilities you need.

For a sample callback function, see Enumeration of Sound Devices. Note that a GUID for each device is obtained as one of the parameters to this function.

The enumeration is set in motion by using the DirectSoundCaptureEnumerate function, as follows:

DWORD pv;  // Can be any 32-bit type.

HRESULT hr = DirectSoundCaptureEnumerate(
        (LPDSENUMCALLBACK)DSEnumProc,
        (VOID*)&pv);


Creating the DirectSoundCapture Object

Create the DirectSoundCapture object by calling the DirectSoundCaptureCreate8 or DirectSoundFullDuplexCreate8 function. Both these functions retrieve a pointer to the IDirectSoundCapture8 interface.

The lpcGUID parameter to DirectSoundCaptureCreate, or the pcGuidRenderDevice parameter to DirectSoundFullDuplexCreate8, can be a GUID obtained by enumeration, or it can be one of the following predefined GUIDs:

DSDEVID_DefaultCapture
The default system capture device. You can also specify this device by passing a NULL pointer in the device GUID parameter.
DSDEVID_DefaultVoiceCapture
The default voice communications capture device. Typically, this is a secondary device such as a USB headset with microphone.

If no device driver is present, the call fails.

You can also use the CoCreateInstance function to create the object. The procedure is similar to that for the DirectSound object; see Creating the DirectSound Object. If you use CoCreateInstance, then the object is created for the default capture device selected by the user in Control Panel.

If you want DirectSound and DirectSoundCapture objects to coexist, then you should create and initialize the DirectSound object before creating and initializing the DirectSoundCapture object, or use DirectSoundFullDuplexCreate8.

Some audio devices aren't configured for full duplex audio by default. If your application has problems with creating and initializing both a DirectSound object and a DirectSoundCapture object, you should advise the user to check the audio device properties to ensure that full duplex is enabled.


Capture Device Capabilities

To retrieve the capabilities of a capture device, call the IDirectSoundCapture8::GetCaps method. The parameter to this method is a pointer to a DSCCAPS structure. As with other such structures, you have to initialize the dwSize member before passing it. On return, the structure contains the number of channels the device supports, as well as a combination of values for supported formats, equivalent to the values in the WAVEINCAPS structure used in the Win32 waveform audio functions.

On non-WDM drivers, a capture device can be used by only one application at a time. If the driver supports simultaneous use of the device by more than one application, DSCCAPS_MULTIPLECAPTURE is returned in the dwFlags member of DSCCAPS. Each application can set its own format for the capture buffer.


Creating a Capture Buffer

Create a capture buffer by calling the IDirectSoundCapture8::CreateCaptureBuffer method.

One of the parameters to the method is a DSCBUFFERDESC structure that describes the characteristics of the desired buffer. The last member of this structure is a WAVEFORMATEX structure, which must be initialized with the details of the desired wave format.

Note that if your application is using DirectSound as well as DirectSoundCapture, capture buffer creation can fail when the format of the capture buffer is not the same as that of the primary buffer. The reason is that some cards have only a single clock and cannot support capture and playback at two different frequencies.

The following example sets up a capture buffer that will hold 1 second of data:

// pDSC is a valid IDirectSoundCapture8 interface pointer.

DSCBUFFERDESC              dscbd;
LPDIRECTSOUNDCAPTUREBUFFER pDSCB;
WAVEFORMATEX               wfx =
    {WAVE_FORMAT_PCM, 2, 44100, 176400, 4, 16, 0};

    // wFormatTag, nChannels, nSamplesPerSec, mAvgBytesPerSec,
    // nBlockAlign, wBitsPerSample, cbSize

dscbd.dwSize = sizeof(DSCBUFFERDESC);
dscbd.dwFlags = 0;
dscbd.dwBufferBytes = wfx.nAvgBytesPerSec;
dscbd.dwReserved = 0;
dscbd.lpwfxFormat = &wfx;
dscbd.dwFXCount = 0;
dscbd.lpDSCFXDesc = NULL;

pDSCB = NULL;

HRESULT hr = pDSC->CreateCaptureBuffer(&dscbd,
        &pDSCB, NULL);


Capture Buffer Information

Use the IDirectSoundCaptureBuffer8::GetCaps method to retrieve the size of a capture buffer. Be sure to initialize the dwSize member of the DSCBCAPS structure before passing it as a parameter.

You can also retrieve information about the format of the data in the buffer, as set when the buffer was created. Call the IDirectSoundCaptureBuffer8::GetFormat method, which returns the format information in a WAVEFORMATEX structure.

Note that your application can allow for extra format information in the WAVEFORMATEX structure by first calling the GetFormat method with NULL as the lpwfxFormat parameter. In this case the DWORD pointed to by the lpdwSizeWritten parameter will receive the size of the structure needed to receive complete format information.

To find out what a capture buffer is currently doing, call the IDirectSoundCaptureBuffer8::GetStatus method. This method fills a DWORD variable with a combination of flags that indicate whether the buffer is busy capturing, and if so, whether it is looping; that is, whether the DSCBSTART_LOOPING flag was set in the last call to IDirectSoundCaptureBuffer8::Start.

Finally, the IDirectSoundCaptureBuffer8::GetCurrentPosition method returns the offsets of the read and capture cursors within the buffer. The read cursor is at the end of the data that has been fully captured into the buffer at this point. The capture cursor is at the end of the block of data that is currently being copied from the hardware. You can safely copy data from the buffer only up to the read cursor.


Capture Buffer Notification

You may want your application to be notified when the read cursor reaches a certain point in the buffer, or when it reaches the end. The read cursor is at the point up to which it is safe to read data from the buffer. With the IDirectSoundNotify8::SetNotificationPositions method, you can set any number of points within the buffer where events are to be signaled.

First, obtain a pointer to the IDirectSoundNotify8 interface. You can do this with the capture buffer's QueryInterface method, as shown in the example under Play Buffer Notification.

Next create an event object with the Win32 CreateEvent function. You put the handle to this event in the hEventNotify member of a DSBPOSITIONNOTIFY structure, and in the dwOffset member of that structure, you specify the offset within the buffer where you want the event to be signaled. Then, you pass the address of the structure—or array of structures, if you want to set more than one notification position—to the IDirectSoundNotify8::SetNotificationPositions method.

The following example sets up three notification positions in a one-second buffer. One event will be signaled when the read position nears the halfway point in the buffer, another will be signaled when it nears the end of the buffer, and the third will be signaled when capture stops.

#define cEvents  3

// It is assumed that the following variables have
// been properly initialized, and that wfx was included in the
// buffer description when the buffer was created.
//
//   LPDIRECTSOUNDNOTIFY8 lpDsNotify;
//   WAVEFORMATEX          wfx;

HANDLE             rghEvent[cEvents] = {0};
DSBPOSITIONNOTIFY  rgdsbpn[cEvents];
HRESULT            hr;
int                i;

// Create the events.
for (i = 0; i < cEvents; ++i)
{
    rghEvent[i] = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (NULL == rghEvent[i])
    {
        hr = GetLastError();
        goto Error;
    }
}

// Describe notifications.

rgdsbpn[0].dwOffset = (wfx.nAvgBytesPerSec/2) -1;
rgdsbpn[0].hEventNotify = rghEvent[0];

rgdsbpn[1].dwOffset = wfx.nAvgBytesPerSec - 1;
rgdsbpn[1].hEventNotify = rghEvent[1];

rgdsbpn[2].dwOffset = DSBPN_OFFSETSTOP;
rgdsbpn[2].hEventNotify = rghEvent[2];

// Create notifications.

hr = lpDsNotify->SetNotificationPositions(cEvents, rgdsbpn);


Capture Buffer Effects

Capture buffer effects are not available on current operating systems.

Set effects on capture buffers by describing them in the DSCBUFFERDESC structure passed to IDirectSoundCapture8::CreateCaptureBuffer. After the buffer has been created, retrieve information about the effects by using IDirectSoundCaptureBuffer8::GetFXStatus.

The following interfaces represent capture effects supported by DirectX 8.0, and can be used to set and retrieve parameters:

  • IDirectSoundCaptureFXAec8
  • IDirectSoundCaptureFXNoiseSuppress8

These interfaces are obtained from the capture buffer object by using IDirectSoundCaptureBuffer8::GetObjectInPath.


Using the Capture Buffer

Capturing a sound consists of the following steps:

  1. Start the buffer by calling the IDirectSoundCaptureBuffer8::Start method. Audio data from the input device begins filling the buffer from the beginning.
  2. Wait until the desired amount of data is available. For one method of determining when the capture cursor reaches a certain point, see Capture Buffer Notification.
  3. When sufficient data is available, lock a portion of the capture buffer by calling the IDirectSoundCaptureBuffer8::Lock method.

    To make sure you are not attempting to lock a portion of memory that is about to be used for capture, you can first obtain the position of the read cursor by calling IDirectSoundCaptureBuffer8::GetCurrentPosition. For an explanation of the read cursor, see Capture Buffer Information.

    As parameters to the Lock method, you pass the size and offset of the block of memory you want to read. The method returns a pointer to the address where the memory block begins, and the size of the block. If the block wraps around from the end of the buffer to the beginning, two pointers are returned, one for each section of the block. The second pointer is NULL if the locked portion of the buffer does not wrap around.

  4. Copy the data from the buffer, using the addresses and block sizes returned by the Lock method.
  5. Unlock the buffer with the IDirectSoundCaptureBuffer8::Unlock method.
  6. Repeat steps 2 to 5 until you are ready to stop capturing data. Then call the IDirectSoundCaptureBuffer8::Stop method.

Normally, the buffer stops capturing automatically when the capture cursor reaches the end of the buffer. However, if the DSCBSTART_LOOPING flag was set in the dwFlags parameter to the IDirectSoundCaptureBuffer8::Start method, the capture will continue until the application calls the IDirectSoundCaptureBuffer8::Stop method.


Writing to a Wave File

The DirectSound API does not include methods for writing to wave files. However, the Dsutil.cpp file used by many of the SDK sample applications implements a CWaveFile class that has the following public methods:

  • Open. Opens a file for writing and retrieves the wave format, or opens the file for writing and writes the header chunks.
  • GetSize. Returns the size of the data chunk, after Open or ResetFile has been called.
  • Read. Copies a portion of the data chunk into a buffer and advances the read cursor.
  • Write. Writes from a buffer to the data chunk and advances the write cursor.
  • ResetFile. Sets the read and write cursors to the beginning of the data chunk.
  • Close. Closes the file.

The first step in writing a wave file is to call the CWaveFile::Open method. This creates the file and writes the wave format chunk. The parameters are the filename, a pointer to an initialized WAVEFORMATEX structure, and the WAVEFILE_WRITE flag. The method returns an HRESULT.

The following code opens a wave file for writing:

CWaveFile     g_pWaveFile;
WAVEFORMATEX  wfxInput;

ZeroMemory( &wfxInput, sizeof(wfxInput));
wfxInput.wFormatTag = WAVE_FORMAT_PCM;
wfxInput.nSamplesPerSec = 22050
wfxInput.wBitsPerSample =  8;
wfxInput.nChannels = 1;
wfxInput.nBlockAlign =
    wfxInput.nChannels * (wfxInput.wBitsPerSample / 8);
wfxInput.nAvgBytesPerSec =
    wfxInput.nBlockAlign * wfxInput.nSamplesPerSec;

g_pWaveFile = new CWaveFile;
if (FAILED(g_pWaveFile->Open("mywave.wav", &wfxInput,
        WAVEFILE_WRITE)))
{
    g_pWaveFile->Close();
}

The application can now begin copying data from the capture buffer to the file. The following function is called each time the read cursor reaches a notification position. The following global variables are used:

  • g_pDSBCapture is a pointer to the IDirectSoundCapture interface of the capture buffer.
  • g_dwNextCaptureOffset tracks the buffer offset of the next block of data that will be copied to the file.
  • g_dwCaptureBufferSize is the size of the capture buffer, used in calculating wraparound.
HRESULT RecordCapturedData()
{
    HRESULT hr;
    VOID*   pbCaptureData    = NULL;
    DWORD   dwCaptureLength;
    VOID*   pbCaptureData2   = NULL;
    DWORD   dwCaptureLength2;
    VOID*   pbPlayData       = NULL;
    UINT    dwDataWrote;
    DWORD   dwReadPos;
    LONG lLockSize;

    if (NULL == g_pDSBCapture)
        return S_FALSE;
    if (NULL == g_pWaveFile)
        return S_FALSE;

    if (FAILED( hr = g_pDSBCapture->GetCurrentPosition(
            NULL, &dwReadPos)))
        return hr;

    // Lock everything between our private cursor
    // and the read cursor, allowing for wraparound.

    lLockSize = dwReadPos - g_dwNextCaptureOffset;
    if( lLockSize < 0 )
        lLockSize += g_dwCaptureBufferSize;

    if( lLockSize == 0 )
        return S_FALSE;

    if (FAILED(hr = g_pDSBCapture->Lock(
            g_dwNextCaptureOffset, lLockSize,
            &pbCaptureData, &dwCaptureLength,
            &pbCaptureData2, &dwCaptureLength2, 0L)))
    return hr;

    // Write the data. This is done in two steps
    // to account for wraparound.

    if (FAILED( hr = g_pWaveFile->Write( dwCaptureLength,
            (BYTE*)pbCaptureData, &dwDataWrote)))
        return hr;

    if (pbCaptureData2 != NULL)
    {
        if (FAILED(hr = g_pWaveFile->Write(
                dwCaptureLength2, (BYTE*)pbCaptureData2,
                &dwDataWrote)))
                return hr;
    }

    // Unlock the capture buffer.

   g_pDSBCapture->Unlock( pbCaptureData, dwCaptureLength,
            pbCaptureData2, dwCaptureLength2  );

    // Move the capture offset along.

    g_dwNextCaptureOffset += dwCaptureLength;
    g_dwNextCaptureOffset %= g_dwCaptureBufferSize;
    g_dwNextCaptureOffset += dwCaptureLength2;
    g_dwNextCaptureOffset %= g_dwCaptureBufferSize;

    return S_OK;
}

When capturing is finished, the application closes the wave file.

g_pWaveFile->Close();

The CWaveFile::Close method writes the chunk sizes to the file before closing it.


Advanced Topics in DirectX Audio

This section contains information needed for specialized applications that need functionality beyond that covered under Using DirectX Audio.

Information is presented in the following topics:

  • DirectMusic Tracks
  • Using DirectMusic Messages
  • Using DirectMusic Ports
  • Custom Loading
  • Using Instrument Collections
  • Low-Level DLS
  • DirectMusic Tools
  • Property Sets
  • Optimizing DirectSound Performance
  • Writing to the Primary Buffer


DirectMusic Tracks

Tracks are the components of a segment that contain its sequenced data, including information about notes, underlying chords, tempo, patch and band changes, and everything else that the performance needs to know to play the sounds.

Each track is represented by an IDirectMusicTrack8 interface. The methods of this interface are called by the performance, and most applications don't need to use them directly. This interface is chiefly of interest for plug-in components that implement their own track types.

When an application calls IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx, DirectMusic calls the IDirectMusicTrack8::Play or IDirectMusicTrack8::PlayEx method on the segment's tracks. Most tracks respond by immediately generating time-stamped messages containing data that is valid for the part of the segment that is being played. These messages are placed in a queue. See Message Creation and Delivery for more information about what happens after that.

A few tracks do not actively generate messages other than notifications in response to IDirectMusicTrack8::Play or IDirectMusicTrack8::PlayEx, but instead do most of their work by responding to requests for information that come from the performance or other tracks. The most important of these are the chord, mute, and command tracks. The tempo track sends messages but also responds to parameter requests.

More information is contained in the following topics:

  • Standard Track Types
  • Track Configuration


Standard Track Types

The following list describes the standard track types implemented by Microsoft® DirectMusic®. The class identifiers, such as CLSID_DirectMusicBandTrack, are used to identify track types in calls to various methods.

Track type | Class GUID | Purpose
Band | CLSID_DirectMusicBandTrack | Downloads DLS data to the performance. Sends messages of type DMUS_PATCH_PMSG, DMUS_TRANSPOSE_PMSG, DMUS_CHANNEL_PRIORITY_PMSG, and DMUS_MIDI_PMSG (for volume and pan). Used in segments based on MIDI files and styles.
Chord | CLSID_DirectMusicChordTrack | Used to convert music values in patterns to MIDI values. Sends messages of type DMUS_NOTIFICATION_PMSG (for GUID_NOTIFICATION_CHORD notifications).
Chordmap | CLSID_DirectMusicChordMapTrack | Used in template segments to compose chord tracks.
Command | CLSID_DirectMusicCommandTrack | Used in template segments to compose chord tracks, and in style segments to determine which patterns are played. Sends messages of type DMUS_NOTIFICATION_PMSG for GUID_NOTIFICATION_COMMAND notifications.
Lyrics | CLSID_DirectMusicLyricsTrack | Used to synchronize words with music. Generates messages of type DMUS_LYRIC_PMSG.
Marker | CLSID_DirectMusicMarkerTrack | Used for flow control. The marker track can hold valid start times for the segment, and play times at which new segments can be cued. For more information, see Segment Timing.
Motif | CLSID_DirectMusicMotifTrack | Used to play motifs to accompany other segments. Sends messages of type DMUS_CURVE_PMSG, DMUS_NOTE_PMSG, and DMUS_NOTIFICATION_PMSG (for GUID_NOTIFICATION_MEASUREANDBEAT notifications).
Mute | CLSID_DirectMusicMuteTrack | Enables performance channels to be remapped or muted. Used with either style-based or MIDI-based segments.
Parameter control | CLSID_DirectMusicParamControlTrack | Controls the settings on tools, effects, and any other objects that support the IMediaParams interface.
Pattern | CLSID_DirectMusicPatternTrack | Contains a single musical pattern. The pattern track is similar to a sequence track, but contains music values rather than fixed notes. This track makes it possible to audition a pattern against different chords, and is used mostly by music-authoring applications. It might also be used to play an accompaniment. It is represented by its own interface, IDirectMusicPatternTrack8.
Script | CLSID_DirectMusicScriptTrack | Calls routines in an audio script.
Segment trigger | CLSID_DirectMusicSegmentTriggerTrack | Triggers the playback of segments. This track enables the author of a file to cue a segment from within a segment, rather than leaving this up to the application developer.
Sequence | CLSID_DirectMusicSeqTrack | Sends sequence messages of type DMUS_NOTE_PMSG and DMUS_MIDI_PMSG. Used in segments based on MIDI files. Also sends messages of type DMUS_CURVE_PMSG for segments saved in the .sgt format.
Signpost | CLSID_DirectMusicSignPostTrack | Used in template segments to compose chord tracks.
Style | CLSID_DirectMusicStyleTrack | Fundamental track for segments based on styles. Sends messages of type DMUS_TIMESIG_PMSG, DMUS_CURVE_PMSG, DMUS_NOTE_PMSG, and DMUS_NOTIFICATION_PMSG (for GUID_NOTIFICATION_MEASUREANDBEAT notifications).
SysEx | CLSID_DirectMusicSysExTrack | Sends system exclusive messages of type DMUS_SYSEX_PMSG. Used in segments based on MIDI files.
Tempo | CLSID_DirectMusicTempoTrack | Controls the tempo of the performance.
Time Signature | CLSID_DirectMusicTimeSigTrack | Sends messages of type DMUS_TIMESIG_PMSG as well as GUID_NOTIFICATION_MEASUREANDBEAT notifications. The time signature track exists in imported MIDI files and authored segments specifically created with one. In most cases, the style track implements the time signature track's functionality, so it is not necessary for a segment that contains a style track to contain a time signature track as well.
Wave | CLSID_DirectMusicWaveTrack | Sends messages of type DMUS_WAVE_PMSG to play time-stamped wave sounds.


Track Configuration

Using the IDirectMusicSegment8::SetTrackConfig and IDirectMusicSegmentState8::SetTrackConfig methods, an application can modify the behavior of any track in a segment. Configuration options include the following:

  • Enable or disable playback.
  • Enable or disable parameter calls on a track in a control segment.
  • Enable or disable notifications.
  • Override notifications in a primary segment with notifications from a secondary control segment.
  • Enable or disable track composition.
  • Control the start point of track data used in composing transitions.

For a list of the track configuration flags and a table of the flags valid on standard tracks, see IDirectMusicSegmentState8::SetTrackConfig.

Two of the configuration flags, DMUS_TRACKCONFIG_CONTROL_PLAY and DMUS_TRACKCONFIG_CONTROL_NOTIFICATION, extend the powers of secondary control segments. Normally, a secondary control segment manages only parameters that are obtained by the performance through calls to IDirectMusicTrack8::GetParam. Like any segment, the control segment can also make changes to the performance by sending messages. For example, it might change the volume of the performance. Such changes might appear to be overriding parameters in the primary segment, but they differ from true control changes in two ways:

  • They are valid only until a similar change is made by another segment. Control segment parameters cannot be overridden by other segments.
  • As long as they are not overridden, they remain valid even after the sending segment has finished playing. Control segment parameters are valid only until another segment becomes the control segment.

When the DMUS_TRACKCONFIG_CONTROL_PLAY or DMUS_TRACKCONFIG_CONTROL_NOTIFICATION flag is set on a track, the equivalent track on the primary segment is disabled. It is reenabled when the controlling segment stops.

The SetTrackConfig method is available on the IDirectMusicSegmentState8 interface as well as on IDirectMusicSegment8. The parameters are identical, but the behavior differs as follows:

  • If you change a flag on a segment, subsequent instances of playing segment states inherit the changed flags. However, segment states that are already playing do not change their behavior.
  • If you change a flag on a segment state, the behavior changes immediately for that segment state only.

Note To ensure that the track configuration on a segment state changes immediately rather than after prepare time, you can call IDirectMusicPerformance8::Invalidate.

The following example code disables a chord progression track in the segment addressed by pSegment. Chord progressions are broadcast as control segment parameters, so this is done by turning off the DMUS_TRACKCONFIG_CONTROL_ENABLED flag:

HRESULT hr = pSegment->SetTrackConfig(CLSID_DirectMusicChordTrack,
        -1, DMUS_SEG_ALLTRACKS, 0, DMUS_TRACKCONFIG_CONTROL_ENABLED);

The next example does the opposite, enabling all chord tracks to play:

hr = pSegment->SetTrackConfig(CLSID_DirectMusicChordTrack,
        -1, DMUS_SEG_ALLTRACKS, DMUS_TRACKCONFIG_CONTROL_ENABLED, 0);

The following topics contain related information:

  • Track Composition
  • Control Segments
  • Self-Controlling Segments


Using DirectMusic Messages

Sound data passes through the DirectMusic performance in the form of messages. For the most part, messages are created and processed behind the scenes, and your application might never have to work directly with them. However, a basic knowledge of messages can help you understand how DirectMusic works, and a more thorough understanding will enable you to use messages for greater control over the performance.

DirectMusic uses two different kinds of messages:

  • Performance messages. All sequenced data passes through the performance engine in this form. These messages contain detailed information about timing and routing of the data.
  • Standard MIDI messages. These can be read from a MIDI file or device and either passed directly (thrued) to another device or converted to performance message format when played by the performance.

Applications don't deal directly with MIDI messages. When a segment is played, all its data is in the form of performance messages and stays that way until it reaches the final output tool, which converts it to MIDI message format before sequencing it to the synthesizer. However, some performance messages contain information similar to that in standard MIDI messages. To help you understand such messages, this section describes some aspects of the MIDI message format.

Note The DMUS_MIDI_PMSG structure contains data equivalent to that in any standard MIDI message. It is, however, a performance message.

Most performance messages are sent by a segment's tracks as the segment is playing. Applications can also send messages to do things like setting a MIDI controller, playing a single note, or changing the tempo.

Once a message has been sent, the application cannot retrieve or alter it except by implementing a tool. For example, a segment authored in DirectMusic Producer might contain a lyrics track that generates DMUS_LYRIC_PMSG messages. The only way an application can display the lyrics is by implementing a tool designed for that purpose. For more information, see DirectMusic Tools.

Notifications are an exception to the rule that messages can be intercepted only by tools. The IDirectMusicPerformance8::GetNotificationPMsg method enables the application to retrieve DMUS_NOTIFICATION_PMSG messages. For more information, see Notification and Event Handling.

The following topics discuss messages and how they are routed:

  • Channels
  • Message Creation and Delivery
  • Application-Created Messages
  • Performance Message Types
  • Curves
  • MIDI Messages


Channels

A channel is a destination for a message that is specific to one part in the performance. For example, a channel might receive a note-on message that causes the instrument on that channel to make a sound, or a program-change message that assigns a different instrument to that part. See MIDI Channel Messages.

Under the MIDI 1.0 standard, there are 16 MIDI channels, meaning that no more than 16 instruments can be playing at one time. To support this standard but at the same time make more channels available to applications, DirectMusic creates channel groups. Up to 65,536 channel groups can exist at one time, each containing 16 channels, for a total of over one million channels. A particular port can be assigned any number of channel groups, up to its capability to support them. MIDI hardware ports have only a single channel group.

System-exclusive messages address all 16 channels within a channel group, but not other channel groups.

Every part in a DirectMusic performance has a unique performance channel, sometimes called a PChannel. The performance channel represents a particular MIDI channel in a particular group on a particular port. When a band is selected by a performance, each instrument in that band is mapped to a performance channel, so the part on that channel will play on that instrument.

When audiopaths are being used, identical performance channels on different audiopaths are mapped to different output channels.

Channel Priority

The number of notes that can be played simultaneously is limited by the number of voices available on the port. A voice is a set of resources dedicated to the synthesis of a single note or wave being played on a channel. In the event that more notes are playing than there are available voices, one or more notes must be suppressed by the synthesizer. The choice is determined by the priority of the voice currently playing the note, which is based in turn on the priority of the channel. By default, channels are ranked according to their index value, except that channel 10, the MIDI percussion channel, is ranked highest.

Applications and synthesizers can set their own channel priorities. For more information, see the Remarks for IDirectMusicPort8::GetChannelPriority. See also DMUS_CHANNEL_PRIORITY_PMSG.


Message Creation and Delivery

When a segment is played, most of its tracks generate messages containing information about events that are to take place during playback. For more information, see DirectMusic Tracks.

A few tracks send more than one kind of message. For example, a style track sends note messages and time signature messages. In such cases, an application can disable certain kinds of messages in the track. For more information, see Disabling and Enabling Track Parameters.

The performance engine determines when each message is to be processed in clock time. In the case of channel messages, the performance also determines which performance channel gets the message. This information, along with other data—including the message type, its source track, and pointers to the first toolgraph and tool that are to receive it—is stored in the message structure.

Certain messages, such as tempo and time signature changes, are immediately processed and freed by the performance. Other messages, such as notes and patch changes, are placed in a queue and processed in order of time stamp.

Notes There is no guarantee that messages with the same time stamp will be processed in any particular order.

Time signature messages are purely informational. The time signature is built into the segment and cannot be changed.

Messages are first sent to any tools in the segment toolgraph, then to the audiopath toolgraph, and finally to the performance toolgraph.

The application is responsible for creating the segment and performance toolgraphs and defining the tools. For more information on creating toolgraphs, see the following topics:

  • IDirectMusicGraph8
  • IDirectMusicPerformance8::SetGraph
  • IDirectMusicSegment8::SetGraph

Audiopath toolgraphs are optional components of audiopath configurations in DirectMusic Producer files. The application doesn't need to do anything to implement an audiopath toolgraph after creating the audiopath.

The first tool in a toolgraph processes the message and then, if it wants to pass it on, has the toolgraph stamp the message with a pointer to the next tool.

At this point the toolgraph also flags the message with a delivery type that determines when the message is delivered to the next tool. This flag is based on what delivery type the tool is expecting, as follows:

  • If the message is flagged as DMUS_PMSGF_TOOL_IMMEDIATE, it is delivered to the next tool immediately.
  • If it is flagged as DMUS_PMSGF_TOOL_QUEUE, the message is delivered just before the time at which it is supposed to play, taking latency into account (see Latency and Bumper Time).
  • If it is flagged as DMUS_PMSGF_TOOL_ATTIME, it is delivered at exactly the time at which it is to be processed. Notification messages are given this flag, because there is little or no latency involved in processing a notification.

The current tool can change the delivery type after the toolgraph has finished stamping and flagging the message.

Ultimately, unless a message has been discarded, it arrives at the DirectMusic output tool, which converts all the data it receives into standard MIDI messages and delivers these to the synthesizer through the port buffer.

For an illustration, see Overview of Audio Data Flow.


Application-Created Messages

Most messages are generated by tracks, but applications can place messages in the queue directly. You might do this, for example, to change the tempo or to play a sound effect as a note on a DLS instrument.

For more information and sample code, see IDirectMusicPerformance8::SendPMsg.

When a performance has multiple audiopaths, DirectMusic may not be able to route application-created messages correctly, because a new message contains no information about what audiopath it belongs to. Even a channel-specific message might belong to a performance channel that is mapped to different audiopaths in different segments.

To ensure that a message is sent to a particular audiopath, first obtain the toolgraph for a segment or audiopath by calling IDirectMusicSegmentState8::GetObjectInPath or IDirectMusicAudioPath8::GetObjectInPath, retrieving the IDirectMusicGraph8 interface from the DMUS_PATH_AUDIOPATH_GRAPH or DMUS_PATH_SEGMENT_GRAPH stage in the audiopath. Then pass the message to IDirectMusicGraph8::StampPMsg.


Performance Message Types

Messages are stored in various structures derived from DMUS_PMSG. Because C does not support inheritance, the members of DMUS_PMSG are included in the declaration for each message type as the DMUS_PMSG_PART macro. These members contain data common to all messages, including the type of the message, time stamps, the performance channel to which the message is directed, and what toolgraph and tool are next in line to process the message. The other members contain data unique to the message type.

The following standard message structures are defined.

Structure | Content
DMUS_PMSG | Simple message with no additional parameters. See Remarks for the structure.
DMUS_CHANNEL_PRIORITY_PMSG | Channel priority change. See Channels.
DMUS_CURVE_PMSG | Curve.
DMUS_LYRIC_PMSG | Text.
DMUS_MIDI_PMSG | Any MIDI message that does not have a unique message type—for example, a control change.
DMUS_NOTE_PMSG | Music note. (Includes duration, so MIDI note-on and note-off messages are combined in this type.)
DMUS_NOTIFICATION_PMSG | Notification. See Notification and Event Handling.
DMUS_PATCH_PMSG | MIDI patch change.
DMUS_SYSEX_PMSG | MIDI system exclusive message.
DMUS_TEMPO_PMSG | Tempo change.
DMUS_TIMESIG_PMSG | Time signature change.
DMUS_TRANSPOSE_PMSG | Transposition.
DMUS_WAVE_PMSG | Wave playback.


Curves

A curve is a series of MIDI controller changes bringing about a smooth transition from one value to another—for example, volume fade-out or fade-in.

You can execute a curve by sending a single performance message of type DMUS_CURVE_PMSG. This structure enables you to set the start and end values, the duration of the curve, and its shape. Optionally, you can also set a reset value, which is the value to which the controller will return in case of an invalidation.

The wMeasure, nOffset, bBeat, bGrid, and mtOriginalStart members of the message structure are for information only, and do not affect the timing of the message. They are set in messages sent by DirectMusic Producer segments, and can be used by tools. Applications can normally set these members to 0.

The wMergeIndex member is used to determine whether changes are cumulative or overriding. Two curve messages with different merge indexes are cumulative; otherwise, each message in turn overrides settings made by a previous message.

The bCCData member contains the MIDI controller number for controller changes, and is otherwise ignored. For information on controller numbers, see the MIDI specification.

The following sample code causes the volume to fade from its current value to zero over five seconds. If an invalidation occurs during that period, which might happen if another segment replaces the currently playing segment, full volume is restored.

DMUS_CURVE_PMSG *pCurveMsg;
HRESULT hr = g_pPerf->AllocPMsg(sizeof(DMUS_CURVE_PMSG),
        (DMUS_PMSG**) &pCurveMsg);
ZeroMemory(pCurveMsg, sizeof(DMUS_CURVE_PMSG));

pCurveMsg->dwSize = sizeof(DMUS_CURVE_PMSG);
pCurveMsg->rtTime = 0;
pCurveMsg->dwFlags = DMUS_PMSGF_DX8 | DMUS_PMSGF_REFTIME
        | DMUS_PMSGF_LOCKTOREFTIME;
pCurveMsg->dwPChannel = DMUS_PCHANNEL_BROADCAST_PERFORMANCE;
pCurveMsg->dwType = DMUS_PMSGT_CURVE;
pCurveMsg->dwGroupID = 0xFFFFFFF;
pCurveMsg->mtDuration = 5000;
pCurveMsg->nEndValue = 0;
pCurveMsg->bCurveShape = DMUS_CURVES_LINEAR;
pCurveMsg->bCCData = 7;
pCurveMsg->bFlags = DMUS_CURVE_RESET | DMUS_CURVE_START_FROM_CURRENT;
pCurveMsg->bType = DMUS_CURVET_CCCURVE ;

pCurveMsg->mtResetDuration = 0;
pCurveMsg->nResetValue = 127;

g_pPerf->SendPMsg((DMUS_PMSG*) pCurveMsg);

Note A simpler way to implement volume fading is by using IDirectMusicAudioPath8::SetVolume. This method always uses the linear shape for the curve.


MIDI Messages

Most applications don't deal directly with MIDI messages. However, an application can send a MIDI command as a performance message—for example, to make a control change.

MIDI messages consist of a status byte and usually one or two data bytes. System exclusive MIDI messages are of variable length.

The status byte indicates the type of message and, in some cases, the channel that is to receive the message. When several events of the same kind are in sequence in the file, the status byte can be omitted. Data bytes are recognizable because the high bit is always clear, whereas in status bytes it is always set.

The timing of MIDI events is controlled by a number before each message, indicating how many ticks separate this event from the last. The actual duration of a tick depends on the time format in the file header.

Note There is no guarantee that MIDI messages will be processed in the same order in which they occur in the source data. DirectMusic messages are delivered in order of time stamp, and two MIDI messages with identical times might not be delivered in the expected order. Care must be taken, in authoring MIDI content, to leave an interval between events if they must take place sequentially. For example, don't place a program change at the same time as a note that depends on the program change.

MIDI messages are divided into two main categories:

  • MIDI Channel Messages
  • MIDI System Messages


MIDI Channel Messages

A channel message is addressed to a particular MIDI channel, which corresponds to a single part in the music.

A channel message can be either a mode message or a voice message.

A mode message determines how a channel will deal with subsequent voice messages. For example, a mode message might instruct the channel to remain silent, ignoring all note-on messages until further notice.

Most channel messages are voice messages. They instruct the channel to begin or stop playing a note or to modify the note in some way, or they change the timbre by assigning a different MIDI patch number to the channel.

The following table describes types of voice messages.

Voice message | Purpose
Note-on | Play a note.
Note-off | Stop playing the note.
Control change | Modify the tone with data from a pedal, lever, or other device; also used for miscellaneous controls such as volume and bank select.
Program (patch) change | Select an instrument for the channel by assigning a patch number.
Aftertouch | Modify an individual note, or all notes on the channel, according to the aftertouch of a key.
Pitch bend change | Modify the pitch of all notes played on the channel.

Keep in mind that these descriptions apply to standard MIDI messages, not MIDI data that has been converted to performance message format. For example, two MIDI messages to start and stop a note are combined by DirectMusic into a single performance message giving the duration of the note. DirectMusic messages also contain much additional information about timing and routing.

MIDI Notes

The data bytes of a note-on message represent the pitch and velocity. In most cases, a pitch value of 0 represents C below subcontra C (called C0 in MIDI notation), 12 represents subcontra C (or C1), 60 is middle C (or C5), and so on. For drum kits, the data byte instead represents a particular drum sound. For example, as long as the General MIDI (GM) percussion key map is being adhered to, a value of 60 represents a high bongo sound. Channel 10 is reserved for drum kits, so the synthesizer knows that note-on messages on that channel are to be treated differently than on other channels.

For information on how DirectMusic converts to and from MIDI notes, see Music Values and MIDI Notes.

Program Changes

Program changes and patch numbers are a key concept in MIDI playback and in DirectMusic. A program change assigns a particular instrument (also called a program or timbre) to a channel so that the notes sent to that channel are played with the appropriate sound. Instruments are identified by patch numbers. If the GM instrument set is loaded, a program change specifying patch number 1 always causes the channel to play its notes as an acoustic grand piano. The actual sound produced at the speakers depends on how the instrument is synthesized.

Bank Selection

Because a single data byte is used to select the patch number in a program change, and only 7 bits in each data byte of a MIDI message are significant, a program change can select from a maximum of 128 instruments. To provide a greater choice, the MIDI specification allows for the use of up to 16,384 instrument banks, each containing up to 128 instruments.

To select an instrument from a different bank, the MIDI sequencer must first send a control change message called bank select. The 2 data bytes of this message are referred to as the most significant byte (MSB) and least significant byte (LSB), and they are combined to identify a bank. Once the bank has been selected, each subsequent program change selects an instrument from that bank.

DirectMusic Patch Numbers

In DirectMusic, the instrument patch number is not the 7-bit MIDI patch number but a 32-bit value that packs the MIDI patch number together with the MSB and LSB of the bank select and a one-bit flag for a drum kit. This extended patch number is returned by the IDirectMusicCollection8::EnumInstrument, IDirectMusicCollection8::GetInstrument, and IDirectMusicInstrument8::GetPatch methods. It can be changed for an instrument by using the IDirectMusicInstrument8::SetPatch method.

The organization of DirectMusic patch values is shown in the following table.

Bits | Purpose
0-7 | MIDI patch number (bit 7 is always 0)
8-15 | LSB bank select (bit 15 is always 0)
16-23 | MSB bank select (bit 23 is always 0)
24-30 | Unused
31 | Flag for drum kit


MIDI System Messages

System messages are not exclusive to any channel. There are three kinds, as shown in the following table.

Message type | Purpose
System common | Miscellaneous commands and data.
System exclusive | Equipment-specific commands and data.
System real-time | Synchronization of clock-based MIDI equipment.

Unlike other MIDI messages, system exclusive messages can contain any number of data bytes. After transmitting the data, the sequencer sends a system common message called an EOX, which signals the end of the system exclusive message.

In DirectMusic, the DMUS_SYSEX_PMSG structure contains the length of the data and a pointer to an array of data bytes.


Using DirectMusic Ports

This section covers access to DirectMusic ports by applications that do not use audiopaths. If your application initializes the performance by using IDirectMusicPerformance8::InitAudio, as is recommended, the audiopath manages ports and the mapping of performance channels to ports.

A port is a device that sends or receives data. It can correspond to a hardware device, a software synthesizer, or a software filter.

Each port in a DirectMusic application is represented by an IDirectMusicPort8 interface. Methods of this interface are used to retrieve information about the device, manage the memory on the device, download and unload DLS instruments, read incoming data, and cue playback buffers.

Every performance must have at least one port. If you want to use a port other than the default port, or to set special parameters for the default port, first set up a DMUS_PORTPARAMS8 structure. You don't have to fill in all members, but you must let DirectMusic know which members have valid information by putting the appropriate flags in the dwValidParams member. Then pass the structure to the IDirectMusic8::CreatePort method.

The following C++ code demonstrates how an object might be created for the default port, setting five channel groups on the port. Assume that pDirectMusic is a valid IDirectMusic8 interface pointer.

IDirectMusicPort8*  pPort;
DMUS_PORTPARAMS    dmos;

ZeroMemory( &dmos, sizeof(DMUS_PORTPARAMS) );
dmos.dwSize = sizeof(DMUS_PORTPARAMS);
dmos.dwValidParams = DMUS_PORTPARAMS_CHANNELGROUPS;
dmos.dwChannelGroups = 5;
HRESULT hr = pDirectMusic->CreatePort( GUID_NULL, &dmos,
        &pPort, NULL )

Once you have a port, you must activate it by calling IDirectMusic8::Activate or IDirectMusicPort8::Activate and attach it to the performance by using the IDirectMusicPerformance8::AddPort method.

When you add a port to a performance, assign a block of PChannels to it by calling the IDirectMusicPerformance8::AssignPChannelBlock method. The only time this isn't necessary is when you add the default port by passing NULL to IDirectMusicPerformance8::AddPort. In that case, PChannels 0 through 15 are assigned to the MIDI channels in the first group on the port.

You can map PChannels differently, add more PChannels, or assign PChannels to a different port by using the IDirectMusicPerformance8::AssignPChannelBlock and IDirectMusicPerformance8::AssignPChannel methods.

More information about ports is contained in the following topics:

  • Default Port
  • Property Sets for DirectMusic Ports


Default Port

Under Windows® 95 and versions of Windows 98 prior to Windows 98 Second Edition, and always when hardware that supports DLS is not available, the Microsoft software synthesizer is the default port. Under later versions of Windows 98 and under Windows 2000, a hardware synthesizer could be the default port.

If you want your application to use the default port, you don't have to call the IDirectMusic8::CreatePort method before adding the port to the performance. Instead, you can pass NULL to IDirectMusicPerformance8::AddPort.

You can obtain the default port by a call to IDirectMusic8::GetDefaultPort, and then check its capabilities by using the IDirectMusicPort8::GetCaps method. If the port does not meet the needs of your application, use the IDirectMusic8::EnumPort method to find the Microsoft software synthesizer or another port.


Custom Loading

Specialized applications might create their own object types that encapsulate data from a file or resource. It can be convenient to have the DirectMusic loader handle the loading of such objects. This is especially true if the custom object is referenced by other objects or contains references to other objects.

To implement a loading mechanism that takes advantage of the DirectMusic loader, take the following steps:

  • Register the object class so that it can be found by IDirectMusicLoader8::GetObject.
  • Implement the IDirectMusicObject8 interface on the object so that the loader can get the information that it needs to find and cache it.
  • Implement the IPersistStream interface on the object, with full functionality in the IPersistStream::Load method. This is where you parse the data that you obtain through calls on the IStream interface passed by the DirectMusic loader.
  • In the implementation of Load, ensure that references to other objects are dealt with by querying the IStream for the IDirectMusicGetLoader8 interface, then calling IDirectMusicGetLoader8::GetLoader to obtain a pointer to the DirectMusic loader that created the stream. Once you have this pointer, you can call IDirectMusicLoader8::GetObject to load the new object.

It might happen that an application needs to manage file input itself—for example, because all objects are stored in a special compressed resource file. The application can create its own loader by creating an object that supports the IDirectMusicLoader8 interface, with the IDirectMusicLoader8::GetObject method implemented. All other methods are optional. This implementation of the loader must also create its own stream object that has both the IStream and the IDirectMusicGetLoader8 interfaces.


Using Instrument Collections

In most applications, DLS instrument data is associated with bands and is downloaded to the synthesizer when the band is downloaded. For more information, see Using Bands.

For specialized DirectMusic applications that do their own DLS management, two steps must be taken: loading the instrument collection and downloading instrument data to a port.

These steps are covered in the following sections:

  • Loading and Downloading Collections
  • Working with Instruments

Applications for editing instruments and collections must work with DLS data at an even lower level. This topic is covered in the following section:

  • Low-Level DLS


Loading and Downloading Collections

Collections are loaded like other objects. For more information, see Loading Audio Data.

To load the standard GM/GS set, pass GUID_DefaultGMCollection to the loader in the guidObject member of the DMUS_OBJECTDESC structure. If you intend to use the loader to access this object more than once, make sure that caching is enabled (as it is by default) so that you don't create another copy of the GM collection each time you request it.

Note The GM/GS Sound Set cannot be altered. For more information, see the Copyright Warning.

The following code example illustrates how to load a collection identified by its GUID:

HRESULT myGetGMCollection(
        IDirectMusicLoader8 *pILoader,
        IDirectMusicCollection8 **ppICollection)
{
    HRESULT hr;
    DMUS_OBJECTDESC desc;

    desc.dwSize = sizeof(DMUS_OBJECTDESC);
    desc.guidClass = CLSID_DirectMusicCollection;
    desc.guidObject = GUID_DefaultGMCollection;
    desc.dwValidData = (DMUS_OBJ_CLASS | DMUS_OBJ_OBJECT);
    hr = pILoader->GetObject(&desc, IID_IDirectMusicCollection8,
            (void **) ppICollection);
    return hr;
}

Once you have obtained a pointer to the IDirectMusicCollection8 interface, you have access to all the instruments in the collection. At this point, though, none of them have been downloaded to a port.

To download an entire collection at once, you must associate the collection with a segment and then call the IDirectMusicSegment8::Download method. For an example, see Playing a MIDI File with Custom Instruments.

These steps are necessary only when you want to use a collection other than the default one. Normally, when you call IDirectMusicSegment8::Download, the instruments downloaded to the port are from the default collection authored into the segment, or from the General MIDI set if the segment does not reference a collection. When you download a band, all DLS data needed by the instruments in that band is downloaded. See Using Bands.


Working with Instruments

When a collection object is created and loaded from a collection file or resource, it is not bound to any specific port. You can download different instruments to different ports or download a single instrument to multiple ports.

You can retrieve the patch number and name of all the available instruments by using the IDirectMusicCollection8::EnumInstrument method.

The following code example enumerates all instruments in a collection and displays their names and patch numbers:

void myListInstruments(
        IDirectMusicCollection8 *pCollection)

{
    HRESULT hr = S_OK;
    DWORD dwPatch;
    WCHAR wszName[MAX_PATH];
    DWORD dwIndex;
    for (dwIndex = 0; hr == S_OK; dwIndex++)
    {
        hr = pCollection->EnumInstrument(
                dwIndex, &dwPatch, wszName, MAX_PATH);
        if (hr == S_OK)
        {
           printf("Patch %lx is %S\n",dwPatch,wszName);
        }
    }
}

Obtain a pointer to a specific instrument by passing its patch number to the IDirectMusicCollection8::GetInstrument method.

After obtaining an instrument, you can change its patch number by using the IDirectMusicInstrument8::SetPatch method.

To download a single instrument to a port, pass an IDirectMusicInstrument8 interface pointer to the IDirectMusicPort8::DownloadInstrument or IDirectMusicPerformance8::DownloadInstrument method. This call makes the DLS data available on the port; it does not associate the instrument with any particular performance or audiopath.

To save memory, only waves and articulation required for given ranges of notes are downloaded. For example, for a bassoon you might specify that only data for the note range from low C through middle B is to be downloaded. Data for regions falling entirely outside that range is not downloaded.

The following code example, given a collection, a patch number, a port, and a range of notes, retrieves the instrument from the collection and downloads it. It sets up an array of one DMUS_NOTERANGE structure and passes this to the IDirectMusicPort8::DownloadInstrument method. Typically, only a single range of notes is specified, but it is possible to specify multiple ranges. If you pass NULL instead of an array, the data for all regions is downloaded.

HRESULT myDownload(
    IDirectMusicCollection8 *pCollection,    // DLS collection
    IDirectMusicPort8 *pPort,                // Destination port
    IDirectMusicDownloadedInstrument8 **ppDLInstrument,
    DWORD dwPatch,                          // Requested instrument
    DWORD dwLowNote,                        // Low note of range
    DWORD dwHighNote)                       // High note of range

{
    HRESULT hr;
    IDirectMusicInstrument8* pInstrument;
    hr = pCollection->GetInstrument(dwPatch, &pInstrument);
    if (SUCCEEDED(hr))
    {
        DMUS_NOTERANGE NoteRange[1];         // Optional note range
        NoteRange[0].dwLowNote = dwLowNote;
        NoteRange[0].dwHighNote = dwHighNote;
        hr = pPort->DownloadInstrument(pInstrument,
                ppDLInstrument,
                NoteRange,   // Array of ranges
                1);          // Number of elements in the array
        pInstrument->Release();
    }
    return hr;
}

The DownloadInstrument method returns a pointer to the IDirectMusicDownloadedInstrument8 interface. This pointer has just one purpose: to identify the instrument in a subsequent call to the IDirectMusicPort8::UnloadInstrument method, which unloads the instance of the instrument on a particular port.

The following function downloads an instrument and then unloads it, which is not useful except to illustrate how the IDirectMusicDownloadedInstrument8 pointer can be used:

HRESULT myFickleDownload(
        IDirectMusicInstrument8* pInstrument,
        IDirectMusicPort8 *pPort,
        DWORD dwPatch)

{
    HRESULT hr;
    IDirectMusicDownloadedInstrument * pDLInstrument;
    hr = pPort->DownloadInstrument(
            pInstrument, &pDLInstrument,
            NULL, 0);
    if (SUCCEEDED(hr))
    {
        pPort->UnloadInstrument(pDLInstrument);
        pDLInstrument->Release();
    }
    return hr;
}


Low-Level DLS

If you are writing an application that edits DLS collections, you need to be able to download instrument data to the synthesizer without encapsulating it in a DirectMusic instrument object.

Working with DLS data requires knowledge of the DLS specification and file structure. For detailed information on these topics, contact the MIDI Manufacturers Association.

To download raw instrument data, you must first get a pointer to the IDirectMusicPortDownload8 interface, as shown in the following code example, where it is assumed that pIPort is a valid pointer to an IDirectMusicPort8 interface:

IDirectMusicPortDownload **ppIDownloadPort;

HRESULT hr = pIPort->QueryInterface(IID_IDirectMusicPortDownload8,
        (void **) ppIDownloadPort);

If the HRESULT is not S_OK, the port does not support DLS downloading.

Next, identify the buffers that must be prepared and downloaded. To send an instrument to the synthesizer, create one instrument buffer that represents the entire instrument definition with all the regions and articulations, and a series of wave buffers, one for each wave that the instrument references for its regions.

Each buffer must be tagged with a unique identifier. Identifiers are used to resolve linkages between buffers, in particular the links between regions and waves. Tally the number of buffers that you need to download, and call IDirectMusicPortDownload8::GetDLId to allocate a range of identifiers. For example, if you are downloading an instrument with three waves, you must download four buffers in all, so request a set of four identifiers.

For each buffer, calculate the size needed; then call IDirectMusicPortDownload8::AllocateBuffer to allocate it. This method returns an IDirectMusicDownload8 interface representing the buffer. Call IDirectMusicDownload8::GetBuffer to access the memory.

Note There are two methods called GetBuffer:

IDirectMusicPortDownload8::GetBuffer returns an IDirectMusicDownload interface pointer for a buffer object whose download identifier is known.

IDirectMusicDownload::GetBuffer returns a pointer to the memory in the buffer.

Now write the data into the buffers. Each buffer starts with a DMUS_DOWNLOADINFO structure, which defines the size and functionality of the download. This structure must be prepared as follows:

  • Set the dwDLType member to either DMUS_DOWNLOADINFO_INSTRUMENT2 for an instrument or DMUS_DOWNLOADINFO_WAVE for a wave.
  • Set the dwDLId member to one of the unique identifiers that you obtained by using IDirectMusicPortDownload::GetDLId.
  • Set the dwNumOffsetTableEntries member to the number of entries in the DMUS_OFFSETTABLE structure.
  • Set the cbSize member to the size of the download chunk, including DMUS_DOWNLOADINFO and DMUS_OFFSETTABLE.

The DMUS_DOWNLOADINFO structure is always followed by a DMUS_OFFSETTABLE structure. This offset table is used to manage all links within the data. Whenever a structure in the data refers to another structure, it addresses it with an integer index instead of a pointer. For every structure within the data that can be referenced, there is a unique index. The DMUS_OFFSETTABLE translates this integer index into a byte offset into the data.

The instrument or wave data follows the DMUS_OFFSETTABLE. If the download is an instrument, the data starts with the DMUS_INSTRUMENT structure. Otherwise, it starts with the DMUS_WAVE structure.

The instrument data that follows the DMUS_INSTRUMENT structure is organized in the following structures:

  • DMUS_ARTICPARAMS
  • DMUS_ARTICULATION
  • DMUS_ARTICULATION2
  • DMUS_COPYRIGHT
  • DMUS_EXTENSIONCHUNK
  • DMUS_INSTRUMENT
  • DMUS_NOTERANGE
  • DMUS_REGION

The wave data pointed to by the DMUS_WAVE structure is organized in a DMUS_WAVEDATA structure.

When the buffers are all ready, download them by using IDirectMusicPortDownload8::Download. Download the wave buffers first so that they are in place and can be referenced when the instrument is downloaded.

Once the buffers have been downloaded, the synthesizer is ready to play the instrument. The memory in the buffer is no longer accessible.

Later, when done playing the instrument, unload the buffers and release them. First unload the instrument buffer, then all the wave buffers. To unload, pass the IDirectMusicDownload8 pointers to IDirectMusicPortDownload8::Unload. Then release each buffer with a call to IDirectMusicDownload8::Release.

To update an instrument that has already been downloaded, you cannot write over the previously downloaded buffer. Instead, replace the instrument, but not the waves. To do this, call IDirectMusicPortDownload8::AllocateBuffer to allocate a new IDirectMusicDownload8 interface with a buffer of the correct size. Be sure to generate a new identifier for the buffer with a call to IDirectMusicPortDownload8::GetDLId. Write the new articulation information into the buffer; then download it. Then unload the previously downloaded buffer with a call to IDirectMusicPortDownload8::Unload.

To update a wave buffer, take one extra step. Create both a new wave buffer and an updated instrument buffer that references it. Download the new wave, then the new instrument. Then unload the old instrument and the old wave.


DirectMusic Tools

A tool is an object that intercepts messages and handles them in some way. The tool might alter the message and then pass it on to the next tool, or free the message, or send a new message based on information in the old one.

DirectMusic has an output tool that is normally the last to receive messages. It is this tool that converts performance messages to standard MIDI messages and streams them to the synthesizer. Other tools are implemented by the application or obtained from libraries.

To implement a tool, you must first create an object that supports the IDirectMusicTool8 interface. The object's implementation of the IDirectMusicTool8 methods determines what messages are processed by the tool and what work is performed on these messages.

All tools other than the output tool are collected in toolgraphs. Even if your application is using only one other tool, you must create a toolgraph to contain it. Then add this toolgraph to a segment or the performance. Toolgraphs provide a convenient mechanism for directing messages from one tool to another.

When the performance engine is playing a segment, it enables each tool in the segment toolgraph, and then each tool in the performance toolgraph, to process each message. After a tool processes a message, it should obtain the IDirectMusicGraph8 pointer from the pGraph member of the DMUS_PMSG structure and then call the IDirectMusicGraph8::StampPMsg method to stamp the message with a pointer to the next tool, if any, that is to receive it.

Tools process messages in a high-priority thread. Do not call time-consuming functions, such as those involving graphics or file input/output, from within a tool's IDirectMusicTool8::ProcessPMsg method. If a tool needs to trigger an action, it should do so by signaling a different thread, perhaps the application's main thread.

When implementing the methods of IDirectMusicTool8, take care not to create circular references to parent objects. Circular references come about when one object creates another and the child keeps an additional reference to the parent. For example, suppose a tool creates a new reference to the toolgraph passed into its IDirectMusicTool8::Init method. If the tool fails to release this reference, there is a problem when the segment attempts to release the toolgraph. Because the tool still has a reference to the toolgraph, the toolgraph is not fully released; and because the toolgraph has a reference to the tool, the tool cannot be released either.

For an example of how to implement a tool, see the MusicTool sample application.


Property Sets

Through property sets, DirectX Audio is able to support extended services offered by ports and sound cards.

Hardware vendors define new capabilities as properties and publish the specification for these properties. A GUID identifies a property set, and a ULONG identifies a particular property within the set. For example, a hardware vendor might design a card capable of reverberation effects and define a property set DSPROPSETID_ReverbProps containing properties such as DSPROPERTY_REVERBPROPS_HALL and DSPROPERTY_REVERBPROPS_STADIUM. Typically, the property identifiers are defined using a C language enumeration starting at ordinal zero.

Individual properties may also have associated parameters. The meaning of the parameters is defined along with the properties.


Property Sets for DirectMusic Ports

Use the IKsControl::KsProperty method to find out whether a property is available and then to set and retrieve values for that property. You obtain the IKsControl interface for a port by calling the IDirectMusicPort8::QueryInterface method, passing IID_IKsControl as the interface identifier.

A property set is represented by a GUID, and each item within the set is represented by a zero-based index. The meaning of the indexed items for a GUID never changes. For a list of the property sets supported by DirectMusic, see KSPROPERTY.

All property sets predefined by DirectMusic have only one item, usually at index 0. However, the full definition of kernel-streaming (KS) properties is supported, and vendors are free to create property sets with any number of items and instances, and data of any size.

Routing of the property item request to the port varies depending on the port implementation. No properties are supported by ports that represent DirectMusic emulation over the Win32® handle-based multimedia calls (the midiOut and midiIn functions).

The following code example uses the IKsControl::KsProperty method to determine if the port supports General MIDI in hardware:

BOOL IsGMSupported(IDirectMusicPort8 *pPort)
{
    HRESULT     hr;
    IKsControl  *pControl;
    KSPROPERTY  ksp;
    DWORD       dwFlags;
    ULONG       cb;
    BOOL        fIsSupported;

    // Query for an IKsControl interface.
    hr = pPort->QueryInterface(IID_IKsControl, (void**)&pControl);
    if (FAILED(hr))
    {
        // Port does not support properties; assume no GM support.
        return FALSE;
    }
    // Ask about GM.
    ksp.Set   = GUID_DMUS_PROP_GM_Hardware;
    ksp.Id    = 0;
    ksp.Flags = KSPROPERTY_TYPE_BASICSUPPORT;
    hr = pControl->KsProperty(&ksp, sizeof(ksp),
            &dwFlags, sizeof(dwFlags), &cb);
    fIsSupported = FALSE;
    if (SUCCEEDED(hr) || (cb >= sizeof(dwFlags))
    {
        // Set is supported.
        fIsSupported = (BOOL)(dwFlags & KSPROPERTY_TYPE_GET);
    }
    pControl->Release();
    return fIsSupported;
}


Property Sets for DirectSound Buffers

To make use of extended properties on sound cards, you must first determine whether the driver supports the IKsPropertySet interface, and obtain a pointer to the interface if it is supported. You can do this by calling the QueryInterface method of an existing interface on a DirectSound 3-D buffer object, as follows:

HRESULT hr = lpDirectSound3DBuffer->QueryInterface(
        IID_IKsPropertySet,
        (void**)&lpKsPropertySet));

In the example, lpDirectSound3DBuffer is a pointer to the buffer's interface and lpKsPropertySet receives the address of the IKsPropertySet interface if one is found. IID_IKsPropertySet is a GUID defined in Dsound.h.

The call will succeed only if the buffer is hardware-accelerated and the underlying driver supports property sets. If it does succeed, you can now look for a particular property using the IKsPropertySet::QuerySupport method. The value of the PropertySetId parameter is a GUID defined by the hardware vendor.

Once you've determined that support for a particular property exists, you can change the state of the property by using the IKsPropertySet::Set method and determine its present state by using the IKsPropertySet::Get method. The state of the property is set or returned in the pPropertyData parameter.

Additional property parameters may also be passed to the object in a structure pointed to by the pPropertyParams parameter to the IKsPropertySet::Set method. The exact way in which this parameter is to be used is defined in the hardware vendor's specifications for the property set, but typically it would be used to define the instance of the property set. In practice, the pPropertyParams parameter is rarely used.


Optimizing DirectSound Performance

This section offers some miscellaneous tips for improving the performance of applications that play their audio data directly into DirectSound buffers. The following topics are covered:

  • Matching Buffer Formats
  • Using Hardware Mixing
  • Dynamic Voice Management
  • Hardware Acceleration on ISA and PCI Cards
  • Playing the Primary Buffer Continuously
  • Minimizing Control Changes
  • CPU Considerations for 3-D Buffers


Matching Buffer Formats

The DirectSound mixer converts the data from each secondary sound buffer into the format of the primary sound buffer. This conversion is done on the fly as data is mixed into the primary buffer, and costs CPU cycles. You can eliminate this overhead by ensuring that your secondary buffers and primary buffer have the same format. Normally, this means setting the primary buffer format to the format of the wave files used for data.

Because of the way DirectSound does format conversion, you only need to match the sample rate and number of channels. It doesn't matter if there is a difference in sample size (8-bit or 16-bit).


Using Hardware Mixing

Most sound cards support some level of hardware mixing if there is a DirectSound driver for the card. The following tips will enable you to make the most of hardware mixing:

  • At run time, use the IDirectSound8::GetCaps method to determine what formats are supported by the sound-accelerator hardware and use only those formats if possible.
  • Create sound buffers first for the sounds you use the most. There is a limit to the number of buffers that can be mixed by hardware.
  • To force a buffer to be created in hardware, specify the DSBCAPS_LOCHARDWARE flag in the dwFlags member of the DSBUFFERDESC structure. If you do this and resources for hardware mixing are not available, the IDirectSound8::CreateSoundBuffer method will fail.
  • Use voice management to enable DirectSound to assign buffers to hardware resources when they are available, and to force termination of less important buffers in order to free hardware resources. See Dynamic Voice Management.


Dynamic Voice Management

Many sound cards maintain their own secondary buffers and handle 3-D effects and mixing for them. These hardware buffers, as they are called, usually reside in system memory rather than on the card itself, but because they are mixed by the device, they make far smaller demands on the system processor than do software buffers. It is therefore most efficient to have as many buffers as possible allocated to hardware, especially 3-D buffers.

By default, DirectSound allocates buffers to hardware whenever it can. However, it can create only as many hardware buffers as the device can play at one time—that is, the number of hardware buffers is limited by the hardware voices available. DirectSound allocates a hardware voice when a buffer is created and releases it only when the buffer is destroyed; the voice is not free even when the buffer is not playing. If an application creates many buffers, chances are that some of them will end up being in software—that is, they will be managed and mixed by the CPU rather than the sound card.

Dynamic voice management helps you overcome the limited availability of hardware resources by deferring voice allocation until buffers are played, and by enabling DirectSound to stop lower-priority sounds prematurely so that their resources can be allocated to new sounds.

To defer the allocation of resources for hardware mixing and 3-D effects to the moment when the buffer is played, specify the DSBCAPS_LOCDEFER flag in the DSBUFFERDESC structure passed to IDirectSound8::CreateSoundBuffer. When you call IDirectSoundBuffer8::Play or IDirectSoundBuffer8::AcquireResources on a buffer created with the DSBCAPS_LOCDEFER flag, DirectSound places the buffer in hardware if possible, and in software otherwise.

When calling Play, you can attempt to free a hardware voice for the buffer by passing one of the flags in the following table, or one of the first two flags in combination with the third. DirectSound then searches for a playing buffer that is suitable for termination as specified by the flags.

Flag | Criterion
DSBPLAY_TERMINATEBY_TIME | Select the buffer that has been playing longer than any other candidate buffers.
DSBPLAY_TERMINATEBY_DISTANCE | Select the 3-D candidate buffer farthest from the listener.
DSBPLAY_TERMINATEBY_PRIORITY | Select the buffer that has the lowest priority of candidate buffers, as set in the call to Play. If this is combined with one of the other two flags, the other flag is used only to resolve ties.

If it finds a suitable buffer, DirectSound stops it and allocates the voice it was using to the newly played buffer. If no buffer is suitable for termination, the newly played buffer is played in software, unless the DSBPLAY_LOCHARDWARE flag was specified, in which case the call to Play fails.

For more information on how deferred buffers are dealt with when played, see IDirectSoundBuffer8::Play.

Note Do not use the DSBCAPS_STATIC flag in combination with DSBCAPS_LOCDEFER when creating buffers. DSBCAPS_STATIC buffers are placed in on-card memory when this is available, as is the case for some PCI cards. If you create such a buffer with the DSBCAPS_LOCDEFER flag, the buffer memory is not copied to the sound card until the buffer is played for the first time, which can result in unacceptable delays. For more information, see Voice Management on ISA and PCI Cards.


Hardware Acceleration on ISA and PCI Cards

In the past few years, sound cards have moved from the ISA bus to the PCI bus. This design change has fundamentally altered the way DirectSound-accelerated cards handle audio data. In addition, DirectSound has introduced voice management, which enables applications to make more efficient use of limited hardware acceleration resources.

This section discusses some considerations in allocating buffers and using voice management on the two kinds of sound cards. The following topics are discussed:

  • DirectSound Buffers on ISA Cards
  • DirectSound Buffers on PCI Cards
  • Voice Management on ISA and PCI Cards


DirectSound Buffers on ISA Cards

When DirectSound was first introduced, all audio devices operated on the ISA bus. The ISA bus was sufficient to stream 16-bit, 22 kHz stereo data from the CPU to the sound card without unduly affecting overall system performance, but attempting to send more data often placed an undue burden on the bus. This limitation had a strong influence on audio hardware design.

To mix DirectSound buffers, a chip on the sound card has two choices: it can reach across the ISA bus into system memory, or it can have dedicated memory on the card itself. Owing to the ISA bus's limited bandwidth, reading audio data from system memory is not practical. Therefore, ISA-based sound cards that do DirectSound acceleration almost always have dedicated on-card RAM.

When such a sound card is used to accelerate DirectSound, the sound data must first be copied from system memory, across the ISA bus, and into the dedicated memory on the card. This copying can take some time. However, once the data is on the card, there is almost no cost to the system for starting, stopping, and mixing sounds; all that is handled by the audio processor chip accessing its own dedicated memory.

ISA-based DirectSound accelerators support static buffers on the card, but not streaming buffers, because it is impractical to stream data across the slow ISA bus. DirectSound buffers created with the DSBCAPS_STATIC flag are located in card memory if it is available. Others are created in system memory.


DirectSound Buffers on PCI Cards

Most audio cards sold today, if not all, are designed to connect to the PCI bus. With the movement to this bus comes a large increase in the available bandwidth between the system and the audio card. It is now practical to have the audio chip reach directly into system memory to retrieve audio data for hardware mixing. As a result, it is no longer worthwhile to have on-board memory for buffers.

On PCI cards, static buffers and streaming buffers are effectively the same. The DSBCAPS_STATIC flag does not affect the location of the buffer, because all buffers are located in system memory.

Note Most sound cards report in DSCAPS that they have static buffers, even though they have no on-card RAM. The streaming and static buffers reported by these cards are often the same buffers.


Voice Management on ISA and PCI Cards

By using the DSBCAPS_LOCDEFER flag when creating a buffer, you can defer the allocation of buffers to hardware-mixed or software-mixed memory until the moment when they are played. For information, see Dynamic Voice Management.

The effect of deferred allocation on application performance depends on the type of DirectSound accelerator in the user's system.

Consider the case of a PCI accelerator. When a deferred buffer is played, DirectSound first determines if there is hardware available to play the sound. Assuming there is, DirectSound then ensures that the hardware has access to the sound data, which remains where it is. Finally, DirectSound tells the hardware to start playing. This process is both efficient and fast.

Note The DirectSound voice manager allocates hardware mixing resources, not memory. On a PCI card, the buffer occupies the same memory before and after it is allocated, regardless of whether it is allocated to the hardware mixer or the software mixer.

If the user has an ISA-based accelerator, the situation is quite different. In this case, the act of getting audio data to a hardware-mixed buffer is very slow, because the data needs to cross the ISA bus and be loaded into memory on the sound card before it can be mixed. For deferred buffers, this can introduce an unacceptable delay between when the play call is made and when the sound starts. For this reason, using voice management is not recommended on ISA-based DirectSound accelerator cards.

It is easy to prevent your application from using voice management on ISA devices. A buffer won't be assigned to a on-card memory unless the DSBCAPS_STATIC flag is set. Therefore, as long as you do not combine DSBCAPS_STATIC and DSBCAPS_LOCDEFER, there is no danger that buffers will be assigned to on-card memory at play time.

Using DSBCAPS_STATIC by itself ensures that the buffer will take advantage of any existing memory on an ISA card, but has no effect on a PCI card, where in the absence of other flags, DirectSound will attempt to place the buffer under hardware control but still in system memory. Using DSBCAPS_LOCDEFER by itself has no effect on an ISA card, since the buffer is always placed in system memory and is not managed by the hardware.

The following table summarizes the effects of the DSBCAPS_STATIC and DSBCAPS_LOCDEFER flags on buffers created for ISA and PCI devices.

Card | Flags | Memory | HW acceleration
ISA | DSBCAPS_STATIC | Hardware if available. | Yes, if in hardware memory.
PCI | DSBCAPS_STATIC | System. | Yes, if hardware voice available; flag has no effect.
ISA | DSBCAPS_LOCDEFER | Hardware if available, if DSBCAPS_STATIC set. | Yes, if in hardware memory; but latency on first play.
PCI | DSBCAPS_LOCDEFER | System. | Yes, if hardware voice available.

To take advantage of acceleration on ISA cards without running into the dangers presented by deferred allocation, first check the capabilities of the device. If the card reports more than zero static buffers and no streaming buffers, it is probably an older ISA card with on-card memory. You can then use the DSBCAPS_STATIC flag, but do not use DSBCAPS_LOCDEFER. If the card reports more than zero streaming buffers, it is probably a newer PCI-based accelerator card. In this case, you'll want to use DSBCAPS_LOCDEFER, and not DSBCAPS_STATIC, to make maximum use of the hardware voices.


Playing the Primary Buffer Continuously

When there are no sounds playing, DirectSound stops the mixer engine and halts DMA (direct memory access) activity. If your application has frequent short intervals of silence, the overhead of starting and stopping the mixer each time a sound is played may be worse than the DMA overhead if you kept the mixer active. Also, some sound hardware or drivers may produce unwanted audible artifacts from frequent starting and stopping of playback.

If your application is playing audio almost continuously with only short breaks of silence, you can force the mixer engine to remain active by calling the IDirectSoundBuffer8::Play method for the primary buffer.

To resume the default behavior of stopping the mixer engine when there are no sounds playing, call the IDirectSoundBuffer8::Stop method for the primary buffer.


Minimizing Control Changes

Performance is affected when you change the pan, volume, or frequency on a secondary buffer. To prevent interruptions in sound output, the DirectSound mixer must mix ahead from 20 to 100 or more milliseconds. Whenever you make a control change, the mixer has to flush its mix-ahead buffer and remix with the changed sound.

It's a good idea to minimize the number of control changes you send. Try reducing the frequency of calls to routines that use the IDirectSoundBuffer8::SetVolume, IDirectSoundBuffer8::SetPan, and IDirectSoundBuffer8::SetFrequency methods. For example, if you have a routine that moves a sound from the left to the right speaker in synchronization with animation frames, try calling the SetPan method only every second or third frame.

Note 3-D control changes (orientation, position, velocity, Doppler factor, and so on) also cause DirectSound to remix its mix-ahead buffer. However, you can group a number of 3-D control changes together and cause only a single remix. See Deferred Settings.


CPU Considerations for 3-D Buffers

Software-emulated 3-D buffers are computationally expensive. You should take this into consideration when deciding when and how to use 3-D buffers in your applications.

Use as few 3-D sounds as you can, and don't use 3-D on sounds that won't really benefit from the effect. Design your application so that it's easy to enable and disable 3-D effects on each sound. You can call the IDirectSound3DBuffer8::SetMode method with the DS3DMODE_DISABLE flag to disable 3-D processing on any 3-D sound buffer.

You can also ensure that 3-D processing is suspended on buffers that are too far away from the listener to be heard. See Minimum and Maximum Distances.


DirectSound Driver Models

Under the VxD driver model, all DirectSound mixing is done in Dsound.vxd, a virtual device driver. Dsound.vxd also provides close access to the actual DMA buffer that the sound card uses to receive data from the host CPU. This is the same as the DirectSound primary buffer. A DirectSound application can set specific properties of the primary buffer, such as sampling rate and bit depth, thus changing the properties of the hardware itself.

Under the Windows Driver Model (WDM), DirectSound does not have direct access to the sound hardware, except in the case of hardware-accelerated buffers. Instead, DirectSound talks to the kernel mixer, or Kmixer. Kmixer's job is to convert the format of multiple audio streams to a common format, mix them together and send the result to the hardware. In a sense, it does what Dsound.vxd does. One major difference is that Dsound.vxd only mixes DirectSound buffer data, but Kmixer mixes all Windows audio data, including data from applications that use the Win32 waveOut functions. The rule that DirectSound and the waveform-audio output device can't both be open at the same time is not true on systems with WDM drivers.

Of particular importance is Kmixer's relationship with the audio hardware. Kmixer is the only software on the system that can specify the format of the hardware's DMA buffer. It selects the format on the basis of sounds it is asked to mix. It sets the output format to the highest-quality format of sounds that it is asked to mix, or to the closest format to this that the hardware supports.

This has one very important implication: DirectSound cannot set the format of the hardware's DMA buffer. For your application, this means that the hardware format is based on the data you actually play. If you play a 44 kHz file, Kmixer will mix all data up to 44 kHz and ensure that the hardware is running at 44 kHz.

As an application developer, you don't choose the driver model used. That is completely determined by the type of sound card, the version of Windows, and the particular driver the user has installed. For that reason, it is very important that you cover all possibilities when you test your application. DirectSound might be using Dsound.vxd or it might be using Kmixer, and you should ensure your application's behavior and performance are acceptable on both.


Writing to the Primary Buffer

For applications that require specialized mixing or other effects not supported by secondary buffers, DirectSound allows direct access to the primary sound buffer.

When you obtain write access to the primary buffer, other DirectSound features become unavailable. Secondary buffers are not mixed, so hardware-accelerated mixing is unavailable.

Most applications should use secondary buffers instead of directly accessing the primary buffer. Applications can write to a secondary buffer easily because the larger buffer size provides more time to write the next block of data, thereby minimizing the risk of gaps in the audio. Even if an application has simple audio requirements, such as using one stream of audio data that does not require mixing, it will achieve better performance by using a secondary buffer to play its audio data.

Note Writing directly to the primary buffer offers no advantages under the WDM driver model. Under WDM, the primary buffer is in effect a secondary buffer that is mixed by the kernel mixer. For more information on WDM, see DirectSound Driver Models.

You cannot specify the size of the primary buffer, and you must accept the returned size after the buffer is created. A primary buffer is typically very small, so if your application writes directly to this kind of buffer, it must write blocks of data at short intervals to prevent the previously written data from being replayed.

You cannot obtain write access to a primary buffer unless it exists in hardware. To determine whether this is the case, call the IDirectSoundBuffer8::GetCaps method and check for the DSBCAPS_LOCHARDWARE flag in the dwFlags member of the DSBCAPS structure that is returned. If you attempt to lock a primary buffer that is emulated in software, the call will fail.

You create an accessible primary buffer by specifying the DSBCAPS_PRIMARYBUFFER flag in the DSBUFFERDESC structure passed to the IDirectSound8::CreateSoundBuffer method. If you want to write to the buffer, the cooperative level must be DSSCL_WRITEPRIMARY.

Primary sound buffers must be played with looping. Ensure that the DSBPLAY_LOOPING flag is set.

The following example shows how to obtain write access to the primary buffer. Note that the primary buffer supports only the IDirectSoundBuffer interface, not IDirectSoundBuffer8.

BOOL AppCreateWritePrimaryBuffer(
    LPDIRECTSOUND8 lpDirectSound,
    LPDIRECTSOUNDBUFFER *lplpDsb,
    LPDWORD lpdwBufferSize,
    HWND hwnd)
{
    DSBUFFERDESC dsbdesc;
    DSBCAPS dsbcaps;
    HRESULT hr;
    WAVEFORMATEX wf;

    // Set up wave format structure.
    memset(&wf, 0, sizeof(WAVEFORMATEX));
    wf.wFormatTag = WAVE_FORMAT_PCM;
    wf.nChannels = 2;
    wf.nSamplesPerSec = 22050;
    wf.nBlockAlign = 4;
    wf.nAvgBytesPerSec =
        wf.nSamplesPerSec * wf.nBlockAlign;
    wf.wBitsPerSample = 16;

    // Set up DSBUFFERDESC structure.
    memset(&dsbdesc, 0, sizeof(DSBUFFERDESC));
    dsbdesc.dwSize = sizeof(DSBUFFERDESC);
    dsbdesc.dwFlags = DSBCAPS_PRIMARYBUFFER;
    // Buffer size is determined by sound hardware.
    dsbdesc.dwBufferBytes = 0;
    dsbdesc.lpwfxFormat = NULL; // Must be NULL for primary buffers.

    // Obtain write-primary cooperative level.
    hr = lpDirectSound->SetCooperativeLevel(hwnd, DSSCL_WRITEPRIMARY);
    if SUCCEEDED(hr)
    {
        // Try to create buffer.
        hr = lpDirectSound->CreateSoundBuffer(&dsbdesc,
                lplpDsb, NULL);
        if SUCCEEDED(hr)
        {
            // Set primary buffer to desired format.
            hr = (*lplpDsb)->SetFormat(&wf);
            if SUCCEEDED(hr)
            {
                // If you want to know the buffer size, call GetCaps.
                    dsbcaps.dwSize = sizeof(DSBCAPS);
                (*lplpDsb)->GetCaps(&dsbcaps);
                *lpdwBufferSize = dsbcaps.dwBufferBytes;
                return TRUE;
            }
        }
    }
    // Failure.
    *lplpDsb = NULL;
    *lpdwBufferSize = 0;
    return FALSE;
}

The following example illustrates how an application might implement a custom mixer. The AppMixIntoPrimaryBuffer sample function would have to be called at regular intervals, frequently enough to prevent the sound device from repeating blocks of data. The CustomMixer function is an application-defined function that mixes several streams together, as specified in the application-defined AppStreamInfo structure, and writes the result to the specified pointer as follows:

BOOL AppMixIntoPrimaryBuffer(
        LPAPPSTREAMINFO lpAppStreamInfo,
        LPDIRECTSOUNDBUFFER lpDsbPrimary,
        DWORD dwDataBytes,
        DWORD dwOldPos,
        LPDWORD lpdwNewPos)
{
    LPVOID lpvPtr1;
    DWORD dwBytes1;
    LPVOID lpvPtr2;
    DWORD dwBytes2;
    HRESULT hr;
    // Obtain write pointer.
    hr = lpDsbPrimary->Lock(dwOldPos, dwDataBytes,
                            &lpvPtr1, &dwBytes1,
                            &lpvPtr2, &dwBytes2, 0);

    // If DSERR_BUFFERLOST is returned, restore and retry lock.

    if (DSERR_BUFFERLOST == hr)
    {
        lpDsbPrimary->Restore();
        hr = lpDsbPrimary->Lock(dwOldPos, dwDataBytes,
                                &lpvPtr1, &dwBytes1,
                                &lpvPtr2, &dwBytes2, 0);
    }
    if SUCCEEDED(hr)
    {
        // Mix data into the returned pointers.
        CustomMixer(lpAppStreamInfo, lpvPtr1, dwBytes1);
        *lpdwNewPos = dwOldPos + dwBytes1;
        if (NULL != lpvPtr2)
        {
            CustomMixer(lpAppStreamInfo, lpvPtr2, dwBytes2);
            *lpdwNewPos = dwBytes2; // Because it wrapped around.
        }
        // Release the data back to DirectSound.
        hr = lpDsbPrimary->Unlock(lpvPtr1, dwBytes1,
                                  lpvPtr2, dwBytes2);
        if SUCCEEDED(hr)
        {
            return TRUE;
        }
    }
    // Lock or Unlock failed.
    return FALSE;
}


Programming Tips and Tools

This section contains information to help you develop DirectX Audio applications efficiently. The following topics are covered:

  • Debugging DirectX Audio Projects
  • Adjusting DirectSound Acceleration for Testing


Debugging DirectX Audio Projects

The DirectMusic and DirectSound dynamic-link libraries (DLLs) installed with the debug version of the DirectX software development kit generate information in the debug output window as the application is running. By default, all available information is shown. These DLLs are available if you installed the debug version of the DirectX SDK. For DirectMusic, they can be dynamically selected through the DirectX property sheet in Control Panel by choosing Use Debug Version of DirectMusic.

For DirectMusic, you can control the volume of information that goes to your debug output window by changing values in Win.ini. The output for each DirectMusic DLL can be set separately, as in the following example:

[Debug]
DMBAND=1
DMCOMPOS=1
DMIME=1
DMLOADER=0
DMUSIC=1
DMSTYLE=3
DMSYNTH=5

Each value can be in the range from -1 through 5, where -1 produces no debugging information and 5 the most detailed information. If there is no entry in Win.ini, the debug output is at level 0. You can focus on problems in a particular DLL by setting lower values for the other components.

You can also set the debug level within the range from 0 to 5 by using the Debug Output Level sliders on the DirectMusic and DirectSound pages of the DirectX property sheet in Control Panel. However, this method sets the same value for all DLLs.

See also Debugging DirectX Applications.


Adjusting DirectSound Acceleration for Testing

By using the Sounds and Multimedia Properties page in Control Panel, you can adjust the performance of DirectSound on the system. Click the Advanced button in the Sound Playback group on the Audio tab. Then choose the Performance tab. A slider lets you adjust hardware acceleration to one of the following settings:

Full
Enables complete DirectSound acceleration, including the enabling of IKsPropertySet extensions. This is the default setting on Windows 98.
Standard
Enables acceleration of DirectSound secondary buffers, but disables any hardware-specific IKsPropertySet extensions. This is the default setting on Windows 2000.
Basic
Disables hardware acceleration of DirectSound secondary buffers. This option is useful if you want to emulate a nonaccelerated sound card for testing purposes.
Emulation
Forces DirectSound into emulation mode, where it acts as if there is no DirectSound-compatible driver on the system. All mixing is done by DirectSound in user mode, and the resulting data is sent to the Win32 waveform-audio functions. This typically results in a large increase in latency.


DirectX Audio C++ Tutorials

This section contains the following tutorials showing how to implement Microsoft® DirectMusic® and Microsoft® DirectSound® in a C++ application:

  • Tutorial 1: Playing Audio Files
  • Tutorial 2: Using Audiopath Objects

Other, more specialized uses of Microsoft® DirectX® Audio are demonstrated in the sample applications provided with the SDK. For a description of these samples, see DirectX Audio C++ Samples.


Tutorial 1: Playing Audio Files

This tutorial is a step-by-step guide to the most basic tasks in DirectX Audio: initializing a DirectMusic performance and playing an audio file. The tutorial is presented in the following steps:

  • Step 1: Initialize
  • Step 2: Load a File
  • Step 3: Play the File
  • Step 4: Close Down

The complete sample code for the tutorial is available in the following folder:

\mssdk\samples\Multimedia\DirectMusic\Tutorials\Tut1

Note If you installed the DirectX SDK in a different root directory, substitute the name of that directory for "mssdk" in the path.


Step 1: Initialize

The following includes are needed for any application that uses the DirectMusic API. Including Dmusici.h also cause the other necessary header files for DirectMusic and DirectSound to be included.

#define INITGUID
#include <dmusici.h>

The tutorial uses three interface pointers, which are declared as follows:

IDirectMusicLoader8*      g_pLoader       = NULL;
IDirectMusicPerformance8* g_pPerformance  = NULL;
IDirectMusicSegment8*     g_pSegment      = NULL;

All the code in this simple application is included in the WinMain function. The application has no main window, so it can proceed straight to the creation of COM and two objects: the loader and the performance:.

INT APIENTRY WinMain( HINSTANCE hInst, HINSTANCE hPrevInst,
    LPSTR pCmdLine, INT nCmdShow )
{
    CoInitialize(NULL);

    CoCreateInstance(CLSID_DirectMusicLoader, NULL,
                     CLSCTX_INPROC, IID_IDirectMusicLoader8,
                     (void**)&g_pLoader);

    CoCreateInstance(CLSID_DirectMusicPerformance, NULL,
                     CLSCTX_INPROC, IID_IDirectMusicPerformance8,
                     (void**)&g_pPerformance );

The next step is to initialize the performance and the synthesizer. The IDirectMusicPerformance8::InitAudio method performs the following tasks:

  • Creates a DirectMusic and a DirectSound object. In most cases you don't need an interface to those objects, and you can pass NULL in the first two parameters.
  • Associates an application window with the DirectSound object. Normally the handle of the main application window is passed as the third parameter, but the tutorial application doesn't have a window, so it passes NULL instead.
  • Sets up a default audiopath of a standard type. The tutorial requests a path of type DMUS_APATH_SHARED_STEREOPLUSREVERB, which is suitable for music.
  • Allocates a number of performance channels to the audiopath. Wave files require only a single performance channel, and MIDI files require up to 16. Segments created in DirectMusic Producer might need more. No harm is done by asking for extra channels.
  • Specifies capabilities and resources of the synthesizer. This can be done in one of two ways: by setting flags or by supplying a DMUS_AUDIOPARAMS structure with more detailed information. Most applications set the DMUS_AUDIOF_ALL flag and let DirectMusic create the synthesizer with default parameters.

In the tutorial, the call to InitAudio is very simple:

    g_pPerformance->InitAudio(
        NULL,                  // IDirectMusic interface not needed.
        NULL,                  // IDirectSound interface not needed.
        NULL,                  // Window handle.
        DMUS_APATH_SHARED_STEREOPLUSREVERB,  // Default audiopath type.
        64,                    // Number of performance channels.
        DMUS_AUDIOF_ALL,       // Features on synthesizer.
        NULL                   // Audio parameters; use defaults.
    );

Next: Step 2: Load a File


Step 2: Load a File

The DirectMusic performance and synthesizer are now ready to process sound data. To get the data, the loader needs to know where to find it. Although a full path can be provided each time a file is loaded, it is more convenient to establish a default directory. Do this by using the IDirectMusicLoader8::SetSearchDirectory method.

In the sample code, the path to the default Windows media directory is given. You can change the value of wstrSearchPath to get files from a different folder.

The following code is from the WinMain function in the tutorial sample:

    // Find the Windows media directory.

    CHAR strPath[MAX_PATH];
    GetWindowsDirectory( strPath, MAX_PATH );
    strcat( strPath, "\\media" );

   // Convert to Unicode.

    WCHAR wstrSearchPath[MAX_PATH];
    MultiByteToWideChar( CP_ACP, 0, strPath, -1,
                         wstrSearchPath, MAX_PATH );

    // Set the search directory.

    g_pLoader->SetSearchDirectory(
        GUID_DirectMusicAllTypes,   // Types of files sought.
        wstrSearchPath,             // Where to look.
        FALSE                       // Don't clear object data.
    );

In the call to SetSearchDirectory, the fClear parameter is set to FALSE because there is no danger of accidentally reloading objects from the wrong directory. This is likely to happen only if the application is loading identically named objects from different folders.

Now that the loader knows where to look for the file, it can load it as a segment:

    WCHAR wstrFileName[MAX_PATH] = L"The Microsoft Sound.wav";

    if (FAILED(g_pLoader->LoadObjectFromFile(
        CLSID_DirectMusicSegment,   // Class identifier.
        IID_IDirectMusicSegment8,   // ID of desired interface.
        wstrFileName,               // Filename.
        (LPVOID*) &g_pSegment       // Pointer that receives interface.
    )))
    {
        MessageBox( NULL, "Media not found, sample will now quit.",
                          "DMusic Tutorial", MB_OK );
        return 0;
    }

Next: Step 3: Play the File


Step 3: Play the File

The wave file loaded in the previous step is now available to the performance through its IDirectMusicSegment8 interface.

Before a segment can be played, its band must be downloaded to the synthesizer. As long as you don't unload the band, this step has to be taken only once for each segment that uses a unique band.

The following code from the WinMain function in the sample downloads the band to the performance. Alternatively, it could be downloaded to an audiopath. As long as only a single synthesizer is in use, it doesn't matter which destination object you choose:

    g_pSegment->Download( g_pPerformance );

To play the file, pass the segment interface to IDirectMusicPerformance8::PlaySegmentEx. This method offers many options for playback, but to play a segment immediately on the default audiopath, all the parameters except the first can be NULL or 0:

    g_pPerformance->PlaySegmentEx(
        g_pSegment,  // Segment to play.
        NULL,        // Used for songs; not implemented.
        NULL,        // For transitions.
        0,           // Flags.
        0,           // Start time; 0 is immediate.
        NULL,        // Pointer that receives segment state.
        NULL,        // Object to stop.
        NULL         // Audiopath, if not default.
    );
    MessageBox( NULL, "Click OK to Exit.", "Play Audio", MB_OK );

Next: Step 4: Close Down


Step 4: Close Down

To exit an audio application cleanly, you must perform four main steps:

  • Stop any playing segments by calling IDirectMusicPerformance8::Stop.
  • Close down the performance. The IDirectMusicPerformance8::CloseDown method performs miscellaneous cleanup tasks and releases internal references to objects.
  • Release all interfaces.
  • Close COM.

The following sample code from the WinMain function in the tutorial sample is called when the dialog box is closed.

    g_pPerformance->Stop(
        NULL,   // Stop all segments.
        NULL,   // Stop all segment states.
        0,      // Do it immediately.
        0       // Flags.
    );

    g_pPerformance->CloseDown();

    g_pLoader->Release();
    g_pPerformance->Release();
    g_pSegment->Release();

    CoUninitialize();

    return 0;  // Return value for WinMain.
}              // End of WinMain.


Tutorial 2: Using Audiopath Objects

This tutorial is a guide to setting up a DirectMusic performance and retrieving an object—in this case, a 3-D buffer—from an audiopath so that sound parameters can be changed. The tutorial is presented in the following steps:

  • Step 1: Create the Audiopath
  • Step 2: Retrieve the Buffer
  • Step 3: Change Buffer Parameters

The complete sample code for the tutorial is available in the following folder:

\mssdk\samples\Multimedia\DirectMusic\Tutorials\Tut2

Note If you installed the DirectX SDK in a different root directory, substitute the name of that directory for "mssdk" in the path.

It is assumed that you have already learned the basic steps of creating the performance and loader objects, and loading and playing a file. These steps are covered in Tutorial 1: Playing Audio Files.


Step 1: Create the Audiopath

The simplest way to create an audiopath is by passing a flag to IDirectMusicPerformance8::InitAudio. The tutorial sample passes the DMUS_APATH_DYNAMIC_STEREO flag, causing InitAudio to set up a default audiopath that supports stereo sounds:

g_pPerformance->InitAudio(
    NULL,                      // IDirectMusic interface not needed.
    NULL,                      // IDirectSound interface not needed.
    NULL,                      // Window handle.
    DMUS_APATH_DYNAMIC_STEREO, // Default audiopath type.
    64,                        // Number of performance channels.
    DMUS_AUDIOF_ALL,           // Features on synthesizer.
    NULL                       // Audio parameters; use defaults.
);

The default audiopath is suitable for sounds that do not have to be located in space, such as background music or narration. However, if an application implements 3-D sound effects, it will play each sound source on its own audiopath, so that 3-D parameters can be set individually.

The sample creates one such audiopath as follows:

IDirectMusicAudioPath8* p3DAudioPath = NULL;
g_pPerformance->CreateStandardAudioPath(
    DMUS_APATH_DYNAMIC_3D,      // Path type.
    64,                         // Number of performance channels.
    TRUE,                       // Activate now.
    &p3DAudioPath               // Pointer that receives audiopath.
);

A segment can now be played on this audiopath as follows:

g_pPerformance->PlaySegmentEx(
    g_pSegment,  // Segment to play.
    NULL,        // Used for songs; not implemented.
    NULL,        // For transitions.
    0,           // Flags.
    0,           // Start time; 0 is immediate.
    NULL,        // Pointer that receives segment state.
    NULL,        // Object to stop.
    p3DAudioPath // Audiopath.
);

Next: Step 2: Retrieve the Buffer


Step 2: Retrieve the Buffer

By using the IDirectMusicAudioPath8::GetObjectInPath method, you can retrieve interfaces to objects that form part of the path. In the case of the DMUS_APATH_DYNAMIC_3D standard audiopath type, such objects could include the secondary buffer itself, the primary buffer, the DirectSound listener, or any DMOs set on buffers after the audiopath was created. The tutorial sample obtains the IDirectSound3DBuffer8 interface to the buffer:

IDirectSound3DBuffer8* pDSB = NULL;

p3DAudioPath->GetObjectInPath(
    DMUS_PCHANNEL_ALL,        // Performance channel.
    DMUS_PATH_BUFFER,         // Stage in the path.
    0,                        // Index of buffer in chain.
    GUID_NULL,                // Class of object.
    0,                        // Index of object in buffer; ignored.
    IID_IDirectSound3DBuffer, // GUID of desired interface.
    (LPVOID*) &pDSB           // Pointer that receives interface.
);

The parameters to IDirectMusicAudioPath8::GetObjectInPath can be a little tricky to set up properly. For information on which parameters are relevant for objects at different stages in the path, see Retrieving Objects from an Audiopath.

In this case, you are retrieving a secondary buffer that is used by all performance channels on this audiopath. Set the dwPChannel parameter to DMUS_PCHANNEL_ALL.

Because the buffer you want is the first and in this case the only buffer in the chain, you pass 0 as dwBuffer. The DMUS_PATH_BUFFER stage contains only buffer objects, and not the DMOs attached to those buffers; therefore dwIndex is ignored.

Next: Step 3: Change Buffer Parameters


Step 3: Change Buffer Parameters

Now that you have the IDirectSound3DBuffer8 interface, you can use it to move the sound in space. The tutorial sample application does so when the user closes a series of message boxes. For example, the following code immediately moves the sound to the left:

pDSB->SetPosition( -0.1f, 0.0f, 0.0f, DS3D_IMMEDIATE );

The first three parameters specify the new position of the sound source in relation to the default listener. The default listener is at coordinates (0.0, 0.0, 0.0), facing toward the positive z-axis, with the top of the head toward the positive y-axis. Distance units are meters by default. Because the x-axis is positive from left to right, the new position of the sound is 10 centimeters directly to the left of the listener. For more information, see Coordinates of 3-D Space and Listener Orientation.

The last parameter of the IDirectSound3DBuffer8::SetPosition method specifies whether the change is to be made immediately or deferred until all changes are committed. For more information, see Deferred Settings.


DirectX Audio C++ Samples

The sample applications described in this section demonstrate the use and capabilities of the Microsoft® DirectMusic® and Microsoft® DirectSound® application programming interfaces (APIs) in Microsoft® DirectX® for C++.

The samples are described under the following headings:

  • DirectMusic C++ Samples. These samples use the DirectMusic API to load and play sounds. Some of them also use elements of the DirectSound API.
  • DirectSound C++ Samples. These samples use only the DirectSound API. However, many of the techniques shown can also be used with buffers obtained from a DirectMusic audiopath.


DirectMusic C++ Samples

The following executable applications using the DirectMusic API, or DirectSound and DirectMusic together, are found on the Start menu under Programs/Microsoft DirectX8 SDK/DirectMusic Samples:

  • 3DAudio
  • AudioFX
  • AudioPath
  • AudioScripts
  • MusicTool
  • PlayAudio
  • PlayMotif

The source code is in the following folder:

\mssdk\samples\Multimedia\DirectMusic

In addition to these samples, the source files for tutorial applications are contained in the following folder:

\mssdk\samples\Multimedia\DirectMusic\Tutorials

For more information, see DirectX Audio C++ Tutorials.

The samples other than the tutorials use common source files that implement functions and classes for basic DirectMusic and DirectSound functionality and for general tasks such as finding media files. These files are found in the following folder:

\mssdk\samples\Multimedia\Common\src

Note If you installed the DirectX SDK in a different root directory, substitute the name of that directory for "mssdk" in all paths.


3DAudio

Description

The 3DAudio sample application shows how to create a 3-D audiopath in a DirectMusic performance, how to obtain an interface to a 3-D buffer and listener in that path, and how to modify the parameters of the buffer and listener.

Path

Source: (SDK Root)\Sample\Multimedia\DirectMusic\3DAudio

Executable: (SDK Root)\Sample\Multimedia\DirectMusic\Bin

User's Guide

Click Open File and load a wave, MIDI, or DirectMusic segment file. Play the segment. The position of the sound source is shown as a red dot on the graph, where the x-axis is from left to right and the z-axis is from bottom to top. Change the range of movement on the two axes by using the sliders.

The listener is located at the center of the graph, and has its default orientation, looking along the positive z-axis; that is, toward the top of the screen. The sound source moves to the listener's left and right and to the listener's front and rear, but does not move above and below the listener.

The sliders in the center of the window control the properties of the listener; that is, the global sound properties. If you click Defer Settings, changes are not applied until you click Apply Settings.

Programming Notes

See Readme.txt in the source code folder.

See Also

3-D Sound, Retrieving Objects from an Audiopath


AudioFX

Description

The AudioFX sample shows how to use DMOs on DirectMusic audiopaths to add effects to sounds, and how to set effect parameters.

Path

Source: (SDK Root)\Sample\Multimedia\DirectMusic\AudioFX

Executable: (SDK Root)\Sample\Multimedia\DirectMusic\Bin

User's Guide

A default sound file is loaded when the application is run. If you wish, load a different one by clicking Open File.

At first, no effects are enabled. Click Play to hear the sound without effects.

Click Stop to stop the buffer. Apply one or more effects by selecting checkboxes in the Enable column. Play the sound again.

To adjust parameters for an effect, select an option button in the Adjust column and change the values in the frame on the right side of the window. This can be done regardless of whether the sound is playing and regardless of whether the effect has been applied yet.

Programming Notes

The application implements a CSoundFXManager class to manage effects. In the CSoundFXManager::Initialize method, it retrieves an IDirectSoundBuffer8 interface from the audiopath. This interface is used to set effects on the buffer in the CSoundFXManager::ActivateFX method. Effect parameters are set in the OnEffectChanged function in response to messages from the interface.

See Also

Using Effects


AudioPath

Description

The AudioPath sample demonstrates how different sounds can be played on an audiopath, and how the parameters of all sounds are affected by changes made on the audiopath.

Path

Source: (SDK Root)\Sample\Multimedia\DirectMusic\AudioPath

Executable: (SDK Root)\Sample\Multimedia\DirectMusic\Bin

User's Guide

Click Lullaby, Snore, and Mumble to play different sounds. Adjust the 3-D position of the sounds by using the sliders. Click Rude Awakening to play a different sound and stop all other sounds.

Programming Notes

This sample is very similar in form to the PlayAudio sample. The AudioPath differs by showing some of the various uses of an audiopath.

On WM_INITDIALOG, the OnInitDialog function does the following:

  1. Calls IDirectMusicPerformance8::CreateStandardAudioPath, passing in DMUS_APATH_DYNAMIC_3D to create a 3-D audiopath represented by the IDirectMusicAudioPath8 interface g_p3DAudiopath.
  2. Uses the CMusicManager framework class to create CMusicSegment objects from a list of files.
  3. Gets the IDirectSound3DListener8 interface from the audiopath.
  4. Calls IDirectSound3DListener8::SetRolloffFactor to change the rate at which the amplitude of sounds diminishes over distance.

When the 3-D position slider is changed, the SetPosition function does the following:

  1. Calls IDirectMusicAudioPath8::GetObjectInPath to retrieve the IDirectSound3DBuffer8 interface.
  2. Calls IDirectSound3DBuffer8::SetPosition to set the position of the buffer.
  3. Releases the buffer.

When a segment is played, the PlaySegment function does one of the following:

  • If the Lullaby button was clicked, the segment is played on the audiopath as the primary segment.
  • If Snore or Mumble was clicked, a secondary segment is played.
  • If Rude Awakening was clicked, all sounds on the audiopath are stopped because the audiopath is passed to IDirectMusicPerformance8::PlaySegmentEx as the pFrom parameter. The alarm sound is then played as a new primary segment.

See Also

Using Audiopaths


AudioScripts

Description

The AudioScripts sample demonstrates how an application and a DirectMusic script work together. The script reads and writes to variables in the application, and the application calls routines in the script that play segments.

The sample also demonstrates how waves can be played as variations in a segment.

Path

Source: (SDK Root)\Sample\Multimedia\DirectMusic\AudioScripts

Executable: (SDK Root)\Sample\Multimedia\DirectMusic\Bin

User's Guide

Select ScriptDemoBasic.spt from the Script File list box. Play a segment by clicking Routine 1. Click Routine 2 to play an ending and stop playback. Play the segment again and click Routine 3 several times. Note how Variable 1 reflects the number of times the button has been clicked, and how the music changes in response to each click.

Select ScriptDemoBaseball.spt from the Script File list box. Click Routine 1 to play various calls from a vendor. Click Routine 2 to play various musical motifs. Change the score by entering different values in the Variable 1 and Variable 2 text boxes. Click Routine 3 to hear the score.

Programming Notes

See Readme.txt in the source code folder.

See Also

Using Audio Scripts


MusicTool

Description

The MusicTool sample demonstrates how to implement a DirectMusic tool that intercepts messages.

Path

Source: (SDK Root)\Sample\Multimedia\DirectMusic\MusicTool

Executable: (SDK Root)\Sample\Multimedia\DirectMusic\Bin

User's Guide

Play the default segment, or choose another wave, MIDI, or DirectMusic segment file by clicking Open File. Apply the echo effect by selecting Echo Tool from the drop-down list.

Programming Notes

See Readme.txt in the source code folder.

See Also

DirectMusic Tools


PlayAudio

Description

The PlayAudio sample shows how to load a segment and play it on an audiopath, how to use DirectMusic notifications, and how to change global performance parameters.

Path

Source: (SDK Root)\Sample\Multimedia\DirectMusic\PlayAudio

Executable: (SDK Root)\Sample\Multimedia\DirectMusic\Bin

User's Guide

Play the default segment, or load another wave, MIDI, or DirectMusic segment file by clicking Open File. Adjust the tempo and volume by using the sliders.

Programming Notes

On WM_INITDIALOG, the OnInitDialog function does the following:

  1. Creates a Win32® event, g_hDMusicMessageEvent. This will be used by DirectMusic to signal the application whenever a DirectMusic notification comes in.
  2. Creates an object of class CMusicManager called g_pMusicManager.
  3. Initializes the CMusicManager object. This does the following:
    • Creates IDirectMusicLoader8 by using CoCreateInstance.
    • Creates IDirectMusicPerformance8 by using CoCreateInstance.
    • Calls IDirectMusicPerformance8::InitAudio to initialize the performance and create a standard audio path.
  4. Calls IDirectMusicPerformance8::AddNotificationType,requesting notifications of type GUID_NOTIFICATION_SEGMENT. DirectMusic will notify the application of all segment events so it can ascertain when the segment has ended.
  5. Calls IDirectMusicPerformance8::SetNotificationHandle, passing in the Win32 event g_hDMusicMessageEvent. This tells DirectMusic to signal this event when a notification is available.

The WinMain function performs the following tasks:

  1. Creates the window by using CreateDialog.
  2. In the messasge loop, calls MsgWaitForMultipleObjects, passing in g_hDMusicMessageEvent. This will tell us when g_hDMusicMessageEvent is signaled. DirectMusic signals this event whenever a DirectMusic notification has come in.
  3. If WAIT_OBJECT_0 is returned, calls ProcessDirectMusicMessages.
  4. If WAIT_OBJECT_0 + 1 is returned, Windows messages are available. The function does standard message processing by using PeekMessage.

When Open File is clicked, the OnOpenSoundFile function performs the following tasks:

  1. Gets the file name.
  2. Releases any previously created segment.
  3. Calls CMusicManager::CollectGarbage in Dmutil.cpp. This calls IDirectMusicLoader8::CollectGarbage, which ensures that unused objects are released. See Garbage Collection.
  4. Calls CMusicManager::SetSearchDirectory. This calls IDirectMusicLoader8::SetSearchDirectory, passing in GUID_DirectMusicAllTypes and a directory. This tells DirectMusic where to look for files referenced by segments.
  5. Calls CMusicManager::CreateSegmentFromFile to create a CMusicSegment called g_pMusicSegment. This entails the following steps:
    • Call IDirectMusicLoader8::LoadObjectFromFile to load the IDirectMusicSegment8 into pSegment.
    • Create a CMusicSegment, passing in pSegment.
    • If the file is a pure MIDI file, call IDirectMusicSegment8::SetParam, passing in GUID_StandardMIDIFile. This ensures that the file is played correctly.
    • Call IDirectMusicSegment8::Download, which downloads the segment's bands to the synthesizer. Some applications might want to wait before downloading, because the more instruments are downloaded, the more memory is required.

When Play is clicked, the OnPlayAudio function does the following:

  1. If the sound is to be looped, calls CMusicSegment::SetRepeats, passing in DMUS_SEG_REPEAT_INFINITE. Otherwise repeats are set to zero.
  2. Call CMusicSegment::Play, which calls IDirectMusicPerformance8::PlaySegmentEx.

When a notification is signaled, the ProcessDirectMusicMessages function looks for a message indicating that a segment has stopped. It performs the following tasks:

  1. Calls IDirectMusicPerformance8::GetNotificationPMsg in a loop to process each available message. The loop tests for S_OK, because S_FALSE is returned when no more messages are available.
  2. If the dwNotificationOption of the DMUS_NOTIFICATION_PMSG structure is DMUS_NOTIFICATION_SEGEND, calls QueryInterface on the punkUser member to obtain the IDirectMusicSegmentState8 interface of the segment instance that ended. The segment itself is obtained by using IDirectMusicSegmentState8::GetSegment. This method returns IDirectMusicSegment, and QueryInterface must be used to obtain IDirectMusicSegment8. The application then compares this point to the global primary segment pointer, to ensure that it was indeed the primary segment that stopped. Segments authored in DirectMusic Producer can trigger other segments, so we can't be sure that only the primary segment was playing.
  3. Cleans up all the interfaces.


PlayMotif

Description

The PlayMotif sample demonstrates how a motif played as a secondary segment can be aligned to the rhythm of the primary segment in various ways.

Path

Source: (SDK Root)\Sample\Multimedia\DirectMusic\PlayMotif

Executable: (SDK Root)\Sample\Multimedia\DirectMusic\Bin

User's Guide

Play the default segment, or load another DirectMusic segment based on a style that contains motifs. Select one of the patterns in the list box and one of the Align Option buttons, and then click Play Motif. Note how the motif does not begin playing until an appropriate boundary in the primary segment has been reached.

Programming Notes

The PlayMotif sample is very similar in form to the PlayAudio sample. For detailed programming notes on the basics of this sample, see PlayAudio.

When loading the file, PlayMotif performs the same steps as PlayAudio, with the following additions in the LoadSegmentFile function:

  1. Loops through styles in the segment, searching it for motifs. It calls IDirectMusicSegment8::GetParam, passing GUID_IDirectMusicStyle and an incrementing index to get each of the styles in turn. The method fails when there are no more styles.
  2. For each style, it calls IDirectMusicStyle8::EnumMotif, passing an incrementing motif index. This call retrieves the motif name at that index. When the call returns S_FALSE, there are no more motifs in the style.

Passes the motif name to IDirectMusicStyle8::GetMotif to get an IDirectMusicSegment8 interface pointer to the motif, and stores this as data associated with the item in the list box.

When Play Motif is clicked, the OnPlayMotif function performs the following tasks:

  1. Retrieves the desired alignment option from the interface.
  2. Gets the selected motif from the listbox, along with its MOTIF_NODE item data. The MOTIF_NODE structure keeps a count of the number of plays currently occurring, as well as a pointer to the IDirectMusicSegment interface of the motif.
  3. Calls IDirectMusicPerformance8::PlaySegment, passing the motif's IDirectMusicSegment and flags including DMUS_SEGF_SECONDARY as well as any alignment option.

DirectMusic notifications are handled much as in PlayAudio, but this application also takes note of any motif starting or stopping and updates the play count in the MOTIF_NODE structure. If the play count is greater than zero then it updates the user interface to show that the motif is playing.

See Also

Using Motifs


DirectSound C++ Samples

The following executable applications using the DirectSound API are found on the Start menu under Programs/Microsoft DirectX8 SDK/DirectSound Samples:

  • AdjustSound
  • AmplitudeModulation
  • CaptureSound
  • EnumDevices
  • FullDuplexFilter
  • Play3DSound
  • PlaySound
  • SoundFX
  • StreamData
  • VoiceManagement

The source code is in the following folder:

\mssdk\samples\Multimedia\DirectSound

In addition to these samples, the source files for tutorial applications are contained in the following folder:

\mssdk\samples\Multimedia\DirectSound\Tutorials

For more information, see DirectX Audio C++ Tutorials.

The samples other than the tutorials use common source files that implement functions and classes for basic DirectMusic and DirectSound functionality and for general tasks such as finding media files. These files are found in the following folder:

\mssdk\samples\Multimedia\Common\src

Note If you installed the DirectX SDK in a different root directory, substitute the name of that directory for "mssdk" in all paths.


AdjustSound

Description

The AdjustSound sample shows how to create a DirectSound secondary buffer to play a wave file, and how to change the parameters of the buffer.

Path

Source: (SDK Root)\Sample\Multimedia\DirectSound\AdjustSound

Executable: (SDK Root)\Sample\Multimedia\DirectSound\Bin

User's Guide

Load a wave file by clicking Sound File. Select Focus and Buffer Mixing options; note that the various settings are explained under Expected Behavior as you select them. Click Play. If you don't hear any sound, check the Status pane. The application might fail to create the buffer in hardware if this option has been selected.

By using the sliders you can adjust the frequency, pan, and volume dynamically as the buffer is playing.

Programming Notes

For a simpler example of how to set up a DirectSound buffer without as many controls, see the PlaySound sample.

To set the focus behavior of the buffer, the application calls IDirectSound8::CreateSoundBuffer with DSBCAPS_GLOBALFOCUS or DSBCAPS_STICKYFOCUS, or neither of these flags. To set the memory location of the buffer, it sets either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE, or neither of these flags to allow DirectSound to create the buffer in a either hardware or software.

Parameters are set by using IDirectSoundBuffer8::SetFrequency, IDirectSoundBuffer8::SetPan, and IDirectSoundBuffer8::SetVolume.

See Also

DirectSound Buffers


AmplitudeModulation

Description

The AmplitudeModulation sample shows how to apply an effect to a DirectSound secondary buffer and modify the parameters of the effect.

Path

Source: (SDK Root)\Sample\Multimedia\DirectSound\AmplitudeModulation

Executable: (SDK Root)\Sample\Multimedia\DirectSound\Bin

User's Guide

Play the default sound or load another wave file by clicking Sound File. Change the parameters of the effect by selecting one of the Wave Form options and moving the slider to change the modulation rate.

Programming Notes

The application takes the following steps to set an effect on a buffer and change its parameters:

  1. Creates the buffer with the DSBCAPS_CTRLFX flag.
  2. Describe the effect in a DSEFFECTDESC structure, setting the guidDSFXClass member to the GUID of the effect desired.
  3. Passes the buffer description to IDirectSoundBuffer8::SetFX.
  4. Calls IDirectSoundBuffer8::GetObjectInPath to get an interface pointer to the effect, in this case IDirectSoundFXGargle8.
  5. In the OnEffectChanged function, uses IDirectSoundFXGargle8::SetAllParameters to change the parameters of the gargle effect.

See Also

Using Effects


CaptureSound

Description

The CaptureSound application shows how to capture wave sounds to a file.

Path

Source: (SDK Root)\Sample\Multimedia\DirectSound\CaptureSound

Executable: (SDK Root)\Sample\Multimedia\DirectSound\Bin

User's Guide

Select a device and a format. Create a file, or replace an existing one, by clicking Sound File. Click Record to start and stop recording.

Programming Notes

See Readme.txt in the source code folder.

See Also

Capturing Waves


EnumDevices

Description

The EnumDevices sample shows how to enumerate and create playback and capture devices.

Path

Source: (SDK Root)\Sample\Multimedia\DirectSound\EnumDevices

Executable: (SDK Root)\Sample\Multimedia\DirectSound\Bin

User's Guide

Select a playback and capture device from the dropdown lists. Click Create.

Programming Notes

See Readme.txt in the source code folder.

See Also

Enumeration of Sound Devices, Enumeration of Capture Devices


FullDuplexFilter

Description

The FullDuplexFilter application shows how to capture and play back sounds at the same time.

Path

Source: (SDK Root)\Sample\Multimedia\DirectSound\FullDuplexFilter

Executable: (SDK Root)\Sample\Multimedia\DirectSound\Bin

User's Guide

Be sure your sound card is configured for full-duplex operation and that you have a microphone attached. Choose a format from the Output Format list. A list of formats appears in the Input Format list. Select one. Click OK. If full duplex is successfully created, another dialog box is displayed with a Record button. Click this button. Speak into the microphone and your voice is heard over the speakers.

Programming Notes

See Readme.txt in the source code folder.


Play3DSound

Description

The Play3DSound sample shows how to create a 3-D sound buffer and manipulate its properties. It is similar to the 3DAudio sample but uses only the DirectSound API.

Path

Source: (SDK Root)\Sample\Multimedia\DirectSound\Play3DSound

Executable: (SDK Root)\Sample\Multimedia\DirectSound\Bin

User's Guide

Click Sound File and load a wave file. Play the sound. The position of the sound source is shown as a red dot on the graph, where the x-axis is from left to right and the z-axis is from bottom to top. Change the range of movement on the two axes by using the sliders.

The listener is located at the center of the graph, and has its default orientation, looking along the positive z-axis; that is, toward the top of the screen. The sound source moves to the listener's left and right and to the listener's front and rear, but does not move above and below the listener.

The sliders in the center of the window control the properties of the listener; that is, the global sound properties. If you click Defer Settings, changes are not applied until you click Apply Settings.

Programming Notes

For a simpler example of how to set up a DirectSound buffer without 3-D positioning, see the PlaySound sample.

The sample obtains an IDirectSound3DListener8 interface as follows:

1. Describes a buffer in a DSBUFFERDESC structure containing the DSBCAPS_CTRL3D and DSBCAPS_PRIMARYBUFFER flags.

2. Passes the buffer description to IDirectSound8::CreateSoundBuffer. This creates a primary buffer object with 3-D capabilities.

3. Calls QueryInterface to obtain the IDirectSound3DListener8 interface. This interface controls global 3-D properties.

The sample obtains an IDirectSound3DBuffer8 interface as follows:

  1. Describes a buffer in a DSBUFFERDESC structure, setting the DSBCAPS_CTRL3D capabilties flag and and a 3-D virtualization algorithm.
  2. Passes the buffer description to IDirectSound8::CreateSoundBuffer, creating a secondary buffer object with 3-D capabilities.
  3. Calls QueryInterface to obtain the IDirectSound3DBuffer8 interface. This interface controls the 3-D properties of sounds played through the buffer.

The application sets the parameters of the listener by calling IDirectSound3DListener8::SetAllParameters. The listener properties are described in a DS3DLISTENER structure. To set the position of the sound source, the application calls IDirectSound3DBuffer8::SetAllParameters, passing in a DS3DBUFFER structure.

If the DS3D_DEFERRED flag is set when parameters are set, nothing is actually changed until IDirectSound3DListener8::CommitDeferredSettings is called. This method commits all deferred settings for buffers as well as the listener, and makes it possible for DirectSound to perform calculations once instead of many times.

See Also

3-D Sound


PlaySound

Description

The PlaySound sample shows how to play a wave file in a DirectSound secondary buffer.

Path

Source: (SDK Root)\Sample\Multimedia\DirectSound\PlaySound

Executable: (SDK Root)\Sample\Multimedia\DirectSound\Bin

User's Guide

Load a wave file by clicking Sound File. Select Loop Sound if you want it to play repeatedly. Click Play.

Programming Notes

The sample shows the basic tasks required to play a sound in a DirectSound Buffer, as follows:

Set up DirectSound:

  1. Call the DirectSoundCreate function to create the DirectSound object.
  2. Call IDirectSound8::SetCooperativeLevel.
  3. Set the primary buffer format. This sample calls the DSUtil_SetPrimaryBufferFormat function in Dsutil.cpp to do this.

Load a wave file into a DirectSound buffer:

  1. Read the wave file header to get the data size and format.
  2. If the wave file is a reasonable size, create a secondary buffer in the same format as the data, large enough to hold the entire file. If the wave file is too large, data will have to be streamed to the buffer. See the StreamData sample.
  3. Fill the buffer with data. Obtain a pointer into the buffer by calling IDirectSoundBuffer8::Lock. Because data is not being streamed as the buffer is playing, the entire buffer can be locked. After the memory has been copied, call IDirectSoundBuffer8::Unlock.

Play the DirectSound buffer:

  1. Check to see if the buffer has been lost. If so, restore it.
  2. To play the buffer call IDirectSoundBuffer8::Play.

Free DirectSound:

Call Release on all the DirectSound interfaces that were obtained. Release buffers before releasing the DirectSound object.

See Also

Filling and Playing Static Buffers


SoundFX

Description

The SoundFX sample shows how to use DMOs with DirectSound and how to manipulate effect parameters. It is similar to the AudioFX sample but does not use an audiopath or any of the DirectMusic interfaces.

Path

Source: (SDK Root)\Sample\Multimedia\DirectSound\SoundFX

Executable: (SDK Root)\Sample\Multimedia\DirectSound\Bin

User's Guide

A default sound file is loaded when the application is run. If you wish, load a different one by clicking Open File.

At first, no effects are enabled. Click Play to hear the sound without effects.

Click Stop to stop the buffer. Apply one or more effects by selecting checkboxes in the Enable column. Play the sound again.

To adjust parameters for an effect, select an option button in the Adjust column and change the values in the frame on the right side of the window. This can be done regardless of whether the sound is playing and regardless of whether the effect has been applied yet.

Programming Notes

The application implements a CSoundFXManager class to manage effects. An IDirectSoundBuffer8 interface is used to set effects on the buffer in the CSoundFXManager::ActivateFX method. Effect parameters are set in the OnEffectChanged function in response to messages from the interface.

See Also

Using Effects, Using Effects in DirectSound


StreamData

Description

The StreamData sample shows how to stream a wave file to a DirectSound secondary buffer. It is similar to the PlaySound sample, but adds support for streaming.

Path

Source: (SDK Root)\Sample\Multimedia\DirectSound\StreamData

Executable: (SDK Root)\Sample\Multimedia\DirectSound\Bin

User's Guide

Load a wave file by clicking Sound File. Select Loop Sound if you want it to play repeatedly. Click Play.

Programming Notes

The sample shows the basic tasks required to play a streaming sound in a DirectSound secondary buffer.

Set up DirectSound:

  1. Call the DirectSoundCreate8 function to create the DirectSound object.
  2. Call IDirectSound8::SetCooperativeLevel.
  3. Set the primary buffer format. The sample calls the DSUtil_SetPrimaryBufferFormat function in Dsutil.cpp to do this.

Create a DirectSound buffer and set up the notifications:

  1. Read the wave file header to get the data size and format.
  2. Choose a DirectSound buffer size. For this sample, the buffer holds about 3 seconds of data.
  3. Create a DirectSound buffer of that size and with the same format as the wave file. Also set the DSBCAPS_CTRLPOSITIONNOTIFY flag so that the buffer can send notification events whenever playback has reached certain points in the buffer. On some drivers, using this flag limits the buffer to software, because the hardware buffers do not support position notifications.
  4. Set up the notifications on the buffer by obtaining an IDirectSoundNotify8 interface from the buffer and calling IDirectSoundNotify8::SetNotificationPositions. See the InitDSoundNotification function. When the play cursor passes a notification position, it signals a Win32® event.

Play the DirectSound buffer:

  1. See if the buffer has been lost, and call IDirectSoundBuffer8::Restore if so.
  2. Fill the entire buffer with data from the file.
  3. Call IDirectSoundBuffer8::Play with the DSBPLAY_LOOPING flag. The looping flag needs to be set so that the buffer will continue playing after the first batch of data has been played.

Check to see if a notification is signaled:

  1. Look for a signaled event in the message loop or in a separate thread by calling MsgWaitForMultipleObjects.
  2. If a buffer notification event has been signaled, lock the section of the buffer that has just been played and fill it with new data. See the HandleNotification function.

Stop the buffer:

When handling the event notification, keep track of how much data has been put in the buffer. When the entire wave file has been put into the buffer, and after DirectSound has played it all, it is necessary to manually stop the buffer since the buffer will continuously loop otherwise.

See Also

Using Streaming Buffers


VoiceManagement

Description

The VoiceManagement sample shows how to implement dynamic voice management when creating DirectSound secondary buffers.

Path

Source: (SDK Root)\Sample\Multimedia\DirectSound\VoiceManagement

Executable: (SDK Root)\Sample\Multimedia\DirectSound\Bin

User's Guide

Load a wave file by clicking Sound File. Select the Voice Allocation Flags, Buffer Priority, and Voice Management Flags options. Note that the effect of the selected options is described under Expected Behavior. Create the buffer and play the sound by clicking Play.

Programming Notes

To use voice management flags, the buffer must be created using DSBCAPS_LOCDEFER. Otherwise DirectSound will not be able to dynamically place the buffer in either hardware or software at run time.

When playing the buffer, call IDirectSoundBuffer8::Play with a valid combination of voice management flags. Run the sample to observe the result of any combination of flags.

See Also

Dynamic Voice Management


DirectMusic C/C++ Reference

This section contains reference information for the API elements of DirectMusic. Reference material is divided into the following categories.

  • DirectMusic Interfaces
  • DirectMusic Messages
  • DirectMusic Structures
  • DLS Structures
  • DirectMusic File Format
  • DirectMusic File Structures
  • Standard Track Parameters
  • DirectMusic Enumerated Types
  • DirectMusic Return Values


DirectMusic Interfaces

This section contains references for DirectMusic COM interfaces.

Interfaces in the current version are either declared or defined with names ending in 8. To be sure of using the latest version of an interface, always include this suffix when declaring the pointer.

Note IKsControl and IReferenceClock are exceptions to this rule.

Interfaces retrieved by methods are always the base version. Where a newer version exists, you must call QueryInterface to obtain it, as in the following example, where lpdmBand is an IDirectMusicBand8 interface pointer.

IDirectMusicSegment * lpdmseg;
IDirectMusicSegment8 * lpdmseg8;

HRESULT hr = lpdmBand->CreateSegment(&lpdmseg);
if (SUCCEEDED(hr))
{
    hr = lpdmseg->QueryInterface(IID_IDirectMusicSegment8,
        (LPVOID *)&lpdmseg8);
}

Where there is no new version of an interface, the interface name with the suffix 8 is only a define. For example, IDirectMusicGraph8 is equivalent in all respects to IDirectMusicGraph. In such cases it is not necessary to query for a new interface, but doing so does no harm and can make your code easier to maintain for future versions of DirectX.

When a method takes an interface pointer as an IN parameter, you can pass in the newer version even where the method is declared as accepting the older version. For example, a pointer to either IDirectMusicSegment or IDirectMusicSegment8 can be passed to IDirectMusicPerformance8::PlaySegmentEx.

This documentation contains full reference topics only for the latest versions of interfaces. Where a define exists, such as IDirectMusicGraph8, the interface is documented under that name.

  • IDirectMusic8
  • IDirectMusicAudioPath8
  • IDirectMusicBand8
  • IDirectMusicBuffer8
  • IDirectMusicChordMap8
  • IDirectMusicCollection8
  • IDirectMusicComposer8
  • IDirectMusicContainer8
  • IDirectMusicDownload8
  • IDirectMusicDownloadedInstrument8
  • IDirectMusicGetLoader8
  • IDirectMusicGraph8
  • IDirectMusicInstrument8
  • IDirectMusicLoader8
  • IDirectMusicObject8
  • IDirectMusicPatternTrack8
  • IDirectMusicPerformance8
  • IDirectMusicPort8
  • IDirectMusicPortDownload8
  • IDirectMusicScript8
  • IDirectMusicSegment8
  • IDirectMusicSegmentState8
  • IDirectMusicSong8
  • IDirectMusicStyle8
  • IDirectMusicThru8
  • IDirectMusicTool8
  • IDirectMusicTrack8
  • IKsControl
  • IReferenceClock


IDirectMusic8

The IDirectMusic8 interface provides methods for managing buffers, ports, and the master clock. There should not be more than one instance of this interface per application.

IDirectMusic8 supersedes IDirectMusic and adds a new method, SetExternalMasterClock.

There is no helper function to create this interface. Applications use the COM CoCreateInstance function, the IDirectMusicPerformance8::Init method, or the IDirectMusicPerformance8::InitAudio method to create a DirectMusic object.

The methods of the IDirectMusic8 interface can be organized into the following groups:

Activation | Activate
Buffers | CreateMusicBuffer
Linkage | SetDirectSound
Ports | CreatePort
 | EnumPort
 | GetDefaultPort
Timing | EnumMasterClock
 | GetMasterClock
 | SetExternalMasterClock
 | SetMasterClock

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTMUSIC8 type is defined as a pointer to the IDirectMusic8 interface.

typedef IDirectMusic8 *LPDIRECTMUSIC8;

Requirements

Header: Declared in dmusicc.h.


IDirectMusic8::Activate

The IDirectMusic8::Activate method activates or deactivates all ports created from this interface.

HRESULT Activate(
  BOOL fEnable
);

Parameters

fEnable
Switch to activate (TRUE) or deactivate (FALSE) all port objects created in this instance of DirectMusic.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DSERR_NODRIVER, indicating that no sound driver is present.

Remarks

Applications should call IDirectMusic8::Activate(FALSE) when they lose input focus if they do not need to play music in the background. This allows another application that has the input focus to have access to the ports. When the application has input focus again, it should call Activate(TRUE) to enable all its allocated ports.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPort8::Activate


IDirectMusic8::CreateMusicBuffer

Creates a DirectMusicBuffer object to hold music messages being sequenced to the port. Most applications do not need to call this method directly because buffer management is handled by the performance when a port is added.

HRESULT CreateMusicBuffer(
  LPDMUS_BUFFERDESC pBufferDesc,
  LPDIRECTMUSICBUFFER *ppBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

pBufferDesc
Address of the DMUS_BUFFERDESC structure that contains the description of the music buffer to be created. The application must initialize the dwSize member of this structure before passing the pointer.
ppBuffer
Address of a variable that receives an IDirectMusicBuffer8 interface pointer.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Because aggregation is not currently supported, this value must be set to NULL.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
CLASS_E_NOAGGREGATION
E_NOINTERFACE
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusicc.h.


IDirectMusic8::CreatePort

Creates an object for a DirectMusic port.

HRESULT CreatePort(
  REFCLSID rclsidPort,
  LPDMUS_PORTPARAMS pPortParams,
  LPDIRECTMUSICPORT *ppPort,
  LPUNKNOWN pUnkOuter
);

Parameters

rclsidPort
Reference to (C++) or address of (C) the GUID that identifies the port for which the IDirectMusicPort8 interface is to be created. The GUID is retrieved through the IDirectMusic8::EnumPort method. If it is GUID_NULL, the returned port is the default port. For more information, see Default Port.
pPortParams
Address of a DMUS_PORTPARAMS8 structure that contains parameters for the port. The dwSize member of this structure must be initialized before the method is called.
ppPort
Address of a variable that receives an IDirectMusicPort interface pointer.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Because aggregation is not currently supported, this value must be NULL.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if a requested parameter is not available.

If it fails, the method can return one of the following error values:

DMUS_E_DSOUND_NOT_SET
E_INVALIDARG
CLASS_E_NOAGGREGATION
E_NOINTERFACE
E_OUTOFMEMORY
E_POINTER

Remarks

By default, the port is inactive when it is created. It must be activated by a call to IDirectMusic8::Activate or IDirectMusicPort8::Activate.

If not all parameters could be obtained, the DMUS_PORTPARAMS8 structure is changed as follows to match the available parameters of the port.

On entry, the dwValidParams member of the structure indicates which members in the structure are valid. If the flag is not set for a member of the structure, a default value is set for that parameter when the port is created.

On return, the flags in dwValidParams show which port parameters were set. If a particular parameter was not requested but was set to the default, that flag is added to those passed in.

If the port supports a specified parameter but the given value for the parameter is out of range, the parameter value in *pPortParams is changed. In this case, the flag in dwValidParams remains set, but S_FALSE is returned to indicate that the value has been changed.

The following code example shows how an application can request reverb capabilities and determine whether they were obtained. For an alternative way of checking and setting port properties, see Property Sets for DirectMusic Ports.

DMUS_PORTPARAMS8 params;

ZeroMemory(&params, sizeof(params));
params.dwSize = sizeof(params);
params.dwValidParams = DMUS_PORTPARAMS_EFFECTS;
params.dwEffectFlags = DMUS_EFFECT_REVERB;
HRESULT hr = pDirectMusic->CreatePort(guidPort, &params,
        &port, NULL);
if (SUCCEEDED(hr))
{
    fGotReverb = TRUE;
    if (hr == S_FALSE)
    {
        if (!(params.dwValidParams & DMUS_PORTPARAMS_EFFECTS))
        {
            // Device does not support any effects.
            fGotReverb = FALSE;
        }
        else if (!(params.dwEffectFlags & DMUS_EFFECT_REVERB))
        {
            // Device understands effects,
            // but could not allocate reverb.
            fGotReverb = FALSE;
        }
    }
}

Requirements

Header: Declared in dmusicc.h.


IDirectMusic8::EnumMasterClock

Enumerates the clocks that DirectMusic can use as the master clock. Each time it is called, this method retrieves information about a single clock.

HRESULT EnumMasterClock(
  DWORD dwIndex,
  LPDMUS_CLOCKINFO lpClockInfo
);

Parameters

dwIndex
Index of the clock for which the description is to be returned. This parameter should be 0 on the first call, and then incremented in each subsequent call until S_FALSE is returned.
lpClockInfo
Address of a DMUS_CLOCKINFO8 structure that receives the description of the clock. The application must initialize the dwSize member of this structure before passing the pointer.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there is no clock with that index number.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_NOINTERFACE
E_POINTER

Remarks

Applications should not rely on or store the index number of a clock. Rebooting or adding and removing hardware can cause the index number of a clock to change.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusic8::SetMasterClock, IDirectMusic8::GetMasterClock


IDirectMusic8::EnumPort

Enumerates and retrieves the capabilities of the DirectMusic ports connected to the system. Each time it is called, this method retrieves information about a single port.

HRESULT EnumPort(
  DWORD dwIndex,
  LPDMUS_PORTCAPS pPortCaps
);

Parameters

dwIndex
Index of the port for which the capabilities are to be returned. This parameter should be 0 on the first call, and then incremented in each subsequent call until S_FALSE is returned.
pPortCaps
Address of the DMUS_PORTCAPS structure that receives the capabilities of the port. The dwSize member of this structure must be initialized before the pointer is passed.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there is no port with that index value.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_NOINTERFACE
E_POINTER

Remarks

Applications should not rely on or store the index number of a port. Rebooting or adding or removing ports could cause the index number of a port to change.

Requirements

Header: Declared in dmusicc.h.


IDirectMusic8::GetDefaultPort

Retrieves the GUID of the default output port. This is the port to be created if GUID_NULL is passed to IDirectMusic8::CreatePort.

HRESULT GetDefaultPort(
  LPGUID pguidPort
);

Parameters

pguidPort
Address of a variable that receives the default port GUID.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusicc.h.

See Also

Default Port


IDirectMusic8::GetMasterClock

Retrieves the GUID and a pointer to the IReferenceClock interface for the clock that is currently set as the DirectMusic master clock.

HRESULT GetMasterClock(
  LPGUID pguidClock,
  IReferenceClock **ppReferenceClock
);

Parameters

pguidClock
Address of a variable that receives the GUID of the master clock. The application can pass NULL if this value is not desired.
ppReferenceClock
Address of a variable that receives the IReferenceClock interface pointer for this clock. The application can pass NULL if this value is not desired.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_NOINTERFACE
E_POINTER

Remarks

The IReferenceClock interface pointer must be released after the application has finished using the interface.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusic8::SetMasterClock


IDirectMusic8::SetDirectSound

Connects DirectMusic to a DirectSound object for output from the synthesizer.

This method is not used by most applications. The DirectSound object is normally created and connected to the performance by IDirectMusicPerformance8::InitAudio.

HRESULT SetDirectSound(
  LPDIRECTSOUND pDirectSound,
  HWND hWnd
);

Parameters

pDirectSound
Address of the IDirectSound8 interface to use for output. If this parameter is NULL, the method creates a DirectSound object and sets the DSSCL_PRIORITY cooperative level. (See Remarks.) If this parameter contains an IDirectSound pointer, the caller is responsible for setting the cooperative level.
hWnd
Window handle to the DirectSound object created by this call. If this value is NULL, the current foreground window is set as the focus window. See Remarks.

If pDirectSound is a valid interface, this parameter is ignored because it is the caller's responsibility to supply a valid window handle in the call to IDirectSound8::SetCooperativeLevel.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_DSOUND_ALREADY_SET.

Remarks

The specified DirectSound object is the one used for rendering audio on all ports. This default can be overridden by using the IDirectMusicPort8::SetDirectSound method.

Whenever the IDirectMusic8::SetDirectSound method is called, any existing DirectSound object is released.

When pDirectSound is NULL, a new DirectSound object is not created until a port that uses DirectSound is activated, and the DirectSound object is automatically released when the last port using it is deactivated.

If you created the DirectSound object yourself, you can release it by calling this method with NULL in the pDirectSound parameter after deactivating all ports. (It is an error to call SetDirectSound on an active port.)

You can pass NULL in the hWnd parameter to pass the current foreground window handle to DirectSound. However, do not assume that the application window is in the foreground during initialization. In general, the top-level application window handle should be passed to DirectMusic and DirectSound. See the Remarks for IDirectSound8::SetCooperativeLevel.

Requirements

Header: Declared in dmusicc.h.


IDirectMusic8::SetExternalMasterClock

Sets the DirectMusic master clock to an existing clock object. There is only one master clock for all DirectMusic applications.

HRESULT SetExternalMasterClock(
  IReferenceClock *pClock
);

Parameters

pClock
IReferenceClock interface pointer that specifies the clock.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_PORTS_OPEN.

Remarks

If another running application is also using DirectMusic, it is not possible to change the master clock until that application is shut down.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusic8::GetMasterClock, IDirectMusic8::EnumMasterClock, IDirectMusic8::SetMasterClock,


IDirectMusic8::SetMasterClock

Sets the DirectMusic master clock to a clock identified by a GUID obtained through the IDirectMusic8::EnumMasterClock call. There is only one master clock for all DirectMusic applications.

HRESULT SetMasterClock(
  REFGUID rguidClock
);

Parameters

rguidClock
Reference to (C++) or address of (C) the GUID that identifies the clock to set as the master clock for DirectMusic. This parameter must be a GUID returned by the IDirectMusic8::EnumMasterClock method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_PORTS_OPEN.

Remarks

If another running application is also using DirectMusic, it is not possible to change the master clock until that application is shut down.

Most applications do not need to call SetMasterClock. It should not be called unless there is a need to synchronize tightly with a hardware timer other than the system clock.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusic8::SetExternalMasterClock, IDirectMusic8::GetMasterClock, IDirectMusic8::EnumMasterClock


IDirectMusicAudioPath8

The IDirectMusicAudioPath8 interface represents the stages of data flow from the performance to the primary sound buffer. The audiopath can be created from an audiopath configuration object by using the IDirectMusicPerformance8::CreateAudioPath method. A standard audiopath can be created by using IDirectMusicPerformance8::CreateStandardAudioPath. A standard default path can also be created by IDirectMusicPerformance8::InitAudio and then retrieved by using IDirectMusicPerformance8::GetDefaultAudioPath.

The IDirectMusicAudioPath8 interface can be passed to IDirectMusicPerformance8::PlaySegmentEx to play the segment on that audiopath.

IDirectMusicAudioPath8 is a type definition for IDirectMusicAudioPath. The two interface names are interchangeable.

The IDirectMusicAudioPath8 interface has the following methods.

IDirectMusicAudioPath8 | Activate
 | ConvertPChannel
 | GetObjectInPath
 | SetVolume

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.


IDirectMusicAudioPath8::Activate

Activates or deactivates the audiopath.

HRESULT Activate(
  BOOL fActivate
);

Parameters

fActivate
Boolean that specifies whether to activate (TRUE) or deactivate (FALSE) the path.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the audiopath is already in the requested state.

Remarks

The behavior of this method is different from that of IDirectMusicPort8::Activate. When a port is deactivated, it no longer produces sound, but the performance can continue playing segments. When an audiopath is deactivated, all playback stops and any attempt to play a segment will fail.

Requirements

Header: Declared in dmusici.h.


IDirectMusicAudioPath8::ConvertPChannel

Translates between a performance channel in a segment and the equivalent channel allocated in the performance for the audiopath. This method is not typically needed by applications, but can be used by components such as tracks.

HRESULT ConvertPChannel(
  DWORD dwPChannelIn,
  DWORD *pdwPChannelOut
);

Parameters

dwPChannelIn
Value that specifies the performance channel to convert.
pdwPChannelOut
Address of a DWORD variable that receives the virtual performance channel.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.


IDirectMusicAudioPath8::GetObjectInPath

Retrieves an interface for an object in the audiopath.

RESULT GetObjectInPath(
  DWORD dwPChannel,
  DWORD dwStage,
  DWORD dwBuffer,
  REFGUID guidObject,
  DWORD dwIndex,
  REFGUID iidInterface,
  void ** ppObject
);

Parameters

dwPChannel
Performance channel to search, or DMUS_PCHANNEL_ALL to search all channels. The first channel is numbered 0. See Remarks.
dwStage
Stage in the path. Can be one of the following values.
DMUS_PATH_AUDIOPATH_GRAPH
Get the audiopath toolgraph. One is created if none exists.
DMUS_PATH_AUDIOPATH_TOOL
Get a tool from the audiopath toolgraph.
DMUS_PATH_BUFFER
Get a DirectSound buffer.
DMUS_PATH_BUFFER_DMO
Get a DMO in a buffer. For information on DMO interfaces, see IDirectSoundBuffer8::GetObjectInPath.
DMUS_PATH_MIXIN_BUFFER
Get a global mix-in buffer.
DMUS_PATH_MIXIN_BUFFER_DMO
Get a DMO in a global mix-in buffer.
DMUS_PATH_PERFORMANCE
Get the performance.
DMUS_PATH_PERFORMANCE_GRAPH
Get the performance toolgraph. One is created if none exists.
DMUS_PATH_PERFORMANCE_TOOL
Get a tool from the performance toolgraph.
DMUS_PATH_PORT
Get the synthesizer.
DMUS_PATH_PRIMARY_BUFFER
Get the primary buffer.
dwBuffer
If dwStage is DMUS_PATH_BUFFER_DMO or DMUS_PATH_MIXIN_BUFFER_DMO, the index of the buffer in which that DMO resides. If dwStage is DMUS_PATH_BUFFER or DMUS_PATH_MIXIN_BUFFER, the index of the buffer. Otherwise must be 0.
guidObject
Class identifier of the object, or GUID_All_Objects to search for an object of any class. This parameter is ignored if only a single class of object can exist at the stage specified by dwStage, and can be set to GUID_NULL.
dwIndex
Index of the object within a list of matching objects. Set to 0 to find the first matching object. If dwStage is DMUS_PATH_BUFFER or DMUS_PATH_MIXIN_BUFFER, this parameter is ignored, and the buffer index is specified by dwBuffer.
iidInterface
Identifier of the desired interface, such as IID_IDirectMusicTool.
ppObject
Address of a variable that receives a pointer to the requested interface.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_INVALIDARG
E_OUTOFMEMORY
E_NOINTERFACE
E_POINTER

Remarks

The value in dwPChannel must be 0 for any stage that is not channel-specific. Objects in the following stages are channel-specific and can be retrieved by setting a channel number or DMUS_PCHANNEL_ALL in dwPChannel:

DMUS_PATH_AUDIOPATH_TOOL
DMUS_PATH_BUFFER
DMUS_PATH_BUFFER_DMO
DMUS_PATH_PERFORMANCE_TOOL
DMUS_PATH_PORT
DMUS_PATH_SEGMENT_TOOL

The precedence of the parameters in filtering out unwanted objects is as follows:

  1. dwStage.
  2. guidObject. If this value is not GUID_All_Objects, only objects whose class identifier equals guidObject are searched. However, this parameter is ignored for stages where only a single class of object can exist, such as DMUS_PATH_AUDIOPATH_GRAPH.
  3. dwPChannel. If the stage is channel-specific and this value is not DMUS_PCHANNEL_ALL, only objects on the channel are searched.
  4. dwBuffer. This is used only if dwStage is DMUS_PATH_BUFFER, DMUS_PATH_MIXIN_BUFFER, DMUS_PATH_BUFFER_DMO, or DMUS_PATH_MIXIN_BUFFER_DMO.
  5. dwIndex.

If a matching object is found but the interface specified by iidInterface cannot be obtained, the method fails.

The following sample shows how to enumerate the buffers in an audiopath. The _stprintf function is declared in Tchar.h.

void DumpAudioPathBuffers(
        IDirectMusicAudioPath *pDirectMusicAudioPath)
{
    TCHAR tcstrText[256];
    DWORD dwBuffer = 0;
    IDirectSoundBuffer *pDirectSoundBuffer;

    while(S_OK == pDirectMusicAudioPath->GetObjectInPath(
        DMUS_PCHANNEL_ALL, DMUS_PATH_BUFFER, dwBuffer,
        GUID_NULL, 0, IID_IDirectSoundBuffer,
        (void**) &pDirectSoundBuffer))
    {
        _stprintf( tcstrText, _T("Found buffer %x.\n"),
                pDirectSoundBuffer);
        OutputDebugString( tcstrText );
        dwBuffer++;
        pDirectSoundBuffer->Release();
    }

    if( dwBuffer == 0 )
    {
        OutputDebugString( _T("No buffers in audiopath.\n") );
    }
}

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegmentState8::GetObjectInPath, Retrieving Objects from an Audiopath


IDirectMusicAudioPath8::SetVolume

Sets the audio volume on the path.

HRESULT SetVolume(
  long lVolume,
  DWORD dwDuration
);

Parameters

lVolume
Value that specifies the attenuation, in hundredths of a decibel. This value must be in the range from -9600 to 0. Zero is full volume.
dwDuration
Value that specifies the time, in milliseconds, over which the volume change takes place. A value of 0 ensures maximum efficiency.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_INVALIDARG

Requirements

Header: Declared in dmusici.h.


IDirectMusicBand8

The IDirectMusicBand8 interface represents a DirectMusic band object. A band is used to set the instrument choices and mixer settings for a set of performance channels. For an overview, see Using Bands. Bands can be stored directly in their own files or embedded in a style's band list or a segment's band track.

IDirectMusicBand8 is a define for IDirectMusicBand. The two interface names are interchangeable.

The DirectMusicBand object also supports the IPersistStream and IDirectMusicObject8 interfaces for loading its data.

The IDirectMusicBand8 interface has the following methods:

Segment creation | CreateSegment
Instrument data | Download
 | Unload

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.


IDirectMusicBand8::CreateSegment

Creates a DirectMusicSegment object that can be played in order to perform the volume, pan, transposition, and patch change commands in the band dynamically.

HRESULT CreateSegment(
  IDirectMusicSegment** ppSegment
);

Parameters

ppSegment
Address of a variable that receives a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_OUTOFMEMORY
E_POINTER

Remarks

For an example of creating a segment from a band, see Making Band Changes Programmatically.

Requirements

Header: Declared in dmusici.h.


IDirectMusicBand8::Download

Downloads the DLS data for instruments in the band to a performance object.

HRESULT Download(
  IDirectMusicPerformance* pPerformance
);

Parameters

pPerformance
Performance to which instruments are to be downloaded. The performance manages the mapping of performance channels to DirectMusic ports.

Return Values

If the method succeeds, the return value is S_OK, or DMUS_S_PARTIALDOWNLOAD. (See Remarks.)

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Remarks

The method downloads each instrument in the band by calling the IDirectMusicPerformance8::DownloadInstrument method. DownloadInstrument, in turn, uses the performance channel of the instrument to find the appropriate port, and then calls the IDirectMusicPort8::DownloadInstrument method on that port.

After a band has been downloaded, the instruments in the band can be selected, either individually with program-change MIDI messages, or all at once by playing a band segment created through a call to the IDirectMusicBand8::CreateSegment method.

Because a downloaded band uses synthesizer resources, it should be unloaded when no longer needed by using the IDirectMusicBand8::Unload method.

This method may return S_OK even though the port does not support DLS.

If the download completely fails, DMUS_E_NOT_INIT is returned. This usually means that the performance was not properly connected to an initialized port. Because this is a complete failure, there is no need to call IDirectMusicBand8::Unload later.

If the download partially succeeds, DMUS_S_PARTIALDOWNLOAD is returned. This means that some of the instruments successfully downloaded and others did not. This usually occurs because of programming error setting up the performance and port. The best way to find the problem is to set debug traces to 1 for Dmime.dll, Dmband.dll, and Dmsynth.dll. See Debugging DirectX Audio Projects.

The following are some common causes of a partial download:

  • The band has instruments on performance channels that have not been set up on the performance (by using IDirectMusicPerformance8::AssignPChannelBlock).
  • The band has instruments on performance channels that are on channel groups not allocated on the port.
  • The band has instruments in a DLS format incompatible with the synthesizer they are being downloaded to.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicBand8::Unload


IDirectMusicBand8::Unload

Unloads the DLS data for instruments in the band previously downloaded by IDirectMusicBand8::Download.

HRESULT Unload(
  IDirectMusicPerformance* pPerformance
);

Parameters

pPerformance
Performance from which to unload instruments.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
DMUS_E_NOT_FOUND

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPort8::UnloadInstrument


IDirectMusicBuffer8

The IDirectMusicBuffer8 interface represents a buffer containing time stamped data (typically in the form of MIDI messages) to be sequenced by a port. Unlike a segment, the buffer contains a small amount of data (typically less than 200 milliseconds) over which the application has control at event granularity.

IDirectMusicBuffer8 is a type definition for IDirectMusicBuffer. The two interface names are interchangeable.

Unless your application is doing its own sequencing, you do not need to use the methods of this interface.

Buffer objects are completely independent of port objects until the buffer is passed to the port by a call to the IDirectMusicPort8::PlayBuffer or the IDirectMusicPort8::Read method. The application is then free to reuse the buffer.

The methods of the IDirectMusicBuffer8 interface can be organized in the following groups:

Data | Flush
 | GetNextEvent
 | GetRawBufferPtr
 | PackStructured
 | PackUnstructured
 | ResetReadPtr
Parameters | GetBufferFormat
 | GetMaxBytes
 | GetUsedBytes
 | SetUsedBytes
Time | GetStartTime
 | SetStartTime
 | TotalTime

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTMUSICBUFFER8 type is defined as a pointer to the IDirectMusicBuffer8 interface.

typedef IDirectMusicBuffer8 *LPDIRECTMUSICBUFFER8;

Requirements

Header: Declared in dmusicc.h.


IDirectMusicBuffer8::Flush

Discards all data in the buffer.

HRESULT Flush();

Parameters

None.

Return Values

The method always returns S_OK.

Requirements

Header: Declared in dmusicc.h.


IDirectMusicBuffer8::GetBufferFormat

Retrieves the GUID that represents the buffer format.

HRESULT GetBufferFormat(
  LPGUID pGuidFormat
);

Parameters

pGuidFormat
Address of a variable that receives the GUID of the buffer format.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

If the format was not specified when the buffer was created, KSDATAFORMAT_SUBTYPE_DIRECTMUSIC is returned in *pGuidFormat.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusic8::CreateMusicBuffer, DMUS_EVENTHEADER


IDirectMusicBuffer8::GetMaxBytes

Retrieves the number of bytes that can be stored in the buffer.

HRESULT GetMaxBytes(
  LPDWORD pcb
);

Parameters

pcb
Address of a variable to contain the maximum number of bytes that the buffer can hold.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusicc.h.


IDirectMusicBuffer8::GetNextEvent

Returns information about the next message in the buffer and advances the read pointer.

HRESULT GetNextEvent(
  LPREFERENCE_TIME prt,
  LPDWORD pdwChannelGroup,
  LPDWORD pdwLength,
  LPBYTE* ppData
);

Parameters

prt
Address of a variable that receives the time of the message.
pdwChannelGroup
Address of a variable that receives the channel group of the message.
pdwLength
Address of a variable that receives the length, in bytes, of the message.
ppData
Address of a variable that receives a pointer to the message data.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there are no messages in the buffer.

If it fails, the method can return E_POINTER.

Remarks

Any of the passed pointers can be NULL if the item is not needed.

The pointer returned in ppData is valid only for the lifetime of the buffer object.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer8::ResetReadPtr


IDirectMusicBuffer8::GetRawBufferPtr

Returns a pointer to the underlying buffer data structure.

HRESULT GetRawBufferPtr(
  LPBYTE* ppData
);

Parameters

ppData
Address of a variable that receives a pointer to the buffer's data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

This method returns a pointer to the raw data of the buffer. The format of the data depends on the implementation. The lifetime of the data is the same as the lifetime of the buffer object; therefore, the returned pointer should not be held after the next call to the IDirectMusicBuffer8::Release method.

Requirements

Header: Declared in dmusicc.h.


IDirectMusicBuffer8::GetStartTime

Retrieves the start time of the data in the buffer, relative to the master clock.

HRESULT GetStartTime(
  LPREFERENCE_TIME prt
);

Parameters

prt
Address of a variable that receives the start time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_BUFFER_EMPTY
E_POINTER

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer8::SetStartTime, IDirectMusicBuffer8::TotalTime


IDirectMusicBuffer8::GetUsedBytes

Retrieves the number of bytes of data in the buffer.

HRESULT GetUsedBytes(
  LPDWORD pcb
);

Parameters

pcb
Address of a variable that receives the number of used bytes.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer8::SetUsedBytes


IDirectMusicBuffer8::PackStructured

Inserts fixed-length data (typically a MIDI channel message), along with timing and routing information, into the buffer.

HRESULT PackStructured(
  REFERENCE_TIME rt,
  DWORD dwChannelGroup,
  DWORD dwChannelMessage
);

Parameters

rt
Absolute time of the message. See Remarks.
dwChannelGroup
Channel group to which the data belongs.
dwChannelMessage
Data (MIDI message) to pack.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_INVALID_EVENT
E_OUTOFMEMORY

Remarks

At least 32 bytes (the size of DMUS_EVENTHEADER plus dwChannelMessage) must be free in the buffer.

The rt parameter must contain the absolute time at which the data is to be sent to the port. To play a message immediately, retrieve the time from the latency clock, and use this as rt. See IDirectMusicPort8::GetLatencyClock.

Messages stamped with the same time do not necessarily play in the same order in which they were placed in the buffer.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer8::PackUnstructured


IDirectMusicBuffer8::PackUnstructured

Inserts unstructured data (typically a MIDI system exclusive message), along with timing and routing information, into the buffer.

HRESULT PackUnstructured(
  REFERENCE_TIME rt,
  DWORD dwChannelGroup,
  DWORD cb,
  LPBYTE lpb
);

Parameters

rt
Absolute time of the message.
dwChannelGroup
Channel group to which the message belongs.
cb
Size of the data, in bytes.
lpb
Address of a buffer containing the data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_OUTOFMEMORY
E_POINTER

Remarks

This method can be used to send any kind of data to the port.

At least 28 bytes (the size of DMUS_EVENTHEADER) plus the size of the data, padded to a multiple of 4 bytes, must be free in the buffer. The buffer space required can be obtained by using the DMUS_EVENT_SIZE(cb) macro, where cb is the size of the data.

The rt parameter must contain the absolute time at which the data is to be sent to the port. To play a message immediately, retrieve the time from the latency clock, and use this as rt. See IDirectMusicPort8::GetLatencyClock.

Messages stamped with the same time do not necessarily play in the same order in which they were placed in the buffer.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer8::PackStructured


IDirectMusicBuffer8::ResetReadPtr

Sets the read pointer to the start of the data in the buffer.

HRESULT ResetReadPtr()

Parameters

None.

Return Values

The method always returns S_OK.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer8::GetNextEvent


IDirectMusicBuffer8::SetStartTime

Sets the start time of the data in the buffer, relative to the master clock.

HRESULT SetStartTime(
  REFERENCE_TIME rt
);

Parameters

rt
New start time for the buffer.

Return Values

The method always returns S_OK.

Remarks

Events already in the buffer are time stamped relative to the start time and play at the same offset from the new start time.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer8::GetStartTime


IDirectMusicBuffer8::SetUsedBytes

Sets the number of bytes of data in the buffer.

HRESULT SetUsedBytes(
  DWORD cb
);

Parameters

cb
Number of valid data bytes in the buffer.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_BUFFER_FULL.

Remarks

This method allows an application to repack a buffer manually. Normally, this should be done only if the data format in the buffer is different from the default format provided by DirectMusic.

The method fails if the specified number of bytes exceeds the maximum buffer size, as returned by the IDirectMusicBuffer8::GetMaxBytes method.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer8::GetUsedBytes


IDirectMusicBuffer8::TotalTime

Returns the total time spanned by the data in the buffer.

HRESULT TotalTime(
  LPREFERENCE_TIME prtTime
);

Parameters

prtTime
Address of a variable that receives the total time spanned by the buffer, in units of 100 nanoseconds.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer8::GetStartTime


IDirectMusicChordMap8

The IDirectMusicChordMap8 interface represents a chordmap. Chordmaps provide the composer (represented by the IDirectMusicComposer8 interface) with the information needed to create chord progressions for segments to be composed. Chordmaps can also be used to change the chords in an existing segment.

The DirectMusicChordMap object also supports the IDirectMusicObject8 and IPersistStream interfaces for loading its data.

IDirectMusicChordMap8 is a type definition for IDirectMusicChordMap. The two interface names are interchangeable.

The interface has the following method:

IDirectMusicChordMap8 GetScale

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.


IDirectMusicChordMap8::GetScale

Retrieves the scale associated with the chordmap.

HRESULT GetScale(
  DWORD* pdwScale
);

Parameters

pdwScale
Address of a variable that receives the scale value.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be E_POINTER.

Remarks

The scale is defined by the bits in a DWORD, split into a scale pattern (lower 24 bits) and a root (upper 8 bits). For the scale pattern, the low bit (0x0001) is the lowest note in the scale, the next higher (0x0002) is a semitone higher, and so on for two octaves. The upper 8 bits give the root of the scale as an integer between 0 and 23 (low C to middle B).

Requirements

Header: Declared in dmusici.h.


IDirectMusicCollection8

The IDirectMusicCollection8 interface manages an instance of a DLS file. The collection provides methods to access instruments and download them to the synthesizer by means of the IDirectMusicPort8 interface.

IDirectMusicCollection8 is a type definition for IDirectMusicCollection. The two interface names are interchangeable.

The DirectMusicCollection object also supports the IDirectMusicObject8 and IPersistStream interfaces for loading its data.

For more information on how to work with collections, see Using Instrument Collections.

The IDirectMusicCollection8 interface has the following methods:

Instruments | EnumInstrument
 | GetInstrument

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusicc.h.


IDirectMusicCollection8::EnumInstrument

Retrieves the patch and name of an instrument by its index in the collection.

HRESULT EnumInstrument(
  DWORD dwIndex,
  DWORD* pdwPatch,
  LPWSTR pwszName,
  DWORD dwNameLen
);

Parameters

dwIndex
Index of the instrument in the collection.
pdwPatch
Address of a variable that receives the patch number.
pwszName
Address of a buffer that receives the instrument name. Can be NULL if the name is not wanted.
dwNameLen
Number of WCHAR values in the instrument name buffer.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there is no instrument with that index number.

If it fails, the method can return one of the following error values:

E_FAIL
E_OUTOFMEMORY
E_POINTER

Remarks

To enumerate all instruments in a collection, start with a dwIndex of 0 and increment until EnumInstrument returns S_FALSE.

The patch number returned in pdwPatch describes the full patch address, including the MIDI parameters for MSB and LSB bank select. For more information, see MIDI Channel Messages.

Although the ordering of the enumeration is consistent within one instance of a DLS collection, it has no relationship to the ordering of instruments in the file, their patch numbers, or their names.

For an example of instrument enumeration, see Working with Instruments.

Requirements

Header: Declared in dmusicc.h.


IDirectMusicCollection8::GetInstrument

Retrieves an instrument from a collection by its patch number.

HRESULT GetInstrument(
  DWORD dwPatch,
  IDirectMusicInstrument** ppInstrument
);

Parameters

dwPatch
Instrument patch number.
ppInstrument
Address of a variable that receives a pointer to the IDirectMusicInstrument8 interface.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_INVALIDPATCH
E_FAIL
E_OUTOFMEMORY
E_POINTER

Remarks

The patch number passed in dwPatch describes the full patch address, including the MIDI parameters for MSB and LSB bank select. MSB is shifted left 16 bits, and LSB is shifted left 8 bits. For more information, see MIDI Channel Messages.

In addition, the high bit is set (0x80000000) if the instrument is specifically a drum kit intended to be played on MIDI channel 10.

For an example of how this method is used, see Working with Instruments.

Requirements

Header: Declared in dmusicc.h.


IDirectMusicComposer8

The IDirectMusicComposer8 interface permits access to the composition engine. In addition to building new segments from templates and chordmaps, the composer can generate transitions between different segments. It can also apply a chordmap to an existing segment, thus altering the chord progression and the mood of the music.

IDirectMusicComposer8 is a define for IDirectMusicComposer. The two interface names are interchangeable.

The methods of the IDirectMusicComposer8 interface can be grouped as follows:

Changing chordmaps | ChangeChordMap
Composing ordinary segments | ComposeSegmentFromShape
 | ComposeSegmentFromTemplate
Composing template segments | ComposeTemplateFromShape
Composing transition segments | AutoTransition
 | ComposeTransition

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.


IDirectMusicComposer8::AutoTransition

Composes a transition from inside a performance's primary segment (or from silence) to another segment, and then cues the transition and the second segment to play.

HRESULT AutoTransition(
  IDirectMusicPerformance* pPerformance,
  IDirectMusicSegment* pToSeg,
  WORD wCommand,
  DWORD dwFlags,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppTransSeg,
  IDirectMusicSegmentState** ppToSegState,
  IDirectMusicSegmentState** ppTransSegState
);

Parameters

pPerformance
Performance in which to make the transition.
pToSeg
Segment to which the transition should smoothly flow. See Remarks.
wCommand
Embellishment to use when composing the transition. This can be one of the DMUS_COMMANDT_TYPES enumeration, or another value defined by the content provider. If this value is DMUS_COMMANDT_ENDANDINTRO, the method composes a segment containing both an ending to the primary segment and an introduction to pToSeg.
dwFlags
Composition options. See DMUS_COMPOSEF_FLAGS.
pChordMap
Pointer to the IDirectMusicChordMap8 interface of the chordmap to be used when composing the transition.
ppTransSeg
Address of a variable that receives a pointer to the created segment. This value can be NULL, in which case the pointer is not returned.
ppToSegState
Address of a variable that receives a pointer to the segment state created by the performance (pPerformance) for the segment following the transition (pToSeg). See Remarks.
ppTransSegState
Address of a variable that receives a pointer to the segment state created by the performance (pPerformance) for the created segment (ppTransSeg). See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NO_MASTER_CLOCK
E_INVALIDARG
E_POINTER

Remarks

The value in pToSeg can be NULL as long as dwFlags does not include DMUS_COMPOSEF_MODULATE. If pToSeg is NULL or does not contain a style track (as would be the case if it is based on a MIDI file), introductory embellishments are not valid. If the currently playing segment is NULL or does not contain a style track, then fill, break, end, and groove embellishments are not valid. If no style track is available either in the currently playing segment or in the one represented by pToSeg, all embellishments are invalid, and no transition occurs. In that case, both ppTransSeg and ppTransSegState return NULL, but the method succeeds and cues the segment represented by pToSeg, if that pointer is not NULL.

The value in pChordMap can be NULL. If it is, an attempt is made to obtain a chordmap from a chordmap track, first from pToSeg, and then from the performance's primary segment. If neither of these segments contains a chordmap track, the chord occurring at the current time in the primary segment is used as the chord in the transition.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicComposer8::ComposeTransition, Using Transitions


IDirectMusicComposer8::ChangeChordMap

Modifies the chords and scale pattern of an existing segment to reflect a new chordmap.

HRESULT ChangeChordMap(
  IDirectMusicSegment* pSegment,
  BOOL fTrackScale,
  IDirectMusicChordMap* pChordMap
);

Parameters

pSegment
Pointer to the IDirectMusicSegment8 interface of the segment in which to change the chordmap. This segment must contain a chordmap track and a style.
fTrackScale
If TRUE, the method transposes all the chords to be relative to the root of the new chordmap's scale, rather than leaving their roots as they were.
pChordMap
Pointer to the IDirectMusicChordMap8 interface of the new chordmap for the segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The method can be called while the segment is playing.

Requirements

Header: Declared in dmusici.h.


IDirectMusicComposer8::ComposeSegmentFromShape

Creates an original segment from a style and a chordmap, based on a predefined shape. The shape represents the way chords and embellishments occur over time across the segment.

HRESULT ComposeSegmentFromShape(
  IDirectMusicStyle* pStyle,
  WORD wNumMeasures,
  WORD wShape,
  WORD wActivity,
  BOOL fIntro,
  BOOL fEnd,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppSegment
);

Parameters

pStyle
Style from which to compose the segment.
wNumMeasures
Length, in measures, of the segment to be composed.
wShape
Shape of the segment to be composed. Possible values are of the DMUS_SHAPET_TYPES enumerated type.
wActivity
Rate of harmonic motion. Valid values are from 0 through 3. Lower values mean more chord changes.
fIntro
TRUE if an introduction is to be composed for the segment.
fEnd
TRUE if an ending is to be composed for the segment.
pChordMap
Pointer to the IDirectMusicChordMap8 interface of the chordmap from which to create the segment.
ppSegment
Address of a variable that receives a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicComposer8::ComposeSegmentFromTemplate, IDirectMusicComposer8::ComposeTemplateFromShape


IDirectMusicComposer8::ComposeSegmentFromTemplate

Creates an original segment from a style, a chordmap, and a template.

HRESULT ComposeSegmentFromTemplate(
  IDirectMusicStyle* pStyle,
  IDirectMusicSegment* pTemplate,
  WORD wActivity,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppSegment
);

Parameters

pStyle
IDirectMusicStyle8 interface pointer that specifies the style from which to create the segment.
pTemplate
IDirectMusicSegment8 interface pointer that specifies the template from which to create the segment.
wActivity
Rate of harmonic motion. Valid values are 0 through 3. Lower values mean more chord changes.
pChordMap
IDirectMusicChordMap8 interface pointer that specifies the chordmap from which to create the segment.
ppSegment
Address of a variable that receives a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

If pStyle is non-NULL, it is used in composing the segment; if it is NULL, a style is retrieved from the template specified in pTempSeg. Similarly, if pChordMap is non-NULL, it is used in composing the segment; if it is NULL, a chordmap is retrieved from the template.

If pStyle is NULL and there is no style track in the template, or pChordMap is NULL and there is no chordmap track, the method returns E_INVALIDARG.

The length of the segment is equal to the length of the template passed in.

The default start point and loop points of the created segment are 0, regardless of the values in the template segment.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicComposer8::ComposeSegmentFromShape, IDirectMusicComposer8::ComposeTemplateFromShape, Using Templates


IDirectMusicComposer8::ComposeTemplateFromShape

Creates a new template segment, based on a predefined shape.

HRESULT ComposeTemplateFromShape(
  WORD wNumMeasures,
  WORD wShape,
  BOOL fIntro,
  BOOL fEnd,
  WORD wEndLength,
  IDirectMusicSegment** ppTemplate
);

Parameters

wNumMeasures
Length, in measures, of the segment to be composed. This value must be greater than 0.
wShape
Shape of the segment to be composed. Possible values are of the DMUS_SHAPET_TYPES enumerated type.
fIntro
TRUE if an introduction is to be composed for the segment.
fEnd
TRUE if an ending is to be composed for the segment.
wEndLength
Length in measures of the ending, if one is to be composed. If fEnd is TRUE, this value must be greater than 0 and equal to or less than the number of measures available (that is, not used in the introduction). See also Remarks.
ppTemplate
Address of a variable that receives a pointer to the created template segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

The value of wEndLength should not be greater than the length of the longest ending available in any style likely to be associated with this template through the IDirectMusicComposer8::ComposeSegmentFromTemplate method. The ending starts playing at wEndLength measures before the end of the segment. If the ending is less than wEndLength measures long, the music then reverts to the basic groove level.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicComposer8::ComposeSegmentFromTemplate, Using Templates


IDirectMusicComposer8::ComposeTransition

Composes a transition from a measure inside one segment to another.

HRESULT ComposeTransition(
  IDirectMusicSegment* pFromSeg,
  IDirectMusicSegment* pToSeg,
  MUSIC_TIME mtTime,
  WORD wCommand,
  DWORD dwFlags,
  IDirectMusicChordMap* pChordMap,
  IDirectMusicSegment** ppTransSeg
);

Parameters

pFromSeg
Segment from which to compose the transition.
pToSeg
Segment to which the transition should smoothly flow. Can be NULL if dwFlags does not include DMUS_COMPOSEF_MODULATE.
mtTime
Time in pFromSeg from which to compose the transition.
wCommand
Embellishment to use when composing the transition. This can be one of the DMUS_COMMANDT_TYPES enumeration, or another value defined by the content provider. If this value is DMUS_COMMANDT_ENDANDINTRO, the method composes a segment containing both an ending to pFromSeg and an introduction to pToSeg.
dwFlags
Composition options. This parameter can contain one or more of the DMUS_COMPOSEF_FLAGS enumerated type values.
pChordMap
Pointer to the IDirectMusicChordMap8 interface chordmap to be used when composing the transition. See Remarks.
ppTransSeg
Address of a variable that receives a pointer to the created segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

The value in pChordMap can be NULL. If it is, an attempt is made to obtain a chordmap from a chordmap track, first from pToSeg, and then from pFromSeg. If neither of these segments contains a chordmap track, the chord occurring at mtTime in pFromSeg is used as the chord in the transition.

The composer looks for a tempo, first in pFromSeg, and then in pToSeg. If neither of those segments contains a tempo track, the tempo for the transition segment is taken from the style.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicComposer8::AutoTransition, Using Transitions


IDirectMusicContainer8

The IDirectMusicContainer8 interface provides access to objects in a container, which is a collection of objects used by a segment or performance. The interface can be obtained when a container is loaded by a call to IDirectMusicLoader8::GetObject or IDirectMusicLoader8::LoadObjectFromFile.

When a container object is loaded, it makes all its objects available to the loader. When the container is released, all objects it refers to are released from the loader. However, any objects still in use when the container is released are not freed until explicitly released. If they are keeping a stream open, as DLS collections and streaming waves do, the stream also stays open. As a result, the container file stays locked, just as an individual wave or DLS file would.

A container can be embedded in a segment. The container is placed in the file before the segment's tracks, so it can be read and its objects installed in the loader before the tracks are loaded. When the tracks are loaded, the loader is able to supply links to referenced objects in the container.

IDirectMusicContainer8 is a type definition for IDirectMusicContainer. The two interface names are interchangeable.

The IDirectMusicContainer8 interface has the following method.

Enumeration EnumObject

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.

See Also

Containers


IDirectMusicContainer8::EnumObject

Retrieves information about an object in the container.

HRESULT EnumObject(
  REFGUID rguidClass,
  DWORD dwIndex,
  LPDMUS_OBJECTDESC pDesc,
  WCHAR* pwszAlias
);

Parameters

rguidClass
Reference to (C++) or address of (C) the unique identifier of the object class, or GUID_DirectMusicAllTypes to obtain an object of any type. For a list of standard loadable classes, see IDirectMusicLoader8.
dwIndex
Index of the object among objects of class rguidClass in the container.
pDesc
Pointer to a DMUS_OBJECTDESC structure that receives a description of the object. This parameter can be NULL if no description is wanted. See Remarks.
pwszAlias
Address of a string buffer of size MAX_PATH that receives the object's alias, if it has one. An alias is a special name used by a script to refer to the object. This parameter can be NULL if no alias is wanted.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The object was enumerated.
S_FALSE | There is no object with an index of dwIndex.
DMUS_S_STRING_TRUNCATED | The alias is longer than MAX_PATH
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, it can return E_POINTER.

Remarks

You must initialize the dwSize member of the DMUS_OBJECTDESC structure before passing it to the method. Other members are ignored. You cannot reduce the scope of the enumeration by, for example, specifying a value in the wszName member. The description returned by the method can be used to retrieve the object by calling IDirectMusicLoader8::GetObject. For sample code, see Containers.

Requirements

Header: Declared in dmusici.h.


IDirectMusicDownload8

The IDirectMusicDownload8 interface represents a contiguous memory chunk used for downloading to a DLS synthesizer port.

IDirectMusicDownload8 is a type definition for IDirectMusicDownload. The two interface names are interchangeable.

The IDirectMusicDownload8 interface and its contained memory chunk are created by the IDirectMusicPortDownload8::AllocateBuffer method. The memory can then be accessed by using the single method of this interface.

This interface is used only by applications that need to access DLS buffers directly rather than letting the performance, band, and segment objects download instrument data. For an overview, see Low-Level DLS.

The interface has the following method:

Memory access GetBuffer

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusicc.h.


IDirectMusicDownload8::GetBuffer

Retrieves a pointer to a buffer containing data to be downloaded.

HRESULT GetBuffer(
  void** ppvBuffer,
  DWORD* pdwSize
);

Parameters

ppvBuffer
Address of a variable that receives a pointer to the data buffer.
pdwSize
Address of a variable that receives the size of the returned buffer, in bytes.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_BUFFERNOTAVAILABLE
E_POINTER

Remarks

The method returns DMUS_E_BUFFERNOTAVAILABLE if the buffer has already been downloaded.

Requirements

Header: Declared in dmusicc.h.


IDirectMusicDownloadedInstrument8

The IDirectMusicDownloadedInstrument8 interface is used to identify an instrument that has been downloaded to the synthesizer by using the IDirectMusicPort8::DownloadInstrument or the IDirectMusicPerformance8::DownloadInstrument method. The interface pointer is then used to unload the instrument through a call to IDirectMusicPort8::UnloadInstrument. After the instrument has been unloaded, the interface pointer must be released by the application. For an example, see Working with Instruments.

IDirectMusicDownloadedInstrument8 is a type definition for IDirectMusicDownloadedInstrument. The two interface names are interchangeable.

The IDirectMusicDownloadedInstrument8 interface has no methods of its own. Like all COM interfaces, it inherits the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusicc.h.


IDirectMusicGetLoader8

The IDirectMusicGetLoader8 interface is used by an object parsing a stream when the object needs to load another object referenced by the stream. If a stream supports the loader, it must provide an IDirectMusicGetLoader8 interface.

For an example of how to obtain the IDirectMusicGetLoader8 interface from the stream, see IDirectMusicGetLoader8::GetLoader.

IDirectMusicGetLoader8 is a type definition for IDirectMusicGetLoader. The two interface names are interchangeable.

The IDirectMusicGetLoader8 interface has the following method:

IDirectMusicGetLoader8 GetLoader

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicLoader8, Loading Audio Data, Custom Loading


IDirectMusicGetLoader8::GetLoader

Retrieves a pointer to the loader object that created the stream.

HRESULT GetLoader8(
  IDirectMusicLoader ** ppLoader
);

Parameters

ppLoader
Address of a variable that receives the IDirectMusicLoader interface pointer. Use QueryInterface to obtain IDirectMusicLoader8. The reference count of the interface is incremented.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_NOINTERFACE.

Remarks

The following code example is from a file parser that finds a reference to an object that needs to be accessed by the loader.

HRESULT myGetReferencedObject(
    DMUS_OBJECTDESC *pDesc,          // Descriptor already prepared
    IStream *pIStream,               // Stream being parsed
    IDirectMusicObject **ppIObject)  // Object to be accessed
{
    IDirectMusicGetLoader *pIGetLoader;
    IDirectMusicLoader *pILoader;
    ppIObject = NULL;
    HRESULT hr = pIStream->QueryInterface(
           IID_IDirectMusicGetLoader,
           (void **) &pIGetLoader );
    if (SUCCEEDED(hr))
    {
        hr = pIGetLoader->GetLoader(&pILoader);
        if (SUCCEEDED(hr))
        {
            hr = pILoader->GetObject(pDesc, IID_DirectMusicLoader,
                  (void**) ppIObject);
            pILoader->Release();
        }
        pIGetLoader->Release();
    }
    return hr;
}

Requirements

Header: Declared in dmusici.h.

See Also

Custom Loading


IDirectMusicGraph8

The IDirectMusicGraph8 interface manages the loading and message flow of tools.

Graphs can occur in two places: performances and segments. The graph of tools in a performance is global in nature; it processes messages from all segments. A graph in a segment exists only for playback of that segment.

IDirectMusicGraph8 is a type definition for IDirectMusicGraph. The two interface names are interchangeable.

The IDirectMusicGraph8 interface has the following methods:

Routing | StampPMsg
Tools | GetTool
 | InsertTool
 | RemoveTool

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.


IDirectMusicGraph8::GetTool

Retrieves a tool by index.

HRESULT GetTool(
  DWORD dwIndex,
  IDirectMusicTool** ppTool
);

Parameters

dwIndex
Zero-based index of the requested tool in the graph.
ppTool
Address of a variable that receives a pointer to the tool.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following values:

DMUS_E_NOT_FOUND
E_POINTER

Remarks

The application is responsible for releasing the retrieved tool.

Requirements

Header: Declared in dmusici.h.


IDirectMusicGraph8::InsertTool

Inserts a tool in the graph.

HRESULT InsertTool(
  IDirectMusicTool * pTool,
  DWORD * pdwPChannels,
  DWORD cPChannels,
  LONG lIndex
);

Parameters

pTool
Tool to insert.
pdwPChannels
Address of an array of PChannels on which the tool accepts messages. If the tool accepts messages on all channels, pass NULL.
cPChannels
Count of how many channels are pointed to by pdwPChannels. Ignored if pdwPChannels is NULL.
lIndex
Position at which to place the tool. This is a zero-based index from the start of the current tool list or, if it is negative, from the end of the list. If lIndex is out of range, the tool is placed at the beginning or end of the list. To place a tool at the end of the list, use a number for lIndex that is larger than the number of tools in the current tool list.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_ALREADY_EXISTS
E_OUTOFMEMORY
E_POINTER

Remarks

The reference count of the tool is incremented.

This method calls IDirectMusicTool8::Init.

Requirements

Header: Declared in dmusici.h.


IDirectMusicGraph8::RemoveTool

Removes a tool from the graph.

HRESULT RemoveTool(
  IDirectMusicTool * pTool
);

Parameters

pTool
Tool to be removed.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_POINTER

Remarks

The graph's reference to the tool object is released.

Requirements

Header: Declared in dmusici.h.


IDirectMusicGraph8::StampPMsg

Stamps a message with a pointer to the next tool that is to receive it. After processing a message, a tool must call this method.

HRESULT StampPMsg(
  DMUS_PMSG* pPMSG
);

Parameters

pPMSG
Address of a structure that contains the message to stamp. This structure is of a type derived from DMUS_PMSG.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_LAST_TOOL. See Remarks.

If it fails, the method can return E_POINTER.

Remarks

On entry, the pTool member of the DMUS_PMSG part of the message structure points to the current tool. StampPMsg uses this member to determine the current tool to find the next tool in the graph. A value of NULL represents the first tool in the graph.

The object pointed to by the pGraph member represents the graph that contains the tool. This is stamped inside StampPMsg, along with the tool itself, and can change while the message travels from the segment state to the performance because there can be multiple toolgraphs.

The value of dwType equals the media type of the message, and is also used to find the next tool. The media types supported are those returned by the IDirectMusicTool8::GetMediaTypes method.

This method calls Release on the current IDirectMusicTool8 pointed to by pTool, replaces it with the next tool in the graph and calls AddRef on the new tool. It also flags the message with the correct delivery type, according to what type the next tool returns in its IDirectMusicTool8::GetMsgDeliveryType method. This flag determines when the message is delivered to the next tool.

Tools should not call StampPMsg until all other tasks have been performed. When audiopaths are in use, StampPMsg can have the effect of changing the value in the dwPChannel member of the message structure. A tool that uses this value cannot rely on it if StampPMsg has already been called

The implementations of this method in the DirectMusicSegmentState and DirectMusicPerformance objects always return S_OK on success. The implementation in DirectMusicGraph returns DMUS_S_LAST_TOOL if there is no tool other than the output tool waiting to receive the message.

Requirements

Header: Declared in dmusici.h.

See Also

DirectMusic Tools


IDirectMusicInstrument8

The IDirectMusicInstrument8 interface represents an individual instrument from a DLS collection.

IDirectMusicInstrument8 is a type definition for IDirectMusicInstrument. The two interface names are interchangeable.

The only way to create a DirectMusicInstrument object to download an instrument is to first create a DirectMusicCollection object, and then call the IDirectMusicCollection8::GetInstrument method. GetInstrument creates a DirectMusicInstrument object and returns its IDirectMusicInstrument8 interface pointer.

To download the instrument, pass its interface pointer to the IDirectMusicPort8::DownloadInstrument or the IDirectMusicPerformance8::DownloadInstrument method. If the method succeeds, it returns a pointer to an IDirectMusicDownloadedInstrument8 interface, which is used only to unload the instrument.

The methods of IDirectMusicInstrument8 operate only on an instrument that has not been downloaded. Any instances of the instrument that have been downloaded to a port are not affected by the IDirectMusicInstrument8::GetPatch and IDirectMusicInstrument8::SetPatch methods.

The interface has the following methods:

IDirectMusicInstrument8 | GetPatch
 | SetPatch

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTMUSICINTRUMENT8 type is defined as a pointer to this interface.

typedef IDirectMusicInstrument8 *LPDIRECTMUSICINSTRUMENT8;

Requirements

Header: Declared in dmusicc.h.


IDirectMusicInstrument8::GetPatch

Retrieves the patch number for the instrument. The patch number is an address composed of the MSB and LSB bank selects and the MIDI patch (program change) number. An optional flag bit indicates that the instrument is a drum, rather than a melodic instrument.

HRESULT GetPatch(
  DWORD* pdwPatch
);

Parameters

pdwPatch
Address of a variable that receives the patch number.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_POINTER

Remarks

The patch number returned at pdwPatch describes the full patch address, including the MIDI parameters for MSB and LSB bank select. In addition, the high bit is set if the instrument is specifically a drum kit, intended to be played on MIDI channel 10. This is a special tag for DLS Level 1, because DLS Level 1 always plays drums on MIDI channel 10. For more information, see MIDI Channel Messages.

Requirements

Header: Declared in dmusicc.h.


IDirectMusicInstrument8::SetPatch

Sets the patch number for the instrument. Although each instrument in a DLS collection has a predefined patch number, the patch number can be reassigned after the IDirectMusicCollection8::GetInstrument method has been used to retrieve the instrument from the collection. For more information on DirectMusic patch numbers, see IDirectMusicInstrument8::GetPatch.

HRESULT SetPatch(
  DWORD dwPatch
);

Parameters

dwPatch
New patch number to assign to instrument.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
DMUS_E_INVALIDPATCH

Remarks

The following code example gets an instrument from a collection, remaps its MSB bank select to a different bank, and then downloads the instrument.

HRESULT myRemappedDownload(
    IDirectMusicCollection8 *pCollection,
    IDirectMusicPort8 *pPort,
    IDirectMusicDownloadedInstrument8 **ppDLInstrument,
    BYTE bMSB,       // Requested MIDI MSB for patch bank select
    DWORD dwPatch)   // Requested patch

{
    HRESULT hr;
    IDirectMusicInstrument8* pInstrument;
    hr = pCollection->GetInstrument(dwPatch, &pInstrument);
    if (SUCCEEDED(hr))
    {
        dwPatch &= 0xFF00FFFF;  // Clear MSB.
        dwPatch |= bMSB << 16;  // Insert new MSB value.
        pInstrument->SetPatch(dwPatch);
        hr = pPort->DownloadInstrument(pInstrument,
                ppDLInstrument,
                NULL, 0);       // Download all regions.
        pInstrument->Release();
    }
    return hr;
}

Requirements

Header: Declared in dmusicc.h.


IDirectMusicLoader8

The IDirectMusicLoader8 interface is used for finding, enumerating, caching, and loading objects. For an overview, see Loading Audio Data.

This interface supersedes IDirectMusicLoader and adds support for garbage collection.

The methods of the IDirectMusicLoader8 interface can be organized into the following groups:

Searching | EnumObject
 | ScanDirectory
 | SetSearchDirectory
Cache and memory management | CacheObject
 | ClearCache
 | CollectGarbage
 | EnableCache
 | ReleaseObject
 | ReleaseObjectByUnknown
Object loading | GetObject
 | LoadObjectFromFile
 | SetObject

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDMUS_LOADER type is defined as a pointer to the IDirectMusicLoader interface.

typedef IDirectMusicLoader __RPC_FAR *LPDMUS_LOADER;

The following table lists the standard types of loadable objects, together with their class identifiers (the rguidClass parameter of various methods that deal with objects) and the usual file name extension.

Object type | Class | Extension
Audiopath | CLSID_DirectMusicAudioPathConfig | aud
Band | CLSID_DirectMusicBand | bnd
Container | CLSID_DirectMusicContainer | con
DLS collection | CLSID_DirectMusicCollection | dls
Chordmap | CLSID_DirectMusicChordMap | cdm
Segment | CLSID_DirectMusicSegment | sgt
Script | CLSID_DirectMusicScript | spt
Song* | CLSID_DirectMusicSong | sng
Style | CLSID_DirectMusicStyle | sty
Template | CLSID_DirectMusicSegment | tpl
Toolgraph | CLSID_DirectMusicGraph | tgr
Wave | CLSID_DirectSoundWave | wav

* Not implemented in DirectX 8.0.

Requirements

Header: Declared in dmusici.h.


IDirectMusicLoader8::CacheObject

Tells the loader to keep a reference to the object. This guarantees that the object is not loaded twice.

HRESULT CacheObject(
  IDirectMusicObject * pObject
);

Parameters

pObject
Address of the IDirectMusicObject interface of the object to cache. Use QueryInterface to obtain IDirectMusicObject8.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the object is already cached.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_LOADER_OBJECTNOTFOUND

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicLoader8::EnableCache, IDirectMusicLoader8::ClearCache, IDirectMusicLoader8::ReleaseObject, Cache Management


IDirectMusicLoader8::ClearCache

Tells the loader to release all references to a particular type of object.

HRESULT ClearCache(
  REFGUID rguidClass
);

Parameters

rguidClass
Reference to (C++) or address of (C) the identifier of the class of objects to clear, or GUID_DirectMusicAllTypes to clear all types. For a list of standard loadable classes, see IDirectMusicLoader8.

Return Values

The method returns S_OK.

Remarks

This method clears all objects that are currently being held, but does not turn off caching. Use the IDirectMusicLoader8::EnableCache method to turn off automatic caching.

To clear a single object from the cache, call the IDirectMusicLoader8::ReleaseObject method.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicLoader8::CacheObject, Cache Management


IDirectMusicLoader8::CollectGarbage

Removes from the cache objects that are no longer in use.

CollectGarbage();

Parameters

None.

Return Values

None.

Remarks

When an application calls IDirectMusicLoader8::ReleaseObject on an object, that object is removed from the cache, and any objects it references become candidates for removal. IDirectMusicLoader8::CollectGarbage finds cached objects that are no longer being used by other objects, removes them from the cache, and releases them from memory.

Requirements

Header: Declared in dmusici.h.

See Also

Garbage Collection


IDirectMusicLoader8::EnableCache

Tells the loader to enable or disable automatic caching of all objects it loads. By default, caching is enabled for all classes.

HRESULT EnableCache(
  REFGUID rguidClass,
  BOOL fEnable
);

Parameters

rguidClass
Reference to (C++) or address of (C) the identifier of the class of objects to cache, or GUID_DirectMusicAllTypes to cache all types. For a list of standard loadable classes, see IDirectMusicLoader8.
fEnable
TRUE to enable caching; FALSE to clear and disable.

Return Values

The method returns S_OK if the cache state is changed, or S_FALSE if the cache is already in the desired state.

Remarks

To clear the cache without disabling caching, call the IDirectMusicLoader8::ClearCache method.

The following code example disables caching only for segment objects so that they do not stay in memory after the application releases them. Other objects that should be shared, such as styles, chordmaps, and DLS collections, continue to be cached. The first call to EnableCache would normally be unnecessary because caching is enabled for all objects by default.

void myPrepareLoader(IDirectMusicLoader8 *pILoader)

{
    pILoader->EnableCache(GUID_DirectMusicAllTypes, TRUE);
    pILoader->EnableCache(CLSID_DirectMusicSegment, FALSE);
}

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicLoader8::CacheObject, IDirectMusicLoader8::ClearCache, Cache Management


IDirectMusicLoader8::EnumObject

Enumerates all available objects of the requested type. Objects are available if they have been loaded or if IDirectMusicLoader8::ScanDirectory has been called on the search directory.

HRESULT EnumObject(
  REFGUID rguidClass,
  DWORD dwIndex,
  LPDMUS_OBJECTDESC pDesc
);

Parameters

rguidClass
Reference to (C++) or address of (C) the identifier for the class of objects to view. For a list of standard loadable classes, see IDirectMusicLoader8.
dwIndex
Index into the list. Typically, starts with 0 and increments.
pDesc
Address of a DMUS_OBJECTDESC structure to be filled with data about the object.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if dwIndex is past the end of the list.

Remarks

For an example of the use of this method, see Enumerating Objects.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicLoader8::ScanDirectory


IDirectMusicLoader8::GetObject

Retrieves the specified object from a file or resource and returns the desired interface.

HRESULT GetObject(
  LPDMUS_OBJECTDESC pDesc,
  REFIID riid,
  LPVOID FAR * ppv
);

Parameters

pDesc
Address of a DMUS_OBJECTDESC structure describing the object.
riid
Unique identifier of the interface. See the IID defines in Dmusici.h. All the standard interfaces have a defined identifier consisting of "IID_" plus the name of the interface. For example, the identifier of IDirectMusicTrack8 is IID_IDirectMusicTrack8.
ppv
Address of a variable that receives a pointer to the desired interface of the object.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_PARTIALLOAD.

DMUS_S_PARTIALLOAD is returned if any referenced object cannot be found, such as a style referenced in a segment. The loader might fail to find the style if it is referenced by name but IDirectMusicLoader8::ScanDirectory has not been called for styles. DMUS_S_PARTIALLOAD might also mean that the default instrument collection file, Gm.dls, is not available.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER
DMUS_E_LOADER_NOCLASSID
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED
REGDB_E_CLASSNOTREG

Remarks

For file objects, it is simpler to use the IDirectMusicLoader8::LoadObjectFromFile method.

DirectMusic does not support loading from URLs. If the dwValidData member of the DMUS_OBJECTDESC structure contains DMUS_OBJ_URL, the method returns DMUS_E_LOADER_FORMATNOTSUPPORTED.

The method does not require that all valid members of the DMUS_OBJECTDESC structure match before retrieving an object. It searches in the following order:

  1. DMUS_OBJ_OBJECT
  2. DMUS_OBJ_MEMORY
  3. DMUS_OBJ_FILENAME and DMUS_OBJ_FULLPATH
  4. DMUS_OBJ_NAME and DMUS_OBJ_CATEGORY
  5. DMUS_OBJ_NAME
  6. DMUS_OBJ_FILENAME

In other words, the highest priority goes to a unique GUID, followed by a resource, followed by the full file path name, followed by an internal name plus category, followed by an internal name, followed by a local file name.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicLoader8::ReleaseObject, IDirectMusicLoader8::ScanDirectory, IDirectMusicLoader8::LoadObjectFromFile


IDirectMusicLoader8::LoadObjectFromFile

Retrieves the specified object from a file and returns the desired interface. This method can be used instead of IDirectMusicLoader8::GetObject when the object is in a file.

HRESULT LoadObjectFromFile(
  REFGUID rguidClassID,
  REFIID iidInterfaceID,
  WCHAR *pwzFilePath,
  void ** ppObject
);

Parameters

rguidClassID
Unique identifier for the class of object. For a list of standard loadable classes, see IDirectMusicLoader8.
iidInterfaceID
Unique identifier of the interface. See the IID defines in Dmusici.h. All the standard interfaces have a defined identifier consisting of "IID_" plus the name of the interface. For example, the identifier of IDirectMusicTrack8 is IID_IDirectMusicTrack8.
pwzFilePath
Name of the file that contains the object. The path can be fully qualified or relative to the search directory.
ppObject
Address of a variable that receives a pointer to the desired interface of the object.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_PARTIALLOAD.

If it fails, the method can return one of the following error values.

E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER
DMUS_E_LOADER_NOCLASSID
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED
REGDB_E_CLASSNOTREG

Remarks

DMUS_S_PARTIALLOAD is returned if any referenced object cannot be found, such as a style referenced in a segment. The loader might fail to find the style if it is referenced by name but IDirectMusicLoader8::ScanDirectory has not been called for styles. DMUS_S_PARTIALLOAD might also mean that the default instrument collection file, Gm.dls, is not available.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicLoader8::GetObject, IDirectMusicLoader8::SetSearchDirectory


IDirectMusicLoader8::ReleaseObject

Releases the loader's reference to the object.

HRESULT ReleaseObject(
  IDirectMusicObject * pObject
);

Parameters

pObject
IDirectMusicObject8 interface pointer of the object to release.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the object has already been released or cannot be found in the cache.

If it fails, the method can return E_POINTER.

Remarks

ReleaseObject is the reciprocal of IDirectMusicLoader8::CacheObject.

Objects can be cached explicitly by using the CacheObject method, or automatically by using the IDirectMusicLoader8::EnableCache method.

To tell the loader to flush all objects of a particular type, call the IDirectMusicLoader8::ClearCache method.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicLoader8::ReleaseObjectByUnknown, DirectMusicLoader8::GetObject, Cache Management


IDirectMusicLoader8::ReleaseObjectByUnknown

Releases the loader's reference to the object. This method is similar to IDirectMusicLoader8::ReleaseObject and is suitable for releasing objects for which the IDirectMusicObject8 interface is not readily available.

HRESULT ReleaseObject(
  IUnknown * pObject
);

Parameters

pObject
Address of the IUnknown interface pointer of the object to release.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the object has already been released or cannot be found in the cache.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicLoader8::GetObject, Cache Management


IDirectMusicLoader8::ScanDirectory

Searches a directory or disk for all files of a requested class type and file name extension. For each file found, it calls the IDirectMusicObject8::ParseDescriptor method to extract the GUID and name of the object. This information is stored in an internal database. After a directory has been scanned, all files of the requested type become available for enumeration through the IDirectMusicLoader8::EnumObject method; in addition, an object can be retrieved by using IDirectMusicLoader8::GetObject, even without a file name.

HRESULT ScanDirectory(
  REFGUID rguidClass,
  WCHAR* pwzFileExtension,
  WCHAR* pwzScanFileName
);

Parameters

rguidClass
Reference to (C++) or address of (C) the identifier of the class of objects. For a list of standard loadable classes, see IDirectMusicLoader8.
pwzFileExtension
File name extension for the type of file to look for. Use L"*" to look in files with any or no extension. See Remarks.
pwzScanFileName
Optional storage file to store and retrieve cached file information. This file is created by the first call to ScanDirectory and used by subsequent calls. Pass NULL if a cache file is not wanted.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if no files were found.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_FAIL
E_OUTOFMEMORY
E_POINTER
REGDB_E_CLASSNOTREG

Remarks

The IDirectMusicLoader8::SetSearchDirectory method must be called first to set the location to search.

The scanned information can be stored in a cache file defined by pwzScanFileName. After it has been so stored, subsequent calls to ScanDirectory are much quicker because only files that have changed are scanned (the cache file stores the file size and date for each object, so it can tell if a file has changed).

GUID_DirectMusicAllTypes is not a valid value for rguidClass.

If the file type has more than one possible extension, call ScanDirectory once for each file name extension.

Requirements

Header: Declared in dmusici.h.

See Also

Scanning a Directory for Objects


IDirectMusicLoader8::SetObject

Tells the loader where to find an object when it is later referenced by another object being loaded, and adds attributes to an object so that it can be referred to by those attributes. For an overview, see Setting Objects.

HRESULT SetObject(
  LPDMUS_OBJECTDESC pDesc
);

Parameters

pDesc
Address of a DMUS_OBJECTDESC structure describing the object. On entry, this structure contains any information the application has about the object. On return, it can contain additional information.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER
DMUS_E_LOADER_NOCLASSID
DMUS_E_LOADER_FAILEDOPEN
DMUS_E_LOADER_FAILEDCREATE
DMUS_E_LOADER_FORMATNOTSUPPORTED
REGDB_E_CLASSNOTREG

Remarks

This method can be used to set attributes that are not currently valid for an object. For example, you can supply a value in the wszName member of the DMUS_OBJECTDESC structure to assign an internal name to an unnamed object, such as a segment based on a MIDI file. However, it cannot be used to change existing attributes. Most authored segments, for example, already have names, and these cannot be changed by the application.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicLoader8::GetObject


IDirectMusicLoader8::SetSearchDirectory

Sets a search path for finding object files. The search path can be set for one object file type or for all files.

HRESULT SetSearchDirectory(
  REFGUID rguidClass,
  WCHAR* pwszPath,
  BOOL fClear
);

Parameters

rguidClass
Reference to (C++) or address of (C) the identifier of the class of objects that the call pertains to. GUID_DirectMusicAllTypes specifies all objects. For a list of standard loadable classes, see IDirectMusicLoader8.
pwszPath
File path for directory. Must be a valid directory and must be less than MAX_PATH in length. The path, if not fully qualified, is relative to the current directory when IDirectMusicLoader8::ScanDirectory is called.
fClear
If TRUE, clears all information about objects before setting the directory. This prevents accessing objects from the previous directory that might have the same name. However, objects are not removed from the cache.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the search directory is already set to pwszPath.

If it fails, the method can return one of the following error values:

E_OUTOFMEMORY
E_POINTER
DMUS_E_LOADER_BADPATH

Remarks

After a search path is set, the loader does not need a full path every time it is given an object to load by file name. This enables objects that refer to other objects to find them by file name without knowing the full path.

When this method has been called, the loader expects the wszFileName member of the DMUS_OBJECTDESC structure to contain only a file name or a path relative to the search directory, unless the DMUS_OBJ_FULLPATH flag is set in the dwValidData member.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicLoader8::ScanDirectory, Setting the Loader's Search Directory


IDirectMusicObject8

All DirectMusic objects that can be loaded from a file support the IDirectMusicObject8 interface so that they can work with the DirectMusic loader. New types of objects need to implement this interface. For more information, see Custom Loading.

Most applications do not use the methods of this interface directly. However, IDirectMusicObject8::GetDescriptor can be used to query an object for information, including its name, GUID, file path, and version.

The IDirectMusicObject8 interface is usually obtained by calling another interface's QueryInterface method. It cannot be obtained by using CoCreateInstance. The interface is also returned by IDirectMusicContainer8::EnumObject.

IDirectMusicObject8 is a define for IDirectMusicObject. The two interface names are interchangeable.

The IDirectMusicObject8 interface has the following methods:

Descriptor | GetDescriptor
 | ParseDescriptor
 | SetDescriptor

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDMUS_OBJECT type is defined as a pointer to the IDirectMusicObject interface.

typedef IDirectMusicObject __RPC_FAR *LPDMUS_OBJECT;

Requirements

Header: Declared in dmusici.h.

See Also

Loading Audio Data, Custom Loading


IDirectMusicObject8::GetDescriptor

Retrieves the object's internal description.

HRESULT GetDescriptor(
  LPDMUS_OBJECTDESC pDesc
);

Parameters

pDesc
Address of a DMUS_OBJECTDESC structure to be filled with data about the object. Depending on the implementation of the object and how it was loaded from a file, some or all of the standard parameters are filled by GetDescriptor. Check the flags in the dwValidData member to ascertain which other members are valid.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_GARBAGE_COLLECTED. See Garbage Collection.

If it fails, the method can return E_POINTER.

Remarks

For an example, see Getting Object Descriptors.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicObject8::SetDescriptor


IDirectMusicObject8::ParseDescriptor

Given a file stream, the IDirectMusicObject8::ParseDescriptor method scans the file for data that it can store in the DMUS_OBJECTDESC structure. All members that are supplied are marked with the appropriate flags in dwValidData.

This method is primarily used by the loader when scanning a directory for objects, and is not normally used directly by an application. However, if an application implements an object type in DirectMusic, it should support this method.

HRESULT ParseDescriptor(
  LPSTREAM pStream,
  LPDMUS_OBJECTDESC pDesc
);

Parameters

pStream
Stream source for the file.
pDesc
Address of a DMUS_OBJECTDESC structure that receives data about the file.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_GARBAGE_COLLECTED. See Garbage Collection.

If it fails, the method can return one of the following error values:

DMUS_E_CHUNKNOTFOUND
DMUS_E_INVALID_BAND
DMUS_E_INVALIDFILE
DMUS_E_NOTADLSCOL
E_FAIL
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicObject8::SetDescriptor


IDirectMusicObject8::SetDescriptor

Sets some or all members of the object's internal description.

This method is primarily used by the loader when creating an object, and is not normally used directly by an application. However, if an application implements an object type in DirectMusic, it should support this method.

HRESULT SetDescriptor(
  LPDMUS_OBJECTDESC pDesc
);

Parameters

pDesc
Address of a DMUS_OBJECTDESC structure that receives data about the object. Data is copied to all members that are enabled in the dwValidData member

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The descriptor was set.
S_FALSE | See Remarks.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

Applications do not normally call this method on standard objects. Although it is possible to change the object descriptor returned by IDirectMusicObject8::GetDescriptor, the new description cannot successfully be passed to the IDirectMusicLoader8::GetObject method. For example, you could change the name of an object, but GetObject will still find the object only under its original name, because it relies on the object's own implementation of SetDescriptor.

Members that are not copied keep their previous values. For example, an object might already have its name and GUID stored internally. A call to its SetDescriptor method with a new name and file path (and DMUS_OBJ_NAME | DMUS_OBJ_FILENAME in the dwValidData member) would replace the name, supply a file name, and leave the GUID as it is.

If the object is unable to set one or more members, it sets the members that it does support, clears the flags in dwValidData that it does not support, and returns S_FALSE. An application-defined object should support at least DMUS_OBJ_NAME and DMUS_OBJ_OBJECT.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicObject8::ParseDescriptor, IDirectMusicObject8::GetDescriptor


IDirectMusicPatternTrack8

The IDirectMusicPatternTrack8 interface represents a track that contains a single pattern. A pattern track is similar to a sequence track, but because it contains music values rather than fixed notes, it responds to chord changes.

You can obtain this interface by passing IID_DirectMusicPatternTrack to the IDirectMusicTrack8::QueryInterface method of the track.

The IDirectMusicPatternTrack8 interface has the following methods:

Creating a segment | CreateSegment
Setting the pattern | SetPatternByName
Setting the variation | SetVariation

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.


IDirectMusicPatternTrack8::CreateSegment

Creates a segment containing the pattern track.

HRESULT CreateSegment(
  IDirectMusicStyle* pStyle,
  IDirectMusicSegment** ppSegment
);

Parameters

pStyle
Style to use in creating the segment.
ppSegment
Address of a variable that receives an IDirectMusicSegment interface pointer for the created segment. Use QueryInterface to obtain IDirectMusicSegment8.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

DMUS_E_NOT_INIT
E_OUTOFMEMORY

Remarks

A pattern track is usually obtained from a segment object loaded from a file or resource, in which case the application already has the IDirectMusicSegment interface. This method is used for creating a segment when the pattern track object has been created by using CoCreateInstance.

Requirements

Header: Declared in dmusici.h.


IDirectMusicPatternTrack8::SetPatternByName

Sets the pattern to be played by the track. The pattern comes from a style.

HRESULT SetPatternByName(
  IDirectMusicSegmentState* pSegState,
  WCHAR* wszName,
  IDirectMusicStyle* pStyle,
  DWORD dwPatternType,
  DWORD* pdwLength
);

Parameters

pSegState
Address of the IDirectMusicSegmentState8 interface of the segment state that is playing the track.
wszName
Name of the pattern to set. The name can be obtained by using IDirectMusicStyle8::EnumPattern.
pStyle
Address of the IDirectMusicStyle or IDirectMusicStyle8 interface of the style containing the pattern.
dwPatternType
One of the DMUS_STYLET_TYPES enumeration that specifies the type of pattern.
pdwLength
Address of a variable that receives the length of the pattern, in music time ticks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

DMUS_E_NOT_FOUND
DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusici.h.


IDirectMusicPatternTrack8::SetVariation

Sets the variations to be played by a part in the track.

HRESULT SetVariation(
  IDirectMusicSegmentState* pSegState,
  DWORD dwVariationFlags,
  DWORD dwPart
);

Parameters

pSegState
Address of the IDirectMusicSegmentState8 interface of the segment state that is playing the track.
dwVariationFlags
Bitmask where a bit is set for each variation that is to be played.
dwPart
Identifier for the part containing the variations. This is the number assigned to the part in the music-authoring application, and is equivalent to the PChannel.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_POINTER

Remarks

Variations can be set for only one part at a time. Each time this method is called, it overrides previous calls.

The following example code plays variations 16 and 32 on performance channel 1.

// pPattern is an IDirectMusicPatternTrack8 pointer.
// pSegmentState is an IDirectMusicSegmentState8 pointer.

#define VARIATION(v)  (1 << ((v) - 1))

HRESULT hr = pPattern->SetVariation(
    pSegmentState, VARIATION(32) | VARIATION(16), 1);

Requirements

Header: Declared in dmusici.h.


IDirectMusicPerformance8

The IDirectMusicPerformance8 interface is the overall manager of music playback. It is used for adding and removing ports, mapping performance channels to ports, playing segments, dispatching messages and routing them through tools, requesting and receiving event notification, and setting and retrieving music parameters. It also has several methods for getting information about timing and for converting time and music values from one system to another.

If an application needs two complete sets of music playing at the same time, it can do so by creating more than one performance. Separate performances obey separate tempo maps, and so play completely asynchronously, whereas all segments within one performance play in lock step.

IDirectMusicPerformance8 supersedes the IDirectMusicPerformance interface and adds new methods.

The methods of IDirectMusicPerformance8 can be organized into the following groups:

Audiopath | CreateAudioPath
 | CreateStandardAudioPath
 | GetDefaultAudioPath
 | SetDefaultAudioPath
Channels | AssignPChannel
 | AssignPChannelBlock
 | PChannelInfo
Instruments | DownloadInstrument
Messages | AllocPMsg
 | ClonePMsg
 | FreePMsg
 | SendPMsg
MIDI conversion | MIDIToMusic
 | MusicToMIDI
Notification | AddNotificationType
 | GetNotificationPMsg
 | RemoveNotificationType
 | SetNotificationHandle
Parameters | GetGlobalParam
 | GetParam
 | GetParamEx
 | SetGlobalParam
 | SetParam
Playback | GetSegmentState
 | IsPlaying
 | PlaySegment
 | PlaySegmentEx
 | Stop
 | StopEx
Ports | AddPort
 | RemovePort
Timing | AdjustTime
 | GetBumperLength
 | GetLatencyTime
 | GetPrepareTime
 | GetQueueTime
 | GetResolvedTime
 | GetTime
 | MusicToReferenceTime
 | ReferenceToMusicTime
 | RhythmToTime
 | SetBumperLength
 | SetPrepareTime
 | TimeToRhythm
Tools | GetGraph
 | SetGraph
Miscellaneous | CloseDown
 | Init
 | InitAudio
 | Invalidate

All COM interfaces inherit the IUnknown interface methods. This interface supports the following methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.


IDirectMusicPerformance8::AddNotificationType

Adds a notification type to the performance. All segments and tracks are automatically updated with the new notification by calling their AddNotificationType methods.

HRESULT AddNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to add. For the defined types, see DMUS_NOTIFICATION_PMSG. Applications can also define their own types for custom tracks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::RemoveNotificationType, IDirectMusicSegment8::AddNotificationType, IDirectMusicTrack8::AddNotificationType, Notification and Event Handling


IDirectMusicPerformance8::AddPort

Assigns a port to the performance. This method is valid only for performances that do not use audiopaths; that is, performances initialized by using IDirectMusicPerformance8::Init.

HRESULT AddPort(
  IDirectMusicPort* pPort
);

Parameters

pPort
Address of a variable that contains the port to add. If NULL, the default port is added. See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
DMUS_E_CANNOT_OPEN_PORT
E_OUTOFMEMORY
E_POINTER

Remarks

When the default port is specified by passing NULL in pPort, it is assigned one channel group. If no performance channels have been set up for any other port, channels 0 through 15 are assigned to MIDI channels 0 through 15.

If pPort is not NULL, it must be a port created by the same DirectMusic object that was passed to, or created by, IDirectMusicPerformance8::Init. The port must be activated by a call to IDirectMusicPort8::Activate, and a block of channels must be assigned by a call to IDirectMusicPerformance8::AssignPChannelBlock.

This method creates a reference to IDirectMusicPort8 that is released by IDirectMusicPerformance8::RemovePort or IDirectMusicPerformance8::CloseDown. However, if NULL is passed to AddPort, the port cannot be removed by RemovePort, because the application has no reference to pass to RemovePort.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::RemovePort, Default Port


IDirectMusicPerformance8::AdjustTime

Adjusts the internal performance time forward or backward. This is mostly used to compensate for drift when synchronizing to another source.

HRESULT AdjustTime(
  REFERENCE_TIME rtAmount
);

Parameters

rtAmount
Amount of time to add or subtract. This can be a number from –10,000,000 through 10,000,000 (–1 second through +1 second).

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_INVALIDARG.

Remarks

The adjusted time is used internally by DirectMusic. It is not reflected in the time retrieved by the IDirectMusicPerformance8::GetTime method.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetTime, Timing


IDirectMusicPerformance8::AllocPMsg

Allocates a performance message.

HRESULT AllocPMsg(
  ULONG cb,
  DMUS_PMSG** ppPMSG
);

Parameters

cb
Size of the message structure. This structure is of a type derived from DMUS_PMSG.
ppPMSG
Address of a variable that receives the pointer to the allocated message structure.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

The dwSize member of the message structure is set to the value of cb. Other members are not necessarily initialized to zero, because of internal caching.

After the message is sent by IDirectMusicPerformance8::SendPMsg, the application no longer owns the memory and is not responsible for freeing the message. However, a tool can free a message within its IDirectMusicTool8::Flush or its IDirectMusicTool8::ProcessPMsg method. Applications are also responsible for freeing notification messages.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::FreePMsg, IDirectMusicPerformance8::SendPMsg, DirectMusic Messages


IDirectMusicPerformance8::AssignPChannel

Assigns a single performance channel to the performance and maps it to a port, group, and MIDI channel.

This method is not used by applications that route their data through audiopaths.

HRESULT AssignPChannel(
  DWORD dwPChannel,
  IDirectMusicPort* pPort,
  DWORD dwGroup,
  DWORD dwMChannel
);

Parameters

dwPChannel
Performance channel to assign.
pPort
Address of a variable that contains the port to which the channel is assigned.
dwGroup
Channel group on the port.
dwMChannel
Channel in the group. Must be in the range from 0 through 15.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE (see Remarks).

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

The method returns S_FALSE if dwGroup is out of the range of the port. The channel has been assigned, but the port cannot play this group.

The method returns E_INVALIDARG if dwMChannel is out of range or the port has not been added to the performance through a call to the IDirectMusicPerformance8::AddPort method.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::AssignPChannelBlock, IDirectMusicPerformance8::PChannelInfo, Channels


IDirectMusicPerformance8::AssignPChannelBlock

Assigns a block of 16 performance channels to the performance and maps them to a port and a channel group. This method is valid only for performances that do not use audiopaths; that is, performances initialized by using IDirectMusicPerformance8::Init.

HRESULT AssignPChannelBlock(
  DWORD dwBlockNum,
  IDirectMusicPort* pPort,
  DWORD dwGroup
);

Parameters

dwBlockNum
Block number, in which 0 represents channels 0 through 15, 1 represents channels 16 through 31, and so on.
pPort
Address of a variable that contains the port to which the channels are assigned.
dwGroup
Channel group on the port. Must be 1 or greater.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE (see Remarks).

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

This method must be called when a port has been added to a performance, except when the default port has been added by passing NULL to IDirectMusicPerformance8::AddPort.

The method returns S_FALSE if dwGroup is out of the range of the port. The channels have been assigned, but the port cannot play this group.

The method returns E_INVALIDARG if the port has not been added to the performance through a call to the IDirectMusicPerformance8::AddPort method.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::AssignPChannel, IDirectMusicPerformance8::PChannelInfo, Channels


IDirectMusicPerformance8::ClonePMsg

Makes a copy of a performance message.

HRESULT ClonePMsg(
  DMUS_PMSG* pSourcePMSG,
  DMUS_PMSG** ppCopyPMSG
);

Parameters

pSourcePMSG
Message to copy.
ppCopyPMSG
Address of a variable that receives a pointer to the copied message.

Return Values

If it succeeds, the method returns S_OK.

If it fails, the method can return one of the following error values.

E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmusici.h.


IDirectMusicPerformance8::CloseDown

Closes down the performance object. An application that created the performance object and called IDirectMusicPerformance8::Init or IDirectMusicPerformance8::InitAudio on it must call CloseDown before the performance is released.

HRESULT CloseDown();

Parameters

None.

Return Values

The method returns S_OK.

Remarks

Failure to call CloseDown can cause memory leaks or program failures.

CloseDown handles the release of the IDirectMusic8 interface if this reference was created by IDirectMusicPerformance8::Init or IDirectMusicPerformance8::InitAudio. If the application explicitly created the DirectMusic object, the application is responsible for releasing the reference.

If the DirectSound object was created in the call to Init or InitAudio but no reference was returned to the application, CloseDown also releases DirectSound and all DirectSound buffers. If your application has obtained any interfaces to DirectSound buffers, it should release them before calling Closedown.

If the application created DirectSound explicitly, or obtained a reference form Init or InitAudio, it is responsible for releasing DirectSound.

The method releases any downloaded instruments that have not been unloaded.

Requirements

Header: Declared in dmusici.h.


IDirectMusicPerformance8::CreateAudioPath

Creates an audiopath object that represents the stages in data flow from the performance to DirectSound buffers.

HRESULT CreateAudioPath(
  IUnknown *pSourceConfig,
  BOOL fActivate,
  IDirectMusicAudioPath **ppNewPath
);

Parameters

pSourceConfig
Address of an interface that represents the audiopath configuration. See Remarks.
fActivate
Boolean value that specifies whether to activate the path on creation.
ppNewPath
Address of a variable that receives an IDirectMusicAudioPath8 interface pointer for the audiopath.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

E_NOINTERFACE
E_POINTER
DMUS_E_NOT_INIT
DMUS_E_AUDIOPATHS_NOT_VALID
DSERR_BUFFERLOST
E_OUTOFMEMORY

Remarks

The object addressed by pSourceConfig can be obtained from a segment by using the IDirectMusicSegment8::GetAudioPathConfig method or can be loaded directly from a file.

The method fails with DSERR_BUFFERLOST if any application has initialized DirectSound with the write-primary cooperative level.

If the audiopath configuration specifies a sound device that is not available, the method returns E_NOINTERFACE.

Requirements

Header: Declared in dmusici.h.

See Also

Creating Audiopaths


IDirectMusicPerformance8::CreateStandardAudioPath

Creates an object that represents the stages in data flow from the performance to DirectSound buffers. This method can be used instead of IDirectMusicPerformance8::CreateAudioPath to create a basic predefined audiopath rather than one defined in a source file.

HRESULT  CreateStandardAudioPath(
  DWORD dwType,
  DWORD dwPChannelCount,
  BOOL  fActivate,
  IDirectMusicAudioPath **ppNewPath
);

Parameters

dwType
Type of the path. The following values are defined.
DMUS_APATH_DYNAMIC_3D
One bus to a 3-D buffer. Does not send to environmental reverb.
DMUS_APATH_DYNAMIC_MONO
One bus to a mono buffer.
DMUS_APATH_SHARED_STEREOPLUSREVERB
Ordinary music setup with stereo outs and reverb.
DMUS_APATH_DYNAMIC_STEREO
Two buses to a stereo buffer.

For more information on these audiopath types, see Standard Audiopaths.

dwPChannelCount
Number of performance channels in the path.
fActivate
Boolean value that specifies whether to activate the path on creation.
ppNewPath
Address of a variable that receives an IDirectMusicAudioPath interface pointer for the audiopath. See IDirectMusicAudioPath8.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_NOT_INIT
DMUS_E_AUDIOPATHS_NOT_VALID
DSERR_BUFFERLOST
E_INVALIDARG
E_OUTOFMEMORY

Remarks

The method fails with DSERR_BUFFERLOST if any application has initialized DirectSound with the write-primary cooperative level.

Requirements

Header: Declared in dmusici.h.


IDirectMusicPerformance8::DownloadInstrument

Downloads DLS data for an instrument to a port.

HRESULT DownloadInstrument(
  IDirectMusicInstrument* pInst,
  DWORD dwPChannel,
  IDirectMusicDownloadedInstrument** ppDownInst,
  DMUS_NOTERANGE* pNoteRanges,
  DWORD dwNumNoteRanges,
  IDirectMusicPort** ppPort,
  DWORD* pdwGroup,
  DWORD* pdwMChannel
);

Parameters

pInst
Pointer to the IDirectMusicInstrument8 interface of the instrument to download.
dwPChannel
Performance channel to which the instrument is assigned.
ppDownInst
Address of a variable that receives an IDirectMusicDownloadedInstrument8 pointer to the downloaded instrument.
pNoteRanges
Address of an array of DMUS_NOTERANGE structures. Each entry in the array specifies a contiguous range of MIDI note messages to which the instrument must respond. An instrument region is downloaded only if at least one note in that region is specified in the DMUS_NOTERANGE structures.
dwNumNoteRanges
Number of DMUS_NOTERANGE structures in the array pointed to by pNoteRanges. If this value is set to 0, the pNoteRanges parameter is ignored, and all regions and wave data for the instrument are downloaded.
ppPort
Address of a variable that receives a pointer to the port to which the instrument was downloaded.
pdwGroup
Address of a variable that receives the group to which the instrument is assigned.
pdwMChannel
Address of a variable that receives the MIDI channel to which the instrument is assigned.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

Most applications do not need to use this method because instrument downloading is normally handled by bands. See Downloading and Unloading Bands.

The method returns E_INVALIDARG if the performance channel is not assigned to a port.

To prevent loss of resources, unload the instrument by using the IDirectMusicPort8::UnloadInstrument method when the instrument is no longer needed.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPort8::DownloadInstrument, IDirectMusicPort8::UnloadInstrument, Working with Instruments


IDirectMusicPerformance8::FreePMsg

Frees a message.

HRESULT FreePMsg(
  DMUS_PMSG* pPMSG
);

Parameters

pPMSG
Address of a variable that contains a message to free. This message must have been allocated using the IDirectMusicPerformance8::AllocPMsg method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_CANNOT_FREE
E_POINTER

Remarks

Most messages are released automatically by the performance after they have been processed, and IDirectMusicPerformance8::FreePMsg must not be called on a message that has been sent by using IDirectMusicPerformance8::SendPMsg. However, IDirectMusicPerformance8::FreePMsg can be used within IDirectMusicTool8::ProcessPMsg or IDirectMusicTool8::Flush to free a message that is no longer needed. It must also be used to free notification messages.

The method returns DMUS_E_CANNOT_FREE in the following cases:

  • If pPMSG is not a message allocated by AllocPMsg.
  • If it is in the performance queue because IDirectMusicPerformance8::SendPMsg was called on it. However, applications cannot assume that FreePMsg will return DMUS_E_CANNOT_FREE for all sent messages, because SendPMsg is not synchronous.
  • If it has already been freed.

If there is a value in the pTool, pGraph, or punkUser members (see DMUS_PMSG), each referenced object is released.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::AllocPMsg, DirectMusic Messages


IDirectMusicPerformance8::GetBumperLength

Retrieves the amount of time between the time at which messages are placed in the port buffer and the time at which they begin to be processed by the port. For an overview of this topic, see Timing.

HRESULT GetBumperLength(
  DWORD* pdwMilliSeconds
);

Parameters

pdwMilliSeconds
Address of a variable that contains the amount of preplay time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The default value is 50 milliseconds.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SetBumperLength


IDirectMusicPerformance8::GetDefaultAudioPath

Retrieves the default audiopath set by IDirectMusicPerformance8::InitAudio or IDirectMusicPerformance8::SetDefaultAudioPath.

HRESULT GetDefaultAudioPath(
  IDirectMusicAudioPath **ppAudioPath
);

Parameters

ppAudioPath
Address of a variable that receives the IDirectMusicAudioPath8 interface pointer of the default audiopath.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_AUDIOPATHS_NOT_VALID
DMUS_E_NOT_INIT

Requirements

Header: Declared in dmusici.h.


IDirectMusicPerformance8::GetGlobalParam

Retrieves global values from the performance.

HRESULT GetGlobalParam(
  REFGUID rguidType,
  void* pParam,
  DWORD dwSize
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data.
pParam
Pointer to the allocated memory that receives a copy of the data. This must be the correct size, which is constant for each type of data. This parameter contains information that was passed in to the IDirectMusicPerformance8::SetGlobalParam method.
dwSize
Size of the data. This is constant for each rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

If SetGlobalParam has never been called for rguidType, the parameter might not be in the list of global data being handled by this performance, and the method might return E_INVALIDARG. In other words, do not assume that any parameter has a default value that can be retrieved by using GetGlobalParam.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SetGlobalParam, IDirectMusicPerformance8::GetParam, Performance Parameters


IDirectMusicPerformance8::GetGraph

Retrieves the toolgraph of a performance.

HRESULT GetGraph(
  IDirectMusicGraph** ppGraph
);

Parameters

ppGraph
Address of a variable that receives a pointer to the toolgraph.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_POINTER

Remarks

The reference count of the graph is incremented.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SetGraph, IDirectMusicSegment8::GetGraph, IDirectMusicPerformance8::SendPMsg


IDirectMusicPerformance8::GetLatencyTime

Retrieves the current latency time. Latency time is the time being heard from the speakers plus the time required to queue and render messages into the IDirectMusicPort8. For an overview of this topic, see Timing.

HRESULT GetLatencyTime(
  REFERENCE_TIME * prtTime
);

Parameters

prtTime
Address of a variable that receives the current latency time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_NO_MASTER_CLOCK

Requirements

Header: Declared in dmusici.h.


IDirectMusicPerformance8::GetNotificationPMsg

Retrieves a pending notification message.

HRESULT GetNotificationPMsg(
  DMUS_NOTIFICATION_PMSG** ppNotificationPMsg
);

Parameters

ppNotificationPMsg
Address of a variable that receives a pointer to a DMUS_NOTIFICATION_PMSG structure. The application retrieving this message is responsible for calling IDirectMusicPerformance8::FreePMsg on it.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if there are no more notification events to return.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

Notification and Event Handling


IDirectMusicPerformance8::GetParam

Retrieves data from a track inside the control segment.

HRESULT GetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Standard Track Parameters.
dwGroupBits
Group of the track from which to obtain the data (see Remarks). Set this value to 0xFFFFFFFF for all groups.
dwIndex
Index of the track in the group from which to obtain the data.
mtTime
Time from which to obtain the data, in performance time.
pmtNext
Address of a variable that receives the time (relative to mtTime) until which the data is valid. If this returns a value of 0, either the data is always valid, or it is not known when it might become invalid. If this information is not needed, pmtNext can be set to NULL. See Remarks.
pParam
Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_GET_UNSUPPORTED
DMUS_E_NO_MASTER_CLOCK
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

Normally, the primary segment is the control segment. However, a secondary segment can be designated as a control segment when it is played. For more information, see Control Segments.

The data returned in *pParam can become invalid before the time returned in *pmtNext if another control segment is cued.

Each track belongs to one or more groups, and each group is represented by a bit in dwGroupBits. For more information, see IDirectMusicSegment8::InsertTrack and Identifying the Track.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicTrack8::GetParamEx, IDirectMusicPerformance8::SetGlobalParam, IDirectMusicPerformance8::GetTime, IDirectMusicPerformance8::GetParamEx, Performance Parameters


IDirectMusicPerformance8::GetParamEx

Retrieves data from a track. This method is similar to IDirectMusicPerformance8::GetParam but adds support for self-controlling segments. It is used chiefly by tools.

HRESULT GetParamEx(
  REFGUID rguidType,
  DWORD dwTrackID,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Standard Track Parameters.
dwTrackID
Unique identifier of a track within the segment state from which the parameter is to be obtained. Every performance message that originates from a track carries an identifier of the track instance that generated the message. This identifier is kept in the dwVirtualTrackID member of the DMUS_PMSG part of the message structure. When this value is passed to GetParamEx, the method is able to determine whether the track is self-controlling, in which case it gets its data from another track in the same segment rather than in the control segment.
dwGroupBits
Group that the track is in (see Remarks). Set this value to 0xFFFFFFFF for all groups.
dwIndex
Index of the track in the group.
mtTime
Time from which to obtain the data, in performance time.
pmtNext
Address of a variable that receives the time (relative to mtTime) until which the data is valid. If this returns a value of 0, either the data is always valid, or it is not known when it might become invalid. If this information is not needed, pmtNext can be set to NULL. See Remarks.
pParam
Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_GET_UNSUPPORTED
DMUS_E_NO_MASTER_CLOCK
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

Each track belongs to one or more groups, and each group is represented by a bit in dwGroupBits. For more information, see IDirectMusicSegment8::InsertTrack and Identifying the Track.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicTrack8::GetParamEx, IDirectMusicPerformance8::SetGlobalParam, IDirectMusicPerformance8::GetTime, Performance Parameters


IDirectMusicPerformance8::GetPrepareTime

Retrieves the interval between the time when messages are sent by tracks and the time when the sound is heard. This interval allows sufficient time for the message to be processed by tools.

HRESULT GetPrepareTime(
  DWORD* pdwMilliSeconds
);

Parameters

pdwMilliSeconds
Address of a variable that receives the amount of prepare time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The default value is 1000 milliseconds.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SetPrepareTime, Prepare Time


IDirectMusicPerformance8::GetQueueTime

Retrieves the current flush time, which is the earliest time in the queue at which messages can be flushed. Messages that have time stamps earlier than this time have already been sent to the port and cannot be invalidated.

HRESULT GetQueueTime(
  REFERENCE_TIME * prtTime
);

Parameters

prtTime
Address of a variable that receives the current flush time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_NO_MASTER_CLOCK

Requirements

Header: Declared in dmusici.h.

See Also

Latency and Bumper Time


IDirectMusicPerformance8::GetResolvedTime

Resolves a given time to a given boundary.

HRESULT GetResolvedTime(
  REFERENCE_TIME rtTime,
  REFERENCE_TIME* prtResolved,
  DWORD dwTimeResolveFlags
);

Parameters

rtTime
Time to resolve. If this is less than the current time, the current time is used.
prtResolved
Address of a variable that receives the resolved time.
dwTimeResolveFlags
One or more DMUS_TIME_RESOLVE_FLAGS describing the resolution desired.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

Timing


IDirectMusicPerformance8::GetSegmentState

Retrieves the currently playing primary segment state or the primary segment state that is playing at a given time.

HRESULT GetSegmentState(
  IDirectMusicSegmentState ** ppSegmentState,
  MUSIC_TIME mtTime
);

Parameters

ppSegmentState
Address of a variable that receives a pointer to the segment state. The caller is responsible for calling Release on this pointer.
mtTime
Time for which the segment state is to be retrieved.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_POINTER

Remarks

To get the currently playing segment state, pass the time returned by the IDirectMusicPerformance8::GetTime method. Because of latency, the currently playing segment state is not necessarily the one being heard.

Requirements

Header: Declared in dmusici.h.


IDirectMusicPerformance8::GetTime

Retrieves the current time of the performance.

HRESULT GetTime(
  REFERENCE_TIME* prtNow,
  MUSIC_TIME* pmtNow
);

Parameters

prtNow
Address of a variable that receives the current time in REFERENCE_TIME format. Can be NULL.
pmtNow
Address of a variable that receives the current time in MUSIC_TIME format. Can be NULL.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NO_MASTER_CLOCK
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

Timing


IDirectMusicPerformance8::Init

Associates the performance with a DirectMusic object and a DirectSound object. If the application is not using audiopaths, this method must be called before the performance can play.

For applications that use audiopaths, this method has been superseded by IDirectMusicPerformance8::InitAudio.

HRESULT Init(
  IDirectMusic** ppDirectMusic,
  LPDIRECTSOUND pDirectSound,
  HWND hWnd
);

Parameters

ppDirectMusic
Address of a variable that specifies or receives an interface pointer to a DirectMusic object.

If the variable pointed to by ppDirectMusic contains a valid IDirectMusic or IDirectMusic8 interface pointer, the existing object is assigned to the performance. The reference count of the interface is incremented. Ports passed to the IDirectMusicPerformance8::AddPort method must be created from this DirectMusic object.

If the variable pointed to by ppDirectMusic contains NULL, a DirectMusic object is created and an IDirectMusic interface pointer is returned. Use QueryInterface to obtain IDirectMusic8.

If ppDirectMusic is NULL, a DirectMusic object is created and used internally by the performance.

See Remarks.

pDirectSound
IDirectSound8 interface pointer to use by default for wave output. If this value is NULL, DirectMusic creates a DirectSound object. There should, however, be only one DirectSound object per process. If your application uses DirectSound separately, it should pass in that interface here, or to IDirectMusic8::SetDirectSound if the application creates the DirectMusic object explicitly.
hWnd
Window handle to be used for the creation of DirectSound. This parameter can be NULL, in which case the foreground window is used. See Remarks.

This parameter is ignored if pDirectSound is not NULL, in which case the application is responsible for setting the window handle in a call to IDirectSound8::SetCooperativeLevel.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_ALREADY_INITED
E_OUTOFMEMORY
E_POINTER

Remarks

This method can be called only once. It cannot be used to retrieve an existing IDirectMusic8 interface.

A DirectMusic object can be associated with the performance in any of the following ways:

  • The application creates its own DirectMusic object and gives it to the performance by passing the address of the IDirectMusic8 pointer in ppDirectMusic. In this case, the pDirectSound and hWnd parameters are ignored because the application is responsible for calling IDirectMusic8::SetDirectSound.
  • The application allows the performance to create the DirectMusic object and needs a pointer to that object. In this case, *ppDirectMusic is NULL on entry, and contains the IDirectMusic pointer on exit.
  • The application allows the performance to initialize itself and does not need a DirectMusic object pointer. In this case, ppDirectMusic is NULL.

The performance must be terminated by using the IDirectMusicPerformance8::CloseDown method before being released.

You can pass NULL in the hWnd parameter to pass the current foreground window handle to DirectSound. However, do not assume that the application window will be in the foreground during initialization. It is best to pass the top-level application window handle.

Requirements

Header: Declared in dmusici.h.

See Also

Migrating from Ports to Audiopaths


IDirectMusicPerformance8::InitAudio

Initializes the performance and optionally sets up a default audiopath. This method must be called before the performance can play using audiopaths.

This method should be used in most cases instead of IDirectMusicPerformance8::Init.

HRESULT InitAudio(
  IDirectMusic** ppDirectMusic,
  IDirectSound** ppDirectSound,
  HWND hWnd,
  DWORD dwDefaultPathType,
  DWORD dwPChannelCount,
  DWORD dwFlags,
  DMUS_AUDIOPARAMS *pParams
);

Parameters

ppDirectMusic
Address of a variable that specifies or receives an interface pointer to a DirectMusic object.

If the variable pointed to by ppDirectMusic contains a valid IDirectMusic or IDirectMusic8 interface pointer, the existing object is assigned to the performance. The reference count of the interface is incremented.

If the variable pointed to by ppDirectMusic contains NULL, a DirectMusic object is created and the IDirectMusic interface pointer is returned. Use QueryInterface to obtain IDirectMusic8.

If ppDirectMusic is NULL, a DirectMusic object is created and used internally by the performance.

See Remarks.

ppDirectSound
Address of a variable that specifies or receives an IDirectSound interface pointer for a DirectSound object to use by default for wave output. If this parameter contains a NULL pointer, DirectMusic creates a private DirectSound object. If the variable pointed to contains NULL, DirectMusic creates a DirectSound object and returns the interface pointer. See Remarks.
hWnd
Window handle to use for the creation of DirectSound. This parameter can be NULL, in which case the foreground window is used. See Remarks.

This parameter is ignored if an IDirectSound interface pointer is passed to the method in ppDirectSound. In that case the application is responsible for setting the window handle by using IDirectSound8::SetCooperativeLevel.

dwDefaultPathType
DWORD value that specifies the default audiopath type. Can be zero if no default path type is wanted. For a list of defined values, see IDirectMusicPerformance8::CreateStandardAudioPath.
dwPChannelCount
Value that specifies the number of performance channels to allocate to the path, if dwDefaultPathType is not zero.
dwFlags
Flags that specify requested features. If pParams is not NULL, this value is ignored and the requested features are specified in the dwFeatures member of the DMUS_AUDIOPARAMS structure. The following values are defined for use in this parameter:
DMUS_AUDIOF_3D
3-D buffers.
DMUS_AUDIOF_ALL
All features.
DMUS_AUDIOF_BUFFERS
Multiple buffers.
DMUS_AUDIOF_ENVIRON
Environmental modeling.
DMUS_AUDIOF_EAX
EAX effects.
DMUS_AUDIOF_STREAMING
Support for streaming waves.
pParams
Address of a DMUS_AUDIOPARAMS structure that specifies parameters for the synthesizer and receives information about what parameters were set. Can be NULL if the default parameters are wanted.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

DMUS_E_ALREADY_INITED
DSERR_BUFFERLOST
DSERR_PRIOLEVELNEEDED
DSERR_UNINITIALIZED
E_NOINTERFACE
E_OUTOFMEMORY
E_POINTER

Remarks

This method can be called only once. It cannot be used to retrieve an existing IDirectMusic8 interface.

A DirectMusic object can be associated with the performance in the following ways.

  • The application allows the performance to create the DirectMusic object and needs a pointer to that object. In this case, *ppDirectMusic is NULL on entry and contains the IDirectMusic pointer on exit.
  • The application allows the performance to initialize itself and does not need a DirectMusic object pointer. In this case, ppDirectMusic is NULL.
  • The application creates its own DirectMusic object and gives it to the performance by passing the address of the IDirectMusic8 pointer in ppDirectMusic. Most applications do not use this technique.

If you specify an interface pointer in ppDirectSound, it must be an interface to an object of class CLSID_DirectSound8. Objects of this class support both IDirectSound and IDirectSound8, but the IDirectSound interface must be passed. For information on how to create an object of this class, see the Remarks for IDirectSound8. The DirectSound object must be fully initialized before being passed to InitAudio. If the object was created by using CoCreateInstance, call IDirectSound8::Initialize. Set the cooperative level to DSSCL_PRIORITY by using IDirectSound8::SetCooperativeLevel.

You can pass NULL in the hWnd parameter to pass the current foreground window handle to DirectSound. However, do not assume that the application window will be in the foreground during initialization. It is best to pass the top-level application window handle.

The parameters set in dwFlags and pParams apply to the default audiopath and any audiopaths created subsequently.

The method fails with DSERR_BUFFERLOST if a value other than zero is passed in dwDefaultPathType and any application has initialized DirectSound with the write-primary cooperative level.

The performance must be terminated by using the IDirectMusicPerformance8::CloseDown method before being released.

Requirements

Header: Declared in dmusici.h.


IDirectMusicPerformance8::Invalidate

Flushes all queued messages from the supplied time forward and causes all tracks of all segments to resend their data from the given time forward.

HRESULT Invalidate(
  MUSIC_TIME mtTime,
  DWORD dwFlags
);

Parameters

mtTime
Time from which to invalidate, adjusted by dwFlags. Setting this value to 0 causes immediate invalidation.
dwFlags
Flags that adjust mtTime to align to measures, beats, or grids. This value can be 0 or one of the following members of the DMUS_SEGF_FLAGS enumeration:

DMUS_SEGF_MEASURE
DMUS_SEGF_BEAT
DMUS_SEGF_GRID

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_NO_MASTER_CLOCK.

Remarks

If mtTime is so long ago that it is impossible to invalidate that time, the earliest possible time is used.

Requirements

Header: Declared in dmusici.h.

See Also

Prepare Time, Segment Timing


IDirectMusicPerformance8::IsPlaying

Determines whether a particular segment or segment state is currently being heard from the speakers.

HRESULT IsPlaying(
  IDirectMusicSegment* pSegment,
  IDirectMusicSegmentState* pSegState
);

Parameters

pSegment
Segment to check. If NULL, check only pSegState.
pSegState
Segment state to check. If NULL, check only pSegment.

Return Values

If the method succeeds and the requested segment or segment state is playing, the return value is S_OK. If neither is playing or only one was requested and it is not playing, the return value is S_FALSE.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_NO_MASTER_CLOCK

Remarks

The method returns S_OK only if the segment or segment state is actually playing at the speakers. Because of latency, this method might return S_FALSE even though IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx has just been called on the segment. Similarly, the method returns S_OK as long as the segment is being heard, even though all messages might already have been dispatched.

Requirements

Header: Declared in dmusici.h.


IDirectMusicPerformance8::MIDIToMusic

Converts a MIDI note value to a DirectMusic music value, using a supplied chord, subchord level, and play mode.

HRESULT MIDIToMusic(
  BYTE bMIDIValue,
  DMUS_CHORD_KEY* pChord,
  BYTE bPlayMode,
  BYTE bChordLevel,
  WORD *pwMusicValue
);

Parameters

bMIDIValue
MIDI note value to convert, in the range from 0 through 127.
pChord
Address of a DMUS_CHORD_KEY structure containing information about the chord and key structure to be used in translating the note. This includes the underlying scale. For example, if the chord is a CM7, the note is interpreted against the chord positions for root note C, chord intervals of a major seventh. The structure carries up to DMUS_MAXSUBCHORD parallel subchords, with chord intervals, root, scale, and inversion flags for each. It also carries the overall key root.
bPlayMode
Play mode determining how the music value is derived from the chord. For a list of values, see DMUS_PLAYMODE_FLAGS.
bChordLevel
Subchord level, defining which subchords can be used. See DMUS_SUBCHORD.
pwMusicValue
Address of a variable that receives the music value. For information on this value, see DMUS_NOTE_PMSG.

Return Values

If the method succeeds, the return value is one of the following. See Remarks.

S_OK
DMUS_S_DOWN_OCTAVE
DMUS_S_UP_OCTAVE

If it fails, the method can return one of the following error values:

DMUS_E_CANNOT_CONVERT
E_INVALIDARG

Remarks

If the method fails, *pwMusicValue is not changed.

If the return value is DMUS_S_UP_OCTAVE or DMUS_DOWN_OCTAVE, the note conversion generated a note value that is less than 0 or greater than 127, so it has been bumped up or down one or more octaves to be in the proper MIDI range of from 0 through 127. This can occur when using play modes DMUS_PLAYMODE_FIXEDTOCHORD and DMUS_PLAYMODE_FIXEDTOKEY, both of which return MIDI values in *pwMusicValue.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::MusicToMIDI, Music Values and MIDI Notes


IDirectMusicPerformance8::MusicToMIDI

Converts a DirectMusic music value to a MIDI note value.

HRESULT MusicToMIDI(
  WORD wMusicValue,
  DMUS_CHORD_KEY* pChord,
  BYTE bPlayMode,
  BYTE bChordLevel,
  BYTE *pbMIDIValue
);

Parameters

wMusicValue
Music value to convert. For information on music values, see DMUS_NOTE_PMSG.
pChord
Address of a DMUS_CHORD_KEY structure containing information about the chord and key structure to be used in translating the note. This includes the underlying scale. For example, if the chord is a CM7, the note is interpreted against the chord positions for root note C, chord intervals of a major seventh. The structure carries up to DMUS_MAXSUBCHORD parallel subchords, with chord intervals, root, scale, and inversion flags for each. It also carries the overall key root.
bPlayMode
Play mode determining how the music value is related to the chord. For a list of values, see DMUS_PLAYMODE_FLAGS.
bChordLevel
Subchord level, defining which subchords can be used. See DMUS_SUBCHORD.
pbMIDIValue
Address of a variable that receives the MIDI value, in the range from 0 through 127.

Return Values

If the method succeeds, the return value is one of the following. See Remarks.

S_OK
DMUS_S_OVER_CHORD
DMUS_S_DOWN_OCTAVE
DMUS_S_UP_OCTAVE

If it fails, the method can return one of the following error values:

DMUS_E_CANNOT_CONVERT
E_INVALIDARG

Remarks

If the method fails or returns DMUS_S_OVER_CHORD, *pwMIDIValue is not changed.

The method returns DMUS_S_OVER_CHORD if no note has been calculated because the music value has the note at a position higher than the top note of the chord. This applies only to DMUS_PLAYMODE_NORMALCHORD play mode. The caller should not do anything with the note, which is not meant to be played against this chord.

If the return value is DMUS_S_UP_OCTAVE or DMUS_DOWN_OCTAVE, the note conversion generated a note value that is less than 0 or greater than 127, so it has been bumped up or down one or more octaves to be in the proper MIDI range of 0 through 127. This can occur when using any play mode except DMUS_PLAYMODE_FIXED.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::MIDIToMusic, Music Values and MIDI Notes


IDirectMusicPerformance8::MusicToReferenceTime

Converts a performance time in MUSIC_TIME format to performance time in REFERENCE_TIME format.

HRESULT MusicToReferenceTime(
  MUSIC_TIME mtTime,
  REFERENCE_TIME* prtTime
);

Parameters

mtTime
Time in MUSIC_TIME format to convert.
prtTime
Address of a variable that receives the converted time in REFERENCE_TIME format.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_NO_MASTER_CLOCK

Remarks

Because reference time has a greater precision than music time, a time that has been converted from reference time to music time, and then back again, probably does not have its original value.

This method converts a time offset from the start of the performance, not a duration. Because the ratio between music time and reference time units depends on the tempo, DirectMusic takes into account all tempo changes since the start of the performance when calculating prtTime. If a master tempo has been set for the performance, it is taken into account as well.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::ReferenceToMusicTime, Clock Time vs. Music Time


IDirectMusicPerformance8::PChannelInfo

Retrieves the port, group, and MIDI channel for a given performance channel.

HRESULT PChannelInfo(
  DWORD dwPChannel,
  IDirectMusicPort** ppPort,
  DWORD* pdwGroup,
  DWORD* pdwMChannel
);

Parameters

dwPChannel
Performance channel for which information is desired.
ppPort
Address of a variable that receives an IDirectMusicPort8 pointer. This value can be NULL if the pointer is not wanted. If a non-NULL pointer is returned, the reference count is incremented, and it is the responsibility of the application to call Release on the pointer. See also Remarks.
pdwGroup
Address of a variable that receives the group on the port. Can be NULL if this value is not wanted.
pdwMChannel
Address of a variable that receives the MIDI channel on the group. Can be NULL if this value is not wanted.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

A NULL pointer is returned in *ppPort if the port has been removed by a call to IDirectMusicPerformance8::RemovePort, but the method succeeds.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::AssignPChannel, IDirectMusicPerformance8::AssignPChannelBlock


IDirectMusicPerformance8::PlaySegment

Begins playback of a segment.

HRESULT PlaySegment(
  IDirectMusicSegment* pSegment,
  DWORD dwFlags,
  __int64 i64StartTime,
  IDirectMusicSegmentState** ppSegmentState
);

Parameters

pSegment
Segment to play.
dwFlags
Flags that modify the method's behavior. See DMUS_SEGF_FLAGS.
i64StartTime
Performance time at which to begin playing the segment, adjusted to any resolution boundary specified in dwFlags. The time is in music time unless the DMUS_SEGF_REFTIME flag is set. A value of 0 causes the segment to start playing as soon as possible.
ppSegmentState
Address of a variable that receives a pointer to the segment state for this instance of the playing segment. This field can be NULL. If it is non-NULL, the segment state pointer is returned, and the application must call Release on it.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_OUTOFMEMORY
E_POINTER
DMUS_E_NO_MASTER_CLOCK
DMUS_E_SEGMENT_INIT_FAILED
DMUS_E_TIME_PAST

Remarks

Segments should be greater than 250 milliseconds in length.

The boundary resolutions in dwFlags are relative to the primary segment.

If a primary segment is scheduled to play while another primary segment is playing, the first one stops unless you set the DMUS_SEGF_QUEUE flag for the second segment, in which case it plays as soon as the first one finishes.

For more information on the exact start time of segments, see Segment Timing. For information on how the start time of segments can be affected by tempo changes, see Clock Time vs. Music Time.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::PlaySegmentEx


IDirectMusicPerformance8::PlaySegmentEx

Begins playback of a segment. The method offers greater functionality than IDirectMusicPerformance8::PlaySegment.

HRESULT PlaySegmentEx(
  IUnknown* pSource,
  WCHAR *pwzSegmentName,
  IUnknown* pTransition,
  DWORD dwFlags,
  __int64 i64StartTime,
  IDirectMusicSegmentState** ppSegmentState,
  IUnknown* pFrom,
  IUnknown* pAudioPath
);

Parameters

pSource
Address of the IUnknown interface of the object to play.
pwzSegmentName
Not implemented in DirectX 8.0. Set to NULL.
pTransition
IUnknown interface pointer of a template segment to use in composing a transition to this segment. Can be NULL. See Remarks.
dwFlags
Flags that modify the method's behavior. See DMUS_SEGF_FLAGS.
i64StartTime
Performance time at which to begin playing the segment, adjusted to any resolution boundary specified in dwFlags. The time is in music time unless the DMUS_SEGF_REFTIME flag is set. A value of zero causes the segment to start playing as soon as possible.
ppSegmentState
Address of a variable that receives an IDirectMusicSegmentState interface pointer for this instance of the playing segment. Use QueryInterface to obtain IDirectMusicSegmentState8. The reference count of the interface is incremented. This parameter can be NULL if no segment state pointer is wanted.
pFrom
IUnknown interface pointer of a segment state or audiopath to stop when the new segment begins playing. If it is an audiopath, all segment states playing on that audiopath are stopped. This value can be NULL.
pAudioPath
IUnknown interface pointer of an object that represents the audiopath on which to play, or NULL to play on the default path.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

DMUS_E_AUDIOPATH_INACTIVE
DMUS_E_AUDIOPATH_NOPORT
DMUS_E_NO_MASTER_CLOCK
DMUS_E_SEGMENT_INIT_FAILED
DMUS_E_TIME_PAST
E_OUTOFMEMORY
E_POINTER

Remarks

Segments should be greater than 250 milliseconds in length.

The boundary resolutions in dwFlags are relative to the primary segment.

If a primary segment is scheduled to play while another primary segment is playing, the first one stops unless you set the DMUS_SEGF_QUEUE flag for the second segment, in which case it plays as soon as the first one finishes.

For more information on the exact start time of segments, see Segment Timing. For information on how the start time of segments can be affected by tempo changes, see Clock Time vs. Music Time.

If DMUS_SEGF_AUTOTRANSITION is specified in dwFlags and a segment is already playing at i64StartTime and is being interrupted, the method composes a transition between the two segments and plays it before playing pSource. The transition is based a template provided at pTransition.

The method can be used to play on a performance that does not use audiopaths; that is, one initialized by using IDirectMusicPerformance8::Init. In this case the pAudioPath parameter must be NULL.

Requirements

Header: Declared in dmusici.h.


IDirectMusicPerformance8::ReferenceToMusicTime

Converts a performance time in REFERENCE_TIME format to a performance time in MUSIC_TIME format.

HRESULT ReferenceToMusicTime(
  REFERENCE_TIME rtTime,
  MUSIC_TIME* pmtTime
);

Parameters

rtTime
Time in REFERENCE_TIME format.
pmtTime
Address of a variable that receives the converted time in MUSIC_TIME format.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

E_POINTER
DMUS_E_NO_MASTER_CLOCK

Remarks

Because music time is less precise than reference time, rounding occurs.

This method converts a time offset from the start of the performance, not a duration. Because the ratio between music time and reference time units depends on the tempo, DirectMusic takes into account all tempo changes since the start of the performance when calculating prtTime.If a master tempo has been set for the performance, it is taken into account as well.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::MusicToReferenceTime, Clock Time vs. Music Time


IDirectMusicPerformance8::RemoveNotificationType

Removes a previously added notification type from the performance. All segments and tracks are updated by a call to their RemoveNotificationType methods.

HRESULT RemoveNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to remove. (For the defined types, see DMUS_NOTIFICATION_PMSG.) If this value is GUID_NULL, all notifications are to be removed.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE (see Remarks).

If it fails, the method can return E_POINTER.

Remarks

S_FALSE is returned when rguidNotificationType is not an active notification.

If a notification was added to a segment that has stopped playing, the performance cannot remove the notification type from that segment because it no longer has a reference to the segment.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::AddNotificationType, IDirectMusicSegment8::RemoveNotificationType, IDirectMusicTrack8::RemoveNotificationType, Notification and Event Handling


IDirectMusicPerformance8::RemovePort

Removes a port from the performance. Any performance channels that map to this port are invalidated, and messages stamped with them do not play.

HRESULT RemovePort(
  IDirectMusicPort* pPort
);

Parameters

pPort
Port to remove.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_POINTER

Remarks

A port added by passing NULL to IDirectMusicPerformance8::AddPort cannot be removed by passing NULL to RemovePort.

This method should not be called by applications that use audiopaths.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::AddPort


IDirectMusicPerformance8::RhythmToTime

Converts rhythm time to music time.

HRESULT RhythmToTime(
  WORD wMeasure,
  BYTE bBeat,
  BYTE bGrid,
  short nOffset,
  DMUS_TIMESIGNATURE *pTimeSig,
  MUSIC_TIME *pmtTime
);

Parameters

wMeasure
Measure of the time to convert.
bBeat
Beat of the time to convert.
bGrid
Grid of the time to convert.
nOffset
Offset from the grid, in music-time ticks, of the time to convert.
pTimeSig
Address of a DMUS_TIMESIGNATURE structure containing information about the time signature.
pmtTime
Address of a variable that receives the music time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::TimeToRhythm


IDirectMusicPerformance8::SendPMsg

Sends a performance message. This method is called by tracks when they are played. It might also be called by a tool to inject new data into a performance.

HRESULT SendPMsg(
  DMUS_PMSG* pPMSG
);

Parameters

pPMSG
Message allocated by IDirectMusicPerformance8::AllocPMsg. This structure is of a type derived from DMUS_PMSG. See DirectMusic Messages.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_ALREADY_SENT
E_INVALIDARG
E_POINTER

Remarks

The dwFlags member (see DMUS_PMSG) must contain either DMUS_PMSGF_MUSICTIME or DMUS_PMSGF_REFTIME, depending on the time stamp in either rtTime or mtTime. The dwFlags member should also contain the appropriate delivery type—DMUS_PMSGF_TOOL_QUEUE, DMUS_PMSGF_TOOL_ATTIME, or DMUS_PMSGF_TOOL_IMMEDIATE—depending on the type of message. If none is selected, DMUS_PMSGF_TOOL_IMMEDIATE is used by default.

If the time of the message is set to 0 and the dwFlags member contains DMUS_PMSGF_REFTIME, it is assumed that this message is cued to go out immediately.

In most cases, the IDirectMusicGraph8::StampPMsg method should be called on the message before SendPMsg is called. However, when sending a message directly to the main output tool, this step can be skipped. If you want the message to pass only through the performance graph, obtain the IDirectMusicGraph8 interface by calling IDirectMusicPerformance8::QueryInterface. Otherwise, obtain it by calling IDirectMusicSegment8::QueryInterface. Do not attempt to obtain the interface by calling IDirectMusicPerformance8::GetGraph or IDirectMusicSegment8::GetGraph; these methods return a pointer to the graph object, rather than to the implementation of the IDirectMusicGraph8 interface on the performance or segment.

Normally, the performance frees the message after it has been processed. For more information, see the Remarks for IDirectMusicPerformance8::FreePMsg.

The follow code example shows how to allocate and send a system exclusive message and a tempo message.

// Assume that pPerformance is a valid IDirectMusicPerformance8
// pointer and that mtTime is an initialized MUSIC_TIME
// variable.

IDirectMusicGraph* pGraph;

// Get the graph pointer from the performance. If you wanted the
// message to go through a segment graph, you would
// QueryInterface a segment object instead.

if ( SUCCEEDED( pPerformance->QueryInterface(
        IID_IDirectMusicGraph, (void**)&pGraph )))
{
    // Allocate a DMUS_SYSEX_PMSG of the appropriate size,
    // and read the system exclusive data into it.

    DMUS_SYSEX_PMSG* pSysEx;

    if ( SUCCEEDED( pPerformance->AllocPMsg(
            sizeof(DMUS_SYSEX_PMSG) + m_dwSysExLength,
            (DMUS_PMSG**)&pSysEx )))
    {
        ZeroMemory(pSysEx, sizeof(DMUS_NOTE_PMSG));
        pSysEx->dwSize = sizeof(DMUS_SYSEX_PMSG);
        pSysEx->dwLen = dwSysExLength;
        pSysEx->mtTime = mtTime;
        pSysEx->dwFlags = DMUS_PMSGF_MUSICTIME;
        pSysEx->dwType = DMUS_PMSGT_SYSEX;

        // Assume that m_pbSysExData is a pointer to an array
        // containing data of length m_dwSysExLength.

        memcpy( pSysEx->abData, m_pbSysExData, m_dwSysExLength );

        pGraph->StampPMsg( (DMUS_PMSG*)pSysEx );
        if (FAILED(pPerformance->SendPMsg( (DMUS_PMSG*)pSysEx )))
        {
            pPerformance->FreePMsg( (DMUS_PMSG*)pSysEx );
        }
    }

    // Change the tempo at time mtTime to 120 bpm.

    DMUS_TEMPO_PMSG* pTempo;

    if( SUCCEEDED( pPerformance->AllocPMsg(
            sizeof(DMUS_TEMPO_PMSG),
            (DMUS_PMSG**)&pTempo )))
    {
        pTempo->dwSize = sizeof(DMUS_TEMPO_PMSG);
        pTempo->dblTempo = 120;
        pTempo->mtTime = mtTime;
        pTempo->dwFlags = DMUS_PMSGF_MUSICTIME;
        pTempo->dwType = DMUS_PMSGT_TEMPO;
        pGraph->StampPMsg( (DMUS_PMSG*)pTempo );
        if (FAILED(pPerformance->SendPMsg( (DMUS_PMSG*)pTempo )))
        {
            pPerformance->FreePMsg( (DMUS_PMSG*)pTempo );
        }
    }

    pGraph->Release();
}

The next code example shows a function that sends a note message associated with the track identified by dwTrackID. The virtual track ID should be 0 if the message is not being generated from a DirectMusicTrack object.

HRESULT CreateNotePMsg(IDirectMusicPerformance8* pPerformance,
        MUSIC_TIME mtTime, DWORD dwTrackID)
{

    // Allocate a Note PMessage.
    DMUS_NOTE_PMSG* pNote = NULL;
    HRESULT hr = pPerformance->AllocPMsg( sizeof(DMUS_NOTE_PMSG),
            (DMUS_PMSG**) &pNote);
    if (FAILED(hr)) return hr;

    pNote->dwSize = sizeof(DMUS_NOTE_PMSG); // Size of a Note Pmessage.
    pNote->rtTime = 0;                      // Ignored.
    pNote->mtTime = mtTime;                 // When to play the note.
    pNote->dwFlags = DMUS_PMSGF_MUSICTIME;  // Use the mtTime field.
    pNote->dwPChannel = 5;                  // Play on PChannel 5.
    pNote->dwVirtualTrackID = dwTrackID;    // Track ID from parameter.

    // The following two fields should be set to NULL when a
    // message is initially sent. They will be updated in
    // IDirectMusicGraph::StampPMsg.
    pNote->pTool = NULL;
    pNote->pGraph = NULL;
    pNote->dwType = DMUS_PMSGT_NOTE;
    pNote->dwVoiceID = 0;           // Always 0
    pNote->dwGroupID = 0xFFFFFFFF;  // All track groups
    pNote->punkUser = NULL;         // Always NULL

    // Get the current time signature from the performance
    // to compute measure and beat information.
    DMUS_TIMESIGNATURE TimeSig;
    MUSIC_TIME mtNext;
    hr = pPerformance->GetParam(GUID_TimeSignature, 0xFFFFFFFF,
            0, mtTime, &mtNext, &TimeSig);
    if (FAILED(hr)) return hr;

    // Recompute TimeSig.mtTime to have the value expected
    // by pPerformance->TimeToRhythm.
    TimeSig.mtTime += mtTime;

    // Get the current chord from the performance
    // to create a note value.
    DMUS_CHORD_KEY Chord;
    hr = pPerformance->GetParam(GUID_ChordParam, 0xFFFFFFFF, 0,
            mtTime, &mtNext, &Chord);
    if (FAILED(hr)) return hr;

    // Create a note with octave 5, chord tone 2 (fifth), scale
    // offset 1 (=> sixth), and no accidentals.
    WORD wMusicValue = 0x5210;

    // Use DMUS_PLAYMODE_PEDALPOINT as your play mode
    // in pPerformance->MusicToMIDI.
    BYTE bPlayModeFlags = DMUS_PLAYMODE_PEDALPOINT;

    // Fill in the fields specific to DMUS_NOTE_PMSG.
    pNote->wMusicValue = wMusicValue;
    hr = pPerformance->MusicToMIDI(
        wMusicValue,
        &Chord,
        bPlayModeFlags,
        0,
        &(pNote->bMidiValue));
    if (FAILED(hr)) return hr;

    hr = pPerformance->TimeToRhythm(
        TimeSig.mtTime,
        &TimeSig,
        &(pNote->wMeasure),
        &(pNote->bBeat),
        &(pNote->bGrid),
        &(pNote->nOffset));
    if (FAILED(hr)) return hr;

    pNote->mtDuration = DMUS_PPQ;       // Quarter note duration.
    pNote->bVelocity = 120;             // MIDI velocity (0 to 127).
    pNote->bFlags = DMUS_NOTEF_NOTEON;  // Always set to this value.
    pNote->bTimeRange = 250;            // Randomize start time a lot.
    pNote->bDurRange = 5;               // Randomize duration a little.
    pNote->bVelRange = 0;               // Don't randomize velocity.
    pNote->bPlayModeFlags = bPlayModeFlags;
    pNote->bSubChordLevel = 0;          // Note uses subchord level 0.
    pNote->cTranspose = 0;              // No transposition.

    // Stamp the message with the performance graph.
    IDirectMusicGraph* pGraph;
    hr = pPerformance->QueryInterface( IID_IDirectMusicGraph,
            (void**)&pGraph );
    if (FAILED(hr)) return hr;

    pGraph->StampPMsg( (DMUS_PMSG*)pNote );
    pGraph->Release();

    // Finally, send the message.
    hr = pPerformance->SendPMsg( (DMUS_PMSG*)pNote);
    if (FAILED(hr))
    {
        pPerformance->FreePMsg( (DMUS_PMSG*)pNote);
        return hr;
    }
    return S_OK;
}

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicTool8::ProcessPMsg, Messages, DirectMusic Messages, DirectMusic Tools


IDirectMusicPerformance8::SetBumperLength

Sets the amount of time to buffer ahead of the port's latency for messages to be sent to the port for rendering. For an overview of this topic, see Timing.

HRESULT SetBumperLength(
  DWORD dwMilliSeconds
);

Parameters

dwMilliSeconds
Amount of preplay time, in milliseconds. The default value is 50.

Return Values

The method returns S_OK.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetBumperLength, IDirectMusicPerformance8::SetPrepareTime


IDirectMusicPerformance8::SetDefaultAudioPath

Sets and activates the default audiopath for the performance.

HRESULT SetDefaultAudioPath(
  IDirectMusicAudioPath *pAudioPath
);

Parameters

pAudioPath
Pointer to the IDirectMusicAudioPath8 interface of the default audiopath, or NULL to remove the current default audiopath.

Return Values

If it succeeds, the method returns S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_AUDIOPATH_NOPORT
DMUS_E_AUDIOPATHS_NOT_VALID
DMUS_E_NOT_INIT
E_INVALIDARG
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetDefaultAudioPath, IDirectMusicPerformance8::InitAudio.


IDirectMusicPerformance8::SetGlobalParam

Sets global values for the performance.

HRESULT SetGlobalParam(
  REFGUID rguidType,
  void* pParam,
  DWORD dwSize
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data.
pParam
Address of data to be copied and stored by the performance.
dwSize
Size of the data. This is constant for each rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_POINTER
E_OUTOFMEMORY

Remarks

The dwSize parameter is needed because the performance does not know about all types of data. New types can be created as needed.

For the parameters defined by DirectMusic and their associated data types, see Setting and Retrieving Global Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetGlobalParam, IDirectMusicPerformance8::SetParam, Performance Parameters


IDirectMusicPerformance8::SetGraph

Replaces the performance's toolgraph.

HRESULT SetGraph(
  IDirectMusicGraph* pGraph
);

Parameters

pGraph
Toolgraph to set. Can be set to NULL to clear the graph from the performance.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

Any messages flowing through tools in the current toolgraph are deleted.

Because the graph's reference count is incremented by this method, it is safe to release the original reference.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::SetGraph, IDirectMusicPerformance8::GetGraph, IDirectMusicPerformance8::SendPMsg


IDirectMusicPerformance8::SetNotificationHandle

Sets the event handle (created by the Microsoft® Win32® CreateEvent function) for notifications. The application should use the Win32 WaitForSingleObject function on this handle. When signaled, the application should call the IDirectMusicPerformance8::GetNotificationPMsg method to retrieve the notification event.

HRESULT SetNotificationHandle(
  HANDLE hNotification,
  REFERENCE_TIME rtMinimum
);

Parameters

hNotification
Event handle created by CreateEvent, or 0 to clear out an existing handle.
rtMinimum
Minimum time that the performance should hold onto old notify events before discarding them. The value 0 means to use the default minimum time of 20,000,000 reference time units, which is 2 seconds, or the previous value if this method has been called previously. If the application has not called GetNotificationPMsg by this time, the event is discarded to free the memory.

Return Values

The method returns S_OK.

Remarks

It is the application's responsibility to call the Win32 CloseHandle function on the notification handle when it is no longer needed.

Requirements

Header: Declared in dmusici.h.

See Also

Notification and Event Handling


IDirectMusicPerformance8::SetParam

Sets data on a track inside the control segment.

HRESULT SetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to set. See Standard Track Parameters.
dwGroupBits
Group that the desired track is in.
dwIndex
Index of the track in the group identified by dwGroupBits in which data is to be set, or DMUS_SEG_ALLTRACKS to set the parameter on all tracks in the group that contain the parameter.
mtTime
Time at which to set the data. Unlike IDirectMusicSegment8::SetParam, this time is in performance time. The start time of the segment is subtracted from this time, and the result is passed to IDirectMusicSegment8::SetParam.
pParam
Address of a structure containing the data. This structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NO_MASTER_CLOCK
DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

Normally the primary segment is the control segment. However, a secondary segment can be designated as the control segment when it is played. See DMUS_SEGF_FLAGS.

For an explanation of dwGroupBits and dwIndex, see Identifying the Track.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicPerformance8::SetGlobalParam, IDirectMusicSegment8::SetParam, IDirectMusicTrack8::SetParamEx, IDirectMusicPerformance8::GetTime, Performance Parameters


IDirectMusicPerformance8::SetPrepareTime

Sets the interval between the time when messages are sent by tracks and the time when the sound is heard. This interval allows sufficient time for the message to be processed by tools.

HRESULT SetPrepareTime(
  DWORD dwMilliSeconds
);

Parameters

dwMilliSeconds
Amount of prepare time, in milliseconds. The default value is 1000.

Return Values

The method returns S_OK.

Remarks

For an overview, see Timing.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetPrepareTime, IDirectMusicPerformance8::SetBumperLength, Prepare Time, Latency and Bumper Time


IDirectMusicPerformance8::Stop

Stops playback of a segment or segment state.

This method has been superseded by IDirectMusicPerformance8::StopEx, which can stop playback of a segment, segment state, or audiopath.

HRESULT Stop(
  IDirectMusicSegment* pSegment,
  IDirectMusicSegmentState* pSegmentState,
  MUSIC_TIME mtTime,
  DWORD dwFlags
);

Parameters

pSegment
Segment to stop playing. All segment states based on this segment are stopped at mtTime. See Remarks.
pSegmentState
Segment state to stop playing. See Remarks.
mtTime
Time at which to stop the segment, segment state, or both. If the time is in the past or if 0 is passed in this parameter, the specified segment and segment states stop playing immediately.
dwFlags
Flag that indicates when the stop should occur. Boundaries are in relation to the current primary segment. For a list of values, see IDirectMusicPerformance8::StopEx.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

If pSegment and pSegmentState are both NULL, all music stops, and all currently cued segments are released. If either pSegment or pSegmentState is not NULL, only the requested segment states are removed from the performance. If both are non-NULL and DMUS_SEGF_DEFAULT is used, the default resolution from the pSegment is used.

If you set all parameters to NULL or 0, everything stops immediately, and controller reset messages and note-off messages are sent to all mapped performance channels.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::PlaySegment, IDirectMusicPerformance8::PlaySegmentEx, IDirectMusicPerformance8::StopEx, DMUS_SEGF_FLAGS


IDirectMusicPerformance8::StopEx

Stops playback of an object.

HRESULT StopEx(
  IUnknown *pObjectToStop,
  __int64 i64StopTime,
  DWORD dwFlags
);

Parameters

pObjectToStop
Pointer to the IUnknown interface of the segment, segment state, or audiopath to stop.
i64StopTime
Time at which to stop. If the time is in the past or if 0 is passed in this parameter, the object stops playing immediately.
dwFlags
Flags that indicate when the stop should occur. Boundaries are in relation to the current primary segment. Can be one of the following values, or DMUS_SEGF_REFTIME combined with one other.
0
Stop immediately.
DMUS_SEGF_AUTOTRANSITION
Compose and play a transition to silence. Valid only when stopping a song. Not implemented in DirectX 8.0.
DMUS_SEGF_BEAT
Stop on the next beat boundary at or after i64StopTime.
DMUS_SEGF_DEFAULT
Stop on the default boundary, as set by the IDirectMusicSegment8::SetDefaultResolution method.
DMUS_SEGF_GRID
Stop on the next grid boundary at or after i64StopTime.
DMUS_SEGF_MEASURE
Stop on the next measure boundary at or after i64StopTime.
DMUS_SEGF_REFTIME
The value in i64StopTime is in reference time.
DMUS_SEGF_SEGMENTEND
Stop at the end of the primary segment.
DMUS_SEGF_MARKER
Stop at the next marker.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

Stopping a segment stops all instances that are playing.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::Stop, IDirectMusicPerformance8::PlaySegmentEx, DMUS_SEGF_FLAGS


IDirectMusicPerformance8::TimeToRhythm

Converts music time to rhythm time.

HRESULT TimeToRhythm(
  MUSIC_TIME mtTime,
  DMUS_TIMESIGNATURE *pTimeSig,
  WORD *pwMeasure,
  BYTE *pbBeat,
  BYTE *pbGrid,
  short *pnOffset
);

Parameters

mtTime
Time to convert.
pTimeSig
Address of a DMUS_TIMESIGNATURE structure that contains information about the time signature.
pwMeasure
Address of a variable that receives the measure in which the time falls.
pbBeat
Address of a variable that receives the beat at which the time falls.
pbGrid
Address of a variable that receives the grid at which the time falls.
pnOffset
Address of a variable that receives the offset from the grid (in music-time ticks) at which the time falls.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::RhythmToTime


IDirectMusicPort8

The IDirectMusicPort8 interface provides access to a DirectMusicPort object, which represents a device that sends or receives music data. The input port of an MPU-401, the output port of an MPU-401, the Microsoft software synthesizer, and an IHV-provided filter are all ports. A physical device such as an MPU-401 might provide multiple ports. A single port, however, cannot both capture and render data.

IDirectMusicPort8 is a define for IDirectMusicPort. The two interface names are interchangeable.

The interface is typically obtained by using the IDirectMusic8::CreatePort method.

For an overview, see Using DirectMusic Ports.

The methods of the IDirectMusicPort8 interface can be organized into the following groups.

Buffers | PlayBuffer
 | Read
 | SetReadNotificationHandle
Channels | GetChannelPriority
 | GetNumChannelGroups
 | SetChannelPriority
 | SetNumChannelGroups
Device management | Activate
 | DeviceIoControl
 | SetDirectSound
DLS data | Compact
 | DownloadInstrument
 | UnloadInstrument
Information | GetCaps
 | GetFormat
 | GetLatencyClock
 | GetRunningStats

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTMUSICPORT8 type is defined as a pointer to the IDirectMusicPort8 interface.

typedef IDirectMusicPort8 *LPDIRECTMUSICPORT8;

Requirements

Header: Declared in dmusicc.h.


IDirectMusicPort8::Activate

Activates or deactivates the port.

HRESULT Activate(
  BOOL fActive
);

Parameters

fActive
Switch to activate (TRUE) or deactivate (FALSE) the port.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DSERR_NODRIVER, indicating that no sound driver is present.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusic8::Activate, Using DirectMusic Ports


IDirectMusicPort8::Compact

Instructs the port to compact DLS or wave-table memory, thus making the largest possible contiguous chunk of memory available for new instruments to be downloaded.

HRESULT Compact();

Parameters

None.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Remarks

This method affects only DLS devices that need to manage their own DLS wavetable memory. On ports that do not manage their own memory (such as software synthesizers or hardware synthesizers that use host system memory), the method returns E_NOTIMPL.

Requirements

Header: Declared in dmusicc.h.


IDirectMusicPort8::DeviceIoControl

Calls the Win32 DeviceIoControl function on the underlying file handle implementing the port.

HRESULT DeviceIoControl(
  DWORD dwIoControlCode,
  LPVOID lpInBuffer,
  DWORD nInBufferSize,
  LPVOID lpOutBuffer,
  DWORD nOutBufferSize,
  LPDWORD lpBytesReturned,
  LPOVERLAPPED lpOverlapped
);

Parameters

dwIoControlCode
Control code of the operation to perform.
lpInBuffer
Buffer that contains input data.
nInBufferSize
Size of input buffer.
lpOutBuffer
Buffer that receives output data.
nOutBufferSize
Size of the output buffer.
lpBytesReturned
Address of a variable that receives the output byte count.
lpOverlapped
Address of an overlapped structure for asynchronous operation.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_NOTIMPL

Remarks

This method is supported only on ports implemented by a Windows Driver Model (WDM) filter graph. In the case of a WDM filter graph, the file handle used is the topmost pin in the graph.

DirectMusic can refuse to perform defined kernel streaming operations on a pin that might collide with operations that it is performing on the filter graph. User-defined operations, however, are never blocked.

Requirements

Header: Declared in dmusicc.h.


IDirectMusicPort8::DownloadInstrument

Downloads an instrument to the DLS device. Downloading an instrument means handing the data that makes up the instrument to the DLS device. This includes articulation data and all waves needed by the instrument. To save wave space, only waves and articulation required for a range are downloaded. The method returns an IDirectMusicDownloadedInstrument8 interface pointer, which is later used to unload the instrument.

HRESULT DownloadInstrument(
  IDirectMusicInstrument *pInstrument,
  IDirectMusicDownloadedInstrument **ppDownloadedInstrument,
  DMUS_NOTERANGE *pNoteRanges,
  DWORD dwNumNoteRanges;
);

Parameters

pInstrument
Pointer to the IDirectMusicInstrument8 interface of the instrument whose data is downloaded.
ppDownloadedInstrument
Address of a variable that receives a pointer to the IDirectMusicDownloadedInstrument8 interface.
pNoteRanges
Address of an array of DMUS_NOTERANGE structures. Each entry in the array specifies a contiguous range of MIDI note messages to which the instrument must respond. An instrument region is downloaded only if at least one note in that region is specified in the DMUS_NOTERANGE structures.
dwNumNoteRanges
Number of DMUS_NOTERANGE structures in the array pointed to by pNoteRanges. If this value is set to 0, the pNoteRanges parameter is ignored, and all regions and wave data for the instrument are downloaded.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_OUTOFMEMORY
E_NOTIMPL

Remarks

To prevent memory loss, the instrument must be unloaded by calling both IDirectMusicPort8::UnloadInstrument and IDirectMusicDownloadedInstrument8::Release when it is no longer needed.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPort8::Compact, Working with Instruments


IDirectMusicPort8::GetCaps

Retrieves the port's capabilities.

HRESULT GetCaps(
  LPDMUS_PORTCAPS pPortCaps
);

Parameters

pPortCaps
Address of a DMUS_PORTCAPS structure that receives the capabilities of the port. The dwSize member of this structure must be properly initialized before the method is called.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_INVALIDARG

Requirements

Header: Declared in dmusicc.h.


IDirectMusicPort8::GetChannelPriority

Retrieves the priority of a MIDI channel. For an overview, see Channels.

HRESULT GetChannelPriority(
  DWORD   dwChannelGroup,
  DWORD   dwChannel,
  LPDWORD pdwPriority
);

Parameters

dwChannelGroup
Group that the channel is in.
dwChannel
Index of the channel on the group.
pdwPriority
Address of a variable that receives the priority ranking. See Remarks.

Return Values

The return value is S_OK.

Remarks

The following values, defined in Dmusicc.h, each represent a range of priorities. They are listed here in descending order of priority.

DAUD_CRITICAL_VOICE_PRIORITY
DAUD_HIGH_VOICE_PRIORITY
DAUD_STANDARD_VOICE_PRIORITY
DAUD_LOW_VOICE_PRIORITY
DAUD_PERSIST_VOICE_PRIORITY

The following values express the default ranking of the channels within a range, according to the DLS Level 1 standard. They are listed here in descending order. Channel 10, the percussion channel, has the highest priority.

DAUD_CHAN10_VOICE_PRIORITY_OFFSET
DAUD_CHAN1_VOICE_PRIORITY_OFFSET
DAUD_CHAN2_VOICE_PRIORITY_OFFSET
DAUD_CHAN3_VOICE_PRIORITY_OFFSET
DAUD_CHAN4_VOICE_PRIORITY_OFFSET
DAUD_CHAN5_VOICE_PRIORITY_OFFSET
DAUD_CHAN6_VOICE_PRIORITY_OFFSET
DAUD_CHAN7_VOICE_PRIORITY_OFFSET
DAUD_CHAN8_VOICE_PRIORITY_OFFSET
DAUD_CHAN9_VOICE_PRIORITY_OFFSET
DAUD_CHAN11_VOICE_PRIORITY_OFFSET
DAUD_CHAN12_VOICE_PRIORITY_OFFSET
DAUD_CHAN13_VOICE_PRIORITY_OFFSET
DAUD_CHAN14_VOICE_PRIORITY_OFFSET
DAUD_CHAN15_VOICE_PRIORITY_OFFSET
DAUD_CHAN16_VOICE_PRIORITY_OFFSET

The priority of a channel is represented by a range plus an offset. For example, DAUD_STANDARD_VOICE_PRIORITY combined with DAUD_CHAN10_VOICE_PRIORITY represents the highest priority within the standard range. Priorities in the standard range are represented by defines in Dmusicc.h beginning with DAUD_CHAN1_DEF_VOICE_PRIORITY.

Channels that have the same priority value have equal priority, regardless of which channel group they belong to.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPort8::SetChannelPriority


IDirectMusicPort8::GetFormat

Retrieves information about the wave format specified in the DMUS_PORTPARAMS8 structure passed to IDirectMusic8::CreatePort, and the recommended size of the buffer to use for wave output. The information can be used to create a compatible DirectSound buffer for the port.

HRESULT GetFormat(
  LPWAVEFORMATEX pWaveFormatEx,
  LPDWORD pdwWaveFormatExSize
  LPDWORD pdwBufferSize
);

Parameters

pWaveFormatEx
Address of the WAVEFORMATEX structure that receives information about the format. This value can be NULL. See Remarks.
pdwWaveFormatExSize
Address of a variable that specifies or receives the size of the structure. See Remarks.
pdwBufferSize
Address of a variable that receives the recommended size of the DirectSound buffer.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK.

If it fails, the method can return E_POINTER.

Remarks

The WAVEFORMATEX structure can have a variable length that depends on the details of the format. Before retrieving the format description, the application should query the synthesizer object for the size of the format by calling this method and specifying NULL for the pWaveFormatEx parameter. The size of the structure is returned in the variable pointed to by pdwWaveFormatExSize. The application can then allocate sufficient memory and call GetFormat again to retrieve the format description.

If pWaveFormatEx is not NULL, DirectMusic writes, at most, pdwWaveFormatExSize bytes to the structure.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPort8::SetDirectSound


IDirectMusicPort8::GetLatencyClock

Retrieves an IReferenceClock interface pointer to the port's latency clock. The latency clock specifies the nearest time in the future at which a message can be played on time. The latency clock is based on the DirectMusic master clock, which is set by using the IDirectMusic8::SetMasterClock method.

HRESULT GetLatencyClock(
  IReferenceClock** ppClock
);

Parameters

ppClock
Address of a variable that receives the latency clock's IReferenceClock interface pointer.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

In accordance with COM rules, GetLatencyClock increments the reference count of the returned interface. Therefore, the application must call Release on the IReferenceClock interface at some point.

Requirements

Header: Declared in dmusicc.h.

See Also

Latency and Bumper Time


IDirectMusicPort8::GetNumChannelGroups

Retrieves the number of channel groups on the port.

HRESULT GetNumChannelGroups(
  LPDWORD pdwChannelGroups
);

Parameters

pdwChannelGroups
Address of a variable that receives the number of channel groups.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPort8::SetNumChannelGroups, Channels


IDirectMusicPort8::GetRunningStats

Retrieves information about the state of the synthesizer.

HRESULT GetRunningStats(
  LPDMUS_SYNTHSTATS pStats
);

Parameters

pStats
Address of a DMUS_SYNTHSTATS8 structure that receives running statistics of the synthesizer. The dwSize member of this structure must be properly initialized before the method is called.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_INVALIDARG
E_NOTIMPL

Remarks

Some hardware synthesizers might continue to report running statistics even though the port has been deactivated.

Requirements

Header: Declared in dmusicc.h.


IDirectMusicPort8::PlayBuffer

Cues a buffer for playback by the port.

HRESULT PlayBuffer(
  LPDIRECTMUSICBUFFER pBuffer
);

Parameters

pBuffer
Address of an IDirectMusicBuffer8 interface pointer of the buffer to be added to the port's playback queue.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Remarks

The buffer is in use by the system only for the duration of this method and can be reused after the method returns.

If no start time has been set by using the IDirectMusicBuffer8::SetStartTime method, the start time is the time of the earliest event in the buffer, as set by the IDirectMusicBuffer8::PackStructured or the IDirectMusicBuffer8::PackUnstructured method.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicBuffer8, IDirectMusic8::CreateMusicBuffer


IDirectMusicPort8::Read

Fills a buffer with incoming MIDI data. The method should be called with new buffer objects until no more data is available to be read.

HRESULT Read(
  LPDIRECTMUSICBUFFER pBuffer
);

Parameters

pBuffer
Address of the IDirectMusicBuffer8 interface pointer of the buffer object to be filled with the incoming MIDI data.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE.

If it fails, the method can return one of the following error values:

E_POINTER
E_NOTIMPL

Remarks

When there is no more data to read, the method returns S_FALSE.

Requirements

Header: Declared in dmusicc.h.

See Also

Capturing MIDI


IDirectMusicPort8::SetChannelPriority

Sets the priority of a MIDI channel. For an overview, see Channels.

HRESULT SetChannelPriority(
  DWORD  dwChannelGroup,
  DWORD  dwChannel,
  DWORD  dwPriority
);

Parameters

dwChannelGroup
Group that the channel is in. This value must be 1 or greater.
dwChannel
Index of the channel on the group.
dwPriority
The priority ranking. See Remarks for IDirectMusicPort8::GetChannelPriority.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_NOTIMPL

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPort8::GetChannelPriority, DMUS_CHANNEL_PRIORITY_PMSG.


IDirectMusicPort8::SetDirectSound

Overrides the default DirectSound object or buffer, or both, to which a port's wave data is streamed. This method is also used to disconnect the port from DirectSound.

HRESULT SetDirectSound(
  LPDIRECTSOUND pDirectSound,
  LPDIRECTSOUNDBUFFER pDirectSoundBuffer
);

Parameters

pDirectSound
Address of the IDirectSound8 interface of the DirectSound object to which the port is to be connected, or NULL to disconnect and release the existing DirectSound object.
pDirectSoundBuffer
Address of the IDirectSoundBuffer8 interface to connect the port to. This value can be NULL, and must be NULL if pDirectSound is NULL. This parameter is not used if the port is the Microsoft software synthesizer in DirectX 8.0 or later.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_NOBUFFERCONTROL. See Remarks.

If it fails, the method can return one of the following error values:

DMUS_E_ALREADY_ACTIVATED
E_INVALIDARG

Remarks

If a valid pointer is passed in pDirectSoundBuffer, the method returns DMUS_S_NOBUFFERCONTROL if control changes in the buffer such as pan and volume do not affect DirectMusic playback. This affects only Windows Driver Model (WDM) ports.

When the port is activated, the primary DirectSound buffer is upgraded, if necessary, to support the sample rate and channel information for this port (specified in the DMUS_PORTPARAMS8 structure passed to IDirectMusic8::CreatePort).

The buffer pointed to by pDirectSoundBuffer must be a secondary streaming buffer with a format that matches the sample rate and channel information for this port. If this parameter is NULL, an appropriate IDirectSoundBuffer instance is created internally.

Neither the IDirectSound nor the IDirectSoundBuffer can be changed after the port has been activated.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPort8::Activate, IDirectMusicPort8::GetFormat


IDirectMusicPort8::SetNumChannelGroups

Changes the number of channel groups that the application needs on the port.

HRESULT SetNumChannelGroups(
  DWORD dwChannelGroups
);

Parameters

dwChannelGroups
Number of channel groups on this port that the application wants to allocate.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPort8::GetNumChannelGroups, Channels


IDirectMusicPort8::SetReadNotificationHandle

Specifies an event that is to be set when MIDI messages are available to be read with the IDirectMusicPort8::Read method. The event is signaled whenever new data is available. To turn off event notification, call SetReadNotificationHandle with a NULL value for the hEvent parameter.

HRESULT SetReadNotificationHandle(
  HANDLE hEvent
);

Parameters

hEvent
Event handle obtained from a call to the Win32 CreateEvent function. It is the application's responsibility to close this handle after the port has been released.

Return Values

If it succeeds, the method returns S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_DMUSIC_RELEASED
E_NOTIMPL

Remarks

A return value of E_NOTIMPL can mean the port is not an input port.

Requirements

Header: Declared in dmusicc.h.

See Also

Capturing MIDI


IDirectMusicPort8::UnloadInstrument

Unloads a previously downloaded DLS instrument.

HRESULT UnloadInstrument(
  IDirectMusicDownloadedInstrument *pDownloadedInstrument
);

Parameters

pDownloadedInstrument
Address of an IDirectMusicDownloadedInstrument8 interface, obtained when the instrument was downloaded by calling the IDirectMusicPort8::DownloadInstrument method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_DOWNLOADED_TO_PORT
E_POINTER
E_NOTIMPL

Remarks

This method must be called to free memory allocated by IDirectMusicPort8::DownloadInstrument.

Requirements

Header: Declared in dmusicc.h.

See Also

Working with Instruments


IDirectMusicPortDownload8

The IDirectMusicPortDownload8 interface allows an application to communicate directly with a port that supports DLS downloading and to download memory chunks directly to the port. The interface is used primarily by authoring applications that edit DLS instruments directly. For an overview, see Low-Level DLS.

To obtain the IDirectMusicPortDownload8 interface, call the IDirectMusicPort8::QueryInterface method, passing in IID_IDirectMusicPortDownload8 as the interface GUID. If the port does not support DLS downloading, this call might fail.

The methods of the IDirectMusicPortDownload8 interface can be grouped as follows:

Buffer management | AllocateBuffer
 | GetAppend
 | GetBuffer
 | GetDLId
Loading | Download
 | Unload

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTMUSICPORTDOWNLOAD8 type is defined as a pointer to this interface.

typedef IDirectMusicPortDownload8 *LPDIRECTMUSICPORTDOWNLOAD8;

Requirements

Header: Declared in dmusicc.h.


IDirectMusicPortDownload8::AllocateBuffer

Allocates a chunk of memory for downloading DLS data to the port and returns an IDirectMusicDownload8 interface pointer that allows access to this buffer.

HRESULT AllocateBuffer(
  DWORD dwSize,
  IDirectMusicDownload** ppIDMDownload
);

Parameters

dwSize
Requested size of buffer.
ppIDMDownload
Address of a variable that receives the IDirectMusicDownload8 interface pointer.

Return Values

If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_INVALIDARG
E_OUTOFMEMORY

Remarks

After a buffer has been allocated, its size cannot change.

The buffer is freed when the IDirectMusicDownload8 interface is released.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPortDownload8::GetBuffer, Low-Level DLS


IDirectMusicPortDownload8::Download

Downloads a wave or instrument definition to the port. The memory must first be allocated by using the IDirectMusicPortDownload8::AllocateBuffer method.

HRESULT Download(
  IDirectMusicDownload* pIDMDownload
);

Parameters

pIDMDownload
Address of the IDirectMusicDownload8 interface for the buffer.

Return Values

Return values are determined by the implementation of the port.

If the method succeeds, it returns S_OK.

If the method fails, it can return one of the following values:

E_POINTER
E_FAIL
DMUS_E_ALREADY_DOWNLOADED
DMUS_E_BADARTICULATION
DMUS_E_BADINSTRUMENT
DMUS_E_BADOFFSETTABLE
DMUS_E_BADWAVE
DMUS_E_BADWAVELINK
DMUS_E_BUFFERNOTSET
DMUS_E_NOARTICULATION
DMUS_E_NOTMONO
DMUS_E_NOTPCM
DMUS_E_UNKNOWNDOWNLOAD

Remarks

For more information on how to prepare the data to be downloaded, see Low-Level DLS.

After the memory has been downloaded, you cannot do anything more with it. To update the download, you must create a new buffer and assign it a new download ID obtained by using the IDirectMusicPortDownload8::GetDLId method, and then send it down.

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPortDownload8::Unload, DMUS_DOWNLOADINFO, DMUS_OFFSETTABLE


IDirectMusicPortDownload8::GetAppend

Retrieves the amount of memory that the port needs to be appended to the end of a download buffer. This extra memory can be used by the port to interpolate across a loop boundary.

HRESULT GetAppend(
  DWORD* pdwAppend
);

Parameters

pdwAppend
Address of a variable that receives the number of appended samples for which memory is required. The amount of memory can be calculated from the wave format.

Return Values

Return values are determined by the port implementation.

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_NOTIMPL

Requirements

Header: Declared in dmusicc.h.


IDirectMusicPortDownload8::GetBuffer

Retrieves the IDirectMusicDownload8 interface pointer of a buffer whose unique identifier is known.

HRESULT GetBuffer(
  DWORD dwDLId,
  IDirectMusicDownload** ppIDMDownload
);

Parameters

dwDLId
Download identifier of the buffer. See DMUS_DOWNLOADINFO.
ppIDMDownload
Address of a variable that receives the IDirectMusicDownload8 interface pointer for the buffer.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
DMUS_E_INVALID_DOWNLOADID
DMUS_E_NOT_DOWNLOADED_TO_PORT

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPortDownload8::GetDLId, IDirectMusicDownload8::GetBuffer, Low-Level DLS.


IDirectMusicPortDownload8::GetDLId

Obtains sequential identifiers for one or more download buffers.

Every memory chunk downloaded to the synthesizer must have a unique identifier placed in its DMUS_DOWNLOADINFO structure. The GetDLId method guarantees that no two downloads have the same identifier.

HRESULT GetDLId(
  DWORD* pdwStartDLId,
  DWORD dwCount
);

Parameters

pdwStartDLId
Address of a variable that receives the first identifier.
dwCount
Number of identifiers to reserve. You might plan to download a whole series of chunks at once. Instead of calling GetDLId for each chunk, set dwCount to the number of chunks. GetDLId returns the first ID of the set, and the additional identifiers are automatically reserved up through *pdwStartDLId plus dwCount. A subsequent call to GetDLId would skip past the reserved values.

Return Values

If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_INVALIDARG

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusicPortDownload8::GetBuffer, Low-Level DLS


IDirectMusicPortDownload8::Unload

Unloads a buffer that was previously downloaded by using IDirectMusicPortDownload8::Download.

HRESULT Unload(
  IDirectMusicDownload* pIDMDownload
);

Parameters

pIDMDownload
Address of the IDirectMusicDownload8 interface for the buffer.

Return Values

Return values are determined by the port implementation.

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following values:

E_NOINTERFACE
DMUS_E_SYNTHNOTCONFIGURED

Requirements

Header: Declared in dmusicc.h.


IDirectMusicScript8

The IDirectMusicScript8 interface represents a script that contains variables that can be set and retrieved by the application, and routines that can be called by the application.

Typically the interface is obtained by using IDirectMusicLoader8::GetObject to load a script file. The application then calls IDirectMusicScript8::Init to associate the script with the DirectMusicPerformance object that performs the actual playback.

The methods of the IDirectMusicScript8 interface can be grouped as follows:

Initialization | Init
Calling routines | CallRoutine
Enumeration | EnumRoutine
 | EnumVariable
Getting variables | GetVariableObject
 | GetVariableNumber
 | GetVariableVariant
Setting variables | SetVariableNumber
 | SetVariableObject
 | SetVariableVariant

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.

See Also

Using Audio Scripts


IDirectMusicScript8::CallRoutine

Executes a routine in the script.

HRESULT CallRoutine(
  WCHAR *pwszRoutineName,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pwszRoutineName
Name of the routine.
pErrInfo
Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_GARBAGE_COLLECTED. See Garbage Collection.

If the method fails, return values can include the following:

DMUS_E_NOT_INIT
DMUS_E_SCRIPT_ERROR_IN_SCRIPT
DMUS_E_SCRIPT_ROUTINE_NOT_FOUND
E_POINTER

Remarks

Control does not return to the application until the routine finishes running.

Requirements

Header: Declared in dmusici.h.


IDirectMusicScript8::EnumRoutine

Retrieves the name of a routine in a script. This method might be used by music-authoring applications that need to enumerate all routines in a script.

HRESULT EnumRoutine(
  DWORD dwIndex,
  WCHAR *pwszName
);

Parameters

dwIndex
Zero-based index of the routine.
pwszName
Pointer to a string buffer that receives the name of the routine. Must contain at least MAX_PATH elements.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The routine was enumerated.
S_FALSE | There is no routine with the supplied index value.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.
DMUS_S_STRING_TRUNCATED | The name is longer than MAX_PATH.

If the method fails, return values can include the following:

DMUS_E_NOT_INIT
E_POINTER

Remarks

The following example, where pScript is a valid IDirectMusicScript8 interface pointer, displays the indexes and names of all routines in the script:

WCHAR wszRoutineName[MAX_PATH];
int i = 0;
while (S_OK == pScript->EnumRoutine(i++, wszRoutineName))
    printf("Routine number %d is called %S\n", i, wszRoutineName);

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicScript8::EnumVariable


IDirectMusicScript8::EnumVariable

Retrieves the name of a variable in a script. This method might be used by music-authoring applications that need to enumerate all variables in a script.

HRESULT EnumVariable(
  DWORD dwIndex,
  WCHAR *pwszName
);

Parameters

dwIndex
Zero-based index of the variable.
pwszName
Address of a string buffer that receives the name of the variable. Must contain at least MAX_PATH elements.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The routine was enumerated.
S_FALSE | There is no routine with the supplied index value.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.
DMUS_S_STRING_TRUNCATED | The name is longer than MAX_PATH.

If the method fails, return values can include the following:

DMUS_E_NOT_INIT

Remarks

The following example, where pScript is a valid IDirectMusicScript8 interface pointer, displays the indexes and names of all variables in the script:

WCHAR wszVariableName[MAX_PATH];
int i = 0;
while (S_OK == pScript->EnumVariable(i++, wszVariableName))
    printf("Variable number %d is called %S\n", i, wszVariableName);

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicScript8::EnumRoutine


IDirectMusicScript8::GetVariableNumber

Retrieves a 32-bit signed value from a variable declared in the script.

HRESULT GetVariableNumber(
  WCHAR *pwszVariableName,
  LONG *plValue,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pwszVariableName
Name of the script variable.
plValue
Address of a variable that receives the value.
pErrInfo
Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The value was retrieved.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

DISP_E_TYPEMISMATCH (See Winerror.h.)
DMUS_E_NOT_INIT
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicScript8::SetVariableNumber


IDirectMusicScript8::GetVariableObject

Retrieves an object pointer from a variable declared in the script.

HRESULT GetVariableObject(
  WCHAR *pwszVariableName,
  REFIID riid,
  LPVOID FAR *ppv,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pwszVariableName
Name of the script variable.
riid
Unique identifier of the interface. See the IID defines in Dmusici.h. All the standard interfaces have a defined identifier consisting of "IID_" plus the name of the interface. For example, the identifier of IDirectMusicTrack8 is IID_IDirectMusicTrack8.
ppv
Address of a variable that receives a pointer to the desired interface of the object.
pErrInfo
Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The value was retrieved.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

DMUS_E_NOT_INIT
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_NOINTERFACE
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicScript8::SetVariableObject


IDirectMusicScript8::GetVariableVariant

Retrieves a variant value from a variable declared in the script.

HRESULT GetVariableVariant(
  WCHAR *pwszVariableName,
  VARIANT *pvarValue,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pwszVariableName
Name of the script variable.
pvarValue
Address of a variable that receives the value.
pErrInfo
Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The value was retrieved.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

DMUS_E_NOT_INIT
DMUS_E_SCRIPT_CONTENT_READONLY
DMUS_E_SCRIPT_UNSUPPORTED_VARTYPE
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicScript8::SetVariableVariant


IDirectMusicScript8::Init

Associates the script with the performance that will play the sounds.

HRESULT Init(
  IDirectMusicPerformance *pPerformance,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pPerformance
Address of the IDirectMusicPerformance8 interface of the performance object.
pErrInfo
Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Requirements

Header: Declared in dmusici.h.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The script was initialized.
S_FALSE | The script has already been attached to a different performance.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

DMUS_E_NOT_INIT
DMUS_E_SCRIPT_CONTENT_READONLY
DMUS_E_SCRIPT_ERROR_IN_SCRIPT
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER
E_NOINTERFACE


IDirectMusicScript8::SetVariableNumber

Assigns a 32-bit signed value to a variable declared in the script.

HRESULT SetVariableNumber(
  WCHAR *pwszVariableName,
  LONG lValue,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pwszVariableName
Name of the script variable.
lValue
Value to assign to the variable.
pErrInfo
Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The value was set.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

DMUS_E_NOT_INIT
DMUS_E_SCRIPT_CONTENT_READONLY
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicScript8::GetVariableNumber


IDirectMusicScript8::SetVariableObject

Assigns an object interface pointer to a variable declared in the script.

HRESULT SetVariableObject(
  WCHAR *pwszVariableName,
  IUnknown *punkValue,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pwszVariableName
Name of the script variable.
punkValue
Interface pointer to assign to the variable. This can be an interface of one of the DirectMusic objects supported by the script engine, such as IDirectMusicSegment8, or an interface of any other object that implements the IDispatch interface.
pErrInfo
Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The value was set.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

DMUS_E_NOT_INIT
DMUS_E_SCRIPT_CONTENT_READONLY
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicScript8::GetVariableObject


IDirectMusicScript8::SetVariableVariant

Assigns a variant value to a variable declared in the script.

HRESULT SetVariableVariant(
  WCHAR *pwszVariableName,
  VARIANT varValue,
  BOOL fSetRef,
  DMUS_SCRIPT_ERRORINFO *pErrInfo
);

Parameters

pwszVariableName
Name of the script variable.
varValue
Value to assign to the variable.
fSetRef
TRUE if the variable is to be set by reference, FALSE if by value. Only objects can be set by reference. This flag should always be TRUE for DirectMusic objects and FALSE for other variants.
pErrInfo
Address of a DMUS_SCRIPT_ERRORINFO structure that receives information if an error occurs. Set this member to NULL if you do not want error information.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The value was set.
S_FALSE | The variable does not exist in the script.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If the method fails, return values can include the following:

DMUS_E_NOT_INIT
DMUS_E_SCRIPT_CONTENT_READONLY
DMUS_E_SCRIPT_NOT_A_REFERENCE
DMUS_E_SCRIPT_UNSUPPORTED_VARTYPE
DMUS_E_SCRIPT_VALUE_NOT_SUPPORTED
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicScript8::GetVariableObject


IDirectMusicSegment8

The IDirectMusicSegment8 interface represents a segment, a piece of music made up of multiple tracks. Most applications deal with musical data at the segment level. For an overview, see Using Segments.

The DirectMusicSegment object also supports the IDirectMusicObject8 and IPersistStream interfaces for loading its data.

IDirectMusicSegment8 supersedes the IDirectMusicSegment interface and introduces new methods.

The methods of the IDirectMusicSegment8 interface can be grouped as follows:

Instruments | Download
 | Unload
Notification | AddNotificationType
 | RemoveNotificationType
Parameters | GetParam
 | SetParam
Timing and looping | GetDefaultResolution
 | GetLength
 | GetLoopPoints
 | GetRepeats
 | GetStartPoint
 | SetDefaultResolution
 | SetLength
 | SetLoopPoints
 | SetRepeats
 | SetStartPoint
Tools | GetGraph
 | SetGraph
Tracks | GetTrack
 | GetTrackGroup
 | InsertTrack
 | RemoveTrack
 | SetTrackConfig
Miscellaneous | Clone
 | Compose
 | GetAudioPathConfig
 | InitPlay
 | SetPChannelsUsed

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.


IDirectMusicSegment8::AddNotificationType

Adds a notification type. This method is called by the IDirectMusicPerformance8::AddNotificationType method, allowing the segment to respond to notifications. The segment calls each track's IDirectMusicTrack8::AddNotificationType method.

HRESULT AddNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to add. For the defined types, see DMUS_NOTIFICATION_PMSG. Applications can also define their own types for custom tracks.

Return Values

If the method succeeds,Remarks

DirectSound does not initialize the contents of the buffer, and the application cannot assume that it contains silence.

If an attempt is made to create a buffer with the DSBCAPS_LOCHARDWARE flag on a system where hardware acceleration is not available, the method fails with DSERR_CONTROLUNAVAIL on Windows 95 and Windows 98. On Windows 2000, it returns DSERR_INVALIDCALL.

the return value is S_OK.

If it fails, the method can return one of the following error values:

E_POINTER
E_OUTOFMEMORY

Remarks

Segments cannot generate notifications of type GUID_NOTIFICATION_PERFORMANCE. To get notifications of this type, you must call IDirectMusicPerformance8::AddNotificationType.

Requirements

Header: Declared in dmusici.h.

See Also

Notification and Event Handling


IDirectMusicSegment8::Clone

Copies all or part of the segment and the tracks that it contains.

HRESULT Clone(
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd,
  IDirectMusicSegment** ppSegment
);

Parameters

mtStart
Start of the part to copy. If less than 0 or greater than the length of the segment, 0 is used.
mtEnd
End of the part to copy. If this value is past the end of the segment, the segment is copied to the end. A value of 0 or anything less than mtStart also copies to the end.
ppSegment
Address of a variable that receives a pointer to the IDirectMusicSegment interface of the created segment. Use QueryInterface to obtain IDirectMusicSegment8. It is the caller's responsibility to call Release when finished with the segment.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if some tracks failed to copy.

If it fails, the method can return one of the following error values:

E_OUTOFMEMORY
E_POINTER

Remarks

Properties of the original segment, including start and loop points, number of repeats, and any toolgraph and default audiopath, are copied to the clone.

For style-based segments, if mtStart is greater than 0, it should be on a measure boundary.

Requirements

Header: Declared in dmusici.h.


IDirectMusicSegment8::Compose

Composes all tracks flagged as DMUS_TRACKCONFIG_COMPOSING and places the composed tracks in this segment or in a clone of this segment.

HRESULT Compose(
  MUSIC_TIME mtTime,
  IDirectMusicSegment* pFromSegment,
  IDirectMusicSegment* pToSegment,
  IDirectMusicSegment** ppComposedSegment
);

Parameters

mtTime
Value of type MUSIC_TIME that specifies the current time in pFromSegment at which to compose a transition. Set to 0 if pFromSegment is NULL.
pFromSegment
Pointer to an IDirectMusicSegment8 interface that specifies the segment leading to a transition. This value is NULL if the calling segment is not a transition.
pToSegment
Pointer to the IDirectMusicSegment8 interface that specifies the segment following a transition. This value is NULL if the calling segment is not a transition or if the transition is an ending.
ppComposedSegment
Address of a variable that receives the IDirectMusicSegment8 interface pointer of the composed segment, or NULL if the calling segment is to be recomposed.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

DMUS_E_NOT_FOUND
E_FAIL
E_OUTOFMEMORY
E_POINTER

Remarks

If the pointer parameters are all NULL, the segment calls IDirectMusicTrack8::Compose on all its tracks. Any composing tracks search for other tracks necessary for composition; if a needed track is not found, DMUS_E_NOT_FOUND is returned.

If ppComposedSegment is not NULL, the method creates a clone of the original segment that contains the recomposed tracks. If either pFromSegment or pToSegment is not NULL, the calling segment is assumed to be a transition and might include tracks that contain only headers referring to one of the bracketing segments.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicTrack8::Compose, IDirectMusicSegment8::SetTrackConfig


IDirectMusicSegment8::Download

Downloads band data to a performance or audiopath.

HRESULT Download(
  IUnknown *pAudioPath
);

Parameters

pAudioPath
Pointer to the IUnknown interface of the performance or audiopath that receives the data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method may return one of the following error values.

DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

All bands and wave data in the segment are downloaded.

Always call IDirectMusicSegment8::Unload before releasing the segment.

Requirements

Header: Declared in dmusici.h.

See Also

Using Bands


IDirectMusicSegment8::GetAudioPathConfig

Retrieves an object that represents an audiopath configuration embedded in the segment. The object can be passed to IDirectMusicPerformance8::CreateAudioPath.

HRESULT GetAudioPathConfig(
  IUnknown ** ppAudioPathConfig
);

Parameters

ppAudioPathConfig
Address of a variable that receives a pointer to the IUnknown interface of the audiopath configuration object.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method may return one of the following error values:

DMUS_E_NO_AUDIOPATH_CONFIG
E_POINTER

Requirements

Header: Declared in dmusici.h.


IDirectMusicSegment8::GetDefaultResolution

Retrieves the default resolution for synchronization.

HRESULT GetDefaultResolution(
  DWORD* pdwResolution
);

Parameters

pdwResolution
Address of a variable that receives the default resolution. See DMUS_SEGF_FLAGS.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::SetDefaultResolution, Segment Timing


IDirectMusicSegment8::GetGraph

Retrieves the segment's toolgraph.

HRESULT GetGraph(
  IDirectMusicGraph** ppGraph
);

Parameters

ppGraph
Address of a variable that receives a pointer to the toolgraph.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_POINTER

Remarks

If there is no graph in the segment, the method returns DMUS_E_NOT_FOUND.

The reference count of the toolgraph is incremented.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::SetGraph


IDirectMusicSegment8::GetLength

Retrieves the length of the segment.

HRESULT GetLength(
  MUSIC_TIME* pmtLength
);

Parameters

pmtLength
Address of a variable that receives the segment's length in music time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The method always returns 1 in *pmtLength for segments created from wave files.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::SetLength


IDirectMusicSegment8::GetLoopPoints

Retrieves the start and end loop points inside the segment that repeat the number of times set by the IDirectMusicSegment8::SetRepeats method.

HRESULT GetLoopPoints(
  MUSIC_TIME* pmtStart,
  MUSIC_TIME* pmtEnd
);

Parameters

pmtStart
Address of a variable that receives the start point of the loop.
pmtEnd
Address of a variable that receives the end point of the loop. A value of 0 indicates that the entire segment loops.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::SetLoopPoints, Segment Timing


IDirectMusicSegment8::GetParam

Retrieves data from a track inside this segment.

HRESULT GetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Standard Track Parameters.
dwGroupBits
Group that the desired track is in. Use 0xFFFFFFFF for all groups. For more information, see Identifying the Track.
dwIndex
Index of the track in the group identified by dwGroupBits from which to obtain the data, or DMUS_SEG_ANYTRACK to find the first track that contains the parameter.
mtTime
Time from which to obtain the data.
pmtNext
Address of a variable that receives the segment time (relative to mtTime) until which the data is valid. If this returns a value of 0, it means either that the data is always valid, or that it is unknown when it might become invalid. If this information is not needed, pmtNext can be set to NULL. See Remarks.
pParam
Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_GET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

The data can become invalid before the time returned in *pmtNext if another control segment is cued. For more information, see Control Segments.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicSegment8::SetParam, IDirectMusicTrack8::GetParamEx, Performance Parameters


IDirectMusicSegment8::GetRepeats

Retrieves the number of times the looping portion of the segment is set to repeat.

HRESULT GetRepeats(
  DWORD* pdwRepeats
);

Parameters

pdwRepeats
Address of a variable that receives the number of times that the looping portion of the segment is set to repeat.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::SetRepeats


IDirectMusicSegment8::GetStartPoint

Retrieves the point within the segment at which it started or will start playing.

HRESULT GetStartPoint(
  MUSIC_TIME* pmtStart
);

Parameters

pmtStart
Address of a variable that receives the time within the segment at which it starts playing.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::SetStartPoint


IDirectMusicSegment8::GetTrack

Searches the list of tracks for the one with the supplied type, group, and index, and retrieves a pointer to the DirectMusicTrack object.

HRESULT GetTrack(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  IDirectMusicTrack** ppTrack
);

Parameters

rguidType
Reference to (C++) or address of (C) the class identifier of the track to find. A value of GUID_NULL retrieves any track. For track identifiers, see Standard Track Types.
dwGroupBits
Track groups in which to scan for the track. A value of 0 is invalid. Each bit in dwGroupBits corresponds to a track group. To scan all tracks, regardless of groups, set this parameter to 0xFFFFFFFF.
dwIndex
Zero-based index into the list of tracks of type rguidType and in group dwGroupBits to return. If multiple groups are selected in dwGroupBits, this index indicates the nth track of type rguidType encountered in the union of the groups selected. See Remarks.
ppTrack
Address of a variable that receives a pointer to the track. The variable is set to NULL if the track is not found.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_FAIL
E_POINTER

Remarks

To enumerate all tracks, use GUID_NULL for the rguidType and 0xFFFFFFFF for dwGroupBits. Call GetTrack starting with 0 for dwIndex, incrementing dwIndex until the method no longer returns a success code.

Tracks in segments created by DirectMusic Producer are not necessarily in the same order as they were in that application. Do not rely on dwIndex alone to find a particular track.

For more information on track groups, see Identifying the Track.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::InsertTrack


IDirectMusicSegment8::GetTrackGroup

Retrieves the group bits set on a track inside the segment.

HRESULT GetTrackGroup(
  IDirectMusicTrack* pTrack,
  DWORD* pdwGroupBits
);

Parameters

pTrack
Track for which to find the group bits.
pdwGroupBits
Address of a variable that receives the groups. Each bit in *pdwGroupBits corresponds to a track group.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
E_INVALIDARG

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::InsertTrack, Identifying the Track


IDirectMusicSegment8::InitPlay

Initializes the play state. This method was for internal use and is not implemented in versions later than DirectX 7.0.

HRESULT InitPlay(
  IDirectMusicSegmentState** ppSegState,
  IDirectMusicPerformance* pPerformance,
  DWORD dwFlags
);

Parameters

ppSegState
Address of a variable that receives a pointer to the IDirectMusicSegmentState8 interface that is created in response to this method call and is used to hold state data. It is returned with a reference count of 1, so a call to its Release method fully releases it.
pPerformance
Address of the IDirectMusicPerformance8 interface. This is needed by the segment and segment state to call methods on the performance object.
dwFlags
DMUS_SEGF_FLAGS that modify the track's behavior.

Return Values

In DirectX 8.0 and later, the method returns E_NOTIMPL.

In earlier versions, if the method succeeds, the return value is S_OK. If it fails, it can return one of the following error values:

E_POINTER
E_OUTOFMEMORY

Requirements

Header: Declared in dmusici.h.


IDirectMusicSegment8::InsertTrack

Inserts the supplied track into the segment's list of tracks.

HRESULT InsertTrack(
  IDirectMusicTrack* pTrack,
  DWORD dwGroupBits
);

Parameters

pTrack
Track to add to the segment.
dwGroupBits
Group or groups into which to insert the track. This value cannot be 0.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

Tracks are put in groups to link them correctly. For example, a segment might contain two style tracks and two mute tracks. Each style track would be put in a different group, along with its associated mute track. For more information on track groups, see Identifying the Track.

If the segment is currently playing, the new track is not included in playback because the segment state was not initialized with the new track.

This method initializes the track. However, if the track data is subsequently changed, the application must initialize it again by calling IDirectMusicTrack8::Init.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::RemoveTrack, IDirectMusicSegment8::GetTrackGroup


IDirectMusicSegment8::RemoveNotificationType

Removes a notification type. This method is called by the IDirectMusicPerformance8::RemoveNotificationType method, allowing the segment to remove notifications. The segment calls each track's IDirectMusicTrack8::RemoveNotificationType method.

HRESULT RemoveNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to remove. (For the defined types, see DMUS_NOTIFICATION_PMSG.) Setting this value to GUID_NULL causes all notifications to be removed.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the notification type was not previously set.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

Notification and Event Handling


IDirectMusicSegment8::RemoveTrack

Removes a track from the segment's track list.

HRESULT RemoveTrack(
  IDirectMusicTrack* pTrack
);

Parameters

pTrack
Track to remove from the segment's track list.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the specified track is not in the track list.

If the method fails, the return value can be E_POINTER.

Remarks

The track is released when removed.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::InsertTrack


IDirectMusicSegment8::SetDefaultResolution

Sets the default resolution for synchronization.

HRESULT SetDefaultResolution(
  DWORD dwResolution
);

Parameters

dwResolution
Desired default resolution. This value can be 0 or one of the following members of the DMUS_SEGF_FLAGS enumeration:

DMUS_SEGF_MEASURE
DMUS_SEGF_BEAT
DMUS_SEGF_GRID

Return Values

The method returns S_OK.

Remarks

This method is used primarily by secondary segments (motifs) to define whether they are synchronized to the measure, beat, or grid resolutions.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::GetDefaultResolution, Segment Timing


IDirectMusicSegment8::SetGraph

Assigns a toolgraph to the segment.

HRESULT SetGraph(
  IDirectMusicGraph* pGraph
);

Parameters

pGraph
Toolgraph pointer. Can be set to NULL to clear the segment graph.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

Any messages flowing through tools in the current toolgraph are deleted.

The graph's reference count is incremented, so it is safe to release the original reference.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SetGraph, DirectMusic Tools


IDirectMusicSegment8::SetLength

Sets the length, in music time, of the segment. This method is usually called by the loader, which retrieves the segment length from the file and passes it to the segment object.

HRESULT SetLength(
  MUSIC_TIME mtLength
);

Parameters

mtLength
Desired length. Must be greater than 0.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
DMUS_E_OUT_OF_RANGE

Remarks

Neglecting to set a primary segment length can cause problems when cueing other primary segments with the DMUS_SEGF_QUEUE flag.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::GetLength


IDirectMusicSegment8::SetLoopPoints

Sets the start and end points of the part of the segment that repeats. It repeats the number of times set by the IDirectMusicSegment8::SetRepeats method.

HRESULT SetLoopPoints(
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd
);

Parameters

mtStart
Point at which to begin the loop.
mtEnd
Point at which to end the loop. A value of 0 loops the entire segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_OUT_OF_RANGE.

Remarks

When the segment is played, it plays from the segment start time until mtEnd, then loops to mtStart, plays the looped portion the number of times set by IDirectMusicSegment8::SetRepeats, and then plays to the end.

The default values are set to loop the entire segment from beginning to end.

The method fails if mtStart is greater than or equal to the length of the segment, or if mtEnd is greater than the length of the segment. If mtEnd is 0, mtStart must be 0, as well.

This method does not affect any currently playing segment states created from this segment.

The loop points of a cached segment persist even if the segment is released, and then reloaded. To ensure that a segment is not subsequently reloaded from the cache, call IDirectMusicLoader8::ReleaseObject on it before releasing it.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::GetLoopPoints, Segment Timing


IDirectMusicSegment8::SetParam

Sets data on a track inside this segment.

HRESULT SetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the type of data to set. See Standard Track Parameters.
dwGroupBits
Group that the desired track is in. Use 0xFFFFFFFF for all groups. For more information, see Identifying the Track.
dwIndex
Index of the track in the group identified by dwGroupBits in which to set the data, or DMUS_SEG_ALLTRACKS to set the parameter on all tracks in the group that contain the parameter.
mtTime
Time at which to set the data.
pParam
Address of a structure containing the data, or NULL if no data is required. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicTrack8::SetParamEx, Performance Parameters


IDirectMusicSegment8::SetPChannelsUsed

Sets the performance channels that this segment uses. This method is usually called by a track in the IDirectMusicTrack8::Init method to inform the segment of which channels the track uses.

HRESULT SetPChannelsUsed(
  DWORD dwNumPChannels,
  DWORD* paPChannels
);

Parameters

dwNumPChannels
Number of PChannels to set. This must be equal to the number of members in the array pointed to by paPChannels.
paPChannels
Address of an array of PChannels.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

This method allows the performance to know which ports are being used by the segment so that it can determine the actual latency, rather than providing for the worst case.

Requirements

Header: Declared in dmusici.h.

See Also

Latency and Bumper Time, Channels


IDirectMusicSegment8::SetRepeats

Sets the number of times the looping portion of the segment is to repeat. By default, the entire segment is looped.

HRESULT SetRepeats(
  DWORD dwRepeats
);

Parameters

dwRepeats
Number of times that the looping portion of the segment is to repeat, or DMUS_SEG_REPEAT_INFINITE to repeat until explicitly stopped. A value of 0 specifies a single play with no repeats.

Return Values

The method returns S_OK.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::GetRepeats, IDirectMusicSegment8::SetLoopPoints, Segment Timing


IDirectMusicSegment8::SetStartPoint

Sets the point within the segment at which it will start playing.

HRESULT SetStartPoint(
  MUSIC_TIME mtStart
);

Parameters

mtStart
Point within the segment at which it is to start playing. Must be greater than or equal to zero and less than the length of the segment.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return DMUS_E_OUT_OF_RANGE.

Remarks

The start point is the first point in the segment that can possibly be heard. However, the actual first point heard may be later, if the start point of the segment is aligned to a past time. For more information, see Segment Timing.

By default, the start point is 0, meaning that the segment starts from the beginning.

If the segment does not already have a length, IDirectMusicSegment8::SetLength must be called before this method.

The method does not affect any currently playing segment states created from this segment.

The start point of a cached segment persists even if the segment is released, and then reloaded. To ensure that a segment is not subsequently reloaded from the cache, call IDirectMusicLoader8::ReleaseObject on it before releasing it.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::GetStartPoint, IDirectMusicSegmentState8::GetStartPoint, IDirectMusicSegment8::SetLength, IDirectMusicSegment8::SetLoopPoints, Segment Timing


IDirectMusicSegment8::SetTrackConfig

Sets the configuration settings of a track.

HRESULT SetTrackConfig(
  REFGUID rguidTrackClassID,
  DWORD dwGroupBits,
  DWORD dwIndex,
  DWORD dwFlagsOn,
  DWORD dwFlagsOff
);

Parameters

rguidTrackClassID
Reference to (C++) or address of (C) the identifier of the track class. For a list of values, see Standard Track Types.
dwGroupBits
Groups to which the track belongs.
dwIndex
Index of the track within the group, or DMUS_SEG_ALLTRACKS to set the configuration of all tracks in the group.
dwFlagsOn
Configuration flags to set. See Remarks.
dwFlagsOff
Configuration flags to clear. See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_TRACK_NOT_FOUND
E_INVALIDARG

Remarks

If you change a flag on a segment, subsequent instances of segment states inherit the change. However, segment states that are already playing do not change their behavior.

The following flags are defined.

DMUS_TRACKCONFIG_COMPOSING
Use this track to compose other tracks.
DMUS_TRACKCONFIG_CONTROL_ENABLED
Enable IDirectMusicTrack8::GetParamEx.
DMUS_TRACKCONFIG_CONTROL_NOTIFICATION
When played in a controlling segment, override notification of primary segment tracks.
DMUS_TRACKCONFIG_CONTROL_PLAY
When played in a controlling segment, override playback of primary segment tracks.
DMUS_TRACKCONFIG_DEFAULT
The combination of DMUS_TRACKCONFIG_CONTROL_ENABLED | DMUS_TRACKCONFIG_PLAY_ENABLED | DMUS_TRACKCONFIG_NOTIFICATION_ENABLED.
DMUS_TRACKCONFIG_FALLBACK
The track tries to get parameters from this segment if the primary and control segments don't return the requested information.
DMUS_TRACKCONFIG_LOOP_COMPOSE
Regenerate data each time the track repeats.
DMUS_TRACKCONFIG_NOTIFICATION_ENABLED
Enable notifications.
DMUS_TRACKCONFIG_OVERRIDE_ALL
The track tries to get parameters from this segment before the control and primary segment.
DMUS_TRACKCONFIG_OVERRIDE_PRIMARY
The track tries to get parameters from this segment before the primary segment.
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
Play in clock time, not music time.
DMUS_TRACKCONFIG_PLAY_COMPOSE
Regenerate data each time the track starts playing.
DMUS_TRACKCONFIG_PLAY_ENABLED
Enable track to send messages.
DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT
In composing transitions, get track information from the current place in the first segment.
DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART
In composing transitions, get track information from the start of the first segment.
DMUS_TRACKCONFIG_TRANS1_TOSEGSTART
In composing transitions, get track information from the start of the second segment.

The following table shows which track configuration flags are valid for standard tracks.

Band
DMUS_TRACKCONFIG_CONTROL_ENABLED
DMUS_TRACKCONFIG_CONTROL_PLAY
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
DMUS_TRACKCONFIG_PLAY_ENABLED
DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT
DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART
DMUS_TRACKCONFIG_TRANS1_TOSEGSTART

Chord
DMUS_TRACKCONFIG_CONTROL_ENABLED
DMUS_TRACKCONFIG_CONTROL_NOTIFICATION
DMUS_TRACKCONFIG_NOTIFICATION_ENABLED
DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT
DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART
DMUS_TRACKCONFIG_TRANS1_TOSEGSTART

Chordmap
DMUS_TRACKCONFIG_CONTROL_ENABLED
DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT
DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART
DMUS_TRACKCONFIG_TRANS1_TOSEGSTART

Command
DMUS_TRACKCONFIG_CONTROL_ENABLED
DMUS_TRACKCONFIG_CONTROL_NOTIFICATION
DMUS_TRACKCONFIG_NOTIFICATION_ENABLED
DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT
DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART
DMUS_TRACKCONFIG_TRANS1_TOSEGSTART

Lyrics
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
DMUS_TRACKCONFIG_PLAY_ENABLED

Marker:
DMUS_TRACKCONFIG_CONTROL_ENABLED

Melody formulation. Not implemented in DirectX 8.0.
DMUS_TRACKCONFIG_COMPOSING
DMUS_TRACKCONFIG_CONTROL_ENABLED
DMUS_TRACKCONFIG_CONTROL_NOTIFICATION
DMUS_TRACKCONFIG_CONTROL_PLAY
DMUS_TRACKCONFIG_LOOP_COMPOSE
DMUS_TRACKCONFIG_NOTIFICATION_ENABLED
DMUS_TRACKCONFIG_PLAY_COMPOSE
DMUS_TRACKCONFIG_PLAY_ENABLED
DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT
DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART
DMUS_TRACKCONFIG_TRANS1_TOSEGSTART

Motif
DMUS_TRACKCONFIG_CONTROL_ENABLED
DMUS_TRACKCONFIG_CONTROL_NOTIFICATION
DMUS_TRACKCONFIG_CONTROL_PLAY
DMUS_TRACKCONFIG_FALLBACK
DMUS_TRACKCONFIG_NOTIFICATION_ENABLED
DMUS_TRACKCONFIG_OVERRIDE_ALL
DMUS_TRACKCONFIG_OVERRIDE_PRIMARY
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
DMUS_TRACKCONFIG_PLAY_ENABLED

Mute
DMUS_TRACKCONFIG_CONTROL_ENABLED

Parameter control
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
DMUS_TRACKCONFIG_PLAY_ENABLED

Pattern
DMUS_TRACKCONFIG_CONTROL_ENABLED
DMUS_TRACKCONFIG_CONTROL_NOTIFICATION
DMUS_TRACKCONFIG_CONTROL_PLAY
DMUS_TRACKCONFIG_FALLBACK
DMUS_TRACKCONFIG_NOTIFICATION_ENABLED
DMUS_TRACKCONFIG_OVERRIDE_ALL
DMUS_TRACKCONFIG_OVERRIDE_PRIMARY
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
DMUS_TRACKCONFIG_PLAY_ENABLED

Script
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
DMUS_TRACKCONFIG_PLAY_ENABLED

Segment Trigger
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
DMUS_TRACKCONFIG_PLAY_ENABLED

Sequence
DMUS_TRACKCONFIG_CONTROL_PLAY
DMUS_TRACKCONFIG_FALLBACK
DMUS_TRACKCONFIG_OVERRIDE_ALL
DMUS_TRACKCONFIG_OVERRIDE_PRIMARY
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
DMUS_TRACKCONFIG_PLAY_ENABLED

Signpost
DMUS_TRACKCONFIG_COMPOSING
DMUS_TRACKCONFIG_CONTROL_NOTIFICATION
DMUS_TRACKCONFIG_CONTROL_PLAY
DMUS_TRACKCONFIG_LOOP_COMPOSE
DMUS_TRACKCONFIG_NOTIFICATION_ENABLED
DMUS_TRACKCONFIG_PLAY_COMPOSE
DMUS_TRACKCONFIG_PLAY_ENABLED
DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT
DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART
DMUS_TRACKCONFIG_TRANS1_TOSEGSTART

Style
DMUS_TRACKCONFIG_CONTROL_ENABLED
DMUS_TRACKCONFIG_CONTROL_NOTIFICATION
DMUS_TRACKCONFIG_CONTROL_PLAY
DMUS_TRACKCONFIG_FALLBACK
DMUS_TRACKCONFIG_NOTIFICATION_ENABLED
DMUS_TRACKCONFIG_OVERRIDE_ALL
DMUS_TRACKCONFIG_OVERRIDE_PRIMARY
DMUS_TRACKCONFIG_PLAY_ENABLED
DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT
DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART
DMUS_TRACKCONFIG_TRANS1_TOSEGSTART

Sysex
DMUS_TRACKCONFIG_CONTROL_PLAY
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
DMUS_TRACKCONFIG_PLAY_ENABLED

Tempo
DMUS_TRACKCONFIG_CONTROL_ENABLED
DMUS_TRACKCONFIG_CONTROL_PLAY
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
DMUS_TRACKCONFIG_PLAY_ENABLED
DMUS_TRACKCONFIG_TRANS1_FROMSEGCURRENT
DMUS_TRACKCONFIG_TRANS1_FROMSEGSTART
DMUS_TRACKCONFIG_TRANS1_TOSEGSTART

Time signature
DMUS_TRACKCONFIG_CONTROL_ENABLED
DMUS_TRACKCONFIG_CONTROL_NOTIFICATION
DMUS_TRACKCONFIG_CONTROL_PLAY
DMUS_TRACKCONFIG_NOTIFICATION_ENABLED
DMUS_TRACKCONFIG_PLAY_ENABLED

Wave
DMUS_TRACKCONFIG_CONTROL_PLAY
DMUS_TRACKCONFIG_FALLBACK
DMUS_TRACKCONFIG_OVERRIDE_ALL
DMUS_TRACKCONFIG_OVERRIDE_PRIMARY
DMUS_TRACKCONFIG_PLAY_CLOCKTIME
DMUS_TRACKCONFIG_PLAY_ENABLED

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegmentState8::SetTrackConfig, Self-Controlling Segments, Track Configuration


IDirectMusicSegment8::Unload

Unloads instrument data from a performance or audiopath.

HRESULT Unload(
  IUnknown *pAudioPath
);

Parameters

pAudioPath
Pointer to the IUnknown interface of the performance or audiopath from which to unload the instrument data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

DMUS_E_TRACK_NOT_FOUND
E_POINTER

Remarks

The method succeeds even if no data was previously downloaded.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::Download


IDirectMusicSegmentState8

When the IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx method is called, the performance engine generates a segment-state object that tracks the state of the playing segment. It also provides the application with a handle to the segment, in the form of the IDirectMusicSegmentState8 interface, which can be used to track the playback status of the segment. This method can also be used directly to stop playback or remove the segment from the performance, using methods of IDirectMusicPerformance8.

IDirectMusicSegmentState8 supersedes IDirectMusicSegmentState and adds new methods.

The interface has the following methods:

Information | GetObjectInPath
 | GetRepeats
 | GetSeek
 | GetSegment
 | GetStartPoint
 | GetStartTime
Track Configuration | SetTrackConfig

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.


IDirectMusicSegmentState8::GetObjectInPath

Retrieves an interface for an object in the audiopath on which this segment state is playing.

HRESULT GetObjectInPath(
  DWORD dwPChannel,
  DWORD dwStage,
  DWORD dwBuffer,
  REFGUID guidObject,
  DWORD dwIndex,
  REFGUID iidInterface,
  void ** ppObject
);

Parameters

dwPChannel
Performance channel to search, or DMUS_PCHANNEL_ALL to search all channels. The first channel is numbered 0. See Remarks.
dwStage
Stage in the path. Can be one of the following values.
DMUS_PATH_AUDIOPATH
The audiopath on which the segment state is playing.
DMUS_PATH_AUDIOPATH_GRAPH
The audiopath toolgraph. One is created if none exists.
DMUS_PATH_AUDIOPATH_TOOL
A tool from the audiopath toolgraph.
DMUS_PATH_BUFFER
A DirectSound buffer.
DMUS_PATH_BUFFER_DMO
A DMO in the buffer. For information on DMO interfaces, see IDirectSoundBuffer8::GetObjectInPath.
DMUS_PATH_MIXIN_BUFFER
A global mix-in buffer.
DMUS_PATH_MIXIN_BUFFER_DMO
A DMO in a global mix-in buffer.
DMUS_PATH_PERFORMANCE
The performance.
DMUS_PATH_PERFORMANCE_GRAPH
The performance toolgraph. One is created if none exists.
DMUS_PATH_PERFORMANCE_TOOL
A tool in the performance graph.
DMUS_PATH_PORT
The synthesizer.
DMUS_PATH_PRIMARY_BUFFER
The primary buffer.
DMUS_PATH_SEGMENT
The segment that owns this segment state.
DMUS_PATH_SEGMENT_GRAPH
The segment toolgraph. One is created if none exists. See Remarks.
DMUS_PATH_SEGMENT_TOOL
A tool from the segment graph. See Remarks.
DMUS_PATH_SEGMENT_TRACK
A track from the segment. See Remarks.
dwBuffer
If dwStage is DMUS_PATH_BUFFER_DMO or DMUS_PATH_MIXIN_BUFFER_DMO, the index of the buffer in which that DMO resides. If dwStage is DMUS_PATH_BUFFER or DMUS_PATH_MIXIN_BUFFER, the index of the buffer. Otherwise must be 0.
guidObject
Class identifier of the objector GUID_All_Objects to search for an object of any class. This parameter is ignored if only a single class of object can exist at the stage specified by dwStage, and can be set to GUID_NULL.
dwIndex
Index of the object in the list of matching objects. Set to 0 to find the first matching object. If dwStage is DMUS_PATH_BUFFER or DMUS_PATH_MIXIN_BUFFER, this parameter is ignored, and the buffer index is specified by dwBuffer.
iidInterface
Identifier of the desired interface, such as IID_IDirectMusicGraph.
ppObject
Address of a variable that receives a pointer to the requested interface.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_GARBAGE_COLLECTED. See Garbage Collection.

If it fails, the method can return one of the following error values.

DMUS_E_NOT_FOUND
E_INVALIDARG
E_NOINTERFACE
E_OUTOFMEMORY

Remarks

The value in dwPChannel must be 0 for any stage that is not channel-specific. Objects in the following stages are channel-specific and can be retrieved by setting a channel number or DMUS_PCHANNEL_ALL in dwPChannel:

DMUS_PATH_AUDIOPATH_TOOL
DMUS_PATH_BUFFER
DMUS_PATH_BUFFER_DMO
DMUS_PATH_PERFORMANCE_TOOL
DMUS_PATH_PORT
DMUS_PATH_SEGMENT_TOOL

The precedence of the parameters in filtering out unwanted objects is as follows:

  1. dwStage.
  2. guidObject. If this value is not GUID_All_Objects, only objects whose class identifier equals guidObject are searched. However, this parameter is ignored when only a single class of object can exist at the specified stage.
  3. dwPChannel. If the stage is channel-specific and this value is not DMUS_PCHANNEL_ALL, only objects on the channel are searched.
  4. dwBuffer. This is used only if dwStage is DMUS_PATH_BUFFER, DMUS_PATH_MIXIN_BUFFER, DMUS_PATH_BUFFER_DMO, or DMUS_PATH_MIXIN_BUFFER_DMO.
  5. dwIndex. Note that tracks in segments created by DirectMusic Producer are not necessarily in the same order as they were in that application. Do not rely on dwIndex alone to find a particular track at stage DMUS_PATH_SEGMENT_TRACK.

If a matching object is found but the interface specified by iidInterface cannot be obtained, the method fails.

The object returned when DMUS_PATH_SEGMENT_GRAPH or DMUS_PATH_SEGMENT_TOOL is specified in dwStage might not be the same one returned for a different segment state based on the same segment. When a segment is played, its toolgraph is copied and any tools that support the IDirectMusicTool8::Clone method are also cloned.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicAudioPath8::GetObjectInPath, Retrieving Objects from an Audiopath


IDirectMusicSegmentState8::GetRepeats

Returns the number of times that the looping portion of the segment is set to repeat.

HRESULT GetRepeats(
  DWORD* pdwRepeats
);

Parameters

pdwRepeats
Address of a variable that receives the repeat count. A value of 0 indicates that the segment is to play through only once, with no portion repeated.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::SetRepeats


IDirectMusicSegmentState8::GetSeek

Retrieves the seek pointer in the segment state. This is the value that is passed in the mtStart parameter of IDirectMusicTrack8::Play the next time that method is called. It does not take into account looping and repeating; if the entire segment state repeats to the beginning, the seek pointer is reset to 0.

HRESULT GetSeek(
  MUSIC_TIME* pmtSeek
);

Parameters

pmtSeek
Address of a variable that receives the seek pointer.

Return Values

If the method succeeds, the return value is S_OK.

If the method fails, the return value can be E_POINTER.

Requirements

Header: Declared in dmusici.h.


IDirectMusicSegmentState8::GetSegment

Returns a pointer to the segment that owns this segment state.

HRESULT GetSegment(
  IDirectMusicSegment** ppSegment
);

Parameters

ppSegment
Address of a variable that receives a pointer to the IDirectMusicSegment interface. Use QueryInterface to obtain IDirectMusicSegment8 interface.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

DMUS_E_NOT_FOUND
E_POINTER

Remarks

The pointer returned in ppSegment must be released by the application.

Requirements

Header: Declared in dmusici.h.


IDirectMusicSegmentState8::GetStartPoint

Returns the offset into the segment at which play will begin or began.

HRESULT GetStartPoint(
  MUSIC_TIME * pmtStart
);

Parameters

pmtStart
Address of a variable that receives the music-time offset from the start of the segment at which the segment state initially played or will play.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The start point is the first point in the segment that can possibly be heard. However, the actual first point heard may be later, if the start point of the segment is aligned to a past time. For more information, see Segment Timing.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::SetStartPoint, IDirectMusicSegmentState8::GetStartTime


IDirectMusicSegmentState8::GetStartTime

Gets the performance time at which the segment started or will start playing.

HRESULT GetStartTime(
  MUSIC_TIME* pmtStart
);

Parameters

pmtStart
Address of a variable that receives the music-time offset stored in this segment state.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Remarks

The time retrieved by this method is the resolved play time within the performance where the segment start time was cued. For more information, see Segment Timing.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::SetStartPoint, IDirectMusicSegment8::GetStartPoint, IDirectMusicSegmentState8::GetStartPoint


IDirectMusicSegmentState8::SetTrackConfig

Sets the configuration settings of a track.

HRESULT SetTrackConfig(
  REFGUID rguidTrackClassID,
  DWORD dwGroupBits,
  DWORD dwIndex,
  DWORD dwFlagsOn,
  DWORD dwFlagsOff
);

Parameters

rguidTrackClassID
Reference to (C++) or address of (C) the identifier of the track class. For a list of values, see Standard Track Types.
dwGroupBits
Groups to which the track belongs.
dwIndex
Index of the track within the group, or DMUS_SEG_ALLTRACKS to set the configuration of all tracks in the group.
dwFlagsOn
Configuration flags to set. For a list of values, see IDirectMusicSegment8::SetTrackConfig.
dwFlagsOff
Configuration flags to clear.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_TRACK_NOT_FOUND
E_INVALIDARG

Remarks

Any change in configuration takes effect after prepare time. If you want the change to take effect immediately, call IDirectMusicPerformance8::Invalidate.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::SetTrackConfig, Self-Controlling Segments, Track Configuration


IDirectMusicSong8

Not implemented in DirectX 8.0.

The IDirectMusicSong8 interface represents a song, which is a collection of segments based on common source material.

The interface has the following methods.

Instruments | Download
 | Unload
Segment retrieval | EnumSegment
 | GetSegment
Miscellaneous | Compose
 | GetAudioPathConfig
 | GetParam

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.


IDirectMusicSong8::Compose

Not implemented in DirectX 8.0.

Creates playable segments from the source material in the song.

HRESULT Compose();

Parameters

None.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The song was composed.
S_FALSE | There were no tracks to be composed.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If it fails, the method can return one of the following error values.

DMUS_E_TRACK_NOT_FOUND
E_INVALIDARG
E_POINTER
E_OUTOFMEMORY

Remarks

The method finds all composing tracks in all segments in the song, joins tracks with the same class identifier and group bits into master composing tracks, composes new tracks from the master composing tracks in priority order, breaks these new tracks up so that they correspond to the original tracks, and inserts the smaller composed tracks into segments of the song in the appropriate places.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::Compose, IDirectMusicTrack8::Compose


IDirectMusicSong8::Download

Not implemented in DirectX 8.0.

Downloads band data to a performance or audiopath.

HRESULT Download(
  IUnknown *pAudioPath
);

Parameters

pAudioPath
Pointer to the IUnknown interface of the performance or audiopath that receives the instrument data.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_PARTIALDOWNLOAD. For more information, see the Remarks for IDirectMusicBand8::Download.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_NOINTERFACE
E_OUTOFMEMORY
E_POINTER

Remarks

All bands in all segments of the song are downloaded.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSong8::Unload


IDirectMusicSong8::EnumSegment

Not implemented in DirectX 8.0.

Retrieves one of the segments that make up the song, by index.

HRESULT EnumSegment(
  DWORD dwIndex,
  IDirectMusicSegment **ppSegment
);

Parameters

dwIndex
Index of the segment within the song.
ppSegment
Address of a variable that receives an IDirectMusicSegment interface pointer if a matching segment is found. Use QueryInterface to obtain IDirectMusicSegment8.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The segment was enumerated.
S_FALSE | There was no segment at dwIndex.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

The method returns S_OK, or S_FALSE if dwIndex does not match any of the segments in the song.

If it fails, the method may return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSong8::GetSegment


IDirectMusicSong8::GetAudioPathConfig

Not implemented in DirectX 8.0.

Retrieves an object that represents the audiopath configuration for the song.

HRESULT GetAudioPathConfig(
  IUnknown ** ppAudioPathConfig
);

Parameters

ppAudioPathConfig
Address of a variable that receives a pointer to the IUnknown interface of the audiopath configuration object.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_GARBAGE_COLLECTED. See Garbage Collection.

If it fails, the method can return one of the following error values:

DMUS_E_NO_AUDIOPATH_CONFIG
E_POINTER

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::GetAudioPathConfig


IDirectMusicSong8::GetParam

Not implemented in DirectX 8.0.

Retrieves data from a track inside this song.

HRESULT GetParam(
  REFGUID rguidType,
  DWORD dwGroupBits,
  DWORD dwIndex,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Standard Track Parameters.
dwGroupBits
Group that the desired track is in. Set this value to 0xFFFFFFFF for all groups. See Remarks.
dwIndex
Index of the track in the group from which to obtain the data.
mtTime
Time from which to obtain the data, in performance time.
pmtNext
Address of a variable that receives the time, relative to mtTime, until which the data is valid. If this returns a value of zero, either the data is always valid, or it is not known when it might become invalid. If this information is not needed, pmtNext can be set to NULL.
pParam
Address of a buffer that receives the parameter data.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_GARBAGE_COLLECTED. See Garbage Collection.

If it fails, the method can return one of the following error values:

DMUS_E_GET_UNSUPPORTED
DMUS_E_NOT_FOUND
DMUS_E_TRACK_NOT_FOUND
E_POINTER

Requirements

Header: Declared in dmusici.h.


IDirectMusicSong8::GetSegment

Not implemented in DirectX 8.0.

Retrieves one of the segments that make up the song, by name.

HRESULT GetSegment(
  WCHAR pwzName,
  IDirectMusicSegment **ppSegment
);

Parameters

pwzName
Name of the segment, or NULL to retrieve the first segment.
ppSegment
Address of a variable that receives an IDirectMusicSegment interface pointer if a matching segment is found. Use QueryInterface to obtain IDirectMusicSegment8.

Return Values

If the method succeeds, one of the following success codes is returned:

S_OK | The segment was retrieved.
S_FALSE | pwzName does not match any segment.
DMUS_S_GARBAGE_COLLECTED | See Garbage Collection.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSong8::EnumSegment


IDirectMusicSong8::Unload

Not implemented in DirectX 8.0.

Unloads instrument data from an audiopath.

HRESULT Unload(
  IUnknown *pAudioPath
);

Parameters

pAudioPath
Pointer to the IUnknown interface of the audiopath from which to unload the instrument data.

Return Values

If the method succeeds, the return value is S_OK or DMUS_S_GARBAGE_COLLECTED. See Garbage Collection.

If it fails, the method may return E_POINTER.

Requirements

Header: Declared in dmusici.h.

Remarks

The method succeeds even if no data was previously downloaded.

See Also

IDirectMusicSong8::Download


IDirectMusicStyle8

The IDirectMusicStyle8 interface provides access to a style object. The style object provides the performance with the information that it needs to play musical patterns. For an overview, see Using Styles.

Because styles usually include bands and motifs, the IDirectMusicStyle8 interface provides methods for accessing these objects.

The DirectMusicStyle object also supports the IDirectMusicObject8 and IPersistStream interfaces for loading its data.

IDirectMusicStyle8 supersedes the IDirectMusicStyle interface and provides a new method, EnumPattern.

The methods of the IDirectMusicStyle8 interface can be organized in the following groups:

Enumeration | EnumBand
 | EnumChordMap
 | EnumMotif
 | EnumPattern
Information | GetBand
 | GetChordMap
 | GetDefaultBand
 | GetDefaultChordMap
 | GetEmbellishmentLength
 | GetMotif
 | GetTempo
 | GetTimeSignature

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusici.h.


IDirectMusicStyle8::EnumBand

Retrieves the name of the band with a given index value.

HRESULT EnumBand(
  DWORD dwIndex,
  WCHAR * pwszName
);

Parameters

dwIndex
Zero-based index into the style's band list.
pwszName
Address of a buffer that receives the band name. This should be of size MAX_PATH.

Return Values

If the method succeeds, it returns S_OK, S_FALSE if there is no band with the given index value, or DMUS_S_STRING_TRUNCATED if the length of the name is greater than MAX_PATH.

If it fails, the method can return one of the following error values:

DMUS_E_TYPE_UNSUPPORTED
E_POINTER

Requirements

Header: Declared in dmusici.h.


IDirectMusicStyle8::EnumChordMap

Retrieves the name of the chordmap with the given index value.

HRESULT EnumChordMap(
  DWORD dwIndex,
  WCHAR * pwszName
);

Parameters

dwIndex
Zero-based index of the chordmap in the style's chordmap list.
pwszName
Address of a buffer that receives the chordmap name. This should be of size MAX_PATH.

Return Values

If the method succeeds, the return value is S_OK, S_FALSE if there is no chordmap with the given index value, or DMUS_S_STRING_TRUNCATED if the length of the name is greater than MAX_PATH.

If it fails, the method can return one of the following error values:

DMUS_E_TYPE_UNSUPPORTED
E_POINTER

Requirements

Header: Declared in dmusici.h.


IDirectMusicStyle8::EnumMotif

Retrieves the name of a motif with a given index value.

HRESULT EnumMotif(
  DWORD dwIndex,
  WCHAR* pwszName
);

Parameters

dwIndex
Zero-based index into the style's motif list.
pwszName
Address of a buffer that receives the motif name. This should be of size MAX_PATH.

Return Values

If the method succeeds, the return value is S_OK, S_FALSE if there is no motif with the given index value, or DMUS_S_STRING_TRUNCATED if the length of the motif name is greater than MAX_PATH.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicStyle8::GetMotif, Using Motifs


IDirectMusicStyle8::EnumPattern

Retrieves the name of a pattern with a given index value and type. The name can be passed to the IDirectMusicPatternTrack8::SetPatternByName method.

HRESULT EnumPattern(
  DWORD dwIndex,
  DWORD dwPatternType,
  WCHAR* pwszName
);

Parameters

dwIndex
Zero-based index into the style's pattern list.
dwPatternType
One of the DMUS_STYLET_TYPES enumeration that specifies the type of pattern.
pwszName
Address of a buffer that receives the pattern name. This should be of size MAX_PATH.

Return Values

If the method succeeds, the return value is S_OK, S_FALSE if there is no pattern with the given index value and type, or DMUS_S_STRING_TRUNCATED if the length of the motif name is greater than MAX_PATH.

If it fails, the method can return one of the following error values.

E_INVALIDARG
E_POINTER.

Requirements

Header: Declared in dmusici.h.


IDirectMusicStyle8::GetBand

Retrieves the named band.

HRESULT GetBand(
  WCHAR* pwszName,
  IDirectMusicBand** ppBand
);

Parameters

pwszName
Name of the band to be retrieved. This name is assigned by the author of the style.
ppBand
Address of a variable that receives the IDirectMusicBand8 interface pointer of the band.

Return Values

If the method succeeds, the return value is S_OK if a band is returned, or S_FALSE if there is no band with that name.

If the method fails, the return value can be E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicStyle8::GetDefaultBand, Using Bands


IDirectMusicStyle8::GetChordMap

Retrieves a named chordmap.

HRESULT GetChordMap(
  WCHAR* pwszName,
  IDirectMusicChordMap** ppChordMap
);

Parameters

pwszName
Name of the chordmap to be retrieved.
ppChordMap
Address of a variable that receives a pointer to the IDirectMusicChordMap8 interface.

Return Values

If the method succeeds, the return value is S_OK if a chordmap is returned, or S_FALSE if there is no chordmap by that name.

If ppChordMap is not a valid pointer, the method returns E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicStyle8::GetDefaultChordMap, Using Chordmaps


IDirectMusicStyle8::GetDefaultBand

Retrieves the style's default band.

HRESULT GetDefaultBand(
  IDirectMusicBand ** ppBand
);

Parameters

ppBand
Address of a variable that receives the IDirectMusicBand8 interface pointer for the default band.

Return Values

If the method succeeds, the return value is S_OK if a band is returned, or S_FALSE if the style does not have a default band.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicStyle8::GetBand, Using Bands


IDirectMusicStyle8::GetDefaultChordMap

Retrieves the style's default chordmap.

HRESULT GetDefaultChordMap(
  IDirectMusicChordMap** ppChordMap
);

Parameters

ppChordMap
Address of a variable that receives a pointer to the IDirectMusicChordMap8 interface.

Return Values

If the method succeeds, the return value is S_OK if a chordmap is returned, or S_FALSE if the style does not have a default chordmap.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicStyle8::GetChordMap, Using Chordmaps


IDirectMusicStyle8::GetEmbellishmentLength

Finds the shortest and longest lengths for patterns of the specified embellishment type and groove level.

HRESULT GetEmbellishmentLength(
  DWORD dwType,
  DWORD dwLevel,
  DWORD* pdwMin,
  DWORD* pdwMax
);

Parameters

dwType
Embellishment type. See DMUS_COMMANDT_TYPES.
dwLevel
Groove level, in the range from 1 through 100. Ignored if dwType is not DMUS_COMMANDT_GROOVE.
pdwMin
Address of a variable that receives the length, in measures, of the shortest pattern of the specified type and groove level.
pdwMax
Address of a variable that receives the length, in measures, of the longest pattern of the specified type and groove level.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE.

If it fails, the method can return E_POINTER.

Remarks

If there are no patterns of the specified type and groove level, the method returns S_FALSE.

Requirements

Header: Declared in dmusici.h.


IDirectMusicStyle8::GetMotif

Creates a segment containing the named motif.

HRESULT GetMotif(
  WCHAR* pwszName,
  IDirectMusicSegment** ppSegment
);

Parameters

pwszName
Name of the motif to be retrieved.
ppSegment
Address of a variable that receives a pointer to a segment containing the named motif.

Return Values

If the method succeeds, the return value is S_OK or S_FALSE.

If it fails, the method can return E_POINTER.

Remarks

The method searches the style's list of motifs for one whose name matches pwszName. If one is found, a segment is created containing a motif track. The track references the style as its associated style and the motif as its pattern.

If there is no motif with the name, the method returns S_FALSE.

Requirements

Header: Declared in dmusici.h.

See Also

Using Motifs


IDirectMusicStyle8::GetTempo

Retrieves the recommended tempo of the style.

HRESULT GetTempo(
  double* pTempo
);

Parameters

pTempo
Address of a variable that receives the recommended tempo of the style.

Return Values

If the method succeeds, the return value is S_OK.

If pTempo is not a valid pointer, the method returns E_POINTER.

Requirements

Header: Declared in dmusici.h.


IDirectMusicStyle8::GetTimeSignature

Retrieves the style's time signature.

HRESULT GetTimeSignature(
  DMUS_TIMESIGNATURE* pTimeSig
);

Parameters

pTimeSig
Address of a DMUS_TIMESIGNATURE structure that receives data.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmusici.h.


IDirectMusicThru8

The IDirectMusicThru8 interface supports thruing of music messages from a capture port to another port. It is obtained by calling QueryInterface on the IDirectMusicPort8 interface for the capture port. For an example, see the Remarks for IDirectMusicThru8::ThruChannel.

IDirectMusicThru8 is a type definition for IDirectMusicThru. The two interface names can be used interchangeably.

The interface has the following method:

IDirectMusicThru8 ThruChannel

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTMUSICTHRU8 type is defined as a pointer to this interface.

typedef IDirectMusicThru8 *LPDIRECTMUSICTHRU8;

Requirements

Header: Declared in dmusici.h.

See Also

Capturing MIDI


IDirectMusicThru8::ThruChannel

Establishes or breaks a thruing connection between a channel on a capture port and a channel on another port.

HRESULT ThruChannel(
  DWORD dwSourceChannelGroup,
  DWORD dwSourceChannel,
  DWORD dwDestinationChannelGroup,
  DWORD dwDestinationChannel,
  LPDIRECTMUSICPORT pDestinationPort
);

Parameters

dwSourceChannelGroup
Channel group on the capture port. This value is always 1.
dwSourceChannel
Source channel.
dwDestinationChannelGroup
Channel group on the destination port.
dwDestinationChannel
Destination channel.
pDestinationPort
Address of the IDirectMusicPort8 interface for the destination channel. Set this value to NULL to break an existing thruing connection.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_NOTIMPL
E_INVALIDARG
DMUS_E_PORT_NOT_RENDER

Remarks

System exclusive messages are not transmitted to the destination port.

Thruing to the Microsoft software synthesizer or other synthesizers that do not have a constant latency is not recommended. Thruing is done as soon as possible upon reception of the incoming MIDI events. Because of the comparatively high latency of the software synthesizer (compared with a hardware port) and the fact that it renders blocks of audio data at the same time, each event is delayed by a small, essentially random amount of time before it plays. This random offset shows up as jitter in the playback of the data. Latency of other devices (such as an MPU-401 port) is small enough that jitter does not occur.

If an application needs to thru to the software synthesizer, it should add a small offset to the incoming note event time stamps to compensate for the rendering latency of the synthesizer.

The following code example obtains the IDirectMusicThru8 interface and establishes a thru connection between all channels on group 1 of the capture port and the equivalent channels on a destination port.

HRESULT SetupOneToOneThru(
    IDirectMusicPort8 *pCapturePort,
    IDirectMusicPort8 *pRenderPort)
{
    HRESULT hr;
    IDirectMusicThru8 *pThru;

    hr = pCapturePort->QueryInterface(IID_IDirectMusicThru8,
            (void**)&pThru);
    if (FAILED(hr))
        return hr;

    for (DWORD dwChannel = 0; dwChannel < 16; dwChannel++)
    {
        hr = pThru->ThruChannel(1, dwChannel,
            1, dwChannel, (IDirectMusicPort*)pRenderPort);
        if (FAILED(hr))
            break;
    }

    pThru->Release();
    return hr;
}

Requirements

Header: Declared in dmusici.h.


IDirectMusicTool8

The IDirectMusicTool8 interface represents a tool object that processes messages. The tool can modify a message, create additional messages, remove messages, and so on.

This interface is of interest chiefly to developers who want to create their own tools. Methods of the interface are implemented by the designer of the tool and are generally called by the performance. The application only needs to insert the tool in the message path by using IDirectMusicGraph8::InsertTool.

IDirectMusicTool8 supersedes the IDirectMusicTool interface and adds a new method.

The methods of the IDirectMusicTool8 interface can be organized in the following groups:

Duplication | Clone
Initialization | Init
Message management | Flush
 | GetMediaTypeArraySize
 | GetMediaTypes
 | GetMsgDeliveryType
 | ProcessPMsg

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmplugin.h.

See Also

Message Creation and Delivery, DirectMusic Tools


IDirectMusicTool8::Clone

Creates a new instance of the tool.

HRESULT Clone(
  IDirectMusicTool** ppTool
);

Parameters

ppTool
Address of a variable that receives a pointer to the IDirectMusicTool interface of the new instance of the tool. Use QueryInterface to obtain IDirectMusicTool8.

Return Values

Return values are determined by the implementation. If it succeeds, the method should return S_OK. If it fails, the return value might be E_POINTER or E_OUTOFMEMORY.

Requirements

Header: Declared in dmplugin.h.


IDirectMusicTool8::Flush

Flushes messages from the queue when the performance stops. The tool can use the method to do whatever is necessary to flush the message. For instance, the output tool uses this method to ensure that any pending note-off messages are processed immediately.

HRESULT Flush(
  IDirectMusicPerformance* pPerf,
  DMUS_PMSG* pPMSG,
  REFERENCE_TIME rtTime
);

Parameters

pPerf
Address of the IDirectMusicPerformance8 interface.
pPMSG
Message to flush.
rtTime
Time at which to flush.

Return Values

Return values are determined by the implementation. If the method succeeds, the return value can be one of the following:

DMUS_S_REQUEUE
DMUS_S_FREE
S_OK

If it fails, the method can return E_POINTER.

Remarks

The message will have DMUS_PMSGF_TOOL_FLUSH set in its dwFlags member. See DMUS_PMSG.

If the method returns DMUS_S_REQUEUE, the tool wants the message to be requeued. This allows the tool to put a new time stamp and parameters on the message and requeue it, or to requeue the message with a different delivery type.

If the return value is DMUS_S_FREE, the tool wants the message freed automatically and does not want to requeue the message.

If S_OK is returned, the tool does not want the message to be freed automatically. Perhaps the tool is holding onto the message for some reason, or has freed it itself.

Be sure not to create a circular reference to the performance represented by pPerf. For more information, see DirectMusic Tools.

Requirements

Header: Declared in dmplugin.h.


IDirectMusicTool8::GetMediaTypeArraySize

Retrieves the size of the array that must be passed in to the IDirectMusicTool8::GetMediaTypes method. A return value of 0 indicates that the tool handles all types, and it is unnecessary to call GetMediaTypes.

HRESULT GetMediaTypeArraySize(
  DWORD* pdwNumElements
);

Parameters

pdwNumElements
Address of a variable that receives the number of media types. If 0 is returned in this field, all types are supported.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK. If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmplugin.h.


IDirectMusicTool8::GetMediaTypes

Retrieves a list of the types of messages that this tool supports.

HRESULT GetMediaTypes(
  DWORD** padwMediaTypes,
  DWORD dwNumElements
);

Parameters

padwMediaTypes
Address of an array of DWORDs. The method fills this array with the media types supported by this tool. For media types, see DMUS_PMSGT_TYPES.
dwNumElements
Number of elements in the padwMediaTypes array. This value is equal to the number returned by the IDirectMusicTool8::GetMediaTypeArraySize method. If dwNumElements is less than this number, the method cannot return all the message types that are supported. If it is greater than this number, the extra elements in the array should be set to 0.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK, or S_FALSE if the method could not fill in all values because dwNumElements was too small. If it fails, the method can return one of the following error values:

E_POINTER
E_INVALIDARG
E_NOTIMPL

Remarks

If the method returns E_NOTIMPL, the tool processes all media types.

Requirements

Header: Declared in dmplugin.h.


IDirectMusicTool8::GetMsgDeliveryType

Retrieves the tool's delivery type, which determines when messages are to be delivered to the tool.

HRESULT GetMsgDeliveryType(
  DWORD* pdwDeliveryType
);

Parameters

pdwDeliveryType
Address of a variable that receives the delivery type. The returned value must be DMUS_PMSGF_TOOL_IMMEDIATE, DMUS_PMSGF_TOOL_QUEUE, or DMUS_PMSGF_TOOL_ATTIME. An unrecognized value in *pdwDeliveryType is treated as DMUS_PMSGF_TOOL_IMMEDIATE by the graph.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK. If it fails, the method can return E_POINTER.

Remarks

For an overview of the delivery mechanism, see Message Creation and Delivery.

Requirements

Header: Declared in dmplugin.h.


IDirectMusicTool8::Init

Initializes the tool. This method is called when the tool is inserted into the graph, giving the tool an opportunity to perform any necessary initialization.

HRESULT Init(
  IDirectMusicGraph* pGraph
);

Parameters

pGraph
Calling graph.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK. If it fails, the method can return one of the following error values:

E_FAIL
E_NOTIMPL

Remarks

Because a tool can be inserted into more than one graph, this method must be able to deal gracefully with multiple calls.

Be sure not to create a circular reference to the graph represented by pGraph. For more information, see DirectMusic Tools.

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicGraph8::InsertTool


IDirectMusicTool8::ProcessPMsg

Performs the main task of the tool. It is called from inside the performance's real-time thread for all messages that match the types specified by IDirectMusicTool8::GetMediaTypes.

HRESULT ProcessPMsg(
  IDirectMusicPerformance* pPerf,
  DMUS_PMSG* pPMSG
);

Parameters

pPerf
Performance that is generating messages.
pPMSG
Message to process.

Return Values

Return values are determined by the implementation. If the method succeeds, the return value can be one of the following:

DMUS_S_REQUEUE
DMUS_S_FREE
S_OK

If it fails, the method can return E_POINTER.

Remarks

If the method returns DMUS_S_REQUEUE, the tool wants the message to be requeued. This allows the tool to put a new time stamp and parameters on the message and requeue it, or to requeue the message with a different delivery type.

If the return value is DMUS_S_FREE, the tool wants the message freed automatically, and does not want to requeue the message.

If S_OK is returned, the tool does not want the message to be freed automatically. Perhaps the tool is holding onto the message for some reason, or has freed it itself.

Tools should not perform time-consuming activities because doing so can severely affect overall performance. Also be sure not to create a circular reference to the performance represented by pPerf. For more information, see DirectMusic Tools.

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicPerformance8::SendPMsg, Messages, Message Creation and Delivery


IDirectMusicTrack8

The IDirectMusicTrack8 interface represents a track object. Almost everything that has to do with the definition of a segment is stored in its tracks. The track mechanism allows segments to be infinitely extensible, and the segment does not need any knowledge of any of the music and audio technologies that it employs.

If you plan to install your own music playback mechanism in DirectMusic, you need to create a DirectMusicTrack object to represent it. Otherwise, the methods of this interface are typically not called directly from the application.

IDirectMusicTrack8 supersedes the IDirectMusicTrack interface and adds new methods.

Note When implementing methods of the IDirectMusicTrack8 interface, be sure not to hold onto references to objects passed in. For example, if IDirectMusicTrack8::Init adds a reference to the IDirectMusicSegment interface that it receives as a parameter, ensure that this reference is released.

The IDirectMusicTrack8 interface has the following methods:

Creation | Clone
 | Compose
 | Join
Initialization | Init
Notification | AddNotificationType
 | RemoveNotificationType
Parameters | GetParam
 | GetParamEx
 | IsParamSupported
 | SetParam
 | SetParamEx
Playback | EndPlay
 | InitPlay
 | Play
 | PlayEx

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The DirectMusicTrack object also supports the IDirectMusicObject8 and IPersistStream interfaces for loading its data.

Requirements

Header: Declared in dmplugin.h.

See Also

DirectMusic Tracks, Setting and Retrieving Track Parameters


IDirectMusicTrack8::AddNotificationType

Enables event notification for a track. It is similar to and called from the IDirectMusicSegment8::AddNotificationType method.

HRESULT AddNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to add. For the defined types, see DMUS_NOTIFICATION_PMSG. Applications can also define their own types for custom tracks.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the track does not support the notification type.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_NOTIMPL

Remarks

If the track does not support notifications, the method returns E_NOTIMPL. A motif or style track returns DMUS_E_NOT_INIT if it has not been initialized.

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicTrack8::RemoveNotificationType, Notification and Event Handling


IDirectMusicTrack8::Clone

Makes a copy of a track.

HRESULT Clone(
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd,
  IDirectMusicTrack** ppTrack
 );

Parameters

mtStart
Start of the part to copy. It should be 0 or greater and less than the length of the track.
mtEnd
End of the part to copy. It should be greater than mtStart and less than the length of the track.
ppTrack
Address of a variable that receives a pointer to the created track, if successful.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_OUTOFMEMORY
E_POINTER

Remarks

It is the caller's responsibility to call Release when finished with the track.

Requirements

Header: Declared in dmplugin.h.


IDirectMusicTrack8::Compose

Recomposes the track based on data from a segment. DirectMusic implements this method on the signpost track to compose a chord track.

HRESULT Compose(
  IUnknown* pContext,
  DWORD dwTrackGroup,
  IDirectMusicTrack** ppResultTrack
 );

Parameters

pContext
IUnknown interface pointer of the object to use in the composition. This is usually the segment that owns this track.
dwTrackGroup
DWORD value that specifies group bits for the track. For more information on group bits, see Identifying the Track.
ppResultTrack
Address of a variable that receives the IDirectMusicTrack interface of the composed track. Use QueryInterface to obtain IDirectMusicTrack8.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

E_INVALIDARG
E_POINTER

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicSegment8::Compose


IDirectMusicTrack8::EndPlay

Called when the object that originally called IDirectMusicTrack8::InitPlay is destroyed.

HRESULT EndPlay(
  void * pStateData
);

Parameters

pStateData
Pointer to state data returned from IDirectMusicTrack8::InitPlay. This data should be freed in the EndPlay method.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return E_POINTER.

Requirements

Header: Declared in dmplugin.h.


IDirectMusicTrack8::GetParam

Retrieves data from a track, in music time.

HRESULT GetParam(
  REFGUID rguidType,
  MUSIC_TIME mtTime,
  MUSIC_TIME* pmtNext,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Standard Track Parameters.
mtTime
Time, in track time, from which to obtain the data.
pmtNext
Address of a variable that receives the track time (relative to the current time) until which the data is valid. If this returns a value of 0, either the data is always valid, or it is unknown when it might become invalid. If this information is not needed, pmtNext can be set to NULL.
pParam
Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_FOUND
DMUS_E_NOT_INIT
DMUS_E_TYPE_DISABLED
DMUS_E_GET_UNSUPPORTED
E_POINTER

Remarks

The IDirectMusicTrack8::GetParamEx method can be used for greater functionality.

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicTrack8::SetParam, IDirectMusicTrack8::IsParamSupported, IDirectMusicPerformance8::GetParam, IDirectMusicSegment8::GetParam, Performance Parameters


IDirectMusicTrack8::GetParamEx

Retrieves data from a track, in either music or reference time.

HRESULT GetParamEx(
  REFGUID rguidType,
  REFERENCE_TIME rtTime,
  REFERENCE_TIME* prtNext,
  void * pParam
  void * pStateData,
  DWORD dwFlags
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to obtain. See Standard Track Parameters.
rtTime
Time from which to obtain the data. Unless DMUS_TRACK_PARAMF_CLOCK is set in dwFlags, this value is in music time.
prtNext
Address of a variable that receives the time until which the data is valid. If this returns a value of zero, either the data is always valid, or it is unknown when it might become invalid. If this information is not needed, prtNext can be set to NULL.
pParam
Address of an allocated structure in which the data is to be returned. The structure must be of the appropriate kind and size for the data type identified by rguidType.
pStateData
Address of a buffer containing state data for the track instance. This value is obtained from IDirectMusicTrack8::InitPlay.
dwFlags
Can be zero or the following flag.
DMUS_TRACK_PARAMF_CLOCK
The value in rtTime is in clock time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

DMUS_E_NOT_FOUND
DMUS_E_NOT_INIT
DMUS_E_TYPE_DISABLED
DMUS_E_GET_UNSUPPORTED
DMUS_E_TRACK_NO_CLOCKTIME_SUPPORT
E_POINTER

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicTrack8::GetParam, IDirectMusicTrack8::SetParamEx


IDirectMusicTrack8::Init

Initializes the track. This method is called by a segment when a track is added.

HRESULT Init(
  IDirectMusicSegment* pSegment
);

Parameters

pSegment
Segment to which this track belongs.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Remarks

If the track plays messages, it should call IDirectMusicSegment8::SetPChannelsUsed in the Init method.

This method should be called whenever track data is changed after the track is inserted in a segment.

Requirements

Header: Declared in dmplugin.h.


IDirectMusicTrack8::InitPlay

Called when a track is ready to start playing. The method returns a pointer to state data.

HRESULT InitPlay(
  IDirectMusicSegmentState* pSegmentState,
  IDirectMusicPerformance* pPerformance,
  void** ppStateData,
  DWORD dwVirtualTrackID,
  DWORD dwFlags
);

Parameters

pSegmentState
Address of the calling IDirectMusicSegmentState or IDirectMusicSegmentState8 interface.
pPerformance
Address of the calling IDirectMusicPerformance or IDirectMusicPerformance8 interface.
ppStateData
Address of a variable that receives a pointer to state information. The format and use of the data is specific to the track. The data should be created in the InitPlay method and freed in the IDirectMusicTrack8::EndPlay method. The pointer is passed to the IDirectMusicTrack8::Play and IDirectMusicTrack8::PlayEx methods.
dwVirtualTrackID
Virtual track ID assigned to this track instance.
dwFlags
DMUS_SEGF_FLAGS that control the track's behavior. See Remarks.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_OUTOFMEMORY
E_POINTER

Remarks

The dwFlags parameter passes the flags that were handed to the performance in the call to IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx. The track determines how it should perform, based on the DMUS_SEGF_CONTROL and DMUS_SEGF_SECONDARY flags. For example, the tempo track automatically plays the tempo changes only if it is part of a primary segment or a secondary control segment (DMUS_SEGF_SECONDARY is not set, or DMUS_SEGF_CONTROL is set).

A track can return NULL in ppStateData.

Requirements

Header: Declared in dmplugin.h.


IDirectMusicTrack8::IsParamSupported

Determines whether the track supports a given data type in the IDirectMusicTrack8::GetParam and IDirectMusicTrack8::SetParam methods.

HRESULT IsParamSupported(
  REFGUID rguidType
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data. See Standard Track Parameters.

Return Values

If the method succeeds and the type is supported, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_TYPE_DISABLED
DMUS_E_TYPE_UNSUPPORTED
E_POINTER
E_NOTIMPL

Remarks

If a parameter has been disabled by using one of the SetParam methods, the IDirectMusicTrack8::IsParamSupported method returns DMUS_E_TYPE_DISABLED when passed the corresponding parameter type (either GUID_TempoParam or GUID_TimeSignature).

The method also returns DMUS_E_TYPE_DISABLED if passed GUID_DisableTempo when that parameter has already been disabled, or if passed GUID_EnableTempo when that parameter is currently enabled. The same is true for GUID_DisableTimeSig and GUID_EnableTimeSig.

The method returns DMUS_E_TYPE_UNSUPPORTED when the track does not support the parameter referred to by a GUID_EnableTempo, GUID_EnableTimeSig, GUID_DisableTempo, or GUID_DisableTimeSig parameter call.

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicTrack8::GetParam, IDirectMusicTrack8::SetParam, Performance Parameters


IDirectMusicTrack8::Join

Appends one track to another.

HRESULT Join(
  IDirectMusicTrack* pNewTrack,
  MUSIC_TIME mtJoin,
  IUnknown* pContext,
  DWORD dwTrackGroup,
  IDirectMusicTrack** ppResultTrack)
);

Parameters

pNewTrack
Pointer to an IDirectMusicTrack8 interface that specifies the track to append to this one.
mtJoin
Time within this track where pNewTrack is to begin.
pContext
IUnknown interface pointer of the context segment. This object determines the time signature for tracks that use measures and beats, such as the signpost track.
dwTrackGroup
Group or groups to which the new track belongs. For more information on track groups, see IDirectMusicSegment8::InsertTrack and Identifying the Track.
ppResultTrack
Address of a variable that receives the IDirectMusicTrack interface of the concatenated track. Use QueryInterface to obtain IDirectMusicTrack8. If NULL, no new track is created and the current track becomes the concatenated track.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

E_POINTER
E_INVALIDARG
E_OUTOFMEMORY

Remarks

This method is supported by the band, chordmap, tempo, style, chord, signpost, and command tracks.

Requirements

Header: Declared in dmplugin.h.


IDirectMusicTrack8::Play

Causes the track to play. It performs any work that the track must do when the segment is played, such as creating and sending messages.

HRESULT Play(
  void* pStateData,
  MUSIC_TIME mtStart,
  MUSIC_TIME mtEnd,
  MUSIC_TIME mtOffset
  DWORD dwFlags,
  IDirectMusicPerformance* pPerf,
  IDirectMusicSegmentState* pSegSt,
  DWORD dwVirtualID
);

Parameters

pStateData
Pointer to state data from the IDirectMusicTrack8::InitPlay method. The format and use of the data is specific to the track.
mtStart
Start time.
mtEnd
End time.
mtOffset
Offset to add to all messages sent to IDirectMusicPerformance8::SendPMsg.
dwFlags
Flags that indicate the state of this call. See DMUS_TRACKF_FLAGS. A value of 0 indicates that this call to Play continues playback from the previous call.
pPerf
Performance used to allocate and send messages.
pSegSt
Segment state that this track belongs to. The IDirectMusicSegmentState8::QueryInterface method can be called to obtain an IDirectMusicGraph8 interface—to call IDirectMusicGraph8::StampPMsg, for instance.
dwVirtualID
Virtual identifier of the track. This value must be put in the dwVirtualTrackID member of any message (see DMUS_PMSG) that is sent by IDirectMusicPerformance8::SendPMsg.

Return Values

If the method succeeds, the return value can be S_OK or DMUS_S_END.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_POINTER

Remarks

If the track is empty, the method returns DMUS_S_END.

Tracks generate messages in a medium-priority thread. You can call time-consuming functions, such as code to stream data from a file, from within a track's Play method. However, be sure to follow the guidelines for safe multithreading.

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicTrack8::PlayEx


IDirectMusicTrack8::PlayEx

Causes the track to play in clock time. It performs any work that the track must do when the segment is played, such as creating and sending messages.

HRESULT PlayEx(
  void* pStateData,
  REFERENCE_TIME rtStart,
  REFERENCE_TIME rtEnd,
  REFERENCE_TIME rtOffset,
  DWORD dwFlags,
  IDirectMusicPerformance* pPerf,
  IDirectMusicSegmentState* pSegSt,
  DWORD dwVirtualID
);

Parameters

pStateData
Pointer to state data from the IDirectMusicTrack8::InitPlay method. The format and use of the data is specific to the track.
rtStart
Start time.
rtEnd
End time.
rtOffset
Offset to add to all messages sent to IDirectMusicPerformance8::SendPMsg.
dwFlags
Flags that indicate the state of this call. See DMUS_TRACKF_FLAGS. A value of zero indicates that this call to PlayEx continues playback from the previous call.
pPerf
Performance used to allocate and send messages.
pSegSt
Segment state that this track belongs to. The IDirectMusicSegmentState8::QueryInterface method can be called to obtain an IDirectMusicGraph8 interface—for instance, to call IDirectMusicGraph8::StampPMsg.
dwVirtualID
Virtual identifier of the track. This value must be put in the dwVirtualTrackID member of any message (see DMUS_PMSG) that is sent by IDirectMusicPerformance8::SendPMsg.

Return Values

If the method succeeds, the return value can be S_OK or DMUS_S_END.

If it fails, the method can return one of the following error values:

DMUS_E_NOT_INIT
E_POINTER

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicTrack8::Play


IDirectMusicTrack8::RemoveNotificationType

Removes an event notification from a track. It is similar to and called from the IDirectMusicSegment8::RemoveNotificationType method.

HRESULT RemoveNotificationType(
  REFGUID rguidNotificationType
);

Parameters

rguidNotificationType
Reference to (C++) or address of (C) the identifier of the notification type to remove. For the defined types, see DMUS_NOTIFICATION_PMSG.

Return Values

If the method succeeds, the return value is S_OK, or S_FALSE if the track does not support the notification type.

If the track does not support notifications, the method returns E_NOTIMPL.

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicTrack8::AddNotificationType, Notification and Event Handling


IDirectMusicTrack8::SetParam

Sets data on a track, in music time.

HRESULT SetParam(
  REFGUID rguidType,
  MUSIC_TIME mtTime,
  void* pParam
);

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to set. See Standard Track Parameters.
mtTime
Time, in track time, at which to set the data.
pParam
Address of a structure containing the data, or NULL if no data is required. The structure must be of the appropriate kind and size for the data type identified by rguidType.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values:

DMUS_E_SET_UNSUPPORTED
DMUS_E_TYPE_DISABLED
E_OUTOFMEMORY
E_POINTER

Remarks

The IDirectMusicTrack8::SetParamEx method can be used for greater functionality.

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicTrack8::GetParam, IDirectMusicTrack8::IsParamSupported, IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::SetParam, Setting and Retrieving Track Parameters


IDirectMusicTrack8::SetParamEx

Sets data on a track, in either clock or music time.

HRESULT SetParamEx(
  REFGUID rguidType,
  REFERENCE_TIME rtTime,
  void* pParam,
  void * pStateData,
  DWORD dwFlags
 );

Parameters

rguidType
Reference to (C++) or address of (C) the identifier of the type of data to set. See Standard Track Parameters.
rtTime
Time at which to set the data. Unless DMUS_TRACK_PARAMF_CLOCK is set in dwFlags, this is in music time.
pParam
Address of a structure that contains the data, or NULL if no data is required. The structure must be of the appropriate kind and size for the data type identified by rguidType.
pStateData
Pointer to a buffer that contains state data for the track.
dwFlags
Can be zero or the following flag.
DMUS_TRACK_PARAMF_CLOCK
The value in rtTime is in clock time.

Return Values

If the method succeeds, the return value is S_OK.

If it fails, the method can return one of the following error values.

DMUS_E_SET_UNSUPPORTED
DMUS_E_TYPE_DISABLED
E_OUTOFMEMORY
E_POINTER

Requirements

Header: Declared in dmplugin.h.

See Also

IDirectMusicTrack8::GetParamEx, IDirectMusicTrack8::SetParam


IKsControl

The IKsControl interface is used to get, set, or query the support of properties, events, and methods. This interface is part of the Windows Driver Model kernel streaming architecture, but is also used by DirectMusic to expose properties of DirectMusic ports. To retrieve this interface, call the IDirectMusicPort8::QueryInterface method with IID_IKsControl in the riid parameter.

Routing of the property item request to the port varies, depending on the port implementation. No properties are supported by ports that represent DirectMusic emulation on top of the Win32 handle-based multimedia calls (midiOut and midiIn functions).

Property item requests to a port that represents a pluggable software synthesizer are answered totally in user mode. The topology of this type of port is a synthesizer (represented by an IDirectMusicSynth interface) connected to a sink node (an IDirectMusicSynthSink interface). The property request is given first to the synthesizer node, and then to the sink node if it is not recognized by the synthesizer.

The interface has the following methods. At present, only KsProperty is supported by DirectMusic.

IKsControl | KsProperty
 | KsEvent
 | KsMethod

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmksctrl.h.

See Also

Property Sets for DirectMusic Ports


IKsControl::KsProperty

Retrieves or sets the value of a property. For an overview, see Property Sets for DirectMusic Ports.

HRESULT KsProperty(
  PKSPROPERTY pProperty,
  ULONG ulPropertyLength,
  LPVOID pvPropertyData,
  ULONG ulDataLength,
  PULONG pulBytesReturned
);

Parameters

pProperty
Address of a KSPROPERTY structure that gives the property set, item, and operation to perform. If this property contains instance data, that data should reside in memory immediately following the structure.
ulPropertyLength
Length of the memory pointed to by pProperty, including any instance data.
pvPropertyData
For a set operation, the address of a memory buffer containing data that represents the new value of the property. For a get operation, the address of a memory buffer big enough to hold the value of the property. For a basic support query, the address of a buffer at least a DWORD in size.
ulDataLength
Length of the buffer pointed to by pvPropertyData.
pulBytesReturned
On a KSPROPERTY_TYPE_GET or KSPROPERTY_TYPE_BASICSUPPORT call, address of a variable that receives the number of bytes returned in pvPropertyData by the port.

Return Values

If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_INVALIDARG
E_NOTIMPL
E_OUTOFMEMORY
E_POINTER
DMUS_E_UNKNOWN_PROPERTY

Requirements

Header: Declared in dmksctrl.h.

See Also

Property Sets for DirectMusic Ports


IReferenceClock

The IReferenceClock interface represents a system reference clock. The DirectMusic master clock and a port's latency clock implement this interface.

The interface has the following methods:

IReferenceClock | GetTime
 | AdviseTime
 | AdvisePeriodic
 | Unadvise

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dmusicc.h.

See Also

IDirectMusic8::GetMasterClock, IDirectMusicPort8::GetLatencyClock, Timing


IReferenceClock::AdvisePeriodic

Requests an asynchronous, periodic notification that a duration has elapsed.

HRESULT AdvisePeriodic(
  REFERENCE_TIME rtStartTime,
  REFERENCE_TIME rtPeriodTime,
  HANDLE hSemaphore,
  DWORD * pdwAdviseCookie
);

Parameters

rtStartTime
Time that the notification should begin.
rtPeriodTime
Period of time between notifications.
hSemaphore
Handle of a semaphore through which to advise.
pdwAdviseCookie
Address of a variable that receives the identifier of the request. This is used to identify this call to AdvisePeriodic in the future—for example, to cancel it.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_POINTER
E_INVALIDARG
E_NOTIMPL

Remarks

When the time indicated by rtStartTime is reached, the semaphore whose handle is set as hSemaphore is released. Thereafter, the semaphore is released repetitively with a period of rtPeriodTime.

Requirements

Header: Declared in dmusicc.h.

See Also

IReferenceClock::Unadvise


IReferenceClock::AdviseTime

Requests an asynchronous notification that a time has elapsed.

HRESULT AdviseTime(
  REFERENCE_TIME rtBaseTime,
  REFERENCE_TIME rtStreamTime,
  HANDLE hEvent,
  DWORD * pdwAdviseCookie
);

Parameters

rtBaseTime
Base reference time.
rtStreamTime
Stream offset time.
hEvent
Handle to an event through which to advise.
pdwAdviseCookie
Address of a variable that receives the identifier of the request. This is used to identify this call to AdviseTime in the future—for example, to cancel it.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_POINTER
E_INVALIDARG
E_NOTIMPL

Remarks

When the time rtBaseTime plus rtStreamTime is reached, the event whose handle is hEvent is set. If the time has already passed, the event is set immediately.

Requirements

Header: Declared in dmusicc.h.

See Also

IReferenceClock::Unadvise


IReferenceClock::GetTime

Retrieves the current time.

HRESULT GetTime(
  REFERENCE_TIME * pTime
);

Parameters

pTime
Address of a variable that receives the current time.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_POINTER
E_INVALIDARG
E_NOTIMPL

Requirements

Header: Declared in dmusicc.h.


IReferenceClock::Unadvise

Cancels a request for notification.

HRESULT Unadvise(
  DWORD dwAdviseCookie
);

Parameters

dwAdviseCookie
Identifier of the request that is to be canceled, as set in the IReferenceClock::AdviseTime or the IReferenceClock::AdvisePeriodic method.

Return Values

Return values are determined by the implementation. If the method succeeds, it returns S_OK.

If it fails, the method can return one of the following error values:

E_FAIL
E_POINTER
E_INVALIDARG
E_NOTIMPL

Requirements

Header: Declared in dmusicc.h.


DirectMusic Messages

DirectMusic message structures are all based on the DMUS_PMSG structure. Because C does not support inheritance, the members of this structure are included in each derived structure as the DMUS_PMSG_PART macro.

For an overview of messages, see Using DirectMusic Messages.

This section contains information about the following structures used to contain message information:

  • DMUS_PMSG
  • DMUS_CHANNEL_PRIORITY_PMSG
  • DMUS_CURVE_PMSG
  • DMUS_LYRIC_PMSG
  • DMUS_MIDI_PMSG
  • DMUS_NOTE_PMSG
  • DMUS_NOTIFICATION_PMSG
  • DMUS_PATCH_PMSG
  • DMUS_SYSEX_PMSG
  • DMUS_TEMPO_PMSG
  • DMUS_TIMESIG_PMSG
  • DMUS_TRANSPOSE_PMSG
  • DMUS_WAVE_PMSG

See Also

IDirectMusicPerformance8::AllocPMsg, IDirectMusicPerformance8::SendPMsg, IDirectMusicPerformance8::FreePMsg, IDirectMusicTool8::ProcessPMsg


DMUS_PMSG

Contains information common to all DirectMusic messages. Because C does not support inheritance, the members of this structure are contained in all message types (including DMUS_PMSG itself) as the DMUS_PMSG_PART macro, which expands to the syntax shown here.

typedef struct DMUS_PMSG {
    DWORD              dwSize;
    REFERENCE_TIME     rtTime;
    MUSIC_TIME         mtTime;
    DWORD              dwFlags;
    DWORD              dwPChannel;
    DWORD              dwVirtualTrackID;
    IDirectMusicTool*  pTool;
    IDirectMusicGraph* pGraph;
    DWORD              dwType;
    DWORD              dwVoiceID;
    DWORD              dwGroupID;
    IUnknown*          punkUser;
} DMUS_PMSG;
dwSize
Size of the structure, in bytes. This member is initialized by IDirectMusicPerformance8::AllocPMsg.
rtTime
Reference time at which the message is to be played, modified by dwFlags. Used only if DMUS_PMSGF_REFTIME is present in dwFlags.
mtTime
Music time at which the message is to be played, modified by dwFlags. Used only if DMUS_PMSGF_MUSICTIME is present in dwFlags.
dwFlags
Flags from the DMUS_PMSGF_FLAGS or DMUS_TIME_RESOLVE_FLAGS enumeration. Must contain DMUS_PMSGF_REFTIME or DMUS_PMSGF_MUSICTIME.
dwPChannel
Performance channel (PChannel). The port, channel group, and MIDI channel can be derived from this value by using the IDirectMusicPerformance8::PChannelInfo method. Set this value to 0 for messages that are not channel-specific, such as tempo messages. To send the message to more than channel, use one of the following values.
DMUS_PCHANNEL_BROADCAST_AUDIOPATH
Send a copy of the message to all channels of the audiopath.
DMUS_PCHANNEL_BROADCAST_GROUPS
Send a copy of the message to each channel group in the performance. Used for messages that need to be sent only once per channel group, such as system exclusive messages.
DMUS_PCHANNEL_BROADCAST_PERFORMANCE
Send a copy of the message to all channels of the performance.
DMUS_PCHANNEL_BROADCAST_SEGMENT
Send a copy of the message to all channels of the segment.
dwVirtualTrackID
Identifier of the track. Set to 0 if the message is not being sent by a track.
pTool
Address of the tool interface. Can be set by using IDirectMusicGraph8::StampPMsg, or can be NULL if the message is not to go to tools other than the output tool.
pGraph
Address of the tool graph interface. Can be set by using IDirectMusicGraph8::StampPMsg, or can be NULL if the message is not to go to tools other than the output tool.
dwType
Message type (see DMUS_PMSGT_TYPES).
dwVoiceID
Reserved. Must be 0.
dwGroupID
Identifier of the track group or groups that the message belongs to if the message is being generated by a track. (Tracks are assigned to groups in the IDirectMusicSegment8::InsertTrack method.) For most purposes, this value can be 0xFFFFFFF.
punkUser
Address of an IUnknown interface supplied by the application. This pointer is always released when the message is freed. If the application wants to retain the object, it should call AddRef before the message is freed. If the message does not need a COM pointer, this value should be NULL.

Remarks

The DMUS_PMSG structure is used by itself for messages containing the following values in the dwType member:

DMUS_PMSGT_STOP
Sending a message of this type stops the performance at the specified time.
DMUS_PMSGT_DIRTY
When a control segment starts or ends, all tools in the segment and performance graphs receive a message of this type, indicating that if they cache data from get-parameter calls, they must call the method again to refresh their data. Tools that want to receive this message type must indicate this through a call to IDirectMusicTool8::GetMediaTypes. Tools in the performance graph receive one copy of the message for each segment in the performance. Such tools can safely ignore the extra messages with the same time stamp.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SendPMsg


DMUS_CHANNEL_PRIORITY_PMSG

Contains message data about a channel priority change.

typedef struct _DMUS_CHANNEL_PRIORITY_PMSG {
    DMUS_PMSG_PART
    DWORD dwChannelPriority;
} DMUS_CHANNEL_PRIORITY_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
dwChannelPriority
Priority of the channel. For a list of defined values, see the Remarks for IDirectMusicPort8::GetChannelPriority.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPort8::SetChannelPriority, IDirectMusicPerformance8::SendPMsg


DMUS_CURVE_PMSG

Contains message data for a curve.

typedef struct DMUS_CURVE_PMSG {
    DMUS_PMSG_PART
    MUSIC_TIME mtDuration;
    MUSIC_TIME mtOriginalStart;
    MUSIC_TIME mtResetDuration;
    short      nStartValue;
    short      nEndValue;
    short      nResetValue;
    WORD       wMeasure;
    short      nOffset;
    BYTE       bBeat;
    BYTE       bGrid;
    BYTE       bType;
    BYTE       bCurveShape;
    BYTE       bCCData;
    BYTE       bFlags;
    WORD       wParamType;
    WORD       wMergeIndex;
} DMUS_CURVE_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
mtDuration
Duration of the curve. This value is in music time unless DMUS_PMSGF_LOCKTOREFTIME is present in the dwFlags member of DMUS_PMSG_PART, in which case it is in milliseconds and is unaffected by a change in tempo.
mtOriginalStart
Original start time. Must be set to either 0 when this message is created, or to the original start time of the curve.
mtResetDuration
Length of time after the end of the curve during which a reset can take place in response to an invalidation. Ignored if DMUS_CURVE_RESET is not in bFlags. This value is in music time unless DMUS_PMSGF_LOCKTOREFTIME is present in the dwFlags member of DMUS_PMSG_PART, in which case it is in milliseconds and is unaffected by a change in tempo.
nStartValue
Start value of the curve.
nEndValue
End value of the curve.
nResetValue
Value to set upon a flush or invalidation. Ignored if DMUS_CURVE_RESET is not in bFlags.
wMeasure
Measure in which this curve occurs.
nOffset
Offset from the grid at which this curve occurs, in music time.
bBeat
Beat count (within a measure) at which this curve occurs.
bGrid
Grid offset from the beat at which this curve occurs.
bType
Type of curve. This can be one of the following values:
DMUS_CURVET_CCCURVE
Continuous controller curve (MIDI Control Change channel voice message; status byte &HBn.).
DMUS_CURVET_MATCURVE
Monophonic aftertouch curve (MIDI Channel Pressure channel voice message; status byte &HDn).
DMUS_CURVET_PATCURVE
Polyphonic aftertouch curve (MIDI Poly Key Pressure channel voice message, status byte &HDn).
DMUS_CURVET_PBCURVE
Pitch-bend curve (MIDI Pitch Bend channel voice message; status byte &HEn).
DMUS_CURVET_RPNCURVE
RPN curve of type defined in wParamType.
DMUS_CURVET_NRPNCURVE
NRPN curve of type defined in wParamType.
bCurveShape
Shape of curve. This can be one of the following values:
DMUS_CURVES_EXP
Exponential curve shape.
DMUS_CURVES_INSTANT
Instant curve shape (beginning and end of curve happen at essentially the same time).
DMUS_CURVES_LINEAR
Linear curve shape.
DMUS_CURVES_LOG
Logarithmic curve shape.
DMUS_CURVES_SINE
Sine curve shape.
bCCData
Controller number, if bType is DMUS_CURVET_CCCURVE.
bFlags
Can be zero, or one or more of the following values.
DMUS_CURVE_RESET
The value of nResetValue must be set when the time is reached or an invalidation occurs because of a transition. If this flag is not set, the curve stays permanently at the new value.
DMUS_CURVE_START_FROM_CURRENT
Ignore nStartValue and start the curve at the current value. Implemented for volume, expression, pitch bend, filter cuttoff, pan, and mod wheel. See Remarks.
wParamType
MIDI parameter number. This value is significant only if DMUS_PMSGF_DX8 is present in the dwFlags member of the DMUS_PMSG part of this structure. See Remarks.
wMergeIndex
Merge index. Supported for pitch bend, volume, and expression controllers. This value is significant only if DMUS_PMSGF_DX8 is present in the dwFlags member of the DMUS_PMSG part of this structure. See Remarks.

Remarks

An RPN or NRPN curve type in wParamType is stored as two bytes with seven significant bits. For example, if the MSB is 0x23 and the LSB is 0x74, the value in wParamType is 0x2374.

Data in nStartValue, nEndValue, and nResetValue is limited to 14 bits. For MIDI data consisting of two seven-bit bytes, the value is stored as a word with the upper two bits empty.

All curves with wMergeIndex of 0 override each other. If wMergeIndex is another value, the values generated by the curve are added to the values for merge index 0. For example, if an application uses curves with 0 and 3, the 0 curves always replace each other but add to the 3 curves, and the 3 curves also always replace each other and add to the 0 curves.

The DMUS_CURVE_START_FROM_CURRENT flag does not cause the current controller value to be saved in the message. Therefore tools do not have access to this data unless they store the last known value.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SendPMsg, Curves


DMUS_LYRIC_PMSG

Contains message data for a string.

typedef struct _DMUS_LYRIC_PMSG {
    DMUS_PMSG_PART
    WCHAR  wszString[1];
} DMUS_LYRIC_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
wszString
Null-terminated Unicode string. The array is sized when the message is created.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SendPMsg


DMUS_MIDI_PMSG

Contains data for a standard MIDI message such as a control change or pitch bend.

typedef struct DMUS_MIDI_PMSGG {
    DMUS_PMSG_PART
    BYTE  bStatus;
    BYTE  bByte1;
    BYTE  bByte2;
    BYTE  bPad[1];
} DMUS_MIDI_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
bStatus
Standard MIDI status byte.
bByte1
First byte of the MIDI message. Ignored for MIDI messages that do not require it.
bByte2
Second byte of the MIDI message. Ignored for MIDI messages that do not require it.
bPad
Padding to a WORD boundary.

Requirements

Header: Declared in dmusici.h.

See Also

MIDI Messages, IDirectMusicPerformance8::SendPMsg


DMUS_NOTE_PMSG

Contains message data for a MIDI note.

typedef struct DMUS_NOTE_PMSG {
    DMUS_PMSG_PART
    MUSIC_TIME mtDuration;
    WORD       wMusicValue;
    WORD       wMeasure;
    short      nOffset;
    BYTE       bBeat;
    BYTE       bGrid;
    BYTE       bVelocity;
    BYTE       bFlags;
    BYTE       bTimeRange;
    BYTE       bDurRange;
    BYTE       bVelRange;
    BYTE       bPlayModeFlags;
    BYTE       bSubChordLevel;
    BYTE       bMidiValue;
    char       cTranspose;
} DMUS_NOTE_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
mtDuration
Duration of the note.
wMusicValue
Description of the note. In most play modes, this is a packed array of 4-bit values, as follows:
Octave
In the range from –2 through 14. The note is transposed up or down by the octave times 12.
Chord position
In the range from 0 through 15, although it should never be above 3. The first position in the chord is 0.
Scale position
In the range from 0 through 15. Typically it is only from 0 through 2, but it is possible to have a one-note chord and have everything above the chord be interpreted as a scale position.
Accidental
In the range from –8 through 7, but typically in the range from –2 through 2. This represents an offset that takes the note out of the scale.

In the fixed-play modes, the music value is a MIDI note value in the range from 0 through 127.

wMeasure
Measure in which this note occurs.
nOffset
Offset from the grid at which this note occurs, in music time.
bBeat
Beat (in measure) at which this note occurs.
bGrid
Grid offset from the beat at which this note occurs.
bVelocity
Note velocity.
bFlags
See DMUS_NOTEF_FLAGS.
bTimeRange
Range by which to randomize time.
bDurRange
Range by which to randomize duration.
bVelRange
Range by which to randomize velocity.
bPlayModeFlags
Play mode determining how the music value is related to the chord and subchord. For a list of values, see DMUS_PLAYMODE_FLAGS.
bSubChordLevel
Subchord level that the note uses. See DMUS_SUBCHORD.
bMidiValue
MIDI note value, converted from wMusicValue.
cTranspose
Transposition to add to bMidiValue after conversion from wMusicValue.

Remarks

When the output tool receives a message with DMUS_NOTEF_NOTEON in bFlags, it sends a MIDI note-on message to the synthesizer. It then clears the DMUS_NOTEF_NOTEON flag, adds mtDuration to the time stamp, and requeues the message so that the note is turned off at the appropriate time.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SendPMsg, Music Values and MIDI Notes


DMUS_NOTIFICATION_PMSG

Contains message data for a notification.

typedef struct DMUS_NOTIFICATION_PMSG {
    DMUS_PMSG_PART
    GUID   guidNotificationType;
    DWORD  dwNotificationOption;
    DWORD  dwField1;
    DWORD  dwField2;
} DMUS_NOTIFICATION_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
guidNotificationType
Identifier of the notification type. The following types are defined:
GUID_NOTIFICATION_CHORD
Chord change.
GUID_NOTIFICATION_COMMAND
Command event.
GUID_NOTIFICATION_MEASUREANDBEAT
Measure and beat event.
GUID_NOTIFICATION_PERFORMANCE
Performance event, further defined in dwNotificationOption.
GUID_NOTIFICATION_RECOMPOSE
A track has been recomposed. In the current version, this is always a chord track.
GUID_NOTIFICATION_SEGMENT
Segment event, further defined in dwNotificationOption.
dwNotificationOption
Identifier of the notification subtype.

If the notification type is GUID_NOTIFICATION_SEGMENT, this member can contain one of the following values:

DMUS_NOTIFICATION_SEGABORT
The segment was stopped prematurely, or was removed from the primary segment queue.
DMUS_NOTIFICATION_SEGALMOSTEND
The segment has reached the end minus the prepare time.
DMUS_NOTIFICATION_SEGEND
The segment has ended.
DMUS_NOTIFICATION_SEGLOOP
The segment has looped.
DMUS_NOTIFICATION_SEGSTART
The segment has started.

If the notification type is GUID_NOTIFICATION_COMMAND, this member can contain one of the following values:

DMUS_NOTIFICATION_GROOVE
Groove level change.
DMUS_NOTIFICATION_EMBELLISHMENT
Embellishment command (intro, fill, break, or end).

If the notification type is GUID_NOTIFICATION_PERFORMANCE, this member can contain one of the following values:

DMUS_NOTIFICATION_MUSICALMOSTEND
The currently playing primary segment has reached the end minus the prepare time, and no more primary segments are cued to play.
DMUS_NOTIFICATION_MUSICSTARTED
Playback has started.
DMUS_NOTIFICATION_MUSICSTOPPED
Playback has stopped.

If the notification type is GUID_NOTIFICATION_MEASUREANDBEAT, this member contains DMUS_NOTIFICATION_MEASUREBEAT. No other subtypes are defined.

If the notification type is GUID_NOTIFICATION_CHORD, this member contains DMUS_NOTIFICATION_CHORD. No other subtypes are defined.

If the notification type is GUID_NOTIFICATION_RECOMPOSE, this member contains DMUS_NOTIFICATION_RECOMPOSE. No other subtypes are defined.

dwField1
Extra data specific to the type of notification. For GUID_NOTIFICATION_MEASUREANDBEAT notifications, this member returns the beat number within the measure.
dwField2
Extra data specific to the type of notification. Reserved for future or application-defined use.

Remarks

For most notifications, the punkUser member (see DMUS_PMSG) contains the IUnknown pointer of the segment state. This is especially useful in the cases of chords and commands, in which you can query for the IDirectMusicSegmentState8 interface, call IDirectMusicSegmentState8::GetSegment to get the IDirectMusicSegment8 pointer, and then call the IDirectMusicSegment8::GetParam method to get the chord or command at the time given in the notification message's mtTime member.

For notifications of type GUID_NOTIFICATION_PERFORMANCE, the punkUser member is always NULL.

Applications can define their own notification message types and subtypes and use dwField1 and dwField2 for extra data. Such custom notification messages can be allocated and sent like any other message. Application-defined tracks can send messages of a particular type after the GUID (guidNotificationType) has been handed to IDirectMusicTrack8::AddNotificationType.

Requirements

Header: Declared in dmusici.h.

See Also

Notification and Event Handling, IDirectMusicPerformance8::SendPMsg


DMUS_PATCH_PMSG

Contains message data for a MIDI program change.

typedef struct DMUS_PATCH_PMSG {
    DMUS_PMSG_PART
    BYTE  byInstrument;
    BYTE  byMSB;
    BYTE  byLSB;
    BYTE  byPad[1];
} DMUS_PATCH_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
byInstrument
Patch number of the instrument.
byMSB
Most significant byte of bank select.
byLSB
Least significant byte of bank select.
byPad
Padding to a WORD boundary. This value is ignored.

Requirements

Header: Declared in dmusici.h.

See Also

DMUS_MIDI_PMSG, IDirectMusicPerformance8::SendPMsg, MIDI Messages


DMUS_SYSEX_PMSG

Contains data for a MIDI system exclusive message.

typedef struct DMUS_SYSEX_PMSG {
    DMUS_PMSG_PART
    DWORD dwLen;
    BYTE  abData[1];
} DMUS_SYSEX_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
dwLen
Length of the data, in bytes.
abData
Array of data. For an example of how to allocate memory and copy data to this member, see the Remarks for IDirectMusicPerformance8::SendPMsg.

Remarks

The data part of a system exclusive message must begin with the System Exclusive identifier (0xF0) and end with EOX (0xF7).

Requirements

Header: Declared in dmusici.h.

See Also

DMUS_MIDI_PMSG, DMUS_PATCH_PMSG, MIDI Messages, IDirectMusicPerformance8::SendPMsg


DMUS_TEMPO_PMSG

Contains data for a message that controls the performance's tempo.

typedef struct DMUS_TEMPO_PMSG {
    DMUS_PMSG_PART
    double dblTempo;
} DMUS_TEMPO_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
dblTempo
Tempo, in the range from DMUS_TEMPO_MIN through DMUS_TEMPO_MAX.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SendPMsg


DMUS_TIMESIG_PMSG

Contains data for a message that controls the time signature of the performance.

typedef struct _DMUS_TIMESIG_PMSG {
    DMUS_PMSG_PART
    BYTE bBeatsPerMeasure;
    BYTE bBeat;
    WORD wGridsPerBeat;
} DMUS_TIMESIG_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
bBeatsPerMeasure
Beats per measure (top of the time signature).
bBeat
Note that receives the beat (bottom of the time signature), where 1 is a whole note, 2 is a half note, 4 is a quarter note, and so on. Zero is a 256th note.
wGridsPerBeat
Grids (subdivisions) per beat. This value determines the timing resolution for certain music events—for example, segments cued with the DMUS_SEGF_GRID flag (see DMUS_SEGF_FLAGS).

Remarks

Time signature messages are generated by the time signature track and the style track. In general, a segment contains one or the other, but not both. A segment representing a MIDI file has a time signature track, but most segments authored with an application such as DirectMusic Producer contain time signature information in the style track.

By default, only the primary segment sends time signature messages. For information on how to change this behavior, see Disabling and Enabling Track Parameters.

The time signature is used by the performance to resolve time to measure, beat, and grid boundaries in all methods in which the time can be adjusted by DMUS_SEGF_FLAGS or DMUS_TIME_RESOLVE_FLAGS. The time signature and style tracks also use the time signature to generate notifications on measure and beat boundaries. See DMUS_NOTIFICATION_PMSG.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SendPMsg, DMUS_TIMESIGNATURE


DMUS_TRANSPOSE_PMSG

Contains message data for a transposition.

typedef struct _DMUS_TRANSPOSE_PMSG {
    DMUS_PMSG_PART
    short nTranspose;
    WORD wMergeIndex;
} DMUS_TRANSPOSE_PMSG;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG.
nTranspose
Number of semitones by which to transpose. This can be a negative value.
wMergeIndex
Merge index. When a transpose message follows a preceding message with the same wMergeIndex, the value in nTranspose becomes the new setting. When the second transpose message has a different wMergeIndex, the value in nTranspose is added to the previous setting. This member is significant only if DMUS_PMSGF_DX8 is present in the dwFlags member of the DMUS_PMSG part of this structure.

Remarks

If the transposition of a note puts it outside the standard MIDI range from 0 through 127, it does not play.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SendPMsg


DMUS_WAVE_PMSG

Contains message data for a wave sound.

typedef struct _DMUS_WAVE_PMSG {
    DMUS_PMSG_PART
    REFERENCE_TIME rtStartOffset;
    REFERENCE_TIME rtDuration;
    long    lOffset;
    long    lVolume;
    long    lPitch;
    BYTE    bFlags;
} DMUS_WAVE_PMSG;
;
DMUS_PMSG_PART
Macro for common message members. See DMUS_PMSG. The punkUser member contains the address of the IUnknown interface of the voice object associated with the wave.
rtStartOffset
How far into the wave to start, in reference time units only.
rtDuration
Duration of the wave. If DMUS_PMSGF_LOCKTOREFTIME is present in the dwFlags member of DMUS_PMSG_PART, this value is in reference time units. Otherwise it is in music time.
lOffset
Offset from actual time to logical time, in either reference or music time.
lVolume
Initial volume, in hundredths of a decibel.
lPitch
Transposition of the pitch, in hundredths of a semitone.
bFlags
Can be zero or the following value.
DMUS_WAVEF_NOINVALIDATE
Do not invalidate this wave.
DMUS_WAVEF_OFF
This message is stopping playback of the wave.
DMUS_WAVEF_STREAMING
Wave is streaming.

Remarks

Applications cannot send messages of this type by using IDirectMusicPerformance8::SendPMsg, because they have no way of obtaining a pointer to a wave object. However, tools can process wave messages.

Requirements

Header: Declared in dmusici.h.


DirectMusic Structures

This section contains reference information for the following run-time structures used in DirectMusic:

  • DMUS_AUDIOPARAMS
  • DMUS_BAND_PARAM
  • DMUS_BUFFERDESC
  • DMUS_CHORD_KEY
  • DMUS_CHORD_PARAM
  • DMUS_CLOCKINFO8
  • DMUS_COMMAND_PARAM
  • DMUS_COMMAND_PARAM_2
  • DMUS_CONNECTION_RULE
  • DMUS_EVENTHEADER
  • DMUS_MUTE_PARAM
  • DMUS_NOTERANGE
  • DMUS_OBJECTDESC
  • DMUS_PLAY_MARKER_PARAM
  • DMUS_PORTCAPS
  • DMUS_PORTPARAMS8
  • DMUS_RHYTHM_PARAM
  • DMUS_SCRIPT_ERRORINFO
  • DMUS_SUBCHORD
  • DMUS_SYNTHSTATS8
  • DMUS_TEMPO_PARAM
  • DMUS_TIMESIGNATURE
  • DMUS_VALID_START_PARAM
  • DMUS_VARIATIONS_PARAM
  • DMUS_VERSION
  • DMUS_WAVES_REVERB_PARAMS
  • KSPROPERTY

Special categories of structures are contained in the following sections:

  • DirectMusic Messages
  • DirectMusic File Structures
  • DLS Structures


DMUS_AUDIOPARAMS

Describes required resources for the default synthesizer and buffers of a performance. Passed to the IDirectMusicPerformance8::InitAudio method to request desired features and to receive information about what requests were granted.

typedef struct _DMUS_AUDIOPARAMS {
    DWORD  dwSize;
    BOOL   fInitNow;
    DWORD  dwValidData;
    DWORD  dwFeatures;
    DWORD  dwVoices;
    DWORD  dwSampleRate;
    CLSID  clsidDefaultSynth;
} DMUS_AUDIOPARAMS;
dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
fInitNow
Boolean value that specifies whether the sink and synthesizer are created immediately. If so, results are returned in this structure.
dwValidData
Flags that specify which members of this structure are valid. If fInitNow is TRUE when the structure is passed, this member receives flags that specify what members received data. The following values are defined.
DMUS_AUDIOPARAMS_FEATURES
The dwFeatures member contains or has received data.
DMUS_AUDIOPARAMS_VOICES
The dwVoices member contains or has received data.
DMUS_AUDIOPARAMS_SAMPLERATE
The dwSampleRate member contains or has received data.
DMUS_AUDIOPARAMS_DEFAULTSYNTH
The clsidDefaultSynth member contains or has received data. If this flag is not set, the Microsoft software synthesizer is the default synthesizer.
dwFeatures
Flags that specify required capabilities. The following values are defined.
DMUS_AUDIOF_3D
3-D buffers.
DMUS_AUDIOF_ALL
Combination of all other flags.
DMUS_AUDIOF_BUFFERS
Multiple buffers. Always set this flag when using audiopaths.
DMUS_AUDIOF_ENVIRON
Environmental modeling.
DMUS_AUDIOF_EAX
EAX effects.
DMUS_AUDIOF_DMOS
Additional DMOs.
DMUS_AUDIOF_STREAMING
Support for streaming waves.
dwVoices
Number of voices. The default value is 64.
dwSampleRate
Sample rate of sink and synthesizer, in the range from 11,025 to 96,000 kHz. The default value is 22,050.
clsidDefaultSynth
Class identifier of the default synthesizer. This is the synthesizer used by standard audiopaths and audiopaths created from configurations that request the default synthesizer.

Requirements

Header: Declared in dmusicf.h.


DMUS_BAND_PARAM

Used as the pParam parameter in calls to the various get-parameter and set-parameter methods when the track is a band track and rguidType is GUID_BandParam.

typedef struct _DMUS_BAND_PARAM {
    MUSIC_TIME mtTimePhysical;
    IDirectMusicBand *pBand;
} DMUS_BAND_PARAM;

Members

mtTimePhysical
Actual time at which the band change will be made. See Remarks.
pBand
Address of the IDirectMusicBand8 interface of the band.

Remarks

The value in mtTimePhysical is the actual time at which the band change will be made, whereas the value in the mtTime parameter of the set-parameter method is the point in the performance where the change belongs, for example, synchronized with a beat or measure. You can set mtTimePhysical to a time slightly before mtTime to ensure that notes are always played by the correct band, even when a band change is made at the start of a loop.

If the track is a clock-time track, mtTimePhysical is interpreted in the track's internal time format. This is the number of milliseconds after the beginning of playback. Because this can be confusing, it is recommended that GUID_BandParam not be used with clock-time tracks.

Requirements

Header: Declared in dmusicf.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicSegment8::SetParam, IDirectMusicTrack8::GetParamEx, IDirectMusicTrack8::SetParamEx, Performance Parameters


DMUS_BUFFERDESC

Used to describe a buffer for the IDirectMusic8::CreateMusicBuffer method.

typedef struct _DMUS_BUFFERDESC {
    DWORD dwSize;
    DWORD dwFlags;
    GUID  guidBufferFormat;
    DWORD cbBuffer;
} DMUS_BUFFERDESC, *LPDMUS_BUFFERDESC;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
dwFlags
No flags are defined.
guidBufferFormat
Identifier of the KS format of the buffer. The value GUID_NULL represents KSDATAFORMAT_SUBTYPE_DIRECTMUSIC.

If guidBufferFormat represents a KS format other than KSDATAFORMAT_SUBTYPE_DIRECTMUSIC, the application must verify that the port playing back the data understands the specified format; if not, the buffer is ignored. To find out whether the port supports a specific KS format, use the IKsControl::KsProperty method.

cbBuffer
Minimum size of the buffer, in bytes. The amount of memory allocated can be slightly higher because the system pads the buffer to a multiple of 4 bytes. The buffer must be at least 32 bytes to accommodate a single MIDI channel message, and at least 28 bytes plus the size of the data to accommodate a system exclusive message or other unstructured data.

Requirements

Header: Declared in dmusici.h.

See Also

DMUS_EVENTHEADER, IDirectMusicBuffer8::PackStructured, IDirectMusicBuffer8::PackUnstructured


DMUS_CHORD_KEY

Used to describe a chord in the IDirectMusicPerformance8::MIDIToMusic and IDirectMusicPerformance8::MusicToMIDI methods.

typedef struct _DMUS_CHORD_KEY {
    WCHAR         wszName[16];
    WORD          wMeasure;
    BYTE          bBeat;
    BYTE          bSubChordCount;
    DMUS_SUBCHORD SubChordList[DMUS_MAXSUBCHORD];
    DWORD         dwScale;
    BYTE          bKey;
    BYTE          bFlags;
} DMUS_CHORD_KEY;

Members

wszName
Name of the chord.
wMeasure
Measure that the chord falls on.
bBeat
Beat that the chord falls on.
bSubChordCount
Number of chords in the chord's list of subchords.
SubChordList
Array of DMUS_SUBCHORD structures, describing the components that make up the chord.
dwScale
Scale underlying the entire chord.
bKey
Key underlying the entire chord.
bFlags
Can be zero, or DMUS_CHORDKEYF_SILENT if the chord is silent. See Remarks.

Remarks

This structure is also defined as a DMUS_CHORD_PARAM structure for use in setting and retrieving the GUID_ChordParam track parameter.

If a chord is flagged as a silent chord, it is not taken into consideration when a pattern is selected to be played. For instance, if there is a chord change on beat 1 and the silent chord is on beat 3, a pattern with a whole measure chord rhythm can still be played.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicSegment8::SetParam, IDirectMusicTrack8::GetParamEx, IDirectMusicTrack8::SetParamEx, Performance Parameters


DMUS_CHORD_PARAM

Used as the pParam parameter in calls to the various get-parameter and set-parameter methods when the track is a chord track and rguidType is GUID_ChordParam.

typedef DMUS_CHORD_KEY DMUS_CHORD_PARAM;

See DMUS_CHORD_KEY.

Requirements

Header: Declared in dmusicf.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicSegment8::SetParam, IDirectMusicTrack8::GetParamEx, IDirectMusicTrack8::SetParamEx, Performance Parameters


DMUS_CLOCKINFO8

Reports information about a clock enumerated by using the IDirectMusic8::EnumMasterClock method.

typedef struct _DMUS_CLOCKINFO{
    DWORD           dwSize;
    DMUS_CLOCKTYPE  ctType;
    GUID            guidClock;
    WCHAR           wszDescription[DMUS_MAX_DESCRIPTION];
    DWORD           dwFlags;
} DMUS_CLOCKINFO8, *LPDMUS_CLOCKINFO8;

typedef DMUS_CLOCKINFO8 DMUS_CLOCKINFO;
typedef DMUS_CLOCKINFO *LPDMUS_CLOCKINFO;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is passed to a method.
ctType
Member of the DMUS_CLOCKTYPE enumeration specifying the type of clock.
guidClock
Identifier of the clock. This value can be passed to the IDirectMusic8::SetMasterClock method to set the master clock for DirectMusic.
wszDescription
Description of the clock.
dwFlags
Flags.

Requirements

Header: Declared in dmusici.h.


DMUS_COMMAND_PARAM

Used as the pParam parameter in calls to various get-parameter and set-parameter methods when the track is a command track and the rguidType parameter is GUID_CommandParam.

typedef struct {
    BYTE bCommand;
    BYTE bGrooveLevel;
    BYTE bGrooveRange;
    BYTE bRepeatMode;
} DMUS_COMMAND_PARAM;

Members

bCommand
Command type. See DMUS_COMMANDT_TYPES.
bGrooveLevel
Groove level of the command. The groove level is a value in the range from 1 through 100.
bGrooveRange
Amount by which the groove level can be randomized. For instance, if the groove level is 35 and the range is 4, the actual groove level could be anywhere from 33 through 37. If bGrooveRange is an odd number, 1 is subtracted from it.
bRepeatMode
Flag that specifies how patterns are selected for repetition. See DMUS_PATTERNT_TYPES.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicSegment8::SetParam, IDirectMusicTrack8::GetParamEx, IDirectMusicTrack8::SetParamEx


DMUS_COMMAND_PARAM_2

Used as the pParam parameter in calls to various get-parameter and set-parameter methods when the track is a command track and the rguidType parameter is GUID_CommandParam2.

typedef struct _DMUS_COMMAND_PARAM_2 {
    MUSIC_TIME mtTime;
    BYTE bCommand;
    BYTE bGrooveLevel;
    BYTE bGrooveRange;
    BYTE bRepeatMode;
} DMUS_COMMAND_PARAM_2;

Members

mtTime
Time of the command.
bCommand
Command type. See DMUS_COMMANDT_TYPES.
bGrooveLevel
Groove level of the command. The groove level is a value in the range from 1 through 100.
bGrooveRange
Amount by which the groove level can be randomized. For instance, if the groove level is 35 and the range is 4, the groove level could be anywhere from 33 through 37. If bGrooveRange is an odd number, 1 is subtracted from it.
bRepeatMode
Flag that specifies how patterns are selected for repetition. See DMUS_PATTERNT_TYPES.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicSegment8::SetParam, IDirectMusicTrack8::GetParamEx, IDirectMusicTrack8::SetParamEx


DMUS_CONNECTION_RULE

Not implemented in DirectX 8.0.

Used in the ConnectionArc member of the DMUS_MELODY_FRAGMENT to specify rules for allowing fragments to flow smoothly from one to another.

typedef struct _DMUS_CONNECTION_RULE {
    DWORD       dwFlags;
    DWORD       dwIntervals;
} DMUS_CONNECTION_RULE;

Members

dwFlags
Flags that specify the connection rules. Can contain zero or more of the following values.
DMUS_CONNECTIONF_INTERVALS
Use the intervals in dwIntervals between the last note of one variation and the first note of the next.
DMUS_CONNECTIONF_OVERLAP
If the two fragments overlap, the first note not played in the first fragment is the same as the first note in the second fragment.
dwIntervals
If DMUS_CONNECTIONF_INTERVALS is set, specifies a set of legal intervals between the last note played in the first fragment and the first note in the second fragment. Each of the lower 24 bits is an interval in a two-octave range.

Requirements

Header: Declared in dmusici.h.


DMUS_EVENTHEADER

Precedes and describes an event in a port buffer.

typedef struct _DMUS_EVENTHEADER {
    DWORD           cbEvent;
    DWORD           dwChannelGroup;
    REFERENCE_TIME  rtDelta;
    DWORD           dwFlags;
} DMUS_EVENTHEADER, *LPDMUS_EVENTHEADER;

Members

cbEvent
Number of bytes in the event.
dwChannelGroup
Group to which the event belongs.
rtDelta
Offset from the start time of the buffer.
dwFlags
Set to DMUS_EVENT_STRUCTURED if the event is parsable MIDI data.

Remarks

The Pshpack4.h header file is included before the declaration of this structure to turn off automatic alignment of structures so that the data immediately follows the header. (For more information, see the comments in Pshpack4.h.) Poppack.h is then included to turn alignment back on, and the entire structure (header plus event) is padded to an 8-byte boundary.

Requirements

Header: Declared in dmusbuff.h.

See Also

IDirectMusicBuffer8::GetNextEvent, IDirectMusicBuffer8::PackStructured, IDirectMusicBuffer8::PackUnstructured


DMUS_MELODY_FRAGMENT

Not implemented in DirectX 8.0.

Describes a fragment in a melody formulation track. A melody fragment is used to select a variation from a pattern during melody composition.

typedef struct _DMUS_MELODY_FRAGMENT {
    MUSIC_TIME  mtTime;
    DWORD  dwID;
    WCHAR  wszVariationLabel[DMUS_MAX_FRAGMENTLABEL];
    DWORD  dwVariationFlags;
    DWORD  dwRepeatFragmentID;
    DWORD  dwFragmentFlags;
    DWORD  dwPlayModeFlags;
    DWORD  dwTransposeIntervals;
    DMUS_COMMAND_PARAM   Command;
    DMUS_CONNECTION_RULE ConnectionArc;
} DMUS_MELODY_FRAGMENT;

Members

mtTime
Time at which the fragment is to play, relative to the beginning of the track.
dwID
Identifier of the track.
wszVariationLabel
Reserved.
dwVariationFlags
DWORD value that specifies the set of allowable variations, where each bit set represents one variation. Ignored if DMUS_FRAGMENTF_USE_REPEAT is included in dwFragmentFlags.
dwRepeatFragmentID
Identifier of an earlier fragment in the track from which to select a variation. Ignored unless DMUS_FRAGMENTF_USE_REPEAT is included in dwFragmentFlags.
dwFragmentFlags
Can contain any of the following values.
DMUS_FRAGMENTF_USE_REPEAT
Use the fragment specified in dwRepeatFragmentID.
DMUS_FRAGMENTF_REJECT_REPEAT
Use a new variation of the earlier fragment.
DMUS_FRAGMENTF_USE_LABEL
Use the set named by wszVariationLabel. Not supported.
dwPlayModeFlags
Reserved. Must be 0.
dwTransposeIntervals
The lower 24 bits each represent an interval in a two-octave range. Specifies a set of intervals by which the notes in a repeated fragment can be transposed to fit the current chord or key. The lower 24 bits each represent an interval in a two-octave range.
Command
DMUS_COMMAND_PARAM structure that specifies the type of pattern to use as the source for the melody.
ConnectionArc
DMUS_CONNECTION_RULE structure that specifies rules for allowing fragments to flow smoothly from one to another.

Remarks

The variations selected for each fragment form a melody. Fragments can be placed on any beat boundary and can cross bar boundaries. If two fragments overlap, the variation selected by the first fragment is truncated so that none of its notes run into the notes from the second fragment.

Each melody fragment contains a description of the variations that are suitable at that point. This could be a range of variations, a list, or some designation for "use all variations." The variation selection can also refer to previous variations. A melody fragment can use a play mode to generate notes in the melody being constructed, or it can select variations that align with the current chord using either chord intervals or scale intervals. Further, a set of intervals can be selected as legal intervals by which to transpose the fragment in order to align it.

Requirements

Header: Declared in dmusici.h.

See Also

GUID_MelodyFragment


DMUS_MUTE_PARAM

Used as the pParam parameter in calls to the various get-parameter and set-parameter methods when the track is a mute track and rguidType is GUID_MuteParam.

typedef struct _DMUS_MUTE_PARAM {
    DWORD  dwPChannel;
    DWORD  dwPChannelMap;
    BOOL   fMute;
} DMUS_MUTE_PARAM;

Members

dwPChannel
Performance channel to mute or remap. If the structure is being passed to a get method, this member must be initialized.
dwPChannelMap
Channel to which dwPChannel is being mapped. This member is ignored if fMute is TRUE.
fMute
TRUE if dwPChannel is being muted.

Remarks

If you wanted all the notes on PChannel 3 to play on PChannel 9 instead, you would set dwPChannel to 3 and dwPChannelMap to 9 before passing the structure to one of the set methods. If you wanted to mute the notes on PChannel 8, you would set dwPChannel to 8 and dwPChannelMap to 0xFFFFFFFF.

Requirements

Header: Declared in dmusicf.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicSegment8::SetParam, IDirectMusicTrack8::GetParamEx, IDirectMusicTrack8::SetParamEx


DMUS_NOTERANGE

Specifies a range of notes that an instrument must respond to. An array of these structures is passed to the IDirectMusicPerformance8::DownloadInstrument and IDirectMusicPort8::DownloadInstrument methods to specify what notes the instrument should respond to and, therefore, what instrument regions need to be downloaded.

typedef struct _DMUS_NOTERANGE {
    DWORD dwLowNote;
    DWORD dwHighNote;
} DMUS_NOTERANGE, *LPDMUS_NOTERANGE;

Members

dwLowNote
Low note for this range of MIDI notes to which the instrument must respond.
dwHighNote
High note for this range of MIDI notes to which the instrument must respond.

Requirements

Header: Declared in dmdls.h.


DMUS_OBJECTDESC

Used to describe a DirectMusic object. This structure is passed to the IDirectMusicLoader8::GetObject method to identify the object that the loader should retrieve from storage. Information about an object is retrieved in this structure by the IDirectMusicLoader8::EnumObject and IDirectMusicObject8::GetDescriptor methods.

typedef struct _DMUS_OBJECTDESC {
    DWORD         dwSize;
    DWORD         dwValidData;
    GUID          guidObject;
    GUID          guidClass;
    FILETIME      ftDate;
    DMUS_VERSION  vVersion;
    WCHAR         wszName[DMUS_MAX_NAME];
    WCHAR         wszCategory[DMUS_MAX_CATEGORY];
    WCHAR         wszFileName[DMUS_MAX_FILENAME];
    LONGLONG      llMemLength;
    LPBYTE        pbMemData;
    IStream       *pStream
} DMUS_OBJECTDESC, *LPDMUS_OBJECTDESC;

Members

dwSize
Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_OBJECTDESC) before the structure is passed to any method.
dwValidData
Flags describing which members are valid and giving further information about some members. The following values are defined:
DMUS_OBJ_CATEGORY
The wszCategory member is valid.
DMUS_OBJ_CLASS
The guidClass member is valid.
DMUS_OBJ_DATE
The ftDate member is valid.
DMUS_OBJ_FILENAME
The wszFileName member is valid. The presence of this flag is assumed if DMUS_OBJ_FULLPATH is set.
DMUS_OBJ_FULLPATH
The wszFileName member contains either the full path of a file or a path relative to the application directory. The directory set by IDirectMusicLoader8::SetSearchDirectory is not searched. If this flag is not set, wszFilename is always assumed to be relative to the application directory, or to the search directory if SetSearchDirectory has been called for this object type.
DMUS_OBJ_LOADED
The object is currently loaded in memory.
DMUS_OBJ_MEMORY
The object is in memory, and llMemLength and pbMemData are valid.
DMUS_OBJ_NAME
The wszName member is valid.
DMUS_OBJ_OBJECT
The guidObject member is valid.
DMUS_OBJ_STREAM
The pStream member contains a pointer to the data stream.
DMUS_OBJ_URL
The wszFileName member contains a URL. URLs are not currently supported by the DirectMusic loader.
DMUS_OBJ_VERSION
The vVersion member is valid.
guidObject
Unique identifier for this object.
guidClass
Unique identifier for the class of object. All the standard objects have defined identifiers consisting of "CLSID_" plus the name of the object. For example, a segment object is identified as CLSID_DirectMusicSegment. See the defines in the Dmusici.h header file.
ftDate
Date that the object was last edited.
vVersion
DMUS_VERSION structure containing version information.
wszName
Name of the object.
wszCategory
Category for the object.
wszFileName
File path. If DMUS_OBJ_FULLPATH is set, this is the full path; otherwise, it is the file name. If the IDirectMusicLoader8::SetSearchDirectory method has been called, this member must contain only a file name.
llMemLength
Size of data in memory.
pbMemData
Data in memory.
pStream
Address of the IStream interface of a custom stream that can be used to load the object into memory. In most cases this value should be NULL.See Remarks.

Remarks

At least one of wszName, guidObject, and wszFileName must be filled with valid data to retrieve the object by using the IDirectMusicLoader8::GetObject method.

The name and category strings use 16-bit characters in the WCHAR format, not 8-bit ANSI characters. Be sure to convert as appropriate. You can use the C library mbstowcs function to convert from multibyte to Unicode and the wcstombs function to convert from Unicode back to multibyte.

Instead of passing on object descriptor to IDirectMusicLoader8::GetObject or IDirectMusicLoader8::SetObject with a filename or memory pointer, an application can pass a stream. This is done by setting the DMUS_OBJ_STREAM flag in dwValidData and a pointer to the stream in pStream. When the application calls GetObject, the loader saves the stream's current location, reads the object from the stream, and then restores the saved location. The application can continue reading from the stream without being affected by the call to GetObject.

When SetObject is called with a stream, the loader makes a copy of the stream which is used if the object is later loaded. Thus an application can release a stream or continue to read from it after passing it to the loader by using SetObject.

Requirements

Header: Declared in dmusici.h.


DMUS_PLAY_MARKER_PARAM

Contains information about a play marker.

typedef struct _DMUS_PLAY_MARKER_PARAM {
    MUSIC_TIME mtTime;
} DMUS_PLAY_MARKER_PARAM;

Members

mtTime
Time of the first legal segment play marker before or at the requested time. The value is an offset from the requested time.

Requirements

Header: Declared in dmusici.h.

See Also

GUID_Play_Marker


DMUS_PORTCAPS

Contains information about a port enumerated by a call to the IDirectMusic8::EnumPort method. The structure is also used to return information through the IDirectMusicPort8::GetCaps method.

typedef struct _DMUS_PORTCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    GUID  guidPort;
    DWORD dwClass;
    DWORD dwType;
    DWORD dwMemorySize;
    DWORD dwMaxChannelGroups;
    DWORD dwMaxVoices;
    DWORD dwMaxAudioChannels;
    DWORD dwEffectFlags;
    WCHAR wszDescription[DMUS_MAX_DESCRIPTION];
} DMUS_PORTCAPS, *LPDMUS_PORTCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_PORTCAPS) before the structure is passed to any method.
dwFlags
Flags describing various capabilities of the port. This field can contain one or more of the following values:
DMUS_PC_AUDIOPATH
Multiple outputs can be connected to DirectSound for audiopaths.
DMUS_PC_DIRECTSOUND
The port supports streaming wave data to DirectSound.
DMUS_PC_DLS
The port supports DLS Level 1 sample collections.
DMUS_PC_DLS2
The port supports DLS Level 2 sample collections.
DMUS_PC_EXTERNAL
The port connects to devices outside the host—for example, devices connected over an external MIDI port such as the MPU-401.
DMUS_PC_GMINHARDWARE
The synthesizer has its own GM instrument set, so GM instruments do not need to be downloaded.
DMUS_PC_GSINHARDWARE
This port contains the Roland GS sound set in hardware.
DMUS_PC_MEMORYSIZEFIXED
Memory available for DLS instruments cannot be adjusted.
DMUS_PC_SHAREABLE
More than one port can be created that uses the same range of channel groups on the device. Unless this bit is set, the port can be opened only in exclusive mode. In exclusive mode, an attempt to create a port fails unless free channel groups are available to assign to the create request.
DMUS_PC_SOFTWARESYNTH
The port is a software synthesizer.
DMUS_PC_WAVE
Streaming and one-shot waves are supported.
DMUS_PC_XGINHARDWARE
The port contains the Yamaha XG extensions in hardware.
guidPort
Identifier of the port. This value can be passed to the IDirectMusic8::CreatePort method to get an IDirectMusicPort8 interface for the port.
dwClass
Class of this port. The following classes are defined:
DMUS_PC_INPUTCLASS
Input port.
DMUS_PC_OUTPUTCLASS
Output port.
dwType
Type of this port. The following types are defined:
DMUS_PORT_WINMM_DRIVER
Windows multimedia driver.
DMUS_PORT_USER_MODE_SYNTH
User-mode synthesizer.
DMUS_PORT_KERNEL_MODE
WDM driver.
dwMemorySize
Amount of memory available to store DLS instruments. If the port is using system memory and the amount is therefore limited only by the available system memory, this member contains DMUS_PC_SYSTEMMEMORY.
dwMaxChannelGroups
Maximum number of channel groups supported by this port. A channel group is a set of 16 MIDI channels.
dwMaxVoices
Maximum number of voices that can be allocated when this port is opened. The value can be –1 if the driver does not support returning this parameter.
dwMaxAudioChannels
Maximum number of audio channels that can be rendered by the port. The value can be –1 if the driver does not support returning this parameter.
dwEffectFlags
Flags indicating what audio effects are available on the port.

The following flags are defined:

DMUS_EFFECT_NONE
No effects are supported.
DMUS_EFFECT_REVERB
The port supports reverb.
DMUS_EFFECT_CHORUS
The port supports chorus.
wszDescription
Description of the port. This can be a system-generated name, such as L"MPU-401 Output Port [330]", or a user-specified friendly name, such as L"Port w/ External SC-55".

Requirements

Header: Declared in dmusicc.h.


DMUS_PORTPARAMS8

Contains parameters for the opening of a DirectMusic port. These parameters are passed in when the IDirectMusic8::CreatePort method is called.

The define DMUS_PORTPARAMS resolves to DMUS_PORTPARAMS8. This structure supersedes the earlier version of DMUS_PORTPARAMS, which is now declared as DMUS_PORTPARAMS7.

typedef struct _DMUS_PORTPARAMS8 {
    DWORD dwSize;
    DWORD dwValidParams;
    DWORD dwVoices;
    DWORD dwChannelGroups;
    DWORD dwAudioChannels;
    DWORD dwSampleRate;
    DWORD dwEffectFlags;
    DWORD fShare;
    DWORD dwFeatures;
} DMUS_PORTPARAMS8;

typedef DMUS_PORTPARAMS8 DMUS_PORTPARAMS;
typedef DMUS_PORTPARAMS *LPDMUS_PORTPARAMS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_PORTPARAMS8) before the structure is passed to a method.
dwValidParams
Specifies which members in this structure are valid. Setting the flag for a particular port parameter means that you want to have this parameter set on the method call or want to override the default value when the port is created. The following flags have been defined:
DMUS_PORTPARAMS_VOICES
DMUS_PORTPARAMS_CHANNELGROUPS
DMUS_PORTPARAMS_AUDIOCHANNELS
DMUS_PORTPARAMS_SAMPLERATE
DMUS_PORTPARAMS_EFFECTS
DMUS_PORTPARAMS_SHARE
DMUS_PORTPARAMS_FEATURES
dwVoices
Number of voices required on this port. This is not an absolute maximum; the port can create additional temporary voices to enable smooth transitions when lower-priority voices have to be dropped.
dwChannelGroups
Number of channel groups to be allocated on this port. Must be less than or equal to the number of channel groups specified in the DMUS_PORTCAPS structure returned by the IDirectMusic8::EnumPort and IDirectMusicPort8::GetCaps methods.
dwAudioChannels
Desired number of output channels.
dwSampleRate
Desired sample rate, in hertz.
dwEffectFlags
Flags indicating which special effects are desired. The following flags are defined:

DMUS_EFFECT_NONE
DMUS_EFFECT_REVERB
DMUS_EFFECT_CHORUS

fShare
If TRUE, all ports use the channel groups assigned to this port. If FALSE, the port is opened in exclusive mode, and the use of the same channel groups by other ports is forbidden.
dwFeatures
Miscellaneous capabilities of the port. The following values are defined.
DMUS_PORT_FEATURE_AUDIOPATH
Supports an audiopath connection to DirectSound buffers.
DMUS_PORT_FEATURE_STREAMING
Supports streaming waves through the synthesizer.

Remarks

The DMUS_PORTPARAMS structure from versions prior to DirectX 8.0 is maintained in Dmusicc.h as DMUS_PORTPARAMS7.

Requirements

Header: Declared in dmusicc.h.

See Also

DMUS_PORTCAPS


DMUS_RHYTHM_PARAM

Used as the pParam parameter in calls to the various get-parameter methods when the track is a chord track and rguidType is GUID_RhythmParam.

typedef struct {
    DMUS_TIMESIGNATURE  TimeSig;
    DWORD               dwRhythmPattern;
} DMUS_RHYTHM_PARAM;

Members

TimeSig
DMUS_TIMESIGNATURE structure containing the time signature of the rhythm parameter. This structure must be initialized before the DMUS_RHYTHM_PARAM structure is passed to the get method.
dwRhythmPattern
Rhythm pattern for a sequence of chords. Each bit represents a beat in one or more measures, with 1 signifying a chord on the beat and 0 signifying no chord.

Requirements

Header: Declared in dmusicf.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicSegment8::SetParam, IDirectMusicTrack8::GetParamEx, IDirectMusicTrack8::SetParamEx


DMUS_SCRIPT_ERRORINFO

Contains information about a script error.

typedef struct _DMUS_SCRIPT_ERRORINFO {
    DWORD   dwSize;
    HRESULT hr;
    ULONG ulLineNumber;
    LONG ichCharPosition;
    WCHAR  wszSourceFile[DMUS_MAX_FILENAME];
    WCHAR  wszSourceComponent[DMUS_MAX_FILENAME];
    WCHAR  wszDescription[DMUS_MAX_FILENAME];
    WCHAR  wszSourceLineText[DMUS_MAX_FILENAME];
} DMUS_SCRIPT_ERRORINFO;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is passed to any of the IDirectMusicScript8 methods.
hr
Result code obtained from DirectMusic or the script engine.
ulLineNumber
Line number in the script where the error occurred.
ichCharPosition
Position in the line where a syntax error was found, if wszSourceLineText contains a string.
wszSourceFile
File name of the script.
wszSourceComponent
Name of the component that generated the error. For example, this could be DirectMusic or the script parsing engine.
wszDescription
Description of the error.
wszSourceLineText
Text of the script line where a syntax error occurred. If the error is not in the syntax, this is an empty string.

Requirements

Header: Declared in dmusici.h.


DMUS_SUBCHORD

Used in the SubChordList member of a DMUS_CHORD_PARAM structure.

typedef struct {
    DWORD dwChordPattern;
    DWORD dwScalePattern;
    DWORD dwInversionPoints;
    DWORD dwLevels;
    BYTE  bChordRoot;
    BYTE  bScaleRoot;
} DMUS_SUBCHORD;

Members

dwChordPattern
Notes in the subchord. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the chord.
dwScalePattern
Notes in the scale. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.
dwInversionPoints
Points in the scale at which inversions can occur. Bits that are off signify that the notes in the interval cannot be inverted. Thus, the pattern 100001111111 indicates that inversions are allowed anywhere except between the fifth and seventh degrees of a major scale.
dwLevels
Bit field showing which levels are supported by this subchord. Each part in a style is assigned a level, and this chord is used only for parts whose levels are contained in this member.
bChordRoot
Root of the subchord, in which 0 is the lowest C in the range and 23 is the top B.
bScaleRoot
Root of the scale, in which 0 is the lowest C in the range and 23 is the top B.

Requirements

Header: Declared in dmusici.h.


DMUS_SYNTHSTATS8

Used by the IDirectMusicPort8::GetRunningStats method to return the current running status of a synthesizer.

typedef struct DMUS_SYNTHSTATS {
    DWORD dwSize;
    DWORD dwValidStats;
    DWORD dwVoices;
    DWORD dwTotalCPU;
    DWORD dwCPUPerVoice;
    DWORD dwLostNotes;
    DWORD dwFreeMemory;
    long  lPeakVolume;
    DWORD   dwSynthMemUse;
} DMUS_SYNTHSTATS8;

typedef struct _DMUS_SYNTHSTATS8 *LPDMUS_SYNTHSTATS8;

Members

dwSize
Size of the structure, in bytes. This member must be initialized to sizeof(DMUS_SYNTHSTATS) before the structure is passed to a method.
dwValidStats
Flags that specify which fields in this structure have been filled in by the synthesizer. The following flags have been defined:

DMUS_SYNTHSTATS_VOICES
DMUS_SYNTHSTATS_TOTAL_CPU
DMUS_SYNTHSTATS_CPU_PER_VOICE
DMUS_SYNTHSTATS_FREE_MEMORY
DMUS_SYNTHSTATS_LOST_NOTES
DMUS_SYNTHSTATS_PEAK_VOLUME

dwVoices
Average number of voices playing.
dwTotalCPU
Total percentage of the CPU being consumed, multiplied by 100.
dwCPUPerVoice
Percentage of the CPU being consumed per voice, multiplied by 100.
dwLostNotes
Number of notes lost. Notes can be dropped because of voice-stealing or because too much of the CPU is being consumed.
dwFreeMemory
Amount of memory currently available to store DLS instruments. If the synthesizer is using system memory and the amount is therefore limited only by the available system memory, this value is set to DMUS_SYNTHSTATS_SYSTEMMEMORY.
lPeakVolume
Peak volume, measured in hundredths of decibels.
dwSynthMemUse
Memory used by synthesizer wave data.

Remarks

All the running status parameters, with the exception of dwFreeMemory, are refreshed every second. For example, dwLostNotes provides the total number of notes lost over a one-second period.

Requirements

Header: Declared in dmusici.h.


DMUS_TEMPO_PARAM

Used as the pParam parameter in calls to the various get-parameter and set-parameter methods when the track is a tempo track and rguidType is GUID_TempoParam.

typedef struct _DMUS_TEMPO_PARAM {
    MUSIC_TIME  mtTime;
    double      dblTempo;
} DMUS_TEMPO_PARAM;

Members

mtTime
Time for which the tempo was retrieved. (This member is not used in set methods, which use their mtTime parameter instead.)
dblTempo
The tempo, in the range from DMUS_TEMPO_MIN through DMUS_TEMPO_MAX.

Requirements

Header: Declared in dmusicf.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicSegment8::SetParam, IDirectMusicTrack8::GetParamEx, IDirectMusicTrack8::SetParamEx


DMUS_TIMESIGNATURE

Used by the IDirectMusicStyle8::GetTimeSignature method to retrieve information about a style's time signature. It is also used in the DMUS_RHYTHM_PARAM structure and in the various get-parameter methods when the rguidType parameter is GUID_TimeSignature and the track is a time signature or style track.

typedef struct _DMUS_TIMESIGNATURE {
    MUSIC_TIME mtTime;
    BYTE  bBeatsPerMeasure;
    BYTE  bBeat;
    WORD  wGridsPerBeat;
} DMUS_TIMESIGNATURE;

Members

mtTime
Music time at which this time signature occurs.
bBeatsPerMeasure
Top of time signature.
bBeat
Bottom of time signature.
wGridsPerBeat
Grids (subdivisions) per beat. This value determines the timing resolution for certain music events—for example, segments cued with the DMUS_SEGF_GRID flag (see DMUS_SEGF_FLAGS).

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicPerformance8::SetParam, IDirectMusicSegment8::GetParam, IDirectMusicSegment8::SetParam, IDirectMusicTrack8::GetParamEx, IDirectMusicTrack8::SetParamEx, DMUS_TIMESIG_PMSG


DMUS_VALID_START_PARAM

Used as the pParam parameter in calls to various get-parameter methods when rguidType is GUID_Valid_Start_Time.

typedef struct _DMUS_VALID_START_PARAM {
    MUSIC_TIME mtTime;
} DMUS_VALID_START_PARAM;

Members

mtTime
Next valid point at which the segment can start.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::GetParam, IDirectMusicSegment8::GetParam, IDirectMusicTrack8::GetParamEx


DMUS_VARIATIONS_PARAM

Contains information about variations associated with channels. It is used when retrieving the GUID_Variations parameter.

typedef struct _DMUS_VARIATIONS_PARAM {
    DWORD   dwPChannelsUsed;
    DWORD*  padwPChannels;
    DWORD*   padwVariations;
} DMUS_VARIATIONS_PARAM;

Members

dwPChannelsUsed
DWORD that receives the number of performance channels in use.
padwPChannels
Address of an array of DWORD values that receives the performance channels in use.
padwVariations
Array of variations in effect for each channel, where each bit set represents a variation.

Requirements

Header: Declared in dmusici.h.


DMUS_VERSION

Contains version information for an object described in the DMUS_OBJECTDESC structure.

typedef struct _DMUS_VERSION {
    DWORD  dwVersionMS;
    DWORD  dwVersionLS;
} DMUS_VERSION, FAR *LPDMUS_VERSION;

Members

dwVersionMS
Most significant DWORD of the version number.
dwVersionLS
Least significant DWORD of the version number.

Requirements

Header: Declared in dmusici.h.


DMUS_WAVES_REVERB_PARAMS

Contains information about reverberation effects in the Microsoft software synthesizer provided with DirectX 7.0.

typedef struct _DMUS_WAVES_REVERB_PARAMS {
    float  fInGain;
    float  fReverbMix;
    float  fReverbTime;
    float  fHighFreqRTRatio;
} DMUS_WAVES_REVERB_PARAMS;

Members

fInGain
Input gain, in decibels (to avoid output overflows). The default value is 0.
fReverbMix
Reverb mix, in decibels. A value of 0 means 100 percent wet reverb (no direct signal). Negative values gives less wet signal. The coefficients are calculated so that the overall output level stays approximately constant, regardless of the amount of reverb mix. The default value is –10.0.
fReverbTime
Reverb decay time, in milliseconds. The default value is 1000.
fHighFreqRTRatio
Ratio of the high frequencies to the global reverb time. Unless very bright reverbs are wanted, this should be set to a value less than 1. For example, if fReverbTime is 1000 ms and dHighFreqRTRatio is 0.1, the decay time for high frequencies is 100 ms. The default value is 0.001.

Remarks

The TrueVerb reverberation technology from Waves is licensed to Microsoft as the SimpleVerb implementation for use in the Microsoft software synthesizer.

In DirectX 8.0 and later, music reverberation is handled by a DMO. For more information, see Waves Reverberation.

Requirements

Header: Declared in dmusicc.h.


KSPROPERTY

Used by the IKsControl::KsProperty method to identify a property and operation.

KSPROPERTY is defined as a KSIDENTIFIER structure, which is declared as follows:

typedef struct {
    union {
        struct {
            GUID   Set;
            ULONG  Id;
            ULONG  Flags;
        };
        LONGLONG    Alignment;
    };
} KSIDENTIFIER, *PKSIDENTIFIER;

Members

Set
Identifier of the property set. The following property-set GUIDs are predefined by DirectMusic:
GUID_DMUS_PROP_DLS1
Item 0 is a Boolean indicating whether or not this port supports downloading DLS level 1 samples.
GUID_DMUS_PROP_DLS2
Item 0 is a Boolean indicating whether or not this port supports downloading DLS level 2 samples.
GUID_DMUS_PROP_Effects
Item 0 contains DMUS_EFFECT_NONE or one or more effects flags (see the dwEffectFlags member of DMUS_PORTCAPS). This property is used to set or retrieve the current state of the effects.
GUID_DMUS_PROP_GM_Hardware
Item 0 is a Boolean indicating whether or not this port supports GM in hardware.
GUID_DMUS_PROP_GS_Capable
Item 0 is a Boolean indicating whether or not this port supports the minimum requirements for Roland GS extensions.
GUID_DMUS_PROP_GS_Hardware
Item 0 is a Boolean indicating whether or not this port supports Roland GS extensions in hardware.
GUID_DMUS_PROP_INSTRUMENT2
Item 0 is a Boolean indicating whether or not this port supports downloading samples using the DMUS_ARTICULATION2 structure.
GUID_DMUS_PROP_LegacyCaps
Item 0 is the MIDIINCAPS or MIDIOUTCAPS structure that describes the underlying Windows multimedia device implementing this port. A MIDIINCAPS structure is returned if dwClass is DMUS_PC_INPUTCLASS in this port's capabilities structure. Otherwise, a MIDIOUTCAPS structure is returned.
GUID_DMUS_PROP_MemorySize
Item 0 is the number of bytes of sample RAM free on this device.
GUID_DMUS_PROP_SampleMemorySize
Item 0 is the number of bytes of sample RAM, both free and used, available on this device.
GUID_DMUS_PROP_SamplePlaybackRate
Item 0 is the synthesizer's sample rate. The DLS level 2 file format supports conditional chunks to determine whether a region or articulation should be downloaded. This allows authors to create optional waves intended for different sample rates.
GUID_DMUS_PROP_SynthSink_DSOUND
Item 0 is a Boolean indicating whether or not this port supports DirectSound.
GUID_DMUS_PROP_SynthSink_WAVE
Item 0 is a Boolean indicating whether or not this port supports wave output using the waveOut functions.
GUID_DMUS_PROP_Volume
Item 1 (DMUS_ITEM_Volume) is a LONG in the range from DMUS_VOLUME_MAX through DMUS_VOLUME_MIN. This is the signed value, in hundredths of a decibel, which is added to the gain of all voices after all DLS articulation has been performed. By default, when a port is added to the performance, this property is set to the master volume. For master volume, see Setting and Retrieving Global Parameters.
GUID_DMUS_PROP_WavesReverb
Item 0 is a DMUS_WAVES_REVERB_PARAMS structure containing reverb parameters.
GUID_DMUS_PROP_WriteLatency
Item 0 is the write latency of the user-mode synthesizer (the dwType member of the DMUS_PORTCAPS structure is DMUS_PORT_USER_MODE_SYNTH) that streams its output to DirectSound. The write latency is the delay between when the synthesizer creates a buffer of sound and when it is heard. By adjusting this value, an application can fine-tune the synthesizer for minimum latency without sound breakup. On some computers, in particular, ones without hardware support for DirectSound, the initial latency is much larger than on others, so the value should always be read first, and then adjusted with a relative value. The write latency can have different values for each port instance. The property must be set each time the port is activated. It is not recommended that applications set the write latency of a synthesizer in an audiopath.
GUID_DMUS_PROP_WritePeriod
Item 0 is the write period, in milliseconds, of the user-mode synthesizer (the dwType member of the DMUS_PORTCAPS structure is DMUS_PORT_USER_MODE_SYNTH) that streams its output to DirectSound. The write period controls how frequently the synthesizer sink allows the synthesizer to mix. By reducing this value, the application can reduce the overall latency of the synthesizer. However, values under 10 milliseconds increase the CPU load. The write period has the same value for all port instances that use the standard DirectSound sink. The property must be set each time the port is activated. This property cannot be set on ports in audiopaths.
GUID_DMUS_PROP_XG_Capable
Item 0 is a Boolean indicating whether or not this port supports the minimum requirements for Yamaha XG extensions.
GUID_DMUS_PROP_XG_Hardware
Item 0 is a Boolean indicating whether or not this port supports Yamaha XG extensions in hardware.
Id
Item within the property set.
Flags
One of the following flags to specify the operation:
KSPROPERTY_TYPE_GET
To retrieve the given property item's value.
KSPROPERTY_TYPE_SET
To set the given property item's value.
KSPROPERTY_TYPE_BASICSUPPORT
To determine the type of support available for the property set. The data returned by IKsControl::KsProperty in *pvPropertyData is a DWORD containing one or both of KSPROPERTY_TYPE_GET and KSPROPERTY_TYPE_SET, indicating which operations are possible.
Alignment
Not used in DirectMusic.

Requirements

Header: Declared in dmksctrl.h.

See Also

Property Sets for DirectMusic Ports


DLS Structures

This section contains reference information for structures used with Downloadable Sounds. Most applications do not need to use these structures, because DirectMusic handles the details of loading DLS collections and downloading instruments to the synthesizer. They are of interest chiefly for applications that edit DLS.

For an overview of using DLS data, see Low-Level DLS.

For more information on DLS data formats, see the specification from the MIDI Manufacturers Association.

The following structures are included in this section:

  • DMUS_ARTICPARAMS
  • DMUS_ARTICULATION
  • DMUS_ARTICULATION2
  • DMUS_COPYRIGHT
  • DMUS_DOWNLOADINFO
  • DMUS_EXTENSIONCHUNK
  • DMUS_INSTRUMENT
  • DMUS_LFOPARAMS
  • DMUS_MSCPARAMS
  • DMUS_OFFSETTABLE
  • DMUS_PEGPARAMS
  • DMUS_REGION
  • DMUS_VEGPARAMS
  • DMUS_WAVE
  • DMUS_WAVEARTDL
  • DMUS_WAVEDATA
  • DMUS_WAVEDL


DMUS_ARTICPARAMS

Describes parameters for a DLS level 1 articulation chunk. All parameters for articulation are stored in one chunk, which comprises a series of structures defining each functional area of the articulation. If an instrument or region uses articulation, it references this chunk by index from the DMUS_ARTICULATION chunk.

typedef struct {
    DMUS_LFOPARAMS LFO;
    DMUS_VEGPARAMS VolEG;
    DMUS_PEGPARAMS PitchEG;
    DMUS_MSCPARAMS Misc;
} DMUS_ARTICPARAMS;

Members

LFO
DMUS_LFOPARAMS structure containing parameters for a low-frequency oscillator.
VolEG
DMUS_VEGPARAMS structure containing parameters for a volume-envelope generator.
PitchEG
DMUS_PEGPARAMS structure containing parameters for a pitch-envelope generator.
Misc
DMUS_MSCPARAMS structure containing the initial pan position.

Remarks

DLS level 2 articulation is handled differently and does not use this structure. See DMUS_ARTICULATION2.

Requirements

Header: Declared in dmdls.h.


DMUS_ARTICULATION

Describes a DLS instrument articulation chunk. It is used when the format identifier in the dwDLType member of the DMUS_DOWNLOADINFO structure is DMUS_DOWNLOADINFO_INSTRUMENT. This chunk connects all available DLS articulation data in one list. For example, it might have a DLS Level 1 chunk and a manufacturer's proprietary articulation chunk. The DLS chunk is referenced by ulArt1Idx, and all additional articulation chunks are referenced by the list that starts with ulFirstExtCkIdx.

typedef struct {
    ULONG ulArt1Idx;
    ULONG ulFirstExtCkIdx;
} DMUS_ARTICULATION;

Members

ulArt1Idx
Index, in the DMUS_OFFSETTABLE structure, of the DLS articulation chunk. If 0, there is no DLS articulation.
ulFirstExtCkIdx
Index of the first third-party extension chunk. If 0, there are no third-party extension chunks associated with the articulation.

Remarks

The articulation chunk consists of a DMUS_ARTICPARAMS structure.

Requirements

Header: Declared in dmdls.h.

See Also

DMUS_ARTICULATION2


DMUS_ARTICULATION2

Describes a DLS instrument articulation chunk. This structure is used when the format identifier in the dwDLType member of the DMUS_DOWNLOADINFO structure is DMUS_DOWNLOADINFO_INSTRUMENT2. The DLS level 1 chunk is referenced by ulArt1Idx, and all additional articulation chunks are referenced by the list that starts with ulFirstExtCkIdx. DLS level 2 articulation chunks also use ulNextArtIdx.

typedef struct {
    ULONG ulArt1Idx;
    ULONG ulFirstExtCkIdx;
    ULONG ulNextArtIdx;
} DMUS_ARTICULATION;

Members

ulArt1Idx
Index, in the DMUS_OFFSETTABLE structure, of the DLS articulation chunk. If 0, there is no DLS level 1 or 2 articulation.
ulFirstExtCkIdx
Index of the first third-party extension chunk. If 0, there are no third-party extension chunks associated with the articulation. DLS level 2 chunks can also be placed here.
ulNextArtIdx
Index of additional articulation chunks to better support DLS level 2 articulations.

Remarks

The articulation chunk consists of a CONNECTIONLIST structure followed by an array of CONNECTION structures. These structures are declared in Dls1.h. For more information, see the Downloadable Sounds Level 2 specification, published by the MIDI Manufacturers Association.

Requirements

Header: Declared in dmdls.h.

See Also

DMUS_ARTICULATION


DMUS_COPYRIGHT

Describes an optional copyright chunk in DLS data.

typedef struct {
    ULONG cbSize;
    BYTE  byCopyright[ ];
} DMUS_COPYRIGHT;

Members

cbSize
Size of data.
byCopyright[ ]
Copyright data.

Requirements

Header: Declared in dmdls.h.


DMUS_DOWNLOADINFO

Used as a header for DLS data to be downloaded to a port. It defines the size and functionality of the download and is always followed by a DMUS_OFFSETTABLE chunk.

typedef struct _DMUS_DOWNLOADINFO {
    DWORD dwDLType;
    DWORD dwDLId;
    DWORD dwNumOffsetTableEntries;
    DWORD cbSize;
} DMUS_DOWNLOADINFO;

Members

dwDLType
Type of data being downloaded. The following types are defined:
DMUS_DOWNLOADINFO_INSTRUMENT
Instrument definition, starting with the DMUS_INSTRUMENT structure.
DMUS_DOWNLOADINFO_INSTRUMENT2
Instrument definition supporting DLS level 2 articulation, starting with the DMUS_INSTRUMENT structure.
DMUS_DOWNLOADINFO_WAVE
PCM wave data, starting with the DMUS_WAVE structure.
dwDLId
Unique 32-bit identifier for the object. See Remarks.
dwNumOffsetTableEntries
Number of entries in the DMUS_OFFSETTABLE structure that follows.
cbSize
Total size of DMUS_DOWNLOADINFO, DMUS_OFFSETTABLE, and the actual data chunk.

Remarks

The identifier in dwDLId is used to connect objects and is obtained by using the IDirectMusicPortDownload8::GetDLId method. Primarily it connects the regions in an instrument to wave chunks. For example, if a wave download is given a dwDLId of 3, an instrument chunk downloads with the value 3 placed in the WaveLink.ulTableIndex member of one of its DMUS_REGION structures. This indicates that the region is connected to the wave chunk.

Requirements

Header: Declared in dmdls.h.

See Also

Low-Level DLS


DMUS_EXTENSIONCHUNK

Describes a DLS extension chunk. All extensions to the DLS file format that are unknown to DirectMusic are downloaded in this variable-size chunk.

typedef struct {
    ULONG  cbSize;
    ULONG  ulNextExtCkIdx;
    FOURCC ExtCkID;
    BYTE   byExtCk[ ];
} DMUS_EXTENSIONCHUNK;

Members

cbSize
Size of chunk.
ulNextExtCkIdx
Index, in the DMUS_OFFSETTABLE structure, of the next extension chunk. If 0, there are no more third-party extension chunks.
ExtCkID
Chunk identifier.
byExtCk[ ]
Data.

Requirements

Header: Declared in dmdls.h.


DMUS_INSTRUMENT

Contains an instrument definition in a DLS download chunk.

typedef struct {
    ULONG ulPatch;
    ULONG ulFirstRegionIdx;
    ULONG ulGlobalArtIdx;
    ULONG ulFirstExtCkIdx;
    ULONG ulCopyrightIdx;
    ULONG ulFlags;
} DMUS_INSTRUMENT;

Members

ulPatch
Patch number of instrument.
ulFirstRegionIdx
Index of first region chunk (see DMUS_REGION) within the instrument. There should always be a region, but for compatibility with future synthesizer architectures, it is acceptable to have 0 in this member.
ulGlobalArtIdx
Index, in the DMUS_OFFSETTABLE structure, of the global articulation chunk (see DMUS_ARTICULATION and DMUS_ARTICULATION2) for the instrument. If 0, the instrument does not have global articulation.
ulFirstExtCkIdx
Index, in the DMUS_OFFSETTABLE structure, of the first extension chunk (see DMUS_EXTENSIONCHUNK) within the instrument. This is used to add new chunks that DirectMusic is unaware of. If 0, no third-party extension chunks are associated with the instrument.
ulCopyrightIdx
Index, in the DMUS_OFFSETTABLE structure, of an optional copyright chunk (see DMUS_COPYRIGHT). If 0, no copyright information is associated with the instrument.
ulFlags
Additional flags for the instrument. The following flag is defined:
DMUS_INSTRUMENT_GM_INSTRUMENT
The instrument is a standard General MIDI instrument. In the case of patch overlap, GM instruments always have lower priority than other DLS instruments. For example, if a GM instrument is downloaded with patch 0 and a non-GM instrument is also downloaded at patch 0, the non-GM instrument is always selected for playback.

Requirements

Header: Declared in dmdls.h.


DMUS_LFOPARAMS

Defines the low-frequency oscillator for a DLS level 1 articulation chunk. It is used in the DMUS_ARTICPARAMS structure.

typedef struct {
    PCENT pcFrequency;
    TCENT tcDelay;
    GCENT gcVolumeScale;
    PCENT pcPitchScale;
    GCENT gcMWToVolume;
    PCENT pcMWToPitch;
} DMUS_LFOPARAMS;

Members

pcFrequency
Frequency, in pitch units. See Remarks.
tcDelay
Initial delay, in time cents. See Remarks.
gcVolumeScale
Scaling of output to control tremolo, in attenuation units. See Remarks.
pcPitchScale
Scaling of LFO output to control vibrato, in pitch units. See Remarks.
gcMWToVolume
Modulation wheel range to control tremolo, in attenuation units. See Remarks.
pcMWToPitch
Modulation wheel range to control tremolo, in attenuation units. See Remarks.

Remarks

The DLS Level 1 specification defines time cents, pitch cents, and attenuation as 32-bit logarithmic values. See the specification from the MIDI Manufacturers Association for details.

Requirements

Header: Declared in dmdls.h.

See Also

DMUS_ARTICPARAMS


DMUS_MSCPARAMS

Defines the pan for a DLS level 1 articulation chunk. This structure is used in the DMUS_ARTICPARAMS structure.

typedef struct {
    PERCENT ptDefaultPan;
} DMUS_MSCPARAMS;

Members

ptDefaultPan
Default pan, ranging from –50 through 50 percent, in units of 0.1 percent shifted left by 16.

Remarks

PERCENT is defined as long. For more information about pan values, see the DLS specification from the MIDI Manufacturers Association.

Requirements

Header: Declared in dmdls.h.

See Also

DMUS_ARTICPARAMS


DMUS_OFFSETTABLE

Used in the header of DLS instrument data being downloaded to a port.

typedef struct _DMUS_OFFSETTABLE {
    ULONG ulOffsetTable[DMUS_DEFAULT_SIZE_OFFSETTABLE];
} DMUS_OFFSETTABLE;

Members

ulOffsetTable
Array of byte offsets into the data.

Requirements

Header: Declared in dmdls.h.

See Also

Low-Level DLS


DMUS_PEGPARAMS

Defines the pitch envelope for a DLS level 1 articulation chunk. It is used in the DMUS_ARTICPARAMS structure.

typedef struct {
    TCENT   tcAttack;
    TCENT   tcDecay;
    PERCENT ptSustain;
    TCENT   tcRelease;
    TCENT   tcVel2Attack;
    TCENT   tcKey2Decay;
    PCENT   pcRange;
} DMUS_PEGPARAMS;

Members

tcAttack
Attack time, in time cents. See Remarks.
tcDecay
Decay time, in time cents. See Remarks.
ptSustain
Sustain, in hundredths of a percent shifted left by 16.
tcRelease
Release time, in time cents. See Remarks.
tcVel2Attack
Velocity to attack, in time cents. See Remarks.
tcKey2Decay
Key to decay, in time cents. See Remarks.
pcRange
Envelope range, in pitch units. See Remarks.

Remarks

The DLS Level 1 specification defines time cents and pitch cents as 32-bit logarithmic values. See the specification from the MIDI Manufacturers Association for details about the values in this structure.

Requirements

Header: Declared in dmdls.h.

See Also

DMUS_ARTICPARAMS


DMUS_REGION

Defines a region for a DLS download. One or more regions can be embedded in an instrument buffer and referenced by the instrument header chunk, DMUS_INSTRUMENT.

typedef struct {
    RGNRANGE RangeKey;
    RGNRANGE RangeVelocity;
    USHORT   fusOptions;
    USHORT   usKeyGroup;
    ULONG    ulRegionArtIdx;
    ULONG    ulNextRegionIdx;
    ULONG    ulFirstExtCkIdx;
    WAVELINK WaveLink;
    WSMPL    WSMP;
    WLOOP    WLOOP[1];
} DMUS_REGION;

Members

RangeKey
Key range for this region.
RangeVelocity
Velocity range for this region.
fusOptions
Options for the synthesis of this region. The following flag is defined:
F_RGN_OPTION_SELFNONEXCLUSIVE
If a second note-on for the same note is received by the synthesis engine, the second note is played, as well as the first. This option is off by default so that the synthesis engine forces a note-off of the first note.
usKeyGroup
Key group for a drum instrument. Key group values allow multiple regions within a drum instrument to belong to the same group. If a synthesis engine is instructed to play a note with a key group setting and any other notes are currently playing with this same key group, the synthesis engine turns off all notes with the same key group value as soon as possible. Currently, key groups from 1 through 15 are legal, and 0 indicates no key group.
ulRegionArtIdx
Index, in the DMUS_OFFSETTABLE structure, of the global articulation chunk for the region. If 0, the region does not have an articulation and relies on the instrument's global articulation.
ulNextRegionIdx
Index, in the DMUS_OFFSETTABLE structure, of the next region in the region list. If 0, there are no more regions.
ulFirstExtCkIdx
Index, in the DMUS_OFFSETTABLE structure, of the third-party extension chunk list. If 0, no extension chunks are associated with the region.
WaveLink
Standard DLS structure (declared in the Dls1.h header file) for managing a link from the region to a wave. The ulTableIndex member of the WAVELINK structure contains the download identifier of the associated wave buffer. (For more information, see DMUS_DOWNLOADINFO and Low-Level DLS.)
WSMP
Standard DLS structure (declared in Dls1.h) for managing the playback of the wave. If the cSampleLoops member is 1, the following WLOOP structure carries the loop start and end points.
WLOOP[ ]
Standard DLS structure (declared in Dls1.h) for describing a loop.

Requirements

Header: Declared in dmdls.h.


DMUS_VEGPARAMS

Defines a volume envelope for a DLS level 1 articulation chunk.

typedef struct {
    TCENT   tcAttack;
    TCENT   tcDecay;
    PERCENT ptSustain;
    TCENT   tcRelease;
    TCENT   tcVel2Attack;
    TCENT   tcKey2Decay;
} DMUS_VEGPARAMS;

Members

tcAttack
Attack time, in time cents. See Remarks.
tcDecay
Decay time, in time cents. See Remarks.
ptSustain
Sustain, in hundredths of a percent and shifted left by 16.
tcRelease
Release time, in time cents. See Remarks.
tcVel2Attack
Velocity to attack, in time cents. See Remarks.
tcKey2Decay
Key to decay, in time cents. See Remarks.

Remarks

The DLS Level 1 specification defines time cents as a 32-bit logarithmic value. See the specification from the MIDI Manufacturers Association for details about the values in this structure.

Requirements

Header: Declared in dmdls.h.

See Also

DMUS_ARTICPARAMS


DMUS_WAVE

Defines a wave chunk for a DLS download.

typedef struct {
    ULONG  ulFirstExtCkIdx;
    ULONG  ulCopyrightIdx;
    ULONG  ulWaveDataIdx;
    WAVEFORMATEX  WaveformatEx;
} DMUS_WAVE;

Members

ulFirstExtCkIdx
Index, in the DMUS_OFFSETTABLE structure, of third-party extension chunks. If 0, no extension chunks are associated with the wave.
ulCopyrightIdx
Index, in the DMUS_OFFSETTABLE structure, of copyright chunks. If 0, no copyright information is associated with the wave.
ulWaveDataIdx
Index, in the DMUS_OFFSETTABLE structure, of wave data. See DMUS_WAVEDATA.
WaveformatEx
WAVEFORMATEX structure that specifies the wave format of the chunk.

Requirements

Header: Declared in dmdls.h.


DMUS_WAVEARTDL

Contains information for downloading wave articulation.

typedef struct _DMUS_WAVEARTDL {
    ULONG   ulDownloadIdIdx;
    ULONG   ulBus;
    ULONG   ulBuffers;
    ULONG   ulMasterDLId;
    USHORT  usOptions
}   DMUS_WAVEARTDL, *LPDMUS_WAVEARTDL;

Members

ulDownloadIdIdx
Download identifiers of each buffer.
ulBus
Playback bus.
ulBuffers
Buffers.
ulMasterDLId
Download identifier of master voice of subordinate group.
usOptions
Downloadable Sounds Level 2 region options.

Requirements

Header: Declared in dmdls.h.


DMUS_WAVEDATA

Contains a data chunk for a DLS wave download. The nature of the wave data is defined by the WaveformatEx member of the DMUS_WAVE structure.

typedef struct {
    ULONG cbSize;
    BYTE byData[ ];
} DMUS_WAVEDATA;

Members

cbSize
Size of data.
byData[ ]
PCM wave data.

Requirements

Header: Declared in dmdls.h.


DMUS_WAVEDL

Contains information about wave data downloaded to the synthesizer.

typedef struct _DMUS_WAVEDL {
    ULONG  cbWaveData;
}   DMUS_WAVEDL, *LPDMUS_WAVEDL;

Members

cbWaveData
Number of bytes of wave data.

Requirements

Header: Declared in dmdls.h.


DirectMusic File Format

This section describes the format of files created in DirectMusic Producer and read by DirectMusic when IDirectMusicLoader8::GetObject or IDirectMusicLoader8::LoadObjectFromFile is called. Most applications don't parse these files directly. This format information is included for developers of music-authoring applications or DirectMusic plug-ins who want to be able to save data in a compatible format or load data into their own objects.

DirectMusic data is stored in the resource interchange file format (RIFF). The following topics contain general information about RIFF files.

  • About RIFF
  • RIFF Notation

The following topics describe how DirectMusic data is organized in RIFF chunks.

  • Common Chunks
  • Audiopath Form
  • Band Form
  • Chord Map Form
  • Container Form
  • DirectSound Buffer Configuration Form
  • Effects Form
  • Reference List
  • Script Form
  • Segment Form
  • Song Form
  • Style Form
  • Tool Form
  • Toolgraph Form
  • Track Form
  • Wave Header Chunk

The following section is a reference to structures used to contain data in RIFF chunks.

  • DirectMusic File Structures


About RIFF

The basic building block of a RIFF file is a chunk. A chunk is a logical unit of data. Each chunk contains the following fields:

  • A four-character code (FOURCC) specifying the chunk identifier. Conventionally, this is uppercase for registered chunk types, and lowercase otherwise.
  • A DWORD value specifying the size of the data member in the chunk.
  • The data.

A chunk contained in another chunk is a subchunk. The only chunks allowed to contain subchunks are those with a chunk identifier of RIFF or LIST.

The first chunk in a file must be identified as RIFF. All other chunks in the file are subchunks of this chunk. RIFF chunks are also called forms.

A LIST chunk is a grouping of subchunks. Some of these subchunks might appear multiple times, but a LIST is not an array. The terminology can be confusing. You might expect the chunk labeled <part-list>, for example, to be a list of musical parts. In fact, it is a list of the elements of a "part" chunk, which describes a single part.

RIFF chunks include an additional field in the first 4 bytes of the data field. This additional field provides the form type of the chunk. The form type is a four-character code identifying the format of the data stored in the file. For example, DirectMusic styles have the form type DMST.

LIST chunks also include an additional field in the first 4 bytes of the data field. This field contains the list type of the field. The list type is a four-character code identifying the contents of the list. For example, DirectMusic styles have a LIST chunk with a list type of "part" that contains data pertaining to a particular part (instrument track) in the performance.

Note Every four-character code used in DirectMusic files has a corresponding macro in Dmusicf.h. For example, the FOURCC for DMST is returned by the DMUS_FOURCC_STYLE_FORM macro.

For more information on RIFF files in general, see Resource Interchange File Format Services in the Platform SDK documentation.


RIFF Notation

The descriptions of DirectMusic files in the following sections use a subset of the conventional notation for RIFF files. The principal parts of this notation are shown in the following table:

Notation | Description
<element> | File element labeled "element", or of type element.
[ <element> ] | Optional file element.
<element>... | One or more copies of the specified element.
[<element>]... | Zero or more copies of the specified element.
name, 'name', NAME, or 'NAME' | FOURCC identifier of a form type, list type, or chunk.
// Comment | Comment.

Labels are used only in the notation, not in the files themselves. The label <cheh-ck> refers to a chunk with a unique FOURCC identifier and format. Wherever a chunk of this kind occurs in the notation, the same label is used.

The data or subelements associated with a label are shown as in the following example:

<cheh-ck> -> cheh( <DMUS_IO_CHORDENTRY> )

This notation indicates that the chunk labeled <cheh-ck> consists of the FOURCC identifier "cheh" followed by a DMUS_IO_CHORDENTRY structure.

Note The data in every chunk is preceded by a DWORD showing the size of the data. This element is not shown in the notation.

The next example shows a list element, consisting of the FOURCC "LIST" followed by the list identifier "cmap" and one or more elements labeled <choe-list>. The <choe-list> element would be expanded elsewhere.

<cmap-list> -> LIST( 'cmap'
    <choe-list>... )


Common Chunks

The following chunks occur in various list chunks and forms.

<guid-ck>

This is the GUID identifier of the element.

<guid-ck> -> guid( <GUID> )

<vers-ck>

This chunk contains version information for the element.

<vers-ck> -> vers( <DMUS_IO_VERSION> )

<UNFO-list>

The UNFO chunk is like a standard RIFF INFO list, except that it uses Unicode characters. INFO and UNFO lists consist of various chunks that contain null-terminated strings.

<UNFO-list> -> LIST( 'UNFO'
    <unfo-text-ck>...
    )

See Also

Reference List


Audiopath Form

The following notation shows the organization of the audiopath form.

RIFF( 'DMAP'
    [<guid-ck>]        // GUID for path
    [<vers-ck>]        // Version information
    [<UNFO-list>]      // Name, author, copyright, comments
    [<DMTG-form>]      // Toolgraph
    [<pcsl-list>]      // Port configurations
    [<dbfl-list>]...   // DirectSound buffer descriptors
)

All elements are optional.

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<DMTG-form>

See Toolgraph Form.

<pcsl-list>

Information about the configuration of ports is stored in this list.

<pcsl-list> -> LIST( 'pcsl'
    <pcfl-list>...
    )

The port configuration list consists of an array of lists in the following format:

LIST( 'pcfl'
    <pcfh-ck>          // Header chunk
    <pprh-ck>          // Port parameters used to create the port
    [<dbfl-list>]...   // DirectSound buffer descriptors
    [<pchl-list>]      // Pchannel-to-buffer assignments
    )

The port configuration list consists of several chunks, starting with headers describing the port configuration and parameters:

<pcfh-ck> -> pcfh( <DMUS_IO_PORTCONFIG_HEADER> )

<pprh-ck> -> pprh( <DMUS_PORTPARAMS8> )

The optional buffer descriptors are each contained in a chunk with the following format.

<dbfl-list> -> LIST( 'dbfl'
    <ddah-ck>       // Buffer attributes header
    [<DSBC-form>]   // Buffer configuration
)

This buffer description list begins with a header describing buffer attributes.

<ddah-ck> -> ( 'ddah' < DMUS_IO_BUFFER_ATTRIBUTES_HEADER > )

The header is followed by an optional DirectSound Buffer Configuration Form. This is not required for standard buffer types.

The final chunk in the port configuration list is a list containing one or more assignments of performance channels to buffers.

pchl-list -> LIST( 'pchl'
    <pchh-ck>...
)

This list consists of an array of chunks, each of which describes one assignment of channels to buffers.

<pchh-ck> -> pchh(
    <DMUS_IO_PCHANNELTOBUFFER_HEADER>
    <GUID>... // Array of GUIDs specifying the buffers
)

<dbfl-list>

The last part of the audiopath form consists of optional buffer descriptors identical in format to those in the port configuration list, <pcsl-list>.


Band Form

The following notation shows the format of the top-level chunk, or form, of a band file. Band forms can also be contained in other chunks.

RIFF( 'DMBD'
    [<guid-ck>]     // GUID for band
    [<vers-ck>]     // Optional version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    <lbil-list>     // Instruments
    )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<lbil-list>

The data is contained in an array of lists.

<lbil-list> -> LIST( 'lbil'
    <lbin-list>...
    )

Each instrument is described in a list that has the following format:

<lbin-list> -> LIST( 'lbin'
    <bins-ck>
    [<DMRF-list>]
    )

Within the instrument list, the following chunk contains a header describing the instrument:

<bins-ck> -> bins( <DMUS_IO_INSTRUMENT> )

The instrument list can also contain <DMRF-list>, which in this case is a reference to a DLS file. See Reference List.


Chord Map Form

The following notation shows the organization of the top-level chunk, or form, of a chordmap file:

RIFF( 'DMPR'
    <perh-ck>       // Chord map header chunk
    [ <guid-ck> ]   // GUID chunk
    [ <vers-ck> ]   // Version chunk
    [ <UNFO-list> ] // UNFO list
    <chdt-ck>       // Chord data chunk
    <chpl-list>     // Chord palette
    <cmap-list>     // Chord graph
    <spsq-list>     // Signpost list
)

<perh-ck>

This is the basic header information for a chordmap.

<perh-ck> -> perh( <DMUS_IO_CHORDMAP> )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<chdt-ck>

<chdt-ck> -> chdt(
    <WORD>    // Size of DMUS_IO_CHORDMAP_SUBCHORD
    <DMUS_IO_CHORDMAP_SUBCHORD>...
    )

The <chdt-ck> chunk contains a WORD indicating the number of bytes per subchord followed by an array of unique subchords. The subchord identifiers referred to in other parts of this file all correspond directly to an index into this array.

<chpl-list>

<chpl-list> -> LIST( 'chpl'
    <chrd-list>...
    )

This list contains the chord palette. There must be exactly 24 items in this list.

<chrd-list> -> LIST( 'chrd'
    <UNAM-ck>    // Chord name
    <sbcn-ck>    // Subchord indexes
    )

This list contains the basic chord information. This information is simply the chord's name and a list of identifiers for the subchords it comprises.

<UNAM-ck> -> UNAM ( <WCHAR>... )

The UNAM chunk stores the name of the chord.

<sbcn-ck> -> sbcn( <WORD>... )

The "sbcn" chunk contains one or more subchord identifiers. These correspond directly to an index into the array found in <chdt-ck>. A maximum of four chords is supported.

<cmap-list>

This list contains the entire chord connection graph for the chordmap. The bulk of the data for the chordmap resides in this chunk.

<cmap-list>  ->  LIST( 'cmap'
    <choe-list>...
    )

Each list contains data for a single entry in the chord graph, along with pointers to all the chords that can occur next in the chord graph.

<choe-list> -> LIST( 'choe'
    <cheh-ck>      // Chord entry data
    <chrd-list>    // Chord data; see above.
    <ncsq-ck>      // Next chord list
    )

<cheh-ck> -> cheh( <DMUS_IO_CHORDENTRY> )

This is the chord entry header. The identifier in the structure is the identifier for the chord connection graph, not a subchord identifier.

<ncsq-ck> -> ncsq (
    <WORD>         // Size of DMUS_IO_NEXTCHORD
    <DMUS_IO_NEXTCHORD>...
    )

The "ncsq" chunk contains data that connects one chord in the connection graph to another. Each chord in the connection graph is represented by a 16-bit identifier.

<spsq-list>

This chunk contains data for each of the signposts.

<spsq-list> -> LIST( 'spsq'
    <spst-list>...
    )

The <spst-list> contains data for a single signpost, consisting of a header, chord information, and optional cadence chords.

<spst-list>  ->  LIST( 'spst'
    <spsh-ck>
    <chrd-list>     // Chord data
    [ <cade-list> ] // Cadence chords
    )

The <spsh-ck> contains the signpost data.

<spsh-ck> -> spsh( <DMUS_IO_CHORDMAP_SIGNPOST> )

For <chrd-list>, see <chpl-list>, described previously.

The <cade-list> chunk contains the chord information for cadence chords. Support for up to two cadence chords in this list is provided. Any additional chords are ignored.

<cade-list> -> LIST( 'cade'
    <chrd-list>...
    )


Container Form

The container form is a chunk that contains other chunks such as segment or style forms. It can be contained within a segment or script file. It is organized as follows:

RIFF ( 'DMCN'
    <conh-ck>       // Container header chunk
    [<guid-ck>]     // GUID for container
    [<vers-ck>]     // Optional version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    <cosl-list>     // List of objects.
)

<conh-ck>

This chunk contains a header structure.

<conh-ck> -> 'conh' ( <DMUS_IO_CONTAINER_HEADER> )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<cosl-list>

The final element of the container form is an array of chunks that describe the objects in the container.

<cosl-list> -> LIST ( 'cosl'
    <cobl-list>...
    )

Each object is stored in the following format:

<cobl-list> -> LIST( 'cobl'
    [<coba-ck>]
    <cobh-ck>       // Required header
    [<data> ] or [ DMRF-list ]

The first element is an alias, or alternative name by which this object is known within the container.

<coba-ck> -> coba( <WCHAR>... )  // Null-terminated string

The second element header for the object.

<cobh-ck> -> cobh ( <DMUS_IO_CONTAINED_OBJECT_HEADER> )

The header is normally followed by object data of the type specified in <cobh-ck>. This can be in the form of a RIFF chunk such as a Segment Form or a Style Form. If it is a DMRF-list, it is a reference to the object. For more information on DMRF, see Reference List.


DirectSound Buffer Configuration Form

The following notation shows the organization of a chunk containing information about a DirectSound buffer configuration.

RIFF ( 'DSBC'
    [<guid-ck>]     // GUID identifier for this buffer configuration
    [<vers-ck>]     // Optional version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    <dsbd-ck>       // DirectSound buffer descriptor
    [<bsid-ck>]     // Bus identifiers
    [<ds3d-ck>]     // 3-D parameters
    [<fxls-list>]   // Effect descriptors
    )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<dsbd-ck>

The DirectSound buffer descriptor is organized as follows:

<dsbd-ck> -> 'dsbd' (
    <DSOUND_IO_DSBUFFERDESC>
    )

<bsid-ck>

The bus identifiers are stored in the following chunk.

<bsid-ck> -> 'bsid' ( <DSOUND_IO_DSBUSID> )

The DSOUND_IO_DSBUSID structure is an array of bytes whose size is specified by the chunk size.

<ds3d-ck>

The 3-D parameters of the buffer are stored in the following chunk.

<ds3d-ck> -> 'ds3d'( <DSOUND_IO_3D> )

<fxls-list>

The next list contains information about DMOs associated with the buffer.

<fxls-list> -> LIST ( 'fxls'
    <DSFX-form>...
    )

Each DMO is stored in an Effects Form.


Effects Form

The effects form describes a DMO effect.

RIFF ( 'DSFX'
    <fxhr-ck>
    [<data-ck>]
)

<fxhr-ck>

The header chunk describes the effect.

<fxhr-ck> -> fxhr ( <DSOUND_IO_DXDMO_HEADER> )

<data-ck>

The data chunk is an optional set of values for the effect parameters in the format expected by the DMO.

<data-ck> -> data ( <DSOUND_IO_DXDMO_DATA> )


Reference List

The reference list chunk contains information about a reference to an object in another file. For example, a band object might contain a reference to a DLS collection in a separate file. This subchunk is used in many different chunks.

The notation for a reference list is as follows:

<DMRF-list> ->LIST( 'DMRF'
    <refh-ck>       // Reference header
    [<guid-ck>]     // Object GUID
    [<date-ck>]     // File date
    [<name-ck>]     // Name
    [<file-ck>]     // File name
    [<catg-ck>]     // Category name
    [<vers-ck>]     // Version information
)

<refh-ck>

The data begins with a header that includes information about the object being referred to:

<refh-ck> -> refh( <DMUS_IO_REFERENCE> )

All other chunks are optional.

<guid-ck>

See Common Chunks.

<date-ck>

The date chunk contains a date in a FILETIME structure.

<date-ck> -> date( <FILETIME> )

<name-ck>, <file-ck>, <catg-ck>

The name, file name, and category name are null-terminated strings.

<name-ck> -> name( <WCHAR>... )
<file-ck> -> file( <WCHAR>... )  // Null-terminated string
<catg-ck> -> catg( <WCHAR>... )  // Null-terminated string

<vers-ck>

See Common Chunks.


Script Form

This section describes the organization of a chunk containing information about a DirectMusic script.

RIFF ( 'DMSC'
    <schd-ck>       // Script header chunk
    [<guid-ck>]     // GUID for script
    [<vers-ck>]     // Optional version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    <scve-ck>       // Version of DirectMusic
    <DMCN-form>     // Container of content referenced by the script
    <scla-ck>       // Scripting language
    <scsr-ck> or <DMRF> // Source code
)

<schd-ck>

The header chunk contains flags in a DMUS_IO_SCRIPT_HEADER structure.

<schd-ck> -> schd( <DMUS_IO_SCRIPT_HEADER> )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<scve-ck>

This chunk describes the version of DirectMusic against which the script was authored.

<scve-ck> -> scve( <DMUS_IO_VERSION> )

<DMCN-form>

For information on this chunk, see Container Form.

<scla-ck>

This chunk consists of a null-terminated string describing the scripting language.

<scla-ck> -> scla( <WCHAR>... )

<scsr-ck> or <DMRF>

The final chunk can contain the source code as a null-terminated array of WCHAR values.

<scsr-ck> -> scsr( <WCHAR>... )

Alternatively, the final chunk can be a Reference List chunk pointing to a text file containing the script code. The guidClassID member of the DMUS_IO_REFERENCE) must be GUID_NULL, because this text file is not a DirectMusic object.


Segment Form

The following notation shows the organization of the top-level chunk of a segment file. This form can also be contained within a Container Form.

RIFF( 'DMSG'
    <segh-ck>       // Segment header chunk
    [<guid-ck>]     // GUID for the segment
    [<vers-ck>]     // Optional version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    [<DMCN-form>]   // Optional container of objects embedded in file
    <trkl-list>     // Tracks
    [<DMTG-form>]   // Optional toolgraph
    [<DMAP-form>]   // Optional audiopath
    )

<segh-ck>

This chunk contains the basic header information for a segment.

<segh-ck> -> segh( <DMUS_IO_SEGMENT_HEADER> )

<guid-ck>, <vers-ck>, <UNFO-list>

See Common Chunks.

<DMCN-form>

See Container Form.

<trkl-list>

This is the track list. Each track is encapsulated in a Track Form.

<trkl-list> -> LIST( 'trkl'
    <DMTK-form>...
    )

<DMTG-form>

See Toolgraph Form.

<DMAP-form>

See Audiopath Form.


Song Form

Not implemented in DirectX 8.0.

The following notation shows the organization of the top-level chunk of a song file. This form can also be contained within a Container Form.

RIFF( 'DMSO'
    <sngh-ck>       // Song header chunk
    [<guid-ck>]     // GUID for song
    [<vers-ck>]     // Optional version info
    [<UNFO-list>]   // Name, author, copyright information, comments
    [<DMCN-form>]   // Container of objects embedded in file
    <segl-list>     // Segments
    [<tlgl-list>]   // Toolgraphs
    [<DMAP-form>]   // Audiopath shared by all segments
    <srsl-list>     // Segment references
)

<sngh-ck>

This chunk contains the basic header information for a song.

<sngh-ck> -> sngh ( <DMUS_IO_SONG_HEADER> )

<guid-ck>, <vers-ck>, <UNFO-list>

See Common Chunks.

<DMCN-form>

See Container Form.

<segl-list>

<segl-list> -> LIST( 'segl'
    <ssgl-list>...
    )

The song segments list contains an array of segments, each of which is described in the following list.

<ssgl-list> -> LIST( 'ssgl'
    [<DMSG-form>]
    [<DMRF-list>]
    )

This list consists of either a Segment Form or a Reference List.

<tlgl-list>

<tlgl-list> -> LIST( 'tlgl'
    <DMTG-form>...
    )

The toolgraph list consists of an array of Toolgraph Forms.

<DMAP-form>

This chunk describes audiopaths shared by all segments in the song. See Audiopath Form.

<srsl-list>

The last chunk in the song form is an array of segment reference lists that are organized as follows:

<srsl-list> -> LIST( 'srsl'
    <sgrl-list>...
    )

<sgrl-list> -> LIST( 'sgrl'
    <sgrh-ck>       // Segment reference header
    <segh-ck>       // Segment header
    [<UNFO-list>]   // Name, author, copyright, comments
    [<strh-ck>]     // Segment transition chunk
    [<trsl-list>]   // Track references
    )

This list starts with a segment reference header.

<sgrh-ck> -> ( 'sgrh' <DMUS_IO_SEGREF_HEADER> )

Next is a segment header. For the syntax of the <segh-ck> chunk, see Segment Form.

For <UNFO-list>, see Common Chunks.

The segment transition chunk specifies valid transitions from other segments to this segment. It is organized as follows:

<strh-ck> -> ( strh
    <DMUS_IO_TRANSITION_DEF>    // Default transition
    <DMUS_IO_TRANSITION_DEF>... // Additional transitions
    )

The last part of the segment reference list chunk contains track references that are used to create a segment from tracks in multiple segments:

<trsl-list> -> LIST( 'trsl'
    <tkrl-list>...
    )

This list consists in turn of an array of track reference lists, each of which is organized as follows:

<tkrl-list> -> ( 'tkrl'
    <tkrh-ck>       // Track reference header chunk
    <trkh-ck>       // Track header chunk
    [<trkx-ck>]     // Track flags
    )

This list consists of three chunks. The first consists of a header structure that identifies the segment containing the track:

tkrh-ck -> tkrh( <DMUS_IO_TRACKREF_HEADER> )

For the other two chunks of the track reference list, see Track Form.


Style Form

The following notation shows the organization of the top-level chunk of a style file. This form can also be contained within a Container Form.

RIFF( 'DMST'
    <styh-ck>       // Style header chunk
    <guid-ck>       // Unique identifier
    [<UNFO-list>]   // Name, author, copyright information, comments
    [<vers-ck>]     // Version chunk
    <part-list>...  // Array of parts in the style, used by patterns
    <pttn-list>...  // Array of patterns in the style
    <DMBD-form>...  // List of bands in the style
    [<prrf-list>]   // List of chordmap references in the style
)

<styh-ck>

This chunk contains the basic header information for a style.

<styh-ck> -> styh( <DMUS_IO_STYLE> )

<guid-ck>,<UNFO-list>, <vers-ck>

For information on these three chunks, see Common Chunks.

<part-list>

Each musical part in the style is described in a chunk with the following format.

<part-list> -> LIST('part'
    <prth-ck>       // Part header chunk
    [<UNFO-list>]
    [<note-ck>]     // Notes in part
    [<crve-ck>]     // Curves in part
    [<mrkr-ck>]     // Markers in part
    [<rsln-ck>]     // Variation resolutions in part
    [<anpn-ck>]     // Resolution anticipations in part
    )

The part list includes a header, an optional UNFO chunk, and a list of elements, as shown in the following notation. (For the UNFO list, see Common Chunks.)

<prth-ck> -> prth( <DMUS_IO_STYLEPART> )

<note-ck> -> note(
    < DWORD >  // Size of DMUS_IO_STYLENOTE
    < DMUS_IO_STYLENOTE >...
    )

<crve-ck> -> crve(
    < DWORD >  // Size of DMUS_IO_STYLECURVE
    < DMUS_IO_STYLECURVE >...
    )

<mrkr-ck> -> mrkr(
    < DWORD > // Size of DMUS_IO_STYLEMARKER
    < DMUS_IO_STYLEMARKER >...
    )

<rsln-ck> -> rsln(
    < DWORD > // Size of DMUS_IO_STYLERESOLUTION
    < DMUS_IO_STYLERESOLUTION >...
    )

<anpn-ck> -> anpn(
    < DWORD > Size of DMUS_IO_STYLE_ANTICIPATION
    < DMUS_IO_STYLE_ANTICIPATION >...
    )

<pttn-list>

Each pattern is described in a chunk with the following format.

<pttn-list> -> LIST( 'pttn'
    <ptnh-ck>       // Pattern header chunk
    <rhtm-ck>       // List of rhythms for chord matching
    <swpt-ck>       // List of pattern switch points
    [<UNFO-list>]
    [<mtfs-ck>]     // Motif settings chunk
    [<DMBD-form>]   // Band to be associated with the pattern
                    // (for motifs)
    <pref-list>...  // Array of part reference IDs
    )

The first chunk of the pattern list is a header:

<ptnh-ck> -> ptnh( <DMUS_IO_PATTERN> )

The second chunk is a rhythm list:

<rhtm-ck> -> rhtm( <DWORD>... )

This chunk consists of an array of DWORDs, one for each measure, giving the rhythm pattern. For information on the arrangement of the bits, see the dwRhythmPattern member of DMUS_RHYTHM_PARAM.

The third chunk of the pattern list is the switch point chunk:

<swpt-ck> -> swpt( <DWORD>... )

The switch point chunk consists of an array of DWORDs, one for each measure, giving valid points where the pattern can start.

For the optional UNFO list, see Common Chunks.

The next chunk of the pattern list describes the motif settings:

<mtfs-ck> -> mtfs( <DMUS_IO_MOTIFSETTINGS> )

For the <DMBD-form> chunk of the pattern list, see Band Form.

The last chunk of the pattern list is a part reference list.

<pref-list> -> LIST( 'pref'
    <prfc-ck>   // Part reference chunk
    )

The only element is a part reference.

<prfc-ck> -> prfc( <DMUS_IO_PARTREF> )

<DMBD-form>

The next chunk in the style form is a Band Form.

<prrf-list>

The final chunk contains an array of chordmap references:

<prrf-list> -> LIST( 'prrf'
    <DMRF-list>...
    )

For more information on <DMRF-list>, see Reference List.


Tool Form

The tool form contains information about tools. Tools can be embedded in a Toolgraph Form or stored as separate files.

<DMTL-form> -> RIFF( 'DMTL'
    <tolh-ck>
    [<data>]        // Tool data
)

<tolh-ck>

This is the tool header chunk.

<tolh-ck> -> tolh( <DMUS_IO_TOOL_HEADER> )

<data>

The <data> element is a chunk of the type identified in the DMUS_IO_TOOL_HEADER structure. The format of this chunk depends on the definition of the tool. It can be a list or a normal chunk.


Toolgraph Form

A toolgraph chunk can occur either as a top-level form or as a subchunk of a Segment Form or Container Form.

RIFF( 'DMTG'
    [<guid-ck>]     // GUID for toolgraph
    [<vers-ck>]     // Version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    <toll-list>     // List of tools
)

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<toll-list>

The main and only required part of the toolgraph chunk is the tool list, which consists of an array of tool forms:

<toll-list> -> LIST( 'toll'
    <DMTL-form>...
    )

For more information on the <DMTL-form> chunk, see Tool Form.


Track Form

The track form contains information about a single track. It can be embedded in a Segment Form or stored in its own file.

<DMTK-form> -> RIFF( 'DMTK'
    <trkh-ck>
    [<trkx-ck>]     // Optional track flags
    [<guid-ck>]     // GUID for track object instance
    [<vers-ck>]     // Version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    [<data>]        // Track data
)

<trkh-ck>

The first chunk contains the basic header information for a track.

<trkh-ck> -> trkh( <DMUS_IO_TRACK_HEADER> )

<trkx-ck>

This optional chunk contains flags for the track.

<trkx-ck> -> trkx( <DMUS_IO_TRACK_EXTRAS_HEADER> )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<data>

The last element in the track form is the data for the track. The chunk type used for the data is identified in the DMUS_IO_TRACK_HEADER structure. The following standard track chunks are defined:

  • Band Track Form
  • Chord Track List
  • Chord Map Track List
  • Command Track Chunk
  • Lyrics Track List
  • Marker Track List
  • Melody Formulation Track List
  • Mute Track Chunk
  • Parameter Control Track List
  • Pattern Track Form
  • Script Track List
  • Segment Trigger Track List
  • Sequence Track Chunk
  • Signpost Track Chunk
  • Style Track List
  • Sysex Track Chunk
  • Tempo Track Chunk
  • Time Signature Track List
  • Wave Track List


Band Track Form

The band track form can be a top-level form but is also found as the data part of a Track Form. It is organized as follows:

RIFF( 'DMBT'
    [<bdth-ck>]     // Band track header
    [<guid-ck>]     // GUID for band track
    [<vers-ck>]     // Version information
    [<UNFO-list>]   // Name, author, copyright information, comments
    <lbdl-list>     // List of band lists
    )

<bdth-ck>

This optional chunk contains header information for a band track. The only data in the structure is a flag for automatic downloading.

<bnth-ck> -> bdth( <DMUS_IO_BAND_TRACK_HEADER> )

<guid-ck>, <vers-ck>, <UNFO-list>

For information on these three chunks, see Common Chunks.

<lbdl-list>

The last chunk contains one or more bands.

<lbdl-list> -> LIST( 'lbdl'
    <lbnd-list>...
    )

Each band is encapsulated in a list of the following type.

<lbnd-list> -> LIST( 'lbnd'
    <bdih-ck> or <bd2h-ck>
    <DMBD-form>
    )

The band list begins with a header. In older files, this is <bdih-ck>; newer content uses <bd2h-ck>.

<bdih-ck> -> ( <DMUS_IO_BAND_ITEM_HEADER> )

<bd2h-ck> -> ( <DMUS_IO_BAND_ITEM_HEADER2> )

The header is followed by a Band Form containing information about the instruments in the band.


Chord Track List

The chord track list contains chord data for a Track Form. It is organized as follows:

<cord-list> -> LIST( 'cord'
    <crdh-ck>       // Header
    <crdb-ck>       // Chord body chunk
    )

<crdh-ck>

<crdh-ck> -> crdh ( <DWORD> )

The header is a DWORD containing the chord root in the upper 8 bits and the scale in the lower 24 bits. For an explanation of what these bits represent, see DMUS_IO_SUBCHORD.

The body of data for the chord track list consists of information about a chord change and the component subchords:

<crdb-ck> -> crdb(
    <DWORD>           // Size of DMUS_IO_CHORD
    <DMUS_IO_CHORD>
    <DWORD>           // Number of subchords
    <DWORD>           // Size of DMUS_IO_SUBCHORD
    <DMUS_IO_SUBCHORD>...
    )


Chord Map Track List

The chordmap track list contains data for a Track Form. It is organized as follows:

<pftr-list> -> LIST('pftr'
    <pfrf-list>...
    )

The data consists of one or more lists containing time stamps and references to chordmaps:

<pfrf-list> -> LIST('pfrf'
    <stmp-ck>
    <DMRF-list>
    )

The notation for the time stamp chunk is as follows:

<stmp-ck> -> stmp( <DWORD> )

For information on <DMRF-list>, see Reference List.


Command Track Chunk

The command track chunk contains data for a Track Form. It is organized as follows:

<cmnd-ck> -> cmnd(
    <DWORD>    //Size of DMUS_IO_COMMAND
    <DMUS_IO_COMMAND>...
    )


Lyrics Track List

The lyrics track list contains data for a Track Form.

<lyrt-list> -> LIST( 'lyrt'
    <lyrl-list>
    )

The sole chunk in the lyrics track list is another list containing an array of lyrics events:

<lyrl-list> -> LIST(
    <lyre-list>...
    )

Each lyrics event is stored in another list, as follows:

<lyre-list> -> LIST(
    <lyrh-ck>         // Event header chunk
    <lyrn-ck>         // Notification text
    )

The first chunk is a header:

<lyrh-ck> -> lyrh( <DMUS_IO_LYRICSTRACK_EVENTHEADER> )

The second chunk contains the text associated with the event, in a null-terminated string:

<lyrn-ck> -> lyrn( <WCHAR>... )


Marker Track List

The marker track list contains data for a Track Form. It is organized as follows:

<mark-list> -> LIST ( 'MARK'
    [<vals-ck>]
    [<play-ck>]
)

The first element in the list is an array of chunks defining valid start points:

<vals-ck> -> vals(
    DWORD    // size of DMUS_IO_VALID_START
    <DMUS_IO_VALID_START>...
    )

The second element is an array of chunks defining valid play points.

<play-ck> -> play(
    DWORD    // size of DMUS_IO_PLAYMARKER
    <DMUS_IO_PLAYMARKER>...
    )


Melody Formulation Track List

Not implemented in DirectX 8.0.

The melody formulation track list contains data for a Track Form. It is organized as follows:

<mfrm-list> -> LIST( 'mfrm'
    <mlfh-ck>    // Melody formulation header
    <mlfb-ck>    // Melody formulation body
    )

The melody formulation header chunk looks like this:

<mlfb-ck> -> mlfb( <DMUS_IO_MELFORM> )

The body of the data is stored in the following chunk:

<mlfb-ck> -> mlfb(
    <DWORD>    //size of DMUS_IO_MELODY_FRAGMENT
    <DMUS_IO_MELODY_FRAGMENT>...
    )

DMUS_IO_MELODY_FRAGMENT is defined as equivalent to DMUS_MELODY_FRAGMENT.


Mute Track Chunk

The mute track chunk contains data for a Track Form. It is organized as follows:

<mute-ck> -> mute(
    <DWORD>    //Size of DMUS_IO_MUTE
    <DMUS_IO_MUTE>...
    )


Parameter Control Track List

The parameter control track list contains data for a Track Form.

<prmt-list> -> LIST( 'prmt'
    <prol-list>...
    )

The list contains an array of lists, each of which describes an object.

<prol-list> -> LIST( 'proh'
    <proh-ck>       // Object header chunk
    <prpl-list>...  // Array of parameters
    )

The first chunk in the object list is a header.

<proh-ck> -> proh( <DMUS_IO_PARAMCONTROLTRACK_OBJECTHEADER> )

The second chunk contains parameter lists, organized as shown in the following notation:

<prpl-list> -> LIST( 'prpl'
    <prph-ck>       // Parameter header
    <prcc-ck>       // Array of curves
    )

The header of the parameter list is described as follows:

<prph-ck> -> prph( <DMUS_IO_PARAMCONTROLTRACK_PARAMHEADER> )

The array of curves is described in the following chunk.

<prcc-ck> -> prcc(
    <DWORD>   // Sizeof DMUS_IO_PARAMCONTROLTRACK_CURVEINFO
   <DMUS_IO_PARAMCONTROLTRACK_CURVEINFO>... // Curves, sorted in order of mtTime
    )


Pattern Track Form

The pattern track form can be a top-level form but is also found as data for a Track Form. It is organized as follows:

RIFF( 'DMPT'
    <styh-ck>       // Style header chunk
    <pttn-list>     // The pattern
    )

For information on <styh-ck> and <pttn-list>, see Style Form.


Script Track List

The script track list contains data for a Track Form.

<scrt-list> -> LIST( 'scrt'
    <scrl-list>
    )

The list contains another list that contains an array of script events.

<scrl-list> -> LIST( 'scrl'
    <scre-list>...
    )

Each <scre-list> chunk describes an event as follows:

<scre-list> -> LIST( 'scre'
    <scrh-ck>         // Event header chunk
    <DMRF>            // Reference
    <scrn-ck>         // Routine name
    )

Each script track event begins with a header:

<scrh-ck> -> 'scrh'( <DMUS_IO_SCRIPTTRACK_EVENTHEADER> )

For information on the DMRF chunk, see Reference List.

The last chunk of the script track event is the null-terminated name of a routine:

<scrn-ck> -> 'scrn'( <WCHAR>... )


Segment Trigger Track List

The segment trigger track list contains data for a Track Form. It is organized as follows:

<SEGT-list> -> LIST( 'segt'
    [<sgth-ck>]     // Segment track header
    <lsgl-list>     // List of segment lists
    )

The first chunk is the track header:

<sgth-ck> -> 'sgth' ( <DMUS_IO_SEGMENT_TRACK_HEADER> )

The next chunk is a list containing an array of segments:

<lsgl-list> -> LIST( 'lsgl'
    <lseg-list>...
    )

Each "lseg" list describes a single segment item:

<lseg-list> -> LIST( 'lseg'
    <sgih-ck>
    <DMRF-list>
    [<snam-ck>]    // Motif name
    )

The first chunk of the segment item is a header:

<sgih-ck> -> ( <DMUS_IO_SEGMENT_ITEM_HEADER> )

This is followed by a reference to a segment file or a style file. It is a reference to a style if the DMUS_SEGMENTTRACKF_MOTIF flag is present in the item header. For more information, see Reference List.

The last chunk of the segment item contains the null-terminated name of a motif, if the DMUS_SEGMENTTRACKF_MOTIF flag is present in the item header.

<snam-ck> -> ( <WCHAR>... )


Sequence Track Chunk

The sequence track chunk contains data for a Track Form. It is organized as follows:

<seqt> -> seqt(
    <evtl-ck>
    <curl-ck>
    )

The sequence track chunk can contain two chunks, one for sequence items and one for curve items:

<evtl-ck> -> evtl(
    <DWORD>     // Size of DMUS_IO_SEQ_ITEM
    <DMUS_IO_SEQ_ITEM>...
    )

<curl-ck> -> curl(
    <DWORD>     // Size of DMUS_IO_CURVE_ITEM
    <DMUS_IO_CURVE_ITEM>...
    )

Note The sequence track chunk does not conform to the convention that only RIFF and LIST chunks can have subchunks.


Signpost Track Chunk

The signpost track chunk contains data for a Track Form. It is organized as follows:

<sgnp-list> -> sgnp(
    <DWORD>    // Size of DMUS_IO_SIGNPOST
    <DMUS_IO_SIGNPOST>...
    )


Style Track List

The style track list contains data for a Track Form. It is organized as follows:

<sttr-list> -> LIST('sttr'(
    <strf-list>...
    )

The data consists of one or more lists containing time stamps and references to styles:

<strf-list> -> LIST('strf'(
    <stmp-ck>
    <DMRF-list>
    )

The first chunk contains time stamp data, as follows:

<stmp-ck> -> stmp( <DWORD> )

For information on <DMRF-list>, see Reference List.


Sysex Track Chunk

The sysex track chunk contains data for a Track Form. It is an array of system exclusive message items, each consisting of a DMUS_IO_SYSEX_ITEM structure followed by the number of bytes specified in the dwSysExLength member.

<syex-ck> -> 'syex' (
    {
    <DMUS_IO_SYSEX_ITEM>
    <BYTE>...     // Data
    }...
    )


Tempo Track Chunk

The tempo track chunk contains data for a Track Form. It is organized as follows:

<tetr-ck> -> tetr(
    <DWORD>    // Size of DMUS_IO_TEMPO_ITEM
    <DMUS_IO_TEMPO_ITEM>...
    )


Time Signature Track List

The time signature track list contains data for a Track Form. It is organized as follows:

<tims-list> -> LIST( 'TIMS'
    <tims-ck> // Time signatures
    )

The time signature array is contained in the following chunk:

<tims-ck> -> tims (
    <DWORD>  // Size of DMUS_IO_TIMESIGNATURE_ITEM
    <DMUS_IO_TIMESIGNATURE_ITEM>...
    )


Wave Track List

The following notation shows the organization of a chunk containing data for a wave track:

<wavt-list> -> LIST ( 'wavt'
    <wath-ck>      // Wave track header
    <wavp-list>... // Wave parts
    }

<wath-ck>

This chunk contains header information for a wave. It is followed by an array of lists describing wave parts:

<wath-ck> -> wath( <DMUS_IO_WAVE_TRACK_HEADER> )

<wavp-list>

<wavp-list> -> LIST ( 'wavp'
    <waph-ck>       //  Wave part header
    <wavi-list>     //  Wave items
    )

The wave part list begins with a header.

<waph-ck> -> 'waph' ( <DMUS_IO_WAVE_PART_HEADER> )

The second part of the wave part list is an array of wave items:

<wavi-list> -> LIST( 'wavi'
    <wave-list>...
    )

Each wave item is described in a list chunk as follows:

<wave-list> -> LIST( 'wave'
    <waih-ck>       //  Wave item header
    <DMRF-list>     //  Reference to wave object
    )

The wave description begins with a header chunk:

<waih-ck> -> ( <DMUS_IO_WAVE_ITEM_HEADER> )

For more information on <DMRF-list>, see Reference List.


Wave Header Chunk

The wave header chunk is a special chunk added to wave files for DirectMusic. It specifies streaming capabilities.

<wavh-ck> -> ( <DMUS_IO_WAVE_HEADER>)


DirectMusic File Structures

This section contains reference information for data structures used in DirectMusic files. Most applications do not need to know about these structures because each standard DirectMusic object handles the loading of its own data through its IPersistStream interface. The structures are chiefly of interest for music-authoring applications that need to save data in a format compatible with DirectMusic.

The following structures are used in DirectMusic files.

  • DMUS_IO_BAND_ITEM_HEADER
  • DMUS_IO_BAND_ITEM_HEADER2
  • DMUS_IO_BAND_TRACK_HEADER
  • DMUS_IO_BUFFER_ATTRIBUTES_HEADER
  • DMUS_IO_CHORD
  • DMUS_IO_CHORDENTRY
  • DMUS_IO_CHORDMAP
  • DMUS_IO_CHORDMAP_SIGNPOST
  • DMUS_IO_CHORDMAP_SUBCHORD
  • DMUS_IO_COMMAND
  • DMUS_IO_CONTAINED_OBJECT_HEADER
  • DMUS_IO_CONTAINER_HEADER
  • DMUS_IO_CURVE_ITEM
  • DMUS_IO_INSTRUMENT
  • DMUS_IO_LYRICSTRACK_EVENTHEADER
  • DMUS_IO_MELFORM
  • DMUS_IO_MOTIFSETTINGS
  • DMUS_IO_MUTE
  • DMUS_IO_NEXTCHORD
  • DMUS_IO_PARAMCONTROLTRACK_CURVEINFO
  • DMUS_IO_PARAMCONTROLTRACK_OBJECTHEADER
  • DMUS_IO_PARAMCONTROLTRACK_PARAMHEADER
  • DMUS_IO_PARTREF
  • DMUS_IO_PATTERN
  • DMUS_IO_PCHANNELTOBUFFER_HEADER
  • DMUS_IO_PLAYMARKER
  • DMUS_IO_PORTCONFIG_HEADER
  • DMUS_IO_REFERENCE
  • DMUS_IO_SCRIPT_HEADER
  • DMUS_IO_SCRIPTTRACK_EVENTHEADER
  • DMUS_IO_SEGMENT_HEADER
  • DMUS_IO_SEGMENT_ITEM_HEADER
  • DMUS_IO_SEGMENT_TRACK_HEADER
  • DMUS_IO_SEGREF_HEADER
  • DMUS_IO_SEQ_ITEM
  • DMUS_IO_SIGNPOST
  • DMUS_IO_SONG_HEADER
  • DMUS_IO_STYLE
  • DMUS_IO_STYLE_ANTICIPATION
  • DMUS_IO_STYLECURVE
  • DMUS_IO_STYLEMARKER
  • DMUS_IO_STYLENOTE
  • DMUS_IO_STYLEPART
  • DMUS_IO_STYLERESOLUTION
  • DMUS_IO_SUBCHORD
  • DMUS_IO_SYSEX_ITEM
  • DMUS_IO_TEMPO_ITEM
  • DMUS_IO_TIMESIG
  • DMUS_IO_TIMESIGNATURE_ITEM
  • DMUS_IO_TOOL_HEADER
  • DMUS_IO_TRACK_EXTRAS_HEADER
  • DMUS_IO_TRACK_HEADER
  • DMUS_IO_TRACKREF_HEADER
  • DMUS_IO_TRANSITION_DEF
  • DMUS_IO_VALID_START
  • DMUS_IO_VERSION
  • DMUS_IO_WAVE_HEADER
  • DMUS_IO_WAVE_ITEM_HEADER
  • DMUS_IO_WAVE_PART_HEADER
  • DMUS_IO_WAVE_TRACK_HEADER
  • DSOUND_IO_3D
  • DSOUND_IO_DSBUFFERDESC
  • DSOUND_IO_DSBUSID
  • DSOUND_IO_DXDMO_DATA
  • DSOUND_IO_DXDMO_HEADER

See Also

DirectMusic File Format


DMUS_IO_BAND_ITEM_HEADER

Contains information about a band change. Used in the Band Track Form of older files. It has been superseded by DMUS_IO_BAND_ITEM_HEADER2.

typedef struct _DMUS_IO_BAND_ITEM_HEADER {
    MUSIC_TIME lBandTime;
} DMUS_IO_BAND_ITEM_HEADER;

Members

lBandTime
Time of the band change.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_BAND_ITEM_HEADER2

Contains information about a band change. Used in the Band Track Form.

typedef struct _DMUS_IO_BAND_ITEM_HEADER2 {
    MUSIC_TIME lBandTimeLogical;
    MUSIC_TIME lBandTimePhysical;
} DMUS_IO_BAND_ITEM_HEADER2;

Members

lBandTimeLogical
Time in the music with which the band change is associated.
lBandTimePhysical
Precise time when band change will take effect. Should be close to logical time.

Requirements

Header: Declared in dmusicf.h.

See Also

Segment Timing


DMUS_IO_BAND_TRACK_HEADER

Contains information about the default behavior of a band track. Used in the Band Track Form.

typedef struct _DMUS_IO_BAND_TRACK_HEADER {
    BOOL bAutoDownload;
} DMUS_IO_BAND_TRACK_HEADER;

Members

bAutoDownload
Flag for automatic downloading of instruments when a segment is played.

Remarks

For more information on automatic downloading, see Using Bands.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_BUFFER_ATTRIBUTES_HEADER

Describes attributes of a DirectSound buffer. Used in the Audiopath Form.

typedef struct _DMUS_IO_BUFFER_ATTRIBUTES_HEADER {
    GUID    guidBufferID;
    DWORD   dwFlags;
} DMUS_IO_BUFFER_ATTRIBUTES_HEADER;

Members

guidBufferID
Unique identifier of the buffer configuration. The following values are defined for standard buffer types.

GUID_Buffer_Reverb
GUID_Buffer_EnvReverb
GUID_Buffer_Stereo
GUID_Buffer_3D_Dry
GUID_Buffer_Mono

dwFlags
Flags describing the buffer. The following values are defined.
DMUS_BUFFERF_DEFINED
One of the standard buffer types.
DMUS_BUFFERF_MIXIN
Mix-in buffer.
DMUS_BUFFERF_SHARED
Buffer shared among audiopaths.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_CHORD

Contains information about a chord change. Used in the Chord Track List.

typedef struct _DMUS_IO_CHORD {
    WCHAR       wszName[16];
    MUSIC_TIME  mtTime;
    WORD        wMeasure;
    BYTE        bBeat;
    BYTE        bFlags
} DMUS_IO_CHORD;

Members

wszName
Name of the chord.
mtTime
Time of the chord.
wMeasure
Measure that the chord falls on.
bBeat
Beat that the chord falls on.
bFlags
Flags. The following value is defined.
DMUS_CHORDKEYF_SILENT
The chord is silent. See the Remarks for DMUS_CHORD_KEY.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_CHORDENTRY

Contains information about a chord entry. Used in the Chord Map Form.

typedef struct _DMUS_IO_CHORDENTRY {
    DWORD   dwFlags;
    WORD    wConnectionID;
} DMUS_IO_CHORDENTRY;

Members

dwFlags
Flag indicating whether the chord is a starting chord (bit 2 set) or an ending chord (bit 3 set) in the chord graph.
wConnectionID
Replaces the run-time pointer to this. Each chord entry is tagged with a unique connection identifier.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_CHORDMAP

Contains information about a chordmap. Used in the Chord Map Form.

typedef struct _DMUS_IO_CHORDMAP {
    WCHAR   wszLoadName[20];
    DWORD   dwScalePattern;
    DWORD   dwFlags;
} DMUS_IO_CHORDMAP;

Members

wszLoadName
Name of the chordmap, used in the object description when the chordmap is loaded.
dwScalePattern
Scale associated with the chordmap. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.
dwFlags
Flags. Can be zero or the following value:
DMUS_CHORDMAPF_VERSION8
The chordmap was created for DirectX 8.0 or later.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_CHORDMAP_SIGNPOST

Contains information about a signpost chord in a chordmap. Used in the Chord Map Form.

typedef struct _DMUS_IO_CHORDMAP_SIGNPOST {
    DWORD   dwChords;
    DWORD   dwFlags;
} DMUS_IO_CHORDMAP_SIGNPOST;

Members

dwChords
Types of signpost supported by this chord. The values are used to match against the same values as they appear in templates. Composing from template consists of (among other things) looking for these values in the template and finding actual chords in the chordmap that match these values. The following flags are defined:
DMUS_SIGNPOSTF_A
DMUS_SIGNPOSTF_B
DMUS_SIGNPOSTF_C
DMUS_SIGNPOSTF_D
DMUS_SIGNPOSTF_E
DMUS_SIGNPOSTF_F
DMUS_SIGNPOSTF_LETTER
DMUS_SIGNPOSTF_1
DMUS_SIGNPOSTF_2
DMUS_SIGNPOSTF_3
DMUS_SIGNPOSTF_4
DMUS_SIGNPOSTF_5
DMUS_SIGNPOSTF_6
DMUS_SIGNPOSTF_7
DMUS_SIGNPOSTF_ROOT
DMUS_SIGNPOSTF_CADENCE
dwFlags
Flags defining whether this chord is to be preceded by cadence chords. Signpost chords can have up to two cadence chords. This value can be SPOST_CADENCE1 (first cadence), SPOST_CADENCE2 (second cadence), or a combination of these two flags.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_IO_SIGNPOST


DMUS_IO_CHORDMAP_SUBCHORD

Contains information about a subchord. Used in the Chord Map Form.

typedef struct _DMUS_IO_CHORDMAP_SUBCHORD {
    DWORD   dwChordPattern;
    DWORD   dwScalePattern;
    DWORD   dwInvertPattern;
    BYTE    bChordRoot;
    BYTE    bScaleRoot;
    WORD    wCFlags;
    DWORD   dwLevels;
} DMUS_IO_CHORDMAP_SUBCHORD;

Members

dwChordPattern
Notes in the subchord. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the chord.
dwScalePattern
Notes in the scale. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.
dwInvertPattern
Points in the scale at which inversions can occur. Bits that are off signify that the notes in the interval cannot be inverted. Thus, the pattern 100001111111 indicates that inversions are allowed anywhere except between the fifth and seventh degrees of a major scale.
bChordRoot
Root of the subchord, where 0 is the lowest C in the range and 23 is the top B.
bScaleRoot
Root of the scale, where 0 is the lowest C in the range and 23 is the top B.
wCFlags
Reserved for future use.
dwLevels
Bit field showing which levels are supported by this subchord. Each part in a style is assigned a level, and this chord is used only for parts whose levels are contained in this member.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_SUBCHORD


DMUS_IO_COMMAND

Contains information about a command event. Used in the Command Track Chunk.

typedef struct _DMUS_IO_COMMAND {
    MUSIC_TIME  mtTime;
    WORD        wMeasure;
    BYTE        bBeat;
    BYTE        bCommand;
    BYTE        bGrooveLevel;
    BYTE        bGrooveRange;
    BYTE        bRepeatMode;
} DMUS_IO_COMMAND;

Members

mtTime
Time of the command.
wMeasure
Measure that the command falls on.
bBeat
Beat that the command falls on.
bCommand
Command type. See DMUS_COMMANDT_TYPES.
bGrooveLevel
Groove level, or 0 if the command is not a groove command.
bGrooveRange
Size of the range within which the groove level can be randomized. If this value is an odd number, the groove range is bGrooveRange – 1. For instance, if the groove level is 35 and bGrooveRange is 5, the adjusted groove range is 4 and the groove level could be anywhere from 33 to 37.
bRepeatMode
Flag that specifies how patterns are selected for repetition. See DMUS_PATTERNT_TYPES.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_CONTAINED_OBJECT_HEADER

Used before each object in a Container Form.

typedef struct _DMUS_IO_CONTAINED_OBJECT_HEADER {
    GUID        guidClassID;
    DWORD       dwFlags;
    FOURCC      ckid;
    FOURCC      fccType;
} DMUS_IO_CONTAINED_OBJECT_HEADER;

Members

guidClassID
Class identifier of the object.
dwFlags
Can be zero or the following flag.
DMUS_CONTAINED_OBJF_KEEP
Keep the object cached in the loader after the container is released.
ckid
Identifier of the data chunk. If this value is zero, it is assumed that the chunk is of type LIST, so fccType is valid and must be nonzero.
fccType
List type. If this value is zero, ckid is valid and must be nonzero.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_CONTAINER_HEADER

Used in the Container Form.

typedef struct _DMUS_IO_CONTAINER_HEADER {
    DWORD       dwFlags;
} DMUS_IO_CONTAINER_HEADER;

Members

dwFlags
DWORD value that specifies flags. Can be zero or the following value.
DMUS_CONTAINER_NOLOADS
Contained items are not loaded when the container is loaded. Entries are created in the loader, but the objects are not created until they are specifically loaded.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_CURVE_ITEM

Contains information about a curve event in a track. Used in the Sequence Track Chunk.

typedef struct _DMUS_IO_CURVE_ITEM {
    MUSIC_TIME  mtStart;
    MUSIC_TIME  mtDuration;
    MUSIC_TIME  mtResetDuration;
    DWORD       dwPChannel;
    short       nOffset;
    short       nStartValue;
    short       nEndValue;
    short       nResetValue;
    BYTE        bType;
    BYTE        bCurveShape;
    BYTE        bCCData;
    BYTE        bFlags;
    WORD        wParamType;
    WORD        wMergeIndex
} DMUS_IO_CURVE_ITEM;

Members

mtStart
Start time of the curve.
mtDuration
Duration of the curve.
mtResetDuration
Time after the curve is finished during which a reset can occur.
dwPChannel
Performance channel for the event.
nOffset
Offset from the grid boundary at which the curve occurs, in music time. Because MIDI curves are associated with the closest grid when loaded, this value can be positive or negative.
nStartValue
Start value.
nEndValue
End value.
nResetValue
Reset value, set upon a flush or invalidation within the time set by mtResetDuration.
bType
Type of curve. The following types are defined:
DMUS_CURVET_CCCURVE
Continuous controller curve (MIDI Control Change channel voice message; status byte &HBn, where n is the channel number).
DMUS_CURVET_MATCURVE
Monophonic aftertouch curve (MIDI Channel Pressure channel voice message; status byte &HDn).
DMUS_CURVET_PATCURVE
Polyphonic aftertouch curve (MIDI Poly Key Pressure channel voice message, status byte &HDn).
DMUS_CURVET_PBCURVE
Pitch-bend curve (MIDI Pitch Bend channel voice message; status byte &HEn).
DMUS_CURVET_NRPNCURVE
NRPN curve.
DMUS_CURVET_RPNCURVE
RPN curve.
bCurveShape
Shape of curve. The following shapes are defined:
DMUS_CURVES_EXP
Exponential curve shape.
DMUS_CURVES_INSTANT
Instant curve shape (beginning and end of curve happen at essentially the same time).
DMUS_CURVES_LINEAR
Linear curve shape.
DMUS_CURVES_LOG
Logarithmic curve shape.
DMUS_CURVES_SINE
Sine curve shape.
bCCData
CC number if this is a control change type.
bFlags
Set to DMUS_CURVE_RESET if the nResetValue must be set when an invalidation occurs because of a transition. If 0, the curve stays permanently at the new value. All other bits are reserved.
wParamType
Parameter number for RPN and NRPN types.
wMergeIndex
Merge index. Supported for mod wheel, reverb send, chorus send, pitch bend, volume, and expression controllers.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_IO_SEQ_ITEM, Curves


DMUS_IO_INSTRUMENT

Contains information about an instrument. Used in the Band Form.

typedef struct _DMUS_IO_INSTRUMENT {
    DWORD  dwPatch;
    DWORD  dwAssignPatch;
    DWORD  dwNoteRanges[4];
    DWORD  dwPChannel;
    DWORD  dwFlags;
    BYTE   bPan;
    BYTE   bVolume;
    short  nTranspose;
    DWORD  dwChannelPriority;
    short  nPitchBendRange;
} DMUS_IO_INSTRUMENT;

Members

dwPatch
MSB, LSB, and program change to define instrument.
dwAssignPatch
MSB, LSB, and program change to assign to instrument when downloading.
dwNoteRanges
128 bits; one for each MIDI note that the instrument must be able to play.
dwPChannel
Performance channel that the instrument plays on.
dwFlags
Control flags. The following values are defined:
DMUS_IO_INST_ASSIGN_PATCH
The dwAssignPatch member is valid.
DMUS_IO_INST_BANKSELECT
The dwPatch member contains a valid bank select, both MSB and LSB.
DMUS_IO_INST_CHANNEL_PRIORITY
The dwChannelPriority member is valid.
DMUS_IO_INST_GM
Instrument is from the General MIDI collection.
DMUS_IO_INST_GS
Instrument is from the Roland GS collection.
DMUS_IO_INST_NOTERANGES
The dwNoteRanges member is valid.
DMUS_IO_INST_PAN
The bPan member is valid.
DMUS_IO_INST_PATCH
The dwPatch member is valid.
DMUS_IO_INST_PITCHBENDRANGE
The nPitchBendRange member is valid.
DMUS_IO_INST_TRANSPOSE
The nTranspose member is valid.
DMUS_IO_INST_USE_DEFAULT_GM_SET
The default General MIDI instrument set should be downloaded to the port, even if the port has GM in hardware. When a MIDI file that contains an XG or GS reset is parsed, the bank-select message is sent, whether or not GUID_StandardMIDIFile was commanded on the band. In other words, GUID_StandardMIDIFile is effective only for pure GM files.
DMUS_IO_INST_VOLUME
The bVolume member is valid.
DMUS_IO_INST_XG
Instrument is from the Yamaha XG collection.
bPan
Pan for the instrument.
bVolume
Volume for the instrument.
nTranspose
Number of semitones to transpose notes.
dwChannelPriority
Channel priority. For a list of defined values, see IDirectMusicPort8::GetChannelPriority.
nPitchBendRange
Number of semitones shifted by pitch bend.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_LYRICSTRACK_EVENTHEADER

Used in a Lyrics Track List.

typedef struct _DMUS_IO_LYRICSTRACK_EVENTHEADER {
    DWORD dwFlags;
    DWORD dwTimingFlags;
    MUSIC_TIME lTimeLogical;
    MUSIC_TIME lTimePhysical;
} DMUS_IO_LYRICSTRACK_EVENTHEADER;

Members

dwFlags
Reserved; must be zero.
dwTimingFlags
Flags to determine the timing of the notification. Can be one or more of the following members of the DMUS_PMSGF_FLAGS enumeration.
DMUS_PMSGF_TOOL_IMMEDIATE
Message should be processed immediately, regardless of its time stamp.
DMUS_PMSGF_TOOL_QUEUE
Message should be processed just before its time stamp, allowing for port latency.
DMUS_PMSGF_TOOL_ATTIME
Message should be processed at the time stamp.
lTimeLogical
Time in the music with which the event is associated.
lTimePhysical
Precise time when the event will be triggered. This should be close to logical time.

Requirements

Header: Declared in dmusicf.h.

See Also

Logical Time vs. Actual Time


DMUS_IO_MELFORM

Not implemented in DirectX 8.0.

Used in the Melody Formulation Track List.

typedef struct _DMUS_IO_MELFORM {
    DWORD  dwPlaymode;
} DMUS_IO_MELFORM;

Members

dwPlaymode
Reserved. Must be 0.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_MOTIFSETTINGS

Contains information about a motif. Used in the Style Form.

typedef struct _DMUS_IO_MOTIFSETTINGS {
    DWORD       dwRepeats;
    MUSIC_TIME  mtPlayStart;
    MUSIC_TIME  mtLoopStart;
    MUSIC_TIME  mtLoopEnd;
    DWORD       dwResolution;
} DMUS_IO_MOTIFSETTINGS;

Members

dwRepeats
Number of repetitions.
mtPlayStart
Start of playback, normally 0.
mtLoopStart
Start of looping portion, normally 0.
mtLoopEnd
End of looping portion. Must be greater than mtLoopStart, or zero to loop the entire motif.
dwResolution
Default resolution. See DMUS_TIME_RESOLVE_FLAGS.

Requirements

Header: Declared in dmusicf.h.

See Also

IDirectMusicSegment8::SetLoopPoints


DMUS_IO_MUTE

Contains information about a mute event on a channel. Used in the Mute Track Chunk.

typedef struct _DMUS_IO_MUTE {
    MUSIC_TIME  mtTime;
    DWORD       dwPChannel;
    DWORD       dwPChannelMap;
} DMUS_IO_MUTE;

Members

mtTime
Time of the event.
dwPChannel
Performance channel to mute or remap.
dwPChannelMap
Channel to which dwPChannel is being mapped, or 0xFFFFFFFF if dwPChannel is to be muted.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_MUTE_PARAM


DMUS_IO_NEXTCHORD

Contains information about the next chord in a chord graph. Used in the Chord Map Form.

typedef struct _DMUS_IO_NEXTCHORD {
    DWORD   dwFlags;
    WORD    nWeight;
    WORD    wMinBeats;
    WORD    wMaxBeats;
    WORD    wConnectionID;
} DMUS_IO_NEXTCHORD;

Members

dwFlags
Reserved for future use.
nWeight
Likelihood (in the range from 1 through 100) that this link is followed when traversing the chord graph.
wMinBeats
Smallest number of beats that this chord is allowed to play in a composed segment.
wMaxBeats
Largest number of beats that this chord is allowed to play in a composed segment.
wConnectionID
Refers to the wConnectionID member of a DMUS_IO_CHORDENTRY structure.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_PARAMCONTROLTRACK_CURVEINFO

Used in a Parameter Control Track List.

typedef struct _DMUS_IO_PARAMCONTROLTRACK_CURVEINFO {
    MUSIC_TIME  mtStartTime;
    MUSIC_TIME  mtEndTime;
    float       fltStartValue;
    float       fltEndValue;
    DWORD       dwCurveType;
    DWORD       dwFlags;
} DMUS_IO_PARAMCONTROLTRACK_CURVEINFO;

Members

mtStartTime
Start time of the curve.
mtEndTime
End time of the curve.
fltStartValue
Start value of the curve.
fltEndValue
End value of the curve.
dwCurveType
Item from the MP_CURVE_TYPE enumeration. See MP_CURVE_TYPE in the DirectShow documentation.
dwFlags
Combination of the MPF_ENVLP_* constants. See Envelope Flags in the DirectShow documentation.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_PARAMCONTROLTRACK_OBJECTHEADER

Used in the Parameter Control Track List.

typedef struct _DMUS_IO_PARAMCONTROLTRACK_OBJECTHEADER {
    DWORD dwFlags;
    GUID guidTimeFormat;
    DWORD dwPChannel;
    DWORD dwStage;
    DWORD dwBuffer;
    GUID guidObject;
    DWORD dwIndex;
} DMUS_IO_PARAMCONTROLTRACK_OBJECTHEADER;

Members

dwFlags
Reserved; must be zero.
guidTimeFormat
Time format to set the object to. Must be GUID_TIME_REFERENCE or GUID_TIME_MUSIC, which are defined in Medparam.h.
dwPChannel
Performance channel, 0, or DMUS_PCHANNEL_ALL.
dwStage
Stage in the path.
dwBuffer
Index of the buffer, if there is more than one.
guidObject
Class identifier of the object, such as GUID_DSFX_STANDARD_CHORUS.
dwIndex
Index of the object in the list of matching objects.

Remarks

For more information on the possible values for each member, see IDirectMusicSegmentState8::GetObjectInPath.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_PARAMCONTROLTRACK_PARAMHEADER

Used in the Parameter Control Track List.

typedef struct _DMUS_IO_PARAMCONTROLTRACK_PARAMHEADER {
    DWORD dwFlags;
    DWORD dwIndex;
} DMUS_IO_PARAMCONTROLTRACK_PARAMHEADER;

Members

dwFlags
Reserved; must be zero.
dwIndex
Index number of the parameter on the object.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_PARTREF

Contains information about a part reference. Used in the Style Form.

typedef struct _DMUS_IO_PARTREF {
    GUID  guidPartID;
    WORD  wLogicalPartID;
    BYTE  bVariationLockID;
    BYTE  bSubChordLevel;
    BYTE  bPriority;
    BYTE  bRandomVariation;
    WORD  wPad;
    DWORD dwPChannel;
} DMUS_IO_PARTREF;

Members

guidPartID
Identifier of the part.
wLogicalPartID
Identifier corresponding to a particular MIDI channel on a port. This member has been superseded by dwPChannel and is no longer used.
bVariationLockID
Variation lock identifier. Parts with the same value in this member always play the same variation. A value of 0 means that the part plays its variations independently of all other parts.
bSubChordLevel
Subchord level that this part wants. See Remarks.
bPriority
Reserved for future use.
bRandomVariation
Can be 0, meaning that matching variations play sequentially, or one of the members of the DMUS_VARIATIONT_TYPES enumeration.
wPad
Padding for alignment; value not used.
dwPChannel
Performance channel of the part.

Remarks

The bSubChordLevel member contains a zero-based index value. At run time, 1 is shifted left by this value to yield a 1-bit value for comparison with the dwLevels member of a DMUS_SUBCHORD structure. Thus, a part with a bSubChordLevel of 0 would be mapped to any subchord that contained 1 in dwLevels.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_PATTERN

Contains information about a pattern. Used in the Style Form.

typedef struct _DMUS_IO_PATTERN {
    DMUS_IO_TIMESIG  timeSig;
    BYTE             bGrooveBottom;
    BYTE             bGrooveTop;
    WORD             wEmbellishment;
    WORD             wNbrMeasures;
    BYTE             bDestGrooveBottom;
    BYTE             bDestGrooveTop;
    DWORD            dwFlags;
} DMUS_IO_PATTERN;

Members

timeSig
DMUS_IO_TIMESIG structure containing a time signature to override the style's default time signature.
bGrooveBottom
Bottom of the groove range.
bGrooveTop
Top of the groove range.
wEmbellishment
Type of embellishment. One of the constants from the DMUS_COMMANDT_TYPES enumeration, or a value defined by the content provider.
wNbrMeasures
Length of the pattern in measures.
bDestGrooveBottom
Bottom of groove range for next pattern.
bDestGrooveTop
Top of groove range for next pattern.
dwFlags
Flags. Can be zero or the following value:
DMUS_PATTERNF_PERSIST_CONTROL
Variation settings in the state data of a pattern-based track persist in the track after it stops playing.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_PCHANNELTOBUFFER_HEADER

Defines a range of performance channels and the buffers they connect to. Used in the port configuration list of an Audiopath Form.

typedef struct _DMUS_IO_PCHANNELTOBUFFER_HEADER {
    DWORD  dwPChannelBase;
    DWORD  dwPChannelCount;
    DWORD  dwBufferCount;
    DWORD  dwFlags;
} DMUS_IO_PCHANNELTOBUFFER_HEADER;

Members

dwPChannelBase
First performance channel.
dwPChannelCount
Number of performance channels.
dwBufferCount
Number of buffers the channels connect to.
dwFlags
Reserved. Must be 0.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_PLAYMARKER

Contains information about a play marker, which is a point within a primary segment where a new segment is permitted to start playing. Used in the Marker Track List.

typedef struct _DMUS_IO_PLAY_MARKER {
    MUSIC_TIME mtTime;
} DMUS_IO_PLAY_MARKER;

Members

mtTime
Time of legal play point.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_PORTCONFIG_HEADER

Used in the Audiopath Form.

typedef struct _DMUS_IO_PORTCONFIG_HEADER {
    GUID    guidPort;
    DWORD   dwPChannelBase;
    DWORD   dwPChannelCount;
    DWORD   dwFlags;
} DMUS_IO_PORTCONFIG_HEADER;

Members

guidPort
Unique identifier of port.
dwPChannelBase
First performance channel.
dwPChannelCount
Number of performance channels.
dwFlags
Configuration flags. The following values are defined.
DMUS_PORTCONFIGF_DRUMSON10
Drums are on channel 10.
DMUS_PORTCONFIGF_USEDEFAULT
Use the default port.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_REFERENCE

Contains information about a reference to another object that might be stored in another file. Used in the Reference List chunk.

typedef struct _DMUS_IO_REFERENCE {
    GUID    guidClassID;
    DWORD   dwValidData;
} DMUS_IO_REFERENCE;

Members

guidClassID
Class identifier.
dwValidData
Flags to indicate which data chunks for the reference are present. For a list of values, see the corresponding member of DMUS_OBJECTDESC.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_SCRIPT_HEADER

Used in the Script Form.

typedef struct _DMUS_IO_SCRIPT_HEADER {
    DWORD  dwFlags;
} DMUS_IO_SCRIPT_HEADER;

Members

dwFlags
DWORD value that specifies the loading behavior of the script. Can be one or more of the following values.
DMUS_SCRIPTIOF_LOAD_ALL_CONTENT
All content in the script's container is loaded.
DMUS_SCRIPTIOF_DOWNLOAD_ALL_SEGMENTS
If DMUS_SCRIPTIOF_LOAD_ALL_CONTENT is set, the bands from all the segments in the script's container are downloaded when the script is initialized. Otherwise, a segment's bands are downloaded when the script loads the segment.

If DMUS_SCRIPTIOF_DOWNLOAD_ALL_SEGMENTS is not set, the script must manually download and unload the segment's bands.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_SCRIPTTRACK_EVENTHEADER

Used in a Script Track List.

typedef struct _DMUS_IO_SCRIPTTRACK_EVENTHEADER {
    DWORD dwFlags;
    MUSIC_TIME lTimeLogical;
    MUSIC_TIME lTimePhysical;
} DMUS_IO_SCRIPTTRACK_EVENTHEADER;

Members

dwFlags
Flag that determines when the event is set. Can be one of the following values.
DMUS_IO_SCRIPTTRACKF_PREPARE
Fire the event in advance of the time stamp, at prepare time. This is the default because it leaves the script enough time to change the music happening at the target time.
DMUS_IO_SCRIPTTRACKF_QUEUE
Fire the event just before the time stamp, at queue time.
DMUS_IO_SCRIPTTRACKF_ATTIME
Fire the event exactly at the time stamp.
lTimeLogical
Logical time of the event.
lTimePhysical
Actual time of the event.

Requirements

Header: Declared in dmusicf.h.

See Also

Logical Time vs. Actual Time


DMUS_IO_SEGMENT_HEADER

Contains information about a segment. Used in the Segment Form.

typedef struct _DMUS_IO_SEGMENT_HEADER {
    DWORD          dwRepeats;
    MUSIC_TIME     mtLength;
    MUSIC_TIME     mtPlayStart;
    MUSIC_TIME     mtLoopStart;
    MUSIC_TIME     mtLoopEnd;
    DWORD          dwResolution;
    REFERENCE_TIME rtLength;
    DWORD          dwFlags;
    DWORD          dwReserved;
} DMUS_IO_SEGMENT_HEADER;

Members

dwRepeats
Number of repetitions.
mtLength
Length of the segment.
mtPlayStart
Start of playback, normally 0.
mtLoopStart
Start of the looping portion, normally 0.
mtLoopEnd
End of the looping portion. Must be greater than mtPlayStart, or zero to loop the entire segment.
dwResolution
Default resolution. See DMUS_TIME_RESOLVE_FLAGS.
rtLength
Length of the segment in reference time. Valid if the DMUS_SEGIOF_REFLENGTH flag is set.
dwFlags
Can be zero or the following flag.
DMUS_SEGIOF_REFLENGTH
The value in rtLength overrides mtLength.
dwReserved
Reserved.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_IO_MOTIFSETTINGS, IDirectMusicSegment8::SetLoopPoints.


DMUS_IO_SEGMENT_ITEM_HEADER

Contains information about a segment referenced in the Segment Trigger Track List.

typedef struct _DMUS_IO_SEGMENT_ITEM_HEADER{
    MUSIC_TIME      lTimeLogical;
    MUSIC_TIME      lTimePhysical;
    DWORD           dwPlayFlags;
    DWORD           dwFlags;
} DMUS_IO_SEGMENT_ITEM_HEADER;

Members

lTimeLogical
Time in the music with which the event is associated.
lTimePhysical
Actual time at which the segment is to play.
dwPlayFlags
Flags that will be passed to IDirectMusicPerformance8::PlaySegmentEx. See DMUS_SEGF_FLAGS.
dwFlags
Can be zero or the following value.
DMUS_SEGMENTTRACKF_MOTIF
The DMRF chunk is a link to a style, and the 'snam' chunk is the name of a motif within the style.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_SEGMENT_TRACK_HEADER

Contains information about a Segment Trigger Track List.

typedef struct _DMUS_IO_SEGMENT_TRACK_HEADER {
    DWORD dwFlags;
} DMUS_IO_SEGMENT_TRACK_HEADER;

Members

dwFlags
Reserved. Must be zero.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_SEGREF_HEADER

Not implemented in DirectX 8.0.

Contains information about a segment reference in a Song Form.

typedef struct _DMUS_IO_SEGREF_HEADER {
    DWORD       dwID;
    DWORD       dwSegmentID;
    DWORD       dwToolGraphID;
    DWORD       dwFlags;
    DWORD       dwNextPlayID;
} DMUS_IO_SEGREF_HEADER;

Members

dwID
Unique identifier of the segment. Must not be greater than DMUS_SONG_MAXSEGID.
dwSegmentID
Identifier of an optional source segment to link to.
dwToolGraphID
Identifier of an optional toolgraph to use for processing.
dwFlags
Reserved. Must be zero.
dwNextPlayID
Identifier of next segment in song chain.


DMUS_IO_SEQ_ITEM

Contains information about an item of data in a sequence track. Used in the Sequence Track Chunk.

typedef struct _DMUS_IO_SEQ_ITEM {
    MUSIC_TIME  mtTime;
    MUSIC_TIME  mtDuration;
    DWORD       dwPChannel;
    short       nOffset
    BYTE        bStatus;
    BYTE        bByte1;
    BYTE        bByte2;
} DMUS_IO_SEQ_ITEM;

Members

mtTime
Logical time of the event.
mtDuration
Duration for which the event is valid.
dwPChannel
Performance channel for the event.
nOffset
Offset from mtTime at which the note is played, in music time.
bStatus
MIDI event type. Equivalent to the MIDI status byte, but without channel information.
bByte1
First byte of the MIDI data.
bByte2
Second byte of the MIDI data.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_IO_CURVE_ITEM, MIDI Messages


DMUS_IO_SIGNPOST

Contains information about a signpost in a signpost track to associate it with signpost chords in a chordmap. Used in the Signpost Track Chunk.

typedef struct _DMUS_IO_SIGNPOST {
    MUSIC_TIME  mtTime;
    DWORD       dwChords;
    WORD        wMeasure;
} DMUS_IO_SIGNPOST;

Members

mtTime
Time of the signpost.
dwChords
Types of signpost chords allowed to be associated with this signpost. The values are used to match against the same values as they appear in templates. Composing from a template consists of (among other things) looking for these values in the template and finding actual chords in the chordmap that match these values. The following flags are defined:
DMUS_SIGNPOSTF_A
DMUS_SIGNPOSTF_B
DMUS_SIGNPOSTF_C
DMUS_SIGNPOSTF_D
DMUS_SIGNPOSTF_E
DMUS_SIGNPOSTF_F
DMUS_SIGNPOSTF_LETTER
DMUS_SIGNPOSTF_1
DMUS_SIGNPOSTF_2
DMUS_SIGNPOSTF_3
DMUS_SIGNPOSTF_4
DMUS_SIGNPOSTF_5
DMUS_SIGNPOSTF_6
DMUS_SIGNPOSTF_7
DMUS_SIGNPOSTF_ROOT
DMUS_SIGNPOSTF_CADENCE

wMeasure
Measure on which the signpost falls.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_IO_CHORDMAP_SIGNPOST


DMUS_IO_SONG_HEADER

Not implemented in DirectX 8.0.

Contains information about a Song Form.

typedef struct _DMUS_IO_SONG_HEADER {
    DWORD  dwFlags;
    DWORD  dwStartSegID;
} DMUS_IO_SONG_HEADER;

Members

dwFlags
Reserved.
dwStartSegID
Identifier of the segment to play first.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_STYLE

Contains information about the time signature and tempo of a style. Used in the Style Form.

typedef struct _DMUS_IO_STYLE {
    DMUS_IO_TIMESIG  timeSig;
    double           dblTempo;
} DMUS_IO_STYLE;

Members

timeSig
DMUS_IO_TIMESIG structure containing the default time signature for the style.
dblTempo
Tempo of the style.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_STYLE_ANTICIPATION

Describes a resolution anticipation. Used in the Style Form.

typedef struct _DMUS_IO_STYLE_ANTICIPATION {
    MUSIC_TIME    mtGridStart;
    DWORD         dwVariation;
    short         nTimeOffset;
    BYTE          bTimeRange;
} DMUS_IO_STYLE_ANTICIPATION;

Members

mtGridStart
Offset within the part, in grids, at which the event is to play. See Remarks.
dwVariation
Variations, where each bit set specifies a valid variation.
nTimeOffset
Offset of the time from mtGridStart.
bTimeRange
Range by which to randomize time. See Remarks.

Remarks

The time of the event can be calculated as follows, where TimeSig is a DMUS_IO_TIMESIG structure containing the time signature.

mtEventTime = nTimeOffset + ((mtGridStart / TimeSig.wGridsPerBeat) *
((DMUS_PPQ * 4) / TimeSig.bBeat) + (mtGridStart %
TimeSig.wGridsPerBeat) * (((DMUS_PPQ * 4)/ TimeSig.bBeat) /
TimeSig.wGridsPerBeat))

The value in bTimeRange is converted to music time when the event occurs, according to the formula given in the Remarks to DMUS_IO_STYLENOTE.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_STYLECURVE

Contains information about a curve in a style. Used in the Style Form.

typedef struct _DMUS_IO_STYLECURVE {
    MUSIC_TIME  mtGridStart;
    DWORD       dwVariation;
    MUSIC_TIME  mtDuration;
    MUSIC_TIME  mtResetDuration;
    short       nTimeOffset;
    short       nStartValue;
    short       nEndValue;
    short       nResetValue;
    BYTE        bEventType;
    BYTE        bCurveShape;
    BYTE        bCCData;
    BYTE        bFlags;
    WORD        wParamType;
    WORD        wMergeIndex;
} DMUS_IO_STYLECURVE;

Members

mtGridStart
Offset, in grids, at which the curve occurs.
dwVariation
Variations that this curve belongs to. Each bit corresponds to one of 32 variations.
mtDuration
Duration of the curve.
mtResetDuration
Time after the curve is finished during which a reset can occur.
nTimeOffset
Offset from mtGridStart at which the curve occurs. See the Remarks for DMUS_IO_STYLE_ANTICIPATION.
nStartValue
Start value.
nEndValue
End value.
nResetValue
Reset value, set upon a flush or invalidation during the time specified by mtResetDuration.
bEventType
Type of curve. See DMUS_IO_CURVE_ITEM.
bCurveShape
Shape of curve. See DMUS_IO_CURVE_ITEM.
bCCData
CC number if this is a control change type.
bFlags
Set to DMUS_CURVE_RESET if the nResetValue must be set when an invalidation occurs because of a transition. If 0, the curve stays permanently at the new value. All other bits are reserved.
wParamType
RPN or NRPN parameter number.
wMergeIndex
Merge index. Supported for mod wheel, reverb send, chorus send, pitch bend, volume, and expression controllers.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_CURVE_PMSG, DMUS_IO_CURVE_ITEM


DMUS_IO_STYLEMARKER

Contains information about a marker in a style. Used in the Style Form.

typedef struct _DMUS_IO_STYLEMARKER {
    MUSIC_TIME  mtGridStart;
    DWORD       dwVariation;
    WORD        wMarkerFlags;
} DMUS_IO_STYLEMARKER;

Members

mtGridStart
Offset, in grids, at which the marker occurs.
dwVariation
Variations that this marker belongs to. Each bit corresponds to one of 32 variations.
wMarkerFlags
Flags that specify behavior of the marker. Can be zero or one or more of the following values. If zero, the behavior is as it was in DirectX version 7.0.
DMUS_MARKERF_START
Start a variation.
DMUS_MARKERF_STOP
Stop a variation.
DMUS_MARKERF_CHORD_ALIGN
New variations must align with a chord. This flag is ignored unless combined with one or both of DMUS_MARKERF_START and DMUS_MARKERF_STOP.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_STYLENOTE

Contains information about a note in a style. Used in the Style Form.

typedef struct _DMUS_IO_STYLENOTE {
    MUSIC_TIME  mtGridStart;
    DWORD       dwVariation;
    MUSIC_TIME  mtDuration;
    short       nTimeOffset;
    WORD        wMusicValue;
    BYTE        bVelocity;
    BYTE        bTimeRange;
    BYTE        bDurRange;
    BYTE        bVelRange;
    BYTE        bInversionID;
    BYTE        bPlayModeFlags;
    BYTE        bNoteFlags;
} DMUS_IO_STYLENOTE;

Members

mtGridStart
Offset, in grids, at which the note occurs.
dwVariation
Variations that this note belongs to. Each bit corresponds to one of 32 variations.
mtDuration
Duration of the note.
nTimeOffset
Time after mtGridStart at which the event occurs. See the Remarks for DMUS_IO_STYLE_ANTICIPATION.
wMusicValue
Position in the scale.
bVelocity
Note velocity.
bTimeRange
Range within which to randomize start time. See Remarks.
bDurRange
Range within which to randomize duration. See Remarks.
bVelRange;
Range within which to randomize velocity.
bInversionID
Identifier of inversion group to which this note belongs.
bPlayModeFlags
Flags to override the play mode of the part. For a list of values, see DMUS_PLAYMODE_FLAGS.
bNoteFlags
Flags. See DMUS_NOTEF_FLAGS.

Remarks

The values in bTimeRange and bDurRange are converted to music time when the note is played, using the following function:

int StoredRangeToActualRange(BYTE bRange)
{
    int nResult = 0;
    if (0 <= bRange && bRange <= 190)
    {
        nResult = bRange;
    }
    else if (191 <= bRange && bRange <= 212)
    {
        nResult = ((bRange - 190) * 5) + 190;
    }
    else if (213 <= bRange && bRange <= 232)
    {
        nResult = ((bRange - 212) * 10) + 300;
    }
    else // bRange > 232
    {
        nResult = ((bRange - 232) * 50) + 500;
    }
    return nResult;
}

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_STYLEPART

Contains information about a musical part. Used in the Style Form.

typedef struct _DMUS_IO_STYLEPART {
    DMUS_IO_TIMESIG  timeSig;
    DWORD            dwVariationChoices[32];
    GUID             guidPartID;
    WORD             wNbrMeasures;
    BYTE             bPlayModeFlags;
    BYTE             bInvertUpper;
    BYTE             bInvertLower;
    BYTE             bPad[3];
    DWORD            dwFlags;
} DMUS_IO_STYLEPART;

Members

timeSig
DMUS_IO_TIMESIG structure containing a time signature to override the style's default time signature.
dwVariationChoices
Each element corresponds to one of 32 possible variations. The flags set in each element indicate which types of chord are supported by that variation (see Remarks). One of the mode masks is also set to indicate whether the variations are in DirectMusic or IMA mode.

The following flags are defined:

DMUS_VARIATIONF_MAJOR
Seven positions in the scale for major chords.
DMUS_VARIATIONF_MINOR
Seven positions in the scale for minor chords.
DMUS_VARIATIONF_OTHER
Seven positions in the scale for other chords.
DMUS_VARIATIONF_ROOT_SCALE
Handles chord roots in the scale.
DMUS_VARIATIONF_ROOT_FLAT
Handles flat chord roots (based on scale notes).
DMUS_VARIATIONF_ROOT_SHARP
Handles sharp chord roots (based on scale notes).
DMUS_VARIATIONF_TYPE_TRIAD
Handles simple chords for triads.
DMUS_VARIATIONF_TYPE_6AND7
Handles simple chords for 6 and 7.
DMUS_VARIATIONF_TYPE_COMPLEX
Handles complex chords.
DMUS_VARIATIONF_DEST_TO1
Handles transitions to the 1 chord.
DMUS_VARIATIONF_DEST_TO5
Handles transitions to the 5 chord.
DMUS_VARIATIONF_MODES
Mode mask. Obsolete.
DMUS_VARIATIONF_MODES_EX
Mode mask.
DMUS_VARIATIONF_IMA25_MODE
Mode mask. If (dwVariationChoices & DMUS_VARIATIONF_MODES_EX) == DMUS_VARIATIONF_IMA25_MODE, the variations are in Interactive Music Architecture mode.
DMUS_VARIATIONF_DMUS_MODE
Mode mask. If dwVariationChoices contains this mask, the variations are in DirectMusic mode. All variations authored in DirectMusic Producer use this mode.
guidPartID
Unique identifier of the part.
wNbrMeasures
Length of the part, in measures.
bPlayModeFlags
Flags to define the play mode. For a list of values, see DMUS_PLAYMODE_FLAGS.
bInvertUpper
Upper limit of inversion.
bInvertLower
Lower limit of inversion.
bPad
Unused.
dwFlags
Flags that specify the behavior of the part. Can include the following values:
DMUS_PARTF_USE_MARKERS
Part uses marker events.
DMUS_PARTF_ALIGN_CHORDS
Part is allowed to switch only on chord-aligned markers.

Remarks

The flags in dwVariationChoices determine the types of chords supported by a given variation in DirectMusic mode. The first seven flags (bits 1 through 7) are set if the variation supports major chords rooted in scale positions. For example, if bits 1, 2, and 4 are set, the variation supports major chords rooted in the tonic, second, and fourth scale positions. The next seven flags serve the same purpose for minor chords, and the following seven flags serve the same purpose for chords that are not major or minor (for example, SUS 4 chords). Bits 22, 23, and 24 are set if the variation supports chords rooted in the scale, chords rooted sharp of scale tones, and chords rooted flat of scale tones, respectively. For example, to support a C# minor chord in the scale of C major, bits 8 (for tonic minor) and 24 (for sharp) must be set. Bits 25, 26, and 27 handle chords that are triads, sixth or seventh chords, and chords with extensions, respectively. Bits 28 and 29 handle chords that are followed by tonic and dominant chords, respectively.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_STYLERESOLUTION

Describes a style resolution. Used in the Style Form.

typedef struct _DMUS_IO_STYLERESOLUTION {
    DWORD  dwVariation;
    WORD   wMusicValue;
    BYTE   bInversionID;
    BYTE   bPlayModeFlags;
} DMUS_IO_STYLERESOLUTION;

Members

dwVariation
Variations, where each bit specifies a valid variation.
wMusicValue
Position in scale.
bInversionID
Inversion group to which this note belongs.
bPlayModeFlags
Play mode flags. See DMUS_PLAYMODE_FLAGS.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_SUBCHORD

Contains information about a subchord. Used in the Chord Track List.

typedef struct _DMUS_IO_SUBCHORD {
    DWORD   dwChordPattern;
    DWORD   dwScalePattern;
    DWORD   dwInversionPoints;
    DWORD   dwLevels;
    BYTE    bChordRoot;
    BYTE    bScaleRoot;
} DMUS_IO_SUBCHORD;

Members

dwChordPattern
Notes in the subchord. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the chord.
dwScalePattern
Notes in the scale. Each of the lower 24 bits represents a semitone, starting with the root at the least significant bit, and the bit is set if the note is in the scale.
dwInversionPoints
Points in the scale at which inversions can occur. Bits that are off signify that the notes in the interval cannot be inverted. Thus, the pattern 100001111111 indicates that inversions are allowed anywhere except between the fifth and seventh degrees of a major scale.
dwLevels
Which levels are supported by this subchord. Certain instruments can be assigned different levels (such as to play only the lower subchords of a chord), and this value is a way of mapping subchords to those levels.
bChordRoot
Root of the subchord, where 0 is the lowest C in the range and 23 is the top B.
bScaleRoot
Root of the scale, where 0 is the lowest C in the range and 23 is the top B.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_SUBCHORD


DMUS_IO_SYSEX_ITEM

Contains information about a system exclusive MIDI message. Used in the Sysex Track Chunk.

typedef struct _DMUS_IO_SYSEX_ITEM {
    MUSIC_TIME  mtTime;
    DWORD       dwPChannel;
    DWORD       dwSysExLength;
} DMUS_IO_SYSEX_ITEM;

Members

mtTime
Time of the message.
dwPChannel
Performance channel of the event.
dwSysExLength
Length of the data, in bytes.

Requirements

Header: Declared in dmusicf.h.

See Also

MIDI System Messages


DMUS_IO_TEMPO_ITEM

Contains information about a tempo change in a track. Used in the Tempo Track Chunk.

typedef struct _DMUS_IO_TEMPO_ITEM {
    MUSIC_TIME  lTime;
    double      dblTempo;
} DMUS_IO_TEMPO_ITEM;

Members

lTime
Time of the tempo change.
dblTempo
Tempo, in beats per minute.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_TIMESIG

Contains information about the time signature of a segment. Used in the DMUS_IO_STYLE, DMUS_IO_VERSION, and DMUS_IO_PATTERN structures.

typedef struct _DMUS_IO_TIMESIG {
    BYTE  bBeatsPerMeasure;
    BYTE  bBeat;
    WORD  wGridsPerBeat;
} DMUS_IO_TIMESIG;

Members

bBeatsPerMeasure
Beats per measure (top of time signature).
bBeat
Note that receives the beat (bottom of the time signature), where 1 is a whole note, 2 is a half note, 4 is a quarter note, and so on. Zero is a 256th note.
wGridsPerBeat
Grids (subdivisions) per beat.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_IO_TIMESIGNATURE_ITEM


DMUS_IO_TIMESIGNATURE_ITEM

Contains information about a time signature change. Used in the Time Signature Track List.

typedef struct _DMUS_IO_TIMESIGNATURE_ITEM {
    MUSIC_TIME  lTime;
    BYTE        bBeatsPerMeasure;
    BYTE        bBeat;
    WORD        wGridsPerBeat;
} DMUS_IO_TIMESIGNATURE_ITEM;

Members

lTime
Time of the event.
bBeatsPerMeasure
Beats per measure (top of time signature).
bBeat
Note that receives the beat (bottom of the time signature), where 1 is a whole note, 2 is a half note, 4 is a quarter note, and so on. Zero is a 256th note.
wGridsPerBeat
Grids (subdivisions) per beat.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_IO_TIMESIG, DMUS_TIMESIG_PMSG


DMUS_IO_TOOL_HEADER

Contains information about a tool. Used in the Tool Form.

typedef struct _DMUS_IO_TOOL_HEADER {
    GUID    guidClassID;
    long    lIndex;
    DWORD   cPChannels;
    FOURCC  ckid;
    FOURCC  fccType;
    DWORD   dwPChannels[1];
} DMUS_IO_TOOL_HEADER;

Members

guidClassID
Class identifier of the tool.
lIndex
Position in the graph.
cPChannels
Number of items in the dwPChannels array.
ckid
Identifier of tool's data chunk. If this value is 0, it is assumed that the chunk is of type LIST, so fccType is valid and must be nonzero.
fccType
List type. If this value is 0, ckid is valid and must be nonzero.
dwPChannels
Array of performance channels for which the tool is valid.

Requirements

Header: Declared in dmusicf.h.

See Also

IDirectMusicGraph8::InsertTool


DMUS_IO_TRACK_EXTRAS_HEADER

Used in the Track Form.

typedef struct _DMUS_IO_TRACK_EXTRAS_HEADER {
    DWORD  dwFlags;
} DMUS_IO_TRACK_EXTRAS_HEADER;

Members

dwFlags
Flags for control tracks. For possible values, see IDirectMusicSegment8::SetTrackConfig.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_TRACK_HEADER

Contains information about a track. Used in the Track Form.

typedef struct _DMUS_IO_TRACK_HEADER {
    GUID     guidClassID;
    DWORD    dwPosition;
    DWORD    dwGroup;
    FOURCC   ckid;
    FOURCC   fccType;
} DMUS_IO_TRACK_HEADER;

Members

guidClassID
Class identifier of the track.
dwPosition
Position in the track list.
dwGroup
Group bits for the track.
ckid
Identifier of the track's data chunk. If this value is 0, it is assumed that the chunk is of type LIST, so fccType is valid and must be nonzero.
fccType
List type. If this value is 0, ckid is valid and must be nonzero.

Requirements

Header: Declared in dmusicf.h.

See Also

IDirectMusicSegment8::GetTrackGroup, IDirectMusicSegment8::InsertTrack, Track Form


DMUS_IO_TRACKREF_HEADER

Not implemented in DirectX 8.0.

Contains information about a track reference in a Song Form.

typedef struct _DMUS_IO_TRACKREF_HEADER {
    DWORD       dwSegmentID;
    DWORD       dwFlags;
} DMUS_IO_TRACKREF_HEADER;

Members

dwSegmentID
Identifier of the containing segment.
dwFlags
Reserved.


DMUS_IO_TRANSITION_DEF

Not implemented in DirectX 8.0.

Describes a transition. Used in the Song Form.

typedef struct _DMUS_IO_TRANSITION_DEF {
    DWORD  dwSegmentID;
    DWORD  dwTransitionID;
    DWORD  dwPlayFlags;
} DMUS_IO_TRANSITION_DEF;

Members

dwSegmentID
Segment after the transition, or one of the following constants:
DMUS_SONG_ANYSEG
Any segment.
DMUS_SONG_NOFROMSEG
No preceding segment; the transition is an intro.
DMUS_SONG_NOSEG
No following segment; the transition is an ending.
dwTransitionID
Template segment to use for the transition.
dwPlayFlags
Flags that control how the transition is played. See DMUS_SEGF_FLAGS.

Remarks

This structure describes a valid transition from another segment to this segment. When a song segment is played with the DMUS_SEGF_AUTOTRANSITION flag, a transition segment is composed and played. To find the appropriate transition segment, the performance looks at the currently playing segment and sees if it is a segment in the song. If it is, it gets the ID of that segment and then searches for it in the transition table of the destination segment. When it finds a match in dwSourceSegment, the performance composes dwTransitionSegment and plays it, using the dwPlayFlags.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_VALID_START

Contains information about a valid start point in a segment that is to be cued to a rhythm. Used in the Marker Track List.

typedef struct _DMUS_IO_VALID_START {
    MUSIC_TIME mtTime;
} DMUS_IO_VALID_START;

Members

mtTime
Time of the start point.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_VERSION

Contains the version number of the data. Used in the version subchunk of various chunks. See Common Chunks.

typedef struct _DMUS_IO_VERSION {
    DWORD  dwVersionMS;
    DWORD  dwVersionLS;
} DMUS_IO_VERSION;

Members

dwVersionMS
High-order 32 bits of the version number.
dwVersionLS
Low-order 32 bits of the version number.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_WAVE_HEADER

Describes streaming characteristics of a wave. Used in the Wave Header Chunk of a wave file.

typedef struct _DMUS_IO_WAVE_HEADER {
    REFERENCE_TIME  rtReadAhead;
    DWORD           dwFlags;
} DMUS_IO_WAVE_HEADER;

Members

rtReadAhead
Time to read ahead in a streaming wave.
dwFlags
Flags. Can be zero or the following value.
DMUS_WAVEF_STREAMING
The wave is a streaming wave.

Requirements

Header: Declared in dmusicf.h.


DMUS_IO_WAVE_ITEM_HEADER

Contains data for a wave sound in a Wave Track List.

typedef struct _DMUS_IO_WAVE_ITEM_HEADER {
    long           lVolume;
    long           lPitch;
    DWORD          dwVariations;
    REFERENCE_TIME rtTime;
    REFERENCE_TIME rtStartOffset;
    REFERENCE_TIME rtReserved;
    REFERENCE_TIME rtDuration;
    MUSIC_TIME     mtLogicalTime;
    DWORD          dwLoopStart;
    DWORD          dwLoopEnd;
    DWORD          dwFlags;
} DMUS_IO_WAVE_ITEM_HEADER;

Members

lVolume
Gain, in hundredths of a decibel. Must be a negative value.
lPitch
Pitch offset, in hundredths of a semitone.
dwVariations
Variation flags. One bit is set for each variation this wave belongs to.
rtTime
Start time, in reference time if the track is in clock time format; otherwise in music time.
rtStartOffset
Distance into wave to start playback, in reference time.
rtReserved
Not used.
rtDuration
Duration, in reference time if the track is in clock time format; otherwise in music time.
mtLogicalTime
Musical boundary where this belongs. Ignored if the track is in clock time format.
dwLoopStart
Start point for a looping wave.
dwLoopEnd
End point for a looping wave.
dwFlags
Flags. Can be 0 or one of the following values:
DMUS_WAVEF_NOINVALIDATE
This wave is not to be invalidated.
DMUS_WAVEF_STREAMING
Wave is streaming.

Requirements

Header: Declared in dmusicf.h.

Remarks

Logical Time vs. Actual Time


DMUS_IO_WAVE_PART_HEADER

Contains data for a Wave Track List.

typedef struct _DMUS_IO_WAVE_PART_HEADER {
    long   lVolume;
    DWORD  dwVariations;
    DWORD  dwPChannel;
    DWORD  dwLockToPart;
    DWORD  dwFlags;
    DWORD  dwIndex;
} DMUS_IO_WAVE_PART_HEADER;

Members

lVolume
Gain, in hundredths of a decibel, to apply to all waves in this wave part. This must be a negative value.
dwVariations
Active variations. One bit is set for each active variation.
dwPChannel
Performance channel of the part.
dwLockToPart
Variation lock identifier. Parts with the same value in this member always play the same variation. A value of 0 means that the part plays its variations independently of all other parts.
dwFlags
Flags for managing how variations are chosen, in the lower four bits. See DMUS_VARIATIONT_TYPES.
dwIndex
Index for distinguishing multiple parts on the same performance channel.


DMUS_IO_WAVE_TRACK_HEADER

Contains data for a wave track in a Wave Track List.

typedef struct _DMUS_IO_WAVE_TRACK_HEADER {
    long   lVolume;
    DWORD  dwFlags;
} DMUS_IO_WAVE_TRACK_HEADER;

Members

lVolume
Gain, hundredths of a decibel, to be applied to all waves.
dwFlags
Flags. Can be 0 or one or more of the following values:
DMUS_WAVETRACKF_SYNC_VAR
The track gets its variations from a pattern track. For more information, see GUID_Variations.
DMUS_WAVETRACKF_PERSIST_CONTROL
Variation control information persists from one playback instance to the next.

Requirements

Header: Declared in dmusicf.h.


DSOUND_IO_3D

Contains 3-D parameters for a DirectSound buffer in a DirectSound Buffer Configuration Form.

typedef struct _DSOUND_IO_3D {
    GUID guid3DAlgorithm;
    DS3DBUFFER ds3d;
} DSOUND_IO_3D;

Members

guid3DAlgorithm
Unique identifier of the 3-D algorithm to use. See DSBUFFERDESC.
ds3d
DS3DBUFFER structure that contains the parameters. This information is valid only if DSBCAPS_CTRL3D is set in the buffer description.

Requirements

Header: Declared in dmusicf.h.


DSOUND_IO_DSBUFFERDESC

Describes a DirectSound buffer. Used in the DirectSound Buffer Configuration Form.

typedef struct _DSOUND_IO_DSBUFFERDESC {
    DWORD dwFlags;
    WORD nChannels;
    LONG lVolume;
    LONG lPan;
    DWORD dwReserved;
} DSOUND_IO_DSBUFFERDESC;

Members

dwFlags
Buffer creation flags. See DSBUFFERDESC.
nChannels
Number of channels. Other parameters of the format are determined by the sink that owns the buffer.
lVolume
Initial volume. Used only if DSBCAPS_CTRLVOLUME is in dwFlags.
lPan
Initial pan. Used only if DSBCAPS_CTRLPAN is in dwFlags.
dwReserved
Reserved. Must be 0.

Requirements

Header: Declared in dmusicf.h.


DSOUND_IO_DSBUSID

Contains bus identifiers. Used in the DirectSound Buffer Configuration Form.

typedef struct _DSOUND_IO_DSBUSID {
    DWORD busid[1];
} DSOUND_IO_DSBUSID;

Members

busid
Array of DWORDs containing the bus identifiers. The size of the array can be determined from the chunk size.

Requirements

Header: Declared in dmusicf.h.


DSOUND_IO_DXDMO_DATA

Contains data for a DMO.

typedef struct _DSOUND_IO_DXDMO_DATA {
    DWORD data[1];
} DSOUND_IO_DXDMO_DATA;

Members

data
Array of DWORD values containing the data. The size of the array can be determined from the chunk size.

Requirements

Header: Declared in dmusicf.h.


DSOUND_IO_DXDMO_HEADER

Contains header information for a DMO chunk in an Effects Form.

typedef struct _DSOUND_IO_DXDMO_HEADER {
    DWORD dwEffectFlags;
    GUID guidDSFXClass;
    GUID guidReserved;
    GUID guidSendBuffer;
    DWORD dwReserved;
} DSOUND_IO_DXDMO_HEADER;

Members

dwEffectFlags
Effect creation flags. See DSEFFECTDESC.
guidDSFXClass
Class identifier of the effect.
guidReserved
Reserved. Must be GUID_NULL.
guidSendBuffer
Unique identifier of the buffer to send to, if this is a send effect.
dwReserved
Reserved. Must be 0.

Requirements

Header: Declared in dmusicf.h.


Standard Track Parameters

This section describes the standard track parameters that can be set and retrieved by using the following methods.

  • IDirectMusicPerformance8::GetParam
  • IDirectMusicPerformance8::GetParamEx
  • IDirectMusicPerformance8::SetParam
  • IDirectMusicSegment8::GetParam
  • IDirectMusicSegment8::SetParam
  • IDirectMusicTrack8::GetParam
  • IDirectMusicTrack8::GetParamEx
  • IDirectMusicTrack8::SetParam
  • IDirectMusicTrack8::SetParamEx

Parameter types are listed in this section under their GUIDs, as specified in the rGuidType parameter of the method call.

The following information is given for each parameter type:

Element | Description
Track type | Tracks to which the parameters apply. See Standard Track Types. Although parameters are always associated with particular tracks, applications usually call the method on the segment or the performance and let DirectMusic find the appropriate track. See Identifying the Track.
Data type | Type of data pointed to by the pParam parameter of the method call by which the parameter is set or retrieved.
mtTime | Significance, if any, of the mtTime parameter of the method call by which the parameter is set or retrieved.

Parameter types are as follows:

  • GUID_BandParam
  • GUID_ChordParam
  • GUID_Clear_All_Bands
  • GUID_Clear_All_MelodyFragments
  • GUID_CommandParam
  • GUID_CommandParam2
  • GUID_CommandParamNext
  • GUID_ConnectToDLSCollection
  • GUID_Disable_Auto_Download
  • GUID_DisableTempo
  • GUID_DisableTimeSig
  • GUID_Download
  • GUID_DownloadToAudioPath
  • GUID_Enable_Auto_Download
  • GUID_EnableTempo
  • GUID_EnableTimeSig
  • GUID_IDirectMusicBand
  • GUID_IDirectMusicChordMap
  • GUID_IDirectMusicStyle
  • GUID_MelodyFragment
  • GUID_MuteParam
  • GUID_Play_Marker
  • GUID_RhythmParam
  • GUID_SeedVariations
  • GUID_StandardMIDIFile
  • GUID_TempoParam
  • GUID_TimeSignature
  • GUID_Unload
  • GUID_UnloadFromAudioPath
  • GUID_Valid_Start_Time
  • GUID_Variations


GUID_BandParam

Sets or retrieves a band.

Track type | Band
Data type (*pParam) | DMUS_BAND_PARAM
mtTime | The logical time at which to set the band, or the time for which to retrieve the band

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_ChordParam

Sets or retrieves a chord change.

Track type | Chord
Data type (*pParam) | DMUS_CHORD_PARAM
mtTime | The time, in track time, at which to add the chord to the track, or the time at or directly after the chord to be retrieved from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_Clear_All_Bands

Clears all bands from the track. This parameter can be set but not retrieved.

Track type | Band
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_Clear_All_MelodyFragments

Not implemented in DirectX 8.0.

Clears all melody fragments from the track. This parameter can be set but not retrieved.

Track type | Melody fragment
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_CommandParam

Sets or retrieves a groove or embellishment command.

Track type | Command
Data type (*pParam) | DMUS_COMMAND_PARAM_2
mtTime | The time, in track time, at which to add the command to the track, or the time at or directly after the command to be retrieved from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_CommandParam2

Sets or retrieves a groove or embellishment command.

Track type | Command
Data type (*pParam) | DMUS_COMMAND_PARAM_2. The mtTime member of this structure gives the actual time of the command.
mtTime | The time, in track time, at which to add the command to the track, or the time at or directly after the command to be retrieved from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_CommandParamNext

Sets or retrieves a groove or embellishment command to follow all other commands in the command track.

Track type | Command
Data type (*pParam) | DMUS_COMMAND_PARAM_2
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_ConnectToDLSCollection

Connects all bands in the track to a DLS collection. This parameter can be set but not retrieved.

Track type | Band
Data type (*pParam) | IDirectMusicCollection8 pointer
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

Playing a MIDI File with Custom Instruments.


GUID_Disable_Auto_Download

Disables automatic downloading of instruments and waves. This parameter can be set but not retrieved.

Track type | Band, wave
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

Using Bands, GUID_Enable_Auto_Download


GUID_DisableTempo

Disables tempo messages. This parameter can be set but not retrieved.

Track type | Tempo
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

Disabling and Enabling Track Parameters, GUID_EnableTempo


GUID_DisableTimeSig

Disables time signature messages. This parameter can be set but not retrieved.

Track type | Pattern, time signature, style, motif
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

Disabling and Enabling Track Parameters, GUID_EnableTimeSig


GUID_Download

Downloads instrument data or wave data. This parameter can be set but not retrieved.

Track type | Band, wave
Data type (*pParam) | IDirectMusicPerformance8 pointer
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::Download


GUID_DownloadToAudioPath

Downloads instrument data or wave data. This parameter can be set but not retrieved.

Track type | Band, wave
Data type (*pParam) | IDirectMusicAudioPath8 pointer
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicSegment8::Download


GUID_Enable_Auto_Download

Enables automatic downloading of instruments and waves. This parameter can be set but not retrieved.

Track type | Band, wave
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

Using Bands, GUID_Disable_Auto_Download


GUID_EnableTempo

Enables tempo messages. This parameter can be set but not retrieved.

Track type | Tempo
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

Disabling and Enabling Track Parameters, GUID_DisableTempo


GUID_EnableTimeSig

Enables time signature messages. This parameter can be set but not retrieved.

Track type | Pattern, time signature, style, motif
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

Disabling and Enabling Track Parameters, GUID_DisableTimeSig


GUID_IDirectMusicBand

Sets a band. This parameter can be set but not retrieved.

Track type | Band
Data type (*pParam) | IDirectMusicBand8
mtTime | The time, in track time, at which to add the band to the track

Remarks

For an explanation of the table, see Standard Track Parameters.

This parameter has been superseded by GUID_BandParam, which allows you to specify the physical time.

Requirements

Header: Declared in dmusici.h.


GUID_IDirectMusicChordMap

Sets or retrieves the chordmap.

Track type | Chordmap
Data type (*pParam) | IDirectMusicChordMap8 pointer or address of a variable to receive this pointer
mtTime | The time, in track time, at which to add the chordmap to the track, or the time at or directly after the chordmap to be retrieved from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_IDirectMusicStyle

Sets or retrieves the style.

Track type | Style
Data type (*pParam) | IDirectMusicStyle8 pointer or address of a variable to receive this pointer
mtTime | The time, in track time, at which to add the style to the track, or the time at or directly after the style to be retrieved from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_MelodyFragment

Not implemented in DirectX 8.0.

Sets or retrieves a melody fragment.

Track type | Melody fragment
Data type (*pParam) | DMUS_MELODY_FRAGMENT
mtTime | The time, in track time, at which to add the fragment to the track, or the time at or directly after the fragment to retrieve from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_MuteParam

Sets or retrieves channel-mapping information.

Track type | Mute
Data type (*pParam) | DMUS_MUTE_PARAM. The dwPChannel member must be initialized before this structure is passed to the get method.
mtTime | The time, in track time, at which to add the mute event to the track, or the time at or directly after the mute event to be retrieved from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

You cannot dynamically change the mapping or muting of a channel by setting this parameter while the mute track is playing. Parameters in the mute track are retrieved by internal GetParam calls from other tracks, and the application has no control over the timing of such calls. Changes in the mapping or muting of channels should be authored into the mute track of a segment played as a controlling segment, or done at run time by tools.

Requirements

Header: Declared in dmusici.h.


GUID_Play_Marker

Retrieves the next point in the currently playing segment at which a new segment can start. This parameter can be retrieved but not set.

Track type | Marker
Data type (*pParam) | DMUS_PLAY_MARKER_PARAM
mtTime | Track time at which to start seeking a marker

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.

See Also

Segment Timing


GUID_RhythmParam

Retrieves the rhythm pattern for a sequence of chords stored in a measure in the track. This parameter can be retrieved but not set.

Track type | Chord
Data type (*pParam) | DMUS_RHYTHM_PARAM. The TimeSig member must be initialized before this structure is passed to the get method.
mtTime | The time, in track time, at or directly after the beginning of the measure containing the rhythm pattern to be retrieved from the track

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_SeedVariations

Seeds the random number generator for variation selection. A nonzero value is used as the seed. A value of 0 resets the default behavior of getting the seed from the system clock. This parameter can be set but not retrieved.

Track type | Pattern, style, motif
Data type (*pParam) | Long
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

Setting this parameter to nonzero is useful for testing because it ensures that the same sequence of random numbers is generated each time. The parameter should be set only once, before the track is played. The style and command track must be designed so that each time that the segment is played, the same patterns are chosen at the same places in the segment. Each loop plays different variations than the one before it does, but each time the entire segment is replayed from the beginning, each loop sounds the same as the first time the segment was played.

Requirements

Header: Declared in dmusici.h.


GUID_StandardMIDIFile

Ensures that a standard MIDI file (one not authored specifically for DirectMusic) plays correctly. This parameter can be set but not retrieved.

Track type | Band
Data type (*pParam) | None
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

This parameter must be set for any segment based on a standard MIDI file before any instruments are downloaded.

Requirements

Header: Declared in dmusici.h.


GUID_TempoParam

Sets or retrieves the tempo.

Track type | Tempo
Data type (*pParam) | DMUS_TEMPO_PARAM. When setting the parameter, the mtTime member of the structure is ignored. When getting the parameter, the mtTime member receives the offset of the tempo change from the requested time and is always 0 or less.
mtTime | The time, in track time, at which to set the tempo, or the time at or directly after the tempo change to retrieve

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_TimeSignature

Obtains the time signature. This parameter can be retrieved but not set.

Track type | Time signature and style
Data type (*pParam) | DMUS_TIMESIGNATURE. The mtTime member receives the offset of the time signature change from the requested time and is always 0 or less.
mtTime | The time, in track time, at which to set the time signature, or the time at or directly after the time signature change to retrieve

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


GUID_Unload

Unloads instrument or wave data. This parameter can be set but not retrieved.

Track type | Band, wave
Data type (*pParam) | IDirectMusicPerformance8 pointer
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

See Also

IDirectMusicSegment8::Unload

Requirements

Header: Declared in dmusici.h.


GUID_UnloadFromAudioPath

Unloads instrument or wave data. This parameter can be set but not retrieved.

Track type | Band, wave
Data type (*pParam) | IDirectMusicAudioPath8 pointer
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

See Also

IDirectMusicSegment8::Unload

Requirements

Header: Declared in dmusici.h.


GUID_Valid_Start_Time

Obtains the next valid point within a segment at which it can start. This parameter can be retrieved but not set.

Track type | Marker, motif, pattern
Data type (*pParam) | DMUS_VALID_START_PARAM
mtTime | Not used

Remarks

For an explanation of the table, see Standard Track Parameters.

See Also

Segment Timing

Requirements

Header: Declared in dmusici.h.


GUID_Variations

Obtains the variations in effect across performance channels. This parameter can be retrieved but not set.

Track type | Pattern
Data type (*pParam) | DMUS_VARIATIONS_PARAM
mtTime | Not used.

Remarks

For an explanation of the table, see Standard Track Parameters.

Requirements

Header: Declared in dmusici.h.


DirectMusic Enumerated Types

This section contains references for the following enumerated types:

  • DMUS_CHORDKEYF_FLAGS
  • DMUS_CLOCKTYPE
  • DMUS_COMMANDT_TYPES
  • DMUS_COMPOSEF_FLAGS
  • DMUS_CURVE_FLAGS
  • DMUS_NOTEF_FLAGS
  • DMUS_PATTERNT_TYPES
  • DMUS_PLAYMODE_FLAGS
  • DMUS_PMSGF_FLAGS
  • DMUS_PMSGT_TYPES
  • DMUS_SEGF_FLAGS
  • DMUS_SHAPET_TYPES
  • DMUS_STYLET_TYPES
  • DMUS_TIME_RESOLVE_FLAGS
  • DMUS_TRACKF_FLAGS
  • DMUS_VARIATIONT_TYPES


DMUS_CHORDKEYF_FLAGS

Used in the bFlags member of the DMUS_CHORD_KEY structure.

typedef enum enumDMUS_CHORDKEYF_FLAGS {
    DMUS_CHORDKEYF_SILENT  = 1,
} DMUS_CHORDKEYF_FLAGS;

Constants

DMUS_CHORDKEYF_SILENT
The chord is silent.

Requirements

Header: Declared in dmusici.h.


DMUS_CLOCKTYPE

Used in the ctType member of the DMUS_CLOCKINFO8 structure.

typedef enum {
    DMUS_CLOCK_SYSTEM = 0,
    DMUS_CLOCK_WAVE   = 1
} DMUS_CLOCKTYPE;

Constants

DMUS_CLOCK_SYSTEM
Clock is the system clock.
DMUS_CLOCK_WAVE
Clock is on a wave-playback device.

Requirements

Header: Declared in dmusicc.h.


DMUS_COMMANDT_TYPES

Used in the wCommand parameter of the IDirectMusicComposer8::AutoTransition and IDirectMusicComposer8::ComposeTransition methods and in the bCommand member of the DMUS_COMMAND_PARAM structure.

typedef enum enumDMUS_COMMANDT_TYPES {
    DMUS_COMMANDT_GROOVE      = 0,
    DMUS_COMMANDT_FILL        = 1,
    DMUS_COMMANDT_INTRO       = 2,
    DMUS_COMMANDT_BREAK       = 3,
    DMUS_COMMANDT_END         = 4,
    DMUS_COMMANDT_ENDANDINTRO = 5
} DMUS_COMMANDT_TYPES;

Constants

DMUS_COMMANDT_GROOVE
The command is a groove command.
DMUS_COMMANDT_FILL
The command is a fill.
DMUS_COMMANDT_INTRO
The command is an introduction.
DMUS_COMMANDT_BREAK
The command is a break.
DMUS_COMMANDT_END
The command is an ending.
DMUS_COMMANDT_ENDANDINTRO
The command is an ending and an introduction.

Requirements

Header: Declared in dmusici.h.


DMUS_COMPOSEF_FLAGS

Used in the dwFlags parameter of the IDirectMusicComposer8::ComposeTransition and IDirectMusicComposer8::AutoTransition methods.

typedef enum enumDMUS_COMPOSEF_FLAGS {
    DMUS_COMPOSEF_NONE                =       0,
    DMUS_COMPOSEF_ALIGN               =     0x1,
    DMUS_COMPOSEF_OVERLAP             =     0x2,
    DMUS_COMPOSEF_IMMEDIATE           =     0x4,
    DMUS_COMPOSEF_GRID                =     0x8,
    DMUS_COMPOSEF_BEAT                =    0x10,
    DMUS_COMPOSEF_MEASURE             =    0x20,
    DMUS_COMPOSEF_AFTERPREPARETIME    =    0x40,
    DMUS_COMPOSEF_VALID_START_BEAT    =    0x80,
    DMUS_COMPOSEF_VALID_START_GRID    =   0x100,
    DMUS_COMPOSEF_VALID_START_TICK    =   0x200,
    DMUS_COMPOSEF_SEGMENTEND          =   0x400,
    DMUS_COMPOSEF_MARKER              =   0x800,
    DMUS_COMPOSEF_MODULATE            =  0x1000,
    DMUS_COMPOSEF_LONG                =  0x2000,
    DMUS_COMPOSEF_ENTIRE_TRANSITION   =  0x4000,
    DMUS_COMPOSEF_1BAR_TRANSITION     =  0x8000,
    DMUS_COMPOSEF_ENTIRE_ADDITION     = 0x10000,
    DMUS_COMPOSEF_1BAR_ADDITION       = 0x20000,
    DMUS_COMPOSEF_VALID_START_MEASURE = 0x40000,
    DMUS_COMPOSEF_DEFAULT             = 0x80000,
    DMUS_COMPOSEF_NOINVALIDATE       = 0x100000,
    DMUS_COMPOSEF_USE_AUDIOPATH      = 0x200000
}  DMUS_COMPOSEF_FLAGS;

Constants

DMUS_COMPOSEF_NONE
No flags. By default, the transition starts on a measure boundary.
DMUS_COMPOSEF_ALIGN
Align transition to the time signature of the currently playing segment.
DMUS_COMPOSEF_OVERLAP
Overlap the transition into pToSeg. This flag is not currently implemented.
DMUS_COMPOSEF_IMMEDIATE
AutoTransition only. Start transition on a music or a reference-time boundary.
DMUS_COMPOSEF_GRID
AutoTransition only. Start transition on a grid boundary.
DMUS_COMPOSEF_BEAT
AutoTransition only. Start transition on a beat boundary.
DMUS_COMPOSEF_MEASURE
AutoTransition only. Start transition on a measure boundary.
DMUS_COMPOSEF_AFTERPREPARETIME
AutoTransition only. Use the DMUS_SEGF_AFTERPREPARETIME flag when cueing the transition.
DMUS_COMPOSEF_VALID_START_BEAT
Allow the switch to occur on any beat. Used in conjunction with DMUS_COMPOSEF_ALIGN.
DMUS_COMPOSEF_VALID_START_GRID
Allow the switch to occur on any grid. Used in conjunction with DMUS_COMPOSEF_ALIGN.
DMUS_COMPOSEF_VALID_START_TICK
Allow the switch to occur at any time. Used in conjunction with DMUS_COMPOSEF_ALIGN.
DMUS_COMPOSEF_SEGMENTEND
Play the transition at the end of the current segment.
DMUS_COMPOSEF_MARKER
Play the transition at the next marker in the current segment.
DMUS_COMPOSEF_MODULATE
Compose a transition that modulates smoothly from pFromSeg to pToSeg, using the chord of pToSeg.
DMUS_COMPOSEF_LONG
Composes a long transition. If this flag is not set, the length of the transition is at most one measure unless the wCommand parameter of ComposeTransition or AutoTransition specifies an ending and the style contains an ending of greater than one measure. If this flag is set, the length of the transition increases by one measure.
DMUS_COMPOSEF_ENTIRE_TRANSITION
Include the entire transition pattern.
DMUS_COMPOSEF_1BAR_TRANSITION
Include one bar of the transition pattern.
DMUS_COMPOSEF_ENTIRE_ADDITION
Include the additional transition pattern in its entirety. Used in combination with DMUS_COMPOSEF_LONG.
DMUS_COMPOSEF_1BAR_ADDITION
Include one bar of the additional transition pattern. This is the default behavior when DMUS_COMPOSEF_LONG is specified.
DMUS_COMPOSEF_VALID_START_MEASURE
Allow the switch to occur on any bar. Used in combination with DMUS_COMPOSEF_ALIGN.
DMUS_COMPOSEF_DEFAULT
Use the segment's default boundary.
DMUS_COMPOSEF_NOINVALIDATE
Do not invalidate segments that are playing.
DMUS_COMPOSEF_USE_AUDIOPATH
Use the audiopaths embedded in the segments.

Requirements

Header: Declared in dmusici.h.

See Also

DMUS_SEGF_FLAGS


DMUS_CURVE_FLAGS

Used in the bFlags member of the DMUS_CURVE_PMSG structure.

typedef enum enumDMUS_CURVE_FLAGS {
    DMUS_CURVE_RESET              = 1,
    DMUS_CURVE_START_FROM_CURRENT = 2,
} DMUS_CURVE_FLAGS;

Constants

DMUS_CURVE_RESET
The value of DMUS_CURVE_PMSG.nResetValue must be set when the time is reached or an invalidation occurs because of a transition. If this flag is not set, the curve stays permanently at the new value.
DMUS_CURVE_START_FROM_CURRENT
Ignore DMUS_CURVE_PMSG.nStartValue and start the curve at the current value. This works only for volume, expression, and pitch bend.

Requirements

Header: Declared in dmusici.h.


DMUS_NOTEF_FLAGS

Used in the bFlags member of the DMUS_NOTE_PMSG structure.

typedef enum enumDMUS_NOTEF_FLAGS {
    DMUS_NOTEF_NOTEON =               1,
    DMUS_NOTEF_NOINVALIDATE =         2,
    DMUS_NOTEF_NOINVALIDATE_INSCALE = 4,
    DMUS_NOTEF_NOINVALIDATE_INCHORD = 8,
    DMUS_NOTEF_REGENERATE =        0x10,
} DMUS_NOTEF_FLAGS;

Constants

DMUS_NOTEF_NOTEON
MIDI note-on. When a DMUS_NOTE_PMSG is first sent by the IDirectMusicPerformance8::SendPMsg method, this flag should be set. If the flag is not set, the message is a note-off.
DMUS_NOTEF_NOINVALIDATE
Do not invalidate the note.
DMUS_NOTEF_NOINVALIDATE_INSCALE
Do not invalidate if the note is still within the scale.
DMUS_NOTEF_NOINVALIDATE_INCHORD
Do not invalidate if the note is still within the chord.
DMUS_NOTEF_REGENERATE
Regenerate the note when a chord change occurs. The note's music value, subchord level, and play mode flags are used to construct a new note according to the new chord and scale. If the original note had a timing offset, this is applied to the start time of the new note.

Remarks

The NOINVALIDATE flags ensure that the note plays for its full duration even when messages are invalidated.

Requirements

Header: Declared in dmusici.h.


DMUS_PATTERNT_TYPES

Used in various command structures to control the way patterns are selected in sequential commands.

typedef enum enumDMUS_PATTERNT_TYPES {
    DMUS_PATTERNT_RANDOM           = 0,
    DMUS_PATTERNT_REPEAT           = 1,
    DMUS_PATTERNT_SEQUENTIAL       = 2,
    DMUS_PATTERNT_RANDOM_START     = 3,
    DMUS_PATTERNT_NO_REPEAT        = 4,
    DMUS_PATTERNT_RANDOM_ROW       = 5
} DMUS_PATTERNT_TYPES;

Constants

DMUS_PATTERNT_RANDOM
Select a random matching pattern. This is the behavior in versions prior to DirectX 8.0.
DMUS_PATTERNT_REPEAT
Repeat the last matching pattern.
DMUS_PATTERNT_SEQUENTIAL
Play matching patterns sequentially, in the order loaded, starting with the first.
DMUS_PATTERNT_RANDOM_START
Play matching patterns sequentially, in the order loaded, starting at a random point in the sequence.
DMUS_PATTERNT_NO_REPEAT
Play randomly, but do not play the same pattern twice.
DMUS_PATTERNT_RANDOM_ROW
Play randomly, but do not repeat any pattern until all have played.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_COMMAND_PARAM, DMUS_COMMAND_PARAM_2, DMUS_IO_COMMAND, DMUS_VARIATIONT_TYPES


DMUS_PLAYMODE_FLAGS

Used in various structures for the basic play modes. The play mode determines how a music value is transposed to a MIDI note.

typedef enum enumDMUS_PLAYMODE_FLAGS {
    DMUS_PLAYMODE_KEY_ROOT          = 1,
    DMUS_PLAYMODE_CHORD_ROOT        = 2,
    DMUS_PLAYMODE_SCALE_INTERVALS   = 4,
    DMUS_PLAYMODE_CHORD_INTERVALS   = 8,
    DMUS_PLAYMODE_NONE              = 16,
} DMUS_PLAYMODE_FLAGS;

Constants

DMUS_PLAYMODE_KEY_ROOT
Transpose over the key root.
DMUS_PLAYMODE_CHORD_ROOT
Transpose over the chord root.
DMUS_PLAYMODE_SCALE_INTERVALS
Use scale intervals from a scale pattern.
DMUS_PLAYMODE_CHORD_INTERVALS
Use chord intervals from a chord pattern.
DMUS_PLAYMODE_NONE
No mode. Indicates that the parent part's mode should be used.

Remarks

The following defined values represent combinations of play mode flags:

DMUS_PLAYMODE_ALWAYSPLAY
Combination of DMUS_PLAYMODE_SCALE_INTERVALS, DMUS_PLAYMODE_CHORD_INTERVALS, and DMUS_PLAYMODE_CHORD_ROOT. If it is desirable to play a note that is above the top of the chord, this mode finds a position for the note by using intervals from the scale. Essentially, this mode is a combination of the normal and melodic playback modes, in which a failure in normal mode causes a second try in melodic mode.
DMUS_PLAYMODE_FIXED
Interpret the music value as a MIDI value. This is defined as 0 and signifies the absence of other flags. This flag is used for drums, sound effects, and sequenced notes that should not be transposed by the chord or scale.
DMUS_PLAYMODE_FIXEDTOCHORD
Same as DMUS_PLAYMODE_CHORD_ROOT. The music value is a fixed MIDI value, but it is transposed over the chord root.
DMUS_PLAYMODE_FIXEDTOKEY
Same as DMUS_PLAYMODE_KEY_ROOT. The music value is a fixed MIDI value, but it is transposed over the key root.
DMUS_PLAYMODE_MELODIC
Combination of DMUS_PLAYMODE_CHORD_ROOT and DMUS_PLAYMODE_SCALE_INTERVALS. The chord root is used, but the notes track only the intervals in the scale. The key root and chord intervals are ignored. This is useful for melodic lines that play relative to the chord root.
DMUS_PLAYMODE_NORMALCHORD
Combination of DMUS_PLAYMODE_CHORD_ROOT and DMUS_PLAYMODE_CHORD_INTERVALS. This is the prevalent playback mode. The notes track the intervals in the chord, which is based on the chord root. If the music value has a scale component, the additional intervals are pulled from the scale and added. If the chord does not have an interval to match the chord component of the music value, the note is silent.
DMUS_PLAYMODE_PEDALPOINT
Combination of DMUS_PLAYMODE_KEY_ROOT and DMUS_PLAYMODE_SCALE_INTERVALS. The key root is used, and the notes track only the intervals in the scale. The chord root and intervals are ignored. This is useful for melodic lines that play relative to the key root.
DMUS_PLAYMODE_PEDALPOINTALWAYS
Combination of DMUS_PLAYMODE_PEDALPOINT and DMUS_PLAYMODE_PEDALPOINTCHORD. Chord intervals are used if possible; otherwise scale intervals are used.
DMUS_PLAYMODE_PEDALPOINTCHORD
Combination of DMUS_PLAYMODE_MELODIC and DMUS_PLAYMODE_NORMALCHORD. The key root is used and the notes track only the intervals in the chord. The chord root and scale intervals are completely ignored. This is useful for chordal lines that play relative to the key root.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::MIDIToMusic, IDirectMusicPerformance8::MusicToMIDI, DMUS_NOTE_PMSG, DMUS_IO_STYLENOTE, DMUS_IO_STYLEPART, Music Values and MIDI Notes


DMUS_PMSGF_FLAGS

Used in the dwFlags member of the DMUS_PMSG structure.

typedef enum enumDMUS_PMSGF_FLAGS {
    DMUS_PMSGF_REFTIME        = 1,
    DMUS_PMSGF_MUSICTIME      = 2,
    DMUS_PMSGF_TOOL_IMMEDIATE = 4,
    DMUS_PMSGF_TOOL_QUEUE     = 8,
    DMUS_PMSGF_TOOL_ATTIME    = 0x10,
    DMUS_PMSGF_TOOL_FLUSH     = 0x20,
    DMUS_PMSGF_LOCKTOREFTIME  = 0x40,
    DMUS_PMSGF_DX8            = 0x80
} DMUS_PMSGF_FLAGS;

Constants

DMUS_PMSGF_REFTIME
The rtTime member is valid.
DMUS_PMSGF_MUSICTIME
The mtTime member is valid.
DMUS_PMSGF_TOOL_IMMEDIATE
Message should be processed immediately, regardless of its time stamp.
DMUS_PMSGF_TOOL_QUEUE
Message should be processed just before its time stamp, allowing for port latency.
DMUS_PMSGF_TOOL_ATTIME
Message should be processed at the time stamp.
DMUS_PMSGF_TOOL_FLUSH
Message is being flushed.
DMUS_PMSGF_LOCKTOREFTIME
Value in rtTime cannot be overridden by a tempo change.
DMUS_PMSGF_DX8
Message has valid members not present in versions prior to DirectX 8.0.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::SendPMsg, IDirectMusicTool8::GetMsgDeliveryType


DMUS_PMSGT_TYPES

Used in the dwType member of the DMUS_PMSG structure to identify the type of message.

typedef enum enumDMUS_PMSGT_TYPES {
    DMUS_PMSGT_MIDI             = 0,
    DMUS_PMSGT_NOTE             = 1,
    DMUS_PMSGT_SYSEX            = 2,
    DMUS_PMSGT_NOTIFICATION     = 3,
    DMUS_PMSGT_TEMPO            = 4,
    DMUS_PMSGT_CURVE            = 5,
    DMUS_PMSGT_TIMESIG          = 6,
    DMUS_PMSGT_PATCH            = 7,
    DMUS_PMSGT_TRANSPOSE        = 8,
    DMUS_PMSGT_CHANNEL_PRIORITY = 9,
    DMUS_PMSGT_STOP             = 10,
    DMUS_PMSGT_DIRTY            = 11,
    DMUS_PMSGT_WAVE             = 12,
    DMUS_PMSGT_LYRIC            = 13,
    DMUS_PMSGT_SCRIPTLYRIC      = 14,
    DMUS_PMSGT_USER             = 255
} DMUS_PMSGT_TYPES;

Constants

DMUS_PMSGT_MIDI
MIDI channel message. See DMUS_MIDI_PMSG.
DMUS_PMSGT_NOTE
Music note. See DMUS_NOTE_PMSG.
DMUS_PMSGT_SYSEX
MIDI system exclusive message. See DMUS_SYSEX_PMSG.
DMUS_PMSGT_NOTIFICATION
Notification message. See DMUS_NOTIFICATION_PMSG.
DMUS_PMSGT_TEMPO
Tempo message. See DMUS_TEMPO_PMSG.
DMUS_PMSGT_CURVE
Control change and pitch-bend curve. See DMUS_CURVE_PMSG.
DMUS_PMSGT_TIMESIG
Time signature. See DMUS_TIMESIG_PMSG.
DMUS_PMSGT_PATCH
Patch change. See DMUS_PATCH_PMSG.
DMUS_PMSGT_TRANSPOSE
Transposition. See DMUS_TRANSPOSE_PMSG.
DMUS_PMSGT_CHANNEL_PRIORITY
Channel priority change. See DMUS_CHANNEL_PRIORITY_PMSG.
DMUS_PMSGT_STOP
Stop message. See DMUS_PMSG.
DMUS_PMSGT_DIRTY
A control segment has started or ended. See DMUS_PMSG.
DMUS_PMSGT_WAVE
Control information for playing a wave. See DMUS_WAVE_PMSG.
DMUS_PMSGT_LYRIC
Lyric message. See DMUS_LYRIC_PMSG.
DMUS_PMSGT_SCRIPTLYRIC
Lyric message sent by a script. See DMUS_LYRIC_PMSG.
DMUS_PMSGT_USER
User-defined message.

Requirements

Header: Declared in dmusici.h.


DMUS_SEGF_FLAGS

Passed to various methods of IDirectMusicPerformance8 to control the timing and other aspects of actions on a segment.

typedef enum enumDMUS_SEGF_FLAGS {
    DMUS_SEGF_REFTIME             = 1<<6,
    DMUS_SEGF_SECONDARY           = 1<<7,
    DMUS_SEGF_QUEUE               = 1<<8,
    DMUS_SEGF_CONTROL             = 1<<9,
    DMUS_SEGF_AFTERPREPARETIME    = 1<<10,
    DMUS_SEGF_GRID                = 1<<11,
    DMUS_SEGF_BEAT                = 1<<12,
    DMUS_SEGF_MEASURE             = 1<<13,
    DMUS_SEGF_DEFAULT             = 1<<14,
    DMUS_SEGF_NOINVALIDATE        = 1<<15,
    DMUS_SEGF_ALIGN               = 1<<16,
    DMUS_SEGF_VALID_START_BEAT    = 1<<17,
    DMUS_SEGF_VALID_START_GRID    = 1<<18,
    DMUS_SEGF_VALID_START_TICK    = 1<<19,
    DMUS_SEGF_AUTOTRANSITION      = 1<<20,
    DMUS_SEGF_AFTERQUEUETIME      = 1<<21,
    DMUS_SEGF_AFTERLATENCYTIME    = 1<<22,
    DMUS_SEGF_SEGMENTEND          = 1<<23,
    DMUS_SEGF_MARKER              = 1<<24,
    DMUS_SEGF_TIMESIG_ALWAYS      = 1<<25,
    DMUS_SEGF_USE_AUDIOPATH       = 1<<26,
    DMUS_SEGF_VALID_START_MEASURE = 1<<27
} DMUS_SEGF_FLAGS;

Constants

DMUS_SEGF_REFTIME
Time parameter is in reference time.
DMUS_SEGF_SECONDARY
Secondary segment.
DMUS_SEGF_QUEUE
Put at the end of the primary segment queue. Valid for primary segments only.
DMUS_SEGF_CONTROL
Play as a control segment. Valid for secondary segments only. See Remarks.
DMUS_SEGF_AFTERPREPARETIME
Play after the prepare time. See IDirectMusicPerformance8::GetPrepareTime.
DMUS_SEGF_GRID
Play on a grid boundary.
DMUS_SEGF_BEAT
Play on a beat boundary.
DMUS_SEGF_MEASURE
Play on a measure boundary.
DMUS_SEGF_DEFAULT
Use the segment's default boundary.
DMUS_SEGF_NOINVALIDATE
Setting this flag in IDirectMusicPerformance8::PlaySegment or IDirectMusicPerformance8::PlaySegmentEx for a primary or control segment causes the new segment not to cause an invalidation. Without this flag, an invalidation occurs, cutting off and resetting any currently playing curve or note. This flag should be combined with DMUS_SEGF_AFTERPREPARETIME so that notes in the new segment do not play over notes played by the old segment.
DMUS_SEGF_ALIGN
The beginning of the segment can be aligned with a boundary, such as measure or beat, that has already passed. For this to happen, the segment must have a valid start point that falls before the next boundary. Start points can be defined in the segment, or one of the DMUS_SEGF_VALID_START_* flags can be used to define the granularity of valid start points. Any DMUS_SEGF_VALID_START_* flag takes effect only if a valid start point is not defined in the segment.
DMUS_SEGF_VALID_START_BEAT
Allow the start to occur on any beat. Used in combination with DMUS_SEGF_ALIGN.
DMUS_SEGF_VALID_START_GRID
Allow the start to occur on any grid. Used in combination with DMUS_SEGF_ALIGN.
DMUS_SEGF_VALID_START_TICK
Allow the start to occur at any time. Used in combination with DMUS_SEGF_ALIGN.
DMUS_SEGF_AUTOTRANSITION
Compose and play a transition segment, using the transition template.
DMUS_SEGF_AFTERQUEUETIME
Play after the queue time. This is the default for primary segments. Ignored if DMUS_SEGF_AFTERPREPARETIME is also set.
DMUS_SEGF_AFTERLATENCYTIME
Play after the latency time. This is true for all segments, so this flag currently has no effect.
DMUS_SEGF_SEGMENTEND
Play at the end of the primary segment that is playing at the start time. Any segments already queued after the currently playing primary segment are flushed. If no primary segment is playing, use other resolution flags.
DMUS_SEGF_MARKER
Play at next marker in the primary segment. If there are no markers, use other resolution flags.
DMUS_SEGF_TIMESIG_ALWAYS
Align start time with current time signature, even if there is no primary segment.
DMUS_SEGF_USE_AUDIOPATH
Use the audiopath embedded in the segment. Automatic downloading of bands must be enabled to ensure that the segment plays correctly.
DMUS_SEGF_VALID_START_MEASURE
Allow the start to occur at the beginning of a measure. Used in combination with DMUS_SEGF_ALIGN.

Remarks

The primary segment is the default control segment. The DMUS_SEGF_CONTROL flag can be used to make a secondary segment the control segment. If the DMUS_SEGF_CONTROL flag is set, DMUS_SEGF_SECONDARY is assumed. For more information, see Control Segments.

No more than one flag from each of the following groups should be specified.

Boundary
This flag controls the point in the currently playing primary segment at which the start point of the cued segment falls. It can be combined with DMUS_SEGF_MARKER, in which case the boundary flag will be used only if no marker exists in the primary segment.

DMUS_SEGF_BEAT
DMUS_SEGF_DEFAULT
DMUS_SEGF_GRID
DMUS_SEGF_MEASURE
DMUS_SEGF_QUEUE
DMUS_SEGF_SEGMENTEND

Alignment
This flag controls the segment start time of the cued segment, when its play time falls in the past. It must be combined with DMUS_SEGF_ALIGN.

DMUS_SEGF_VALID_START_BEAT
DMUS_SEGF_VALID_START_GRID
DMUS_SEGF_VALID_START_MEASURE
DMUS_SEGF_VALID_START_TICK

It is possible to combine one flag from each group. For example, combining DMUS_SEGF_MEASURE with DMUS_SEGF_ALIGN and DMUS_SEGF_VALID_START_BEAT causes the start point of the cued segment to fall at a measure boundary in the current primary segment. If this boundary has already passed, the cued segment starts playing at the next beat boundary within itself that is not aligned to a past time. For more information, see Segment Timing.

Requirements

Header: Declared in dmusici.h.

See Also

IDirectMusicPerformance8::Invalidate, IDirectMusicPerformance8::PlaySegment, IDirectMusicPerformance8::PlaySegmentEx, IDirectMusicPerformance8::Stop, IDirectMusicSegment8::GetDefaultResolution, IDirectMusicSegment8::SetDefaultResolution, DMUS_TIME_RESOLVE_FLAGS


DMUS_SHAPET_TYPES

Used in the wShape parameter of the IDirectMusicComposer8::ComposeSegmentFromShape and IDirectMusicComposer8::ComposeTemplateFromShape methods to specify the desired pattern of the groove level.

typedef enum enumDMUS_SHAPET_TYPES {
    DMUS_SHAPET_FALLING  = 0,
    DMUS_SHAPET_LEVEL    = 1,
    DMUS_SHAPET_LOOPABLE = 2,
    DMUS_SHAPET_LOUD     = 3,
    DMUS_SHAPET_QUIET    = 4,
    DMUS_SHAPET_PEAKING  = 5,
    DMUS_SHAPET_RANDOM   = 6,
    DMUS_SHAPET_RISING   = 7,
    DMUS_SHAPET_SONG     = 8
} DMUS_SHAPET_TYPES;

Constants

DMUS_SHAPET_FALLING
Groove level falls.
DMUS_SHAPET_LEVEL
Groove level remains even.
DMUS_SHAPET_LOOPABLE
Segment is arranged to loop back to the beginning.
DMUS_SHAPET_LOUD
Groove level is high.
DMUS_SHAPET_QUIET
Groove level is low.
DMUS_SHAPET_PEAKING
Groove level rises to a peak, and then falls.
DMUS_SHAPET_RANDOM
Groove level is random.
DMUS_SHAPET_RISING
Groove level rises.
DMUS_SHAPET_SONG
Segment is in a song form. Several phrases of 6 to 8 bars are composed and put together to give a verse-chorus effect, with variations in groove level.

Requirements

Header: Declared in dmusici.h.


DMUS_STYLET_TYPES

Used in the IDirectMusicPatternTrack8::SetPatternByName and IDirectMusicStyle8::EnumPattern methods to specify a type of pattern.

typedef enum enumDMUS_STYLET_TYPES {
    DMUS_STYLET_PATTERN  = 0,
    DMUS_STYLET_MOTIF    = 1,
    DMUS_STYLET_FRAGMENT = 2,
} DMUS_STYLET_TYPES;

Constants

DMUS_STYLET_PATTERN
Normal pattern.
DMUS_STYLET_MOTIF
Motif pattern.
DMUS_STYLET_FRAGMENT
Not implemented.

Requirements

Header: Declared in dmusici.h.


DMUS_TIME_RESOLVE_FLAGS

Used in the dwFlags member of the DMUS_PMSG structure and in the dwTimeResolveFlags parameter of the IDirectMusicPerformance8::GetResolvedTime method.

typedef enum enumDMUS_TIME_RESOLVE_FLAGS {
    DMUS_TIME_RESOLVE_AFTERPREPARETIME =
            DMUS_SEGF_AFTERPREPARETIME,
    DMUS_TIME_RESOLVE_AFTERQUEUETIME   =
            DMUS_SEGF_AFTERQUEUETIME,
    DMUS_TIME_RESOLVE_AFTERLATENCYTIME =
            DMUS_SEGF_AFTERLATENCYTIME,
    DMUS_TIME_RESOLVE_GRID    = DMUS_SEGF_GRID,
    DMUS_TIME_RESOLVE_BEAT    = DMUS_SEGF_BEAT,
    DMUS_TIME_RESOLVE_MEASURE = DMUS_SEGF_MEASURE
    DMUS_TIME_RESOLVE_MARKER  = DMUS_SEGF_MARKER,
    DMUS_TIME_RESOLVE_SEGMENTEND = DMUS_SEGF_SEGMENTEND,
} DMUS_TIME_RESOLVE_FLAGS;

Constants

DMUS_TIME_RESOLVE_AFTERPREPARETIME
Resolve to a time after the prepare time.
DMUS_TIME_RESOLVE_AFTERQUEUETIME
Resolve to a time after the queue time.
DMUS_TIME_RESOLVE_AFTERLATENCYTIME
Resolve to a time after the latency time.
DMUS_TIME_RESOLVE_GRID
Resolve to a time on a grid boundary.
DMUS_TIME_RESOLVE_BEAT
Resolve to a time on a beat boundary.
DMUS_TIME_RESOLVE_MEASURE
Resolve to a time on a measure boundary.
DMUS_TIME_RESOLVE_MARKER
Resolve to a marker.
DMUS_TIME_RESOLVE_SEGMENTEND
Resolve to the end of the segment.

Remarks

These flags can be used interchangeably with the corresponding DMUS_SEGF_FLAGS.

Requirements

Header: Declared in dmusici.h.

See Also

Timing


DMUS_TRACKF_FLAGS

Used in the dwFlags parameter of the IDirectMusicTrack8::Play and IDirectMusicTrack8::PlayEx methods.

typedef enum enumDMUS_TRACKF_FLAGS {
    DMUS_TRACKF_SEEK       = 1,
    DMUS_TRACKF_LOOP       = 2,
    DMUS_TRACKF_START      = 4,
    DMUS_TRACKF_FLUSH      = 8,
    DMUS_TRACKF_DIRTY      = 0x10,
    DMUS_TRACKF_NOTIFY_OFF = 0x20,
    DMUS_TRACKF_PLAYOFF    = 0x40,
    DMUS_TRACKF_LOOPEND    = 0x80,
    DMUS_TRACKF_STOP       = 0x100,
    DMUS_TRACKF_RECOMPOSE  = 0x200,
    DMUS_TRACKF_CLOCK      = 0x400,
} DMUS_TRACKF_FLAGS;

Constants

DMUS_TRACKF_SEEK
IDirectMusicTrack8::Play was called in response to seeking, meaning that the mtStart parameter is not necessarily the same as the mtEnd of the previous call.
DMUS_TRACKF_LOOP
Play was called in response to a loop.
DMUS_TRACKF_START
This is the first call to IDirectMusicTrack8::Play. DMUS_TRACKF_SEEK can also be set if the track is not playing from the beginning.
DMUS_TRACKF_FLUSH
Play was called in response to a flush or invalidation that requires the track to replay something that it played previously. In this case, DMUS_TRACKF_SEEK is set, as well.
DMUS_TRACKF_DIRTY
A control segment has begun or ended. Tracks that normally wait until mtNext to call IDirectMusicTrack8::GetParam or IDirectMusicTrack8::GetParamEx should make the call right away, instead of waiting, because their data might now be invalid. For more information on setting control segments, see DMUS_SEGF_FLAGS.
DMUS_TRACKF_NOTIFY_OFF
Track is not to send notifications.
DMUS_TRACKF_PLAYOFF
Track is not to play, but can still send notifications.
DMUS_TRACKF_LOOPEND
End of range is also a loop end.
DMUS_TRACKF_STOP
End of range is also end of playing this segment.
DMUS_TRACKF_RECOMPOSE
Track should be recomposed on each loop. A signpost track is recomposed using a different chord progression, and a melody formulation track is recomposed using different melody fragments.
DMUS_TRACKF_CLOCK
Time parameters are in reference time. Valid only for IDirectMusicTrack8::PlayEx.

Remarks

When Play is called in response to a repeat, DMUS_TRACKF_LOOP and DMUS_TRACKF_SEEK are set.

To support invalidation, tracks must support seeking..

Requirements

Header: Declared in dmplugin.h.


DMUS_VARIATIONT_TYPES

Used in the DMUS_IO_PARTREF structure to specify the way variations are selected in sequential commands.

typedef enum enumDMUS_VARIATIONT_TYPES
{
    DMUS_VARIATIONT_SEQUENTIAL       = 0,
    DMUS_VARIATIONT_RANDOM           = 1,
    DMUS_VARIATIONT_RANDOM_START     = 2,
    DMUS_VARIATIONT_NO_REPEAT        = 3,
    DMUS_VARIATIONT_RANDOM_ROW       = 4
} DMUS_VARIATIONT_TYPES;

Constants

DMUS_VARIATIONT_SEQUENTIAL
Play matching variations sequentially, in the order loaded, starting with the first.
DMUS_VARIATIONT_RANDOM
Select a random matching variation. This is the behavior in versions prior to DirectX 8.0.
DMUS_VARIATIONT_RANDOM_START
Play matching variations sequentially, in the order loaded, starting at a random point in the sequence.
DMUS_VARIATIONT_NO_REPEAT
Play randomly, but do not play the same variation twice.
DMUS_VARIATIONT_RANDOM_ROW
Play randomly, but do not repeat any variation until all have played.

Requirements

Header: Declared in dmusicf.h.

See Also

DMUS_COMMAND_PARAM, DMUS_COMMAND_PARAM_2, DMUS_IO_COMMAND, DMUS_PATTERNT_TYPES


DirectMusic Return Values

This section provides a brief explanation of the various error codes that can be returned by DirectMusic methods. For a list of the specific codes that each method can return, see the individual method descriptions. The lists given there are not necessarily comprehensive.

Error codes are presented in the following sections:

  • DirectMusic Return Values By Number
  • DirectMusic Return Values By Name


DirectMusic Return Values By Number

The following table lists DirectMusic return values sorted by hexadecimal value. For a description, click on the constant.

Hexadecimal | Constant
0x00000000 | S_OK
0x00000001 | S_FALSE
0x08781091 | DMUS_S_PARTIALLOAD
0x08781092 | DMUS_S_PARTIALDOWNLOAD
0x08781200 | DMUS_S_REQUEUE
0x08781201 | DMUS_S_FREE
0x08781202 | DMUS_S_END
0x08781210 | DMUS_S_STRING_TRUNCATED
0x08781211 | DMUS_S_LAST_TOOL
0x08781212 | DMUS_S_OVER_CHORD
0x08781213 | DMUS_S_UP_OCTAVE
0x08781214 | DMUS_S_DOWN_OCTAVE
0x08781215 | DMUS_S_NOBUFFERCONTROL
0x08781216 | DMUS_S_GARBAGE_COLLECTED
0x80004001 | E_NOTIMPL
0x80004002 | E_NOINTERFACE
0x80004003 | E_POINTER
0x80040110 | CLASS_E_NOAGGREGATION
0x80040110 | CLASS_E_NOAGGREGATION
0x80040154 | REGDB_E_CLASSNOTREG
0x8007000E | E_OUTOFMEMORY
0x80070057 | E_FAIL
0x80070057 | E_INVALIDARG
0x88781101 | DMUS_E_DRIVER_FAILED
0x88781102 | DMUS_E_PORTS_OPEN
0x88781103 | DMUS_E_DEVICE_IN_USE
0x88781104 | DMUS_E_INSUFFICIENTBUFFER
0x88781105 | DMUS_E_BUFFERNOTSET
0x88781106 | DMUS_E_BUFFERNOTAVAILABLE
0x88781108 | DMUS_E_NOTADLSCOL
0x88781109 | DMUS_E_INVALIDOFFSET
0x88781111 | DMUS_E_ALREADY_LOADED
0x88781113 | DMUS_E_INVALIDPOS
0x88781114 | DMUS_E_INVALIDPATCH
0x88781115 | DMUS_E_CANNOTSEEK
0x88781116 | DMUS_E_CANNOTWRITE
0x88781117 | DMUS_E_CHUNKNOTFOUND
0x88781119 | DMUS_E_INVALID_DOWNLOADID
0x88781120 | DMUS_E_NOT_DOWNLOADED_TO_PORT
0x88781121 | DMUS_E_ALREADY_DOWNLOADED
0x88781122 | DMUS_E_UNKNOWNDOWNLOAD
0x88781123 | DMUS_E_SET_UNSUPPORTED
0x88781124 | DMUS_E_GET_UNSUPPORTED
0x88781125 | DMUS_E_NOTMONO
0x88781126 | DMUS_E_BADARTICULATION
0x88781127 | DMUS_E_BADINSTRUMENT
0x88781128 | DMUS_E_BADWAVELINK
0x88781128 | DMUS_E_BUFFER_EMPTY
0x8878112A | DMUS_E_NOTPCM
0x8878112B | DMUS_E_BADWAVE
0x8878112C | DMUS_E_BADOFFSETTABLE
0x8878112D | DMUS_E_UNKNOWN_PROPERTY
0x8878112E | DMUS_E_NOSYNTHSINK
0x8878112F | DMUS_E_ALREADYOPEN
0x88781130 | DMUS_E_ALREADYCLOSED
0x88781131 | DMUS_E_SYNTHNOTCONFIGURED
0x88781132 | DMUS_E_SYNTHACTIVE
0x88781133 | DMUS_E_CANNOTREAD
0x88781134 | DMUS_E_DMUSIC_RELEASED
0x88781136 | DMUS_E_BUFFER_FULL
0x88781137 | DMUS_E_PORT_NOT_CAPTURE
0x88781138 | DMUS_E_PORT_NOT_RENDER
0x88781139 | DMUS_E_DSOUND_NOT_SET
0x8878113A | DMUS_E_ALREADY_ACTIVATED
0x8878113B | DMUS_E_INVALIDBUFFER
0x8878113C | DMUS_E_WAVEFORMATNOTSUPPORTED
0x8878113D | DMUS_E_SYNTHINACTIVE
0x8878113E | DMUS_E_DSOUND_ALREADY_SET
0x8878113F | DMUS_E_INVALID_EVENT
0x88781150 | DMUS_E_UNSUPPORTED_STREAM
0x88781151 | DMUS_E_ALREADY_INITED
0x88781152 | DMUS_E_INVALID_BAND
0x88781155 | DMUS_E_TRACK_HDR_NOT_FIRST_CK
0x88781156 | DMUS_E_TOOL_HDR_NOT_FIRST_CK
0x88781157 | DMUS_E_INVALID_TRACK_HDR
0x88781158 | DMUS_E_INVALID_TOOL_HDR
0x88781159 | DMUS_E_ALL_TOOLS_FAILED
0x88781160 | DMUS_E_ALL_TRACKS_FAILED
0x88781161 | DMUS_E_NOT_FOUND
0x88781162 | DMUS_E_NOT_INIT
0x88781163 | DMUS_E_TYPE_DISABLED
0x88781164 | DMUS_E_TYPE_UNSUPPORTED
0x88781165 | DMUS_E_TIME_PAST
0x88781166 | DMUS_E_TRACK_NOT_FOUND
0x88781167 | DMUS_E_TRACK_NO_CLOCKTIME_SUPPORT
0x88781170 | DMUS_E_NO_MASTER_CLOCK
0x88781170 | DMUS_E_NOARTICULATION
0x88781180 | DMUS_E_LOADER_NOCLASSID
0x88781181 | DMUS_E_LOADER_BADPATH
0x88781182 | DMUS_E_LOADER_FAILEDOPEN
0x88781183 | DMUS_E_LOADER_FORMATNOTSUPPORTED
0x88781184 | DMUS_E_LOADER_FAILEDCREATE
0x88781185 | DMUS_E_LOADER_OBJECTNOTFOUND
0x88781186 | DMUS_E_LOADER_NOFILENAME
0x88781200 | DMUS_E_INVALIDFILE
0x88781201 | DMUS_E_ALREADY_EXISTS
0x88781202 | DMUS_E_OUT_OF_RANGE
0x88781203 | DMUS_E_SEGMENT_INIT_FAILED
0x88781204 | DMUS_E_ALREADY_SENT
0x88781205 | DMUS_E_CANNOT_FREE
0x88781206 | DMUS_E_CANNOT_OPEN_PORT
0x88781207 | DMUS_E_CANNOT_CONVERT
0x88781210 | DMUS_E_DESCEND_CHUNK_FAIL
0x88781211 | DMUS_E_NOT_LOADED
0x88781213 | DMUS_E_SCRIPT_LANGUAGE_INCOMPATIBLE
0x88781214 | DMUS_E_SCRIPT_UNSUPPORTED_VARTYPE
0x88781215 | DMUS_E_SCRIPT_ERROR_IN_SCRIPT
0x88781216 | DMUS_E_SCRIPT_CANTLOAD_OLEAUT32
0x88781217 | DMUS_E_SCRIPT_LOADSCRIPT_ERROR
0x88781218 | DMUS_E_SCRIPT_INVALID_FILE
0x88781219 | DMUS_E_INVALID_SCRIPTTRACK
0x8878121A | DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
0x8878121B | DMUS_E_SCRIPT_ROUTINE_NOT_FOUND
0x8878121C | DMUS_E_SCRIPT_CONTENT_READONLY
0x8878121D | DMUS_E_SCRIPT_NOT_A_REFERENCE
0x8878121E | DMUS_E_SCRIPT_VALUE_NOT_SUPPORTED
0x88781220 | DMUS_E_INVALID_SEGMENTTRIGGERTRACK
0x88781221 | DMUS_E_INVALID_LYRICSTRACK
0x88781222 | DMUS_E_INVALID_PARAMCONTROLTRACK
0x88781223 | DMUS_E_AUDIOVBSCRIPT_SYNTAXERROR
0x88781224 | DMUS_E_AUDIOVBSCRIPT_RUNTIMEERROR
0x88781225 | DMUS_E_AUDIOVBSCRIPT_OPERATIONFAILURE
0x88781226 | DMUS_E_AUDIOPATHS_NOT_VALID
0x88781227 | DMUS_E_AUDIOPATHS_IN_USE
0x88781228 | DMUS_E_NO_AUDIOPATH_CONFIG
0x88781229 | DMUS_E_AUDIOPATH_INACTIVE
0x8878122A | DMUS_E_AUDIOPATH_NOBUFFER
0x8878122B | DMUS_E_AUDIOPATH_NOPORT
0x8878122C | DMUS_E_NO_AUDIOPATH
0x8878122D | DMUS_E_INVALIDCHUNK
0x8878122E | DMUS_E_AUDIOPATH_NOGLOBALFXBUFFER
0x8878122F | DMUS_E_INVALID_CONTAINER_OBJECT


DirectMusic Return Values by Name

The following list describes all DirectMusic return values. To find a constant from its value, see DirectMusic Return Values By Number.

CLASS_E_NOAGGREGATION
Aggregation is not supported. The LPUNKNOWN parameter should be set to NULL.
DMUS_E_ALL_TOOLS_FAILED
The graph object was unable to load all tools from the IStream object data, perhaps because of errors in the stream or because the tools are incorrectly registered on the client.
DMUS_E_ALL_TRACKS_FAILED
The segment object was unable to load all tracks from the IStream object data, perhaps because of errors in the stream or because the tracks are incorrectly registered on the client.
DMUS_E_ALREADY_ACTIVATED
The port has been activated, and the parameter cannot be changed.
DMUS_E_ALREADY_DOWNLOADED
The buffer has already been downloaded.
DMUS_E_ALREADY_EXISTS
The tool is already contained in the graph. You must create a new instance.
DMUS_E_ALREADY_INITED
The object has already been initialized.
DMUS_E_ALREADY_LOADED
A DLS collection is already open.
DMUS_E_ALREADY_SENT
The message has already been sent.
DMUS_E_ALREADYCLOSED
The port is not open.
DMUS_E_ALREADYOPEN
The port is already open.
DMUS_E_AUDIOPATH_INACTIVE
The audiopath is inactive, perhaps because the performance has been closed down.
DMUS_E_AUDIOPATH_NOBUFFER
The audiopath could not be created because a requested buffer could not be created.
DMUS_E_AUDIOPATH_NOGLOBALFXBUFFER
An attempt was made to create an audiopath that sends to a nonexistent global effects buffer.
DMUS_E_AUDIOPATH_NOPORT
The audiopath could not be used for playback because it lacked port assignments.
DMUS_E_AUDIOPATHS_IN_USE
The performance has set up audiopaths, so performance channels cannot be allocated.
DMUS_E_AUDIOPATHS_NOT_VALID
Performance channels have been set up by using IDirectMusicPerformance8::AssignPChannel, so the performance cannot support audiopaths.
DMUS_E_AUDIOVBSCRIPT_OPERATIONFAILURE
A script routine written in AudioVBScript failed because a function outside the script failed to complete.
DMUS_E_AUDIOVBSCRIPT_RUNTIMEERROR
A script routine written in AudioVBScript failed because an invalid operation occurred—for example, adding an integer to an object, or attempting to call a routine that does not exist.
DMUS_E_AUDIOVBSCRIPT_SYNTAXERROR
A script routine written in AudioVBScript could not be read because it contained a statement not allowed by the language.
DMUS_E_BADARTICULATION
Invalid articulation chunk in DLS collection.
DMUS_E_BADINSTRUMENT
Invalid instrument chunk in DLS collection.
DMUS_E_BADOFFSETTABLE
The offset table has errors.
DMUS_E_BADWAVE
Corrupt wave header.
DMUS_E_BADWAVELINK
The wave-link chunk in DLS collection points to invalid wave.
DMUS_E_BUFFER_EMPTY
There is no data in the buffer.
DMUS_E_BUFFER_FULL
The specified number of bytes exceeds the maximum buffer size.
DMUS_E_BUFFERNOTAVAILABLE
The buffer is not available for download.
DMUS_E_BUFFERNOTSET
No buffer was prepared for the data.
DMUS_E_CANNOT_CONVERT
The requested conversion between music and MIDI values could not be made. This usually occurs when the provided DMUS_CHORD_KEY structure has an invalid chord or scale pattern.
DMUS_E_CANNOT_FREE
The message could not be freed, either because it was not allocated or because it has already been freed.
DMUS_E_CANNOT_OPEN_PORT
The default system port could not be opened.
DMUS_E_CANNOTREAD
An error occurred when trying to read from the IStream object.
DMUS_E_CANNOTSEEK
The IStream object does not support Seek.
DMUS_E_CANNOTWRITE
The IStream object does not support Write.
DMUS_E_CHUNKNOTFOUND
A chunk with the specified header could not be found.
DMUS_E_DESCEND_CHUNK_FAIL
An attempt to descend into a chunk failed.
DMUS_E_DEVICE_IN_USE
The device is in use, possibly by a non-DirectMusic client, and cannot be opened again.
DMUS_E_DMUSIC_RELEASED
The operation cannot be performed because the final instance of the DirectMusic object was released. Ports cannot be used after final release of the DirectMusic object.
DMUS_E_DRIVER_FAILED
An unexpected error was returned from a device driver, indicating possible failure of the driver or hardware.
DMUS_E_DSOUND_ALREADY_SET
A DirectSound object has already been set.
DMUS_E_DSOUND_NOT_SET
The port could not be created because no DirectSound object has been specified.
DMUS_E_GET_UNSUPPORTED
Getting the parameter is not supported.
DMUS_E_INSUFFICIENTBUFFER
The buffer is not large enough for the requested operation.
DMUS_E_INVALID_BAND
The file does not contain a valid band.
DMUS_E_INVALID_CONTAINER_OBJECT
The file does not contain a valid container object.
DMUS_E_INVALID_DOWNLOADID
An invalid download identifier was used in the process of creating a download buffer.
DMUS_E_INVALID_EVENT
The event either is not a valid MIDI message or makes use of running status and cannot be packed into the buffer.
DMUS_E_INVALID_LYRICSTRACK
The file contains an invalid lyrics track.
DMUS_E_INVALID_PARAMCONTROLTRACK
The file contains an invalid parameter control track.
DMUS_E_INVALID_SCRIPTTRACK
The file contains an invalid script track.
DMUS_E_INVALID_SEGMENTTRIGGERTRACK
The file contains an invalid segment trigger track.
DMUS_E_INVALID_TOOL_HDR
The IStream object's data contains an invalid tool header and cannot be read by the graph object.
DMUS_E_INVALID_TRACK_HDR
The IStream object's data contains an invalid track header and cannot be read by the segment object.
DMUS_E_INVALIDBUFFER
An invalid DirectSound buffer was handed to a port.
DMUS_E_INVALIDCHUNK
Invalid data was found in a RIFF file chunk.
DMUS_E_INVALIDFILE
Not a valid file.
DMUS_E_INVALIDOFFSET
Wave chunks in the DLS collection file are at incorrect offsets.
DMUS_E_INVALIDPATCH
No instrument in the collection matches the patch number.
DMUS_E_INVALIDPOS
Error reading wave data from a DLS collection. Indicates bad file.
DMUS_E_LOADER_BADPATH
The file path is invalid.
DMUS_E_LOADER_FAILEDCREATE
The object could not be found or created.
DMUS_E_LOADER_FAILEDOPEN
File open failed because the file does not exist or is locked.
DMUS_E_LOADER_FORMATNOTSUPPORTED
The object cannot be loaded because the data format is not supported.
DMUS_E_LOADER_NOCLASSID
No class identifier was supplied in the object description.
DMUS_E_LOADER_NOFILENAME
No file name was supplied in the object description.
DMUS_E_LOADER_OBJECTNOTFOUND
The object was not found.
DMUS_E_NO_AUDIOPATH
An attempt was made to play on a nonexistent audiopath.
DMUS_E_NO_AUDIOPATH_CONFIG
The object does not contain an embedded audiopath configuration.
DMUS_E_NO_MASTER_CLOCK
There is no master clock in the performance. Be sure to call the IDirectMusicPerformance8::Init method.
DMUS_E_NOARTICULATION
Articulation missing from an instrument in the DLS collection.
DMUS_E_NOSYNTHSINK
No sink is connected to the synthesizer.
DMUS_E_NOT_DOWNLOADED_TO_PORT
The object cannot be unloaded because it is not present on the port.
DMUS_E_NOT_FOUND
The requested item is not contained by the object.
DMUS_E_NOT_INIT
A required object is not initialized or failed to initialize.
DMUS_E_NOT_LOADED
An attempt to use this object failed because it was not loaded.
DMUS_E_NOTADLSCOL
The object being loaded is not a valid DLS collection.
DMUS_E_NOTMONO
The wave chunk has more than one interleaved channel. DLS format requires mono.
DMUS_E_NOTPCM
Wave data is not in PCM format.
DMUS_E_OUT_OF_RANGE
The requested time is outside the range of the segment.
DMUS_E_PORT_NOT_CAPTURE
The port is not a capture port.
DMUS_E_PORT_NOT_RENDER
The port is not an output port.
DMUS_E_PORTS_OPEN
The requested operation cannot be performed while there are instantiated ports in any process in the system.
DMUS_E_SCRIPT_CANTLOAD_OLEAUT32
Loading of Oleaut32.dll failed. ActiveX scripting languages require use of oleaut32.dll. On platforms where this file is not present, only the AudioVBScript language can be used.
DMUS_E_SCRIPT_CONTENT_READONLY
Script variables for content referenced or embedded in a script cannot be set.
DMUS_E_SCRIPT_ERROR_IN_SCRIPT
An error was encountered while parsing or executing the script.
DMUS_E_SCRIPT_INVALID_FILE
The script file is invalid.
DMUS_E_SCRIPT_LANGUAGE_INCOMPATIBLE
The ActiveX scripting engine for the script's language is not compatible with DirectMusic.
DMUS_E_SCRIPT_LOADSCRIPT_ERROR
The script that was loaded contains an error.
DMUS_E_SCRIPT_NOT_A_REFERENCE
An attempt was made to set a script's variable by reference to a value that is not an object type.
DMUS_E_SCRIPT_ROUTINE_NOT_FOUND
The script does not contain a routine with the specified name.
DMUS_E_SCRIPT_UNSUPPORTED_VARTYPE
A variant was used that had a type not supported by DirectMusic.
DMUS_E_SCRIPT_VALUE_NOT_SUPPORTED
An attempt was made to set a script's variable by value to an object that does not support a default value property.
DMUS_E_SCRIPT_VARIABLE_NOT_FOUND
The script does not contain a variable with the specified name.
DMUS_E_SEGMENT_INIT_FAILED
Segment initialization failed, probably because of a critical memory situation.
DMUS_E_SET_UNSUPPORTED
Setting the parameter is not supported.
DMUS_E_SYNTHACTIVE
The synthesizer has been activated, and the parameter cannot be changed.
DMUS_E_SYNTHINACTIVE
The synthesizer has not been activated and cannot process data.
DMUS_E_SYNTHNOTCONFIGURED
The synthesizer is not properly configured or opened.
DMUS_E_TIME_PAST
The time requested is in the past.
DMUS_E_TOOL_HDR_NOT_FIRST_CK
The stream object's data does not have a tool header as the first chunk and, therefore, cannot be read by the graph object.
DMUS_E_TRACK_HDR_NOT_FIRST_CK
The stream object's data does not have a track header as the first chunk and, therefore, cannot be read by the segment object.
DMUS_E_TRACK_NO_CLOCKTIME_SUPPORT
The track does not support clock-time playback or parameter retrieval.
DMUS_E_TRACK_NOT_FOUND
There is no track of the requested type.
DMUS_E_TYPE_DISABLED
A track parameter is unavailable because it has been disabled.
DMUS_E_TYPE_UNSUPPORTED
Parameter is unsupported on this track.
DMUS_E_UNKNOWN_PROPERTY
The property set or item is not implemented by this port.
DMUS_E_UNKNOWNDOWNLOAD
The synthesizer does not support this type of download.
DMUS_E_UNSUPPORTED_STREAM
The IStream object does not contain data supported by the loading object.
DMUS_E_WAVEFORMATNOTSUPPORTED
Invalid buffer format was handed to the synthesizer sink.
DMUS_S_DOWN_OCTAVE
The note has been lowered by one or more octaves to fit within the range of MIDI values.
DMUS_S_END
The operation succeeded and reached the end of the data.
DMUS_S_FREE
The allocated memory should be freed.
DMUS_S_GARBAGE_COLLECTED
The requested operation was not performed because the object has been released.
DMUS_S_LAST_TOOL
There are no more tools in the graph.
DMUS_S_NOBUFFERCONTROL
Although the audio output from the port is routed to the same device as the given DirectSound buffer, buffer controls such as pan and volume do not affect the output.
DMUS_S_OVER_CHORD
No MIDI values have been calculated because the music value has the note at a position higher than the top note of the chord.
DMUS_S_PARTIALDOWNLOAD
Some instruments could not be downloaded to the port.
DMUS_S_PARTIALLOAD
The object could only load partially. This can happen if some components, such as embedded tracks and tools, are not registered properly. It can also happen if some content is missing; for example, if a segment uses a DLS collection that is not in the loader's current search directory.
DMUS_S_REQUEUE
The message should be passed to the next tool.
DMUS_S_STRING_TRUNCATED
The method succeeded, but the returned string was truncated.
DMUS_S_UP_OCTAVE
The note has been raised by one or more octaves to fit within the range of MIDI values.
E_FAIL
The method did not succeed.
E_INVALIDARG
Invalid argument. Often, this error results from failing to initialize the dwSize member of a structure before passing it to the method.
E_NOINTERFACE
No object interface is available.
E_NOTIMPL
The method is not implemented. This value might be returned if a driver does not support a feature necessary for the operation.
E_OUTOFMEMORY
Insufficient memory to complete the task.
E_POINTER
An invalid pointer, usually NULL, was passed as a parameter.
REGDB_E_CLASSNOTREG
The object class is not registered.
S_FALSE
The method succeeded, but there was nothing to do.
S_OK
The operation was completed successfully.


DirectSound C/C++ Reference

This section contains reference information for the Microsoft® DirectSound® application programming interface (API). This section contains reference information for the API elements that DirectSound provides. Reference material is divided into the following categories.

  • DirectSound Interfaces
  • DirectSound Callback Function
  • DirectSound Functions
  • DirectSound Structures
  • DirectSound Return Values


DirectSound Interfaces

This section contains references for methods of the following DirectSound interfaces:

  • IDirectSound8
  • IDirectSound3DBuffer8
  • IDirectSound3DListener8
  • IDirectSoundBuffer8
  • IDirectSoundCapture8
  • IDirectSoundCaptureBuffer8
  • IDirectSoundCaptureFXAec8
  • IDirectSoundCaptureFXNoiseSuppress8
  • IDirectSoundFullDuplex8
  • IDirectSoundFXChorus8
  • IDirectSoundFXCompressor8
  • IDirectSoundFXDistortion8
  • IDirectSoundFXEcho8
  • IDirectSoundFXFlanger8
  • IDirectSoundFXGargle8
  • IDirectSoundFXI3DL2Reverb8
  • IDirectSoundFXParamEq8
  • IDirectSoundNotify8
  • IKsPropertySet

For DirectX 8.0, only IDirectSound8, IDirectSoundBuffer8, and IDirectSoundCaptureBuffer8 are new interfaces that supersede interfaces with similar, unnumbered names. Other interface names ending in 8 are simple defines for unchanged or new unnumbered interfaces. For example, IDirectSoundCapture8 is exactly equivalent to IDirectSoundCapture.

All interfaces that have a define ending in 8 are documented under that defined name, and it is recommended that you always use this name in your code. When recompiling for future versions, you can substitute the latest number in all your declarations and be sure of getting the latest version of any updated interfaces.

When a method takes an interface pointer as a parameter, you can pass in the newer version even where the method is declared as accepting the older version. For example, a pointer to either IDirectSoundBuffer or IDirectSoundBuffer8 can be passed to IDirectSound8::DuplicateSoundBuffer as the pDSBufferOriginal parameter.

When a method returns an interface, however, it is usually the older interface, and the newer interface must be obtained by using QueryInterface. This is the case, for example, with the ppDSBuffer parameter of IDirectSound8::CreateSoundBuffer.


IDirectSound8

Used to create buffer objects and set up the environment.

The IDirectSound8 interface supersedes IDirectSound and adds new methods. See Remarks.

Obtain this interface by using the DirectSoundCreate8 or DirectSoundFullDuplexCreate8 function, or by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSound8.

The methods of the IDirectSound8 interface can be organized into the following groups:

Initialization | Initialize
 | SetCooperativeLevel
Buffer creation | CreateSoundBuffer
 | DuplicateSoundBuffer
Device capabilities | GetCaps
 | VerifyCertification
Memory management | Compact
Speaker configuration | GetSpeakerConfig
 | SetSpeakerConfig

The IDirectSound8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUND8 type is defined as a pointer to the IDirectSound8 interface:

typedef struct IDirectSound8    *LPDIRECTSOUND8;

Remarks

Only objects of class CLSID_DirectSound8 support this interface. All DirectSound objects created by DirectSoundCreate8 and DirectSoundFullDuplexCreate8 fall into this category. Objects of class CLSID_DirectSound, which include all those created by using DirectSoundCreate, support only the earlier IDirectSound interface.

The behavior of CLSID_DirectSound8 objects is somewhat different than that of CLSID_DirectSound objects. These differences are found in the IDirectSound interface as well as the IDirectSound8 interface. Specific differences in the behavior of the newer object include the following:

  • In IDirectSound8::CreateSoundBuffer, DSBCAPS_CTRL3D cannot be set on a buffer with a non-mono format, and DSBCAPS_CTRL3D cannot be combined with DSBCAPS_CTRLPAN.
  • New buffer creation flags are supported.
  • Buffers are not filled with silence on creation.
  • The IDirectSoundBuffer interface returned by CreateSoundBuffer can be queried for the IDirectSoundBuffer8 interface.
  • Wave formats in the DSBUFFERDESC structure that have the WAVE_FORMAT_EXTENSIBLE format tag are checked more strictly for validity.

Requirements

Header: Declared in dsound.h.


IDirectSound8::Compact

Moves the unused portions of on-board sound memory, if any, to a contiguous block so that the largest portion of free memory will be available.

HRESULT Compact();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED
DSERR_UNINITIALIZED

Remarks

The application's DirectSound object must have at least the DSSCL_PRIORITY cooperative level. See IDirectSound8::SetCooperativeLevel.

This method will fail if any operations are in progress.

Requirements

Header: Declared in dsound.h


IDirectSound8::CreateSoundBuffer

Creates a DirectSoundBuffer object to hold a sequence of audio samples.

HRESULT CreateSoundBuffer(
  LPCDSBUFFERDESC pcDSBufferDesc,
  LPDIRECTSOUNDBUFFER * ppDSBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

pcDSBufferDesc
Address of a DSBUFFERDESC structure that describes the sound buffer to create.
ppDSBuffer
Address of a variable that receives the IDirectSoundBuffer interface of the new buffer object. Use QueryInterface to obtain IDirectSoundBuffer8. IDirectSoundBuffer8 is not available for primary buffers. See Remarks.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Return Values

If the method succeeds, the return value is DS_OK, or DS_NO_VIRTUALIZATION if a requested 3-D algorithm was not available and stereo panning was substituted. See the description of the guid3DAlgorithm member of DSBUFFERDESC.

If the method fails, the return value may be one of the following error values:

DSERR_ALLOCATED
DSERR_CONTROLUNAVAIL
DSERR_BADFORMAT
DSERR_BUFFERTOOSMALL
DSERR_DS8_REQUIRED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

DirectSound does not initialize the contents of the buffer, and the application cannot assume that it contains silence.

If the application is multithreaded, the thread that creates the buffer must continue to exist for the lifetime of the buffer. Buffers created on WDM drivers stop playing when the thread is terminated.

If an attempt is made to create a buffer with the DSBCAPS_LOCHARDWARE flag on a system where hardware acceleration is not available, the method fails with either DSERR_CONTROLUNAVAIL or DSERR_INVALIDCALL, depending on the operating system.

Requirements

Header: Declared in dsound.h.

See Also

Creating Secondary Buffers, IDirectSound8::DuplicateSoundBuffer


IDirectSound8::DuplicateSoundBuffer

Creates a new DirectSoundBuffer object that duplicates or shares the original buffer's memory.

HRESULT DuplicateSoundBuffer(
  LPDIRECTSOUNDBUFFER pDSBufferOriginal,
  LPDIRECTSOUNDBUFFER * ppDSBufferDuplicate
);

Parameters

pDSBufferOriginal
Address of the IDirectSoundBuffer or IDirectSoundBuffer8 interface of the buffer to duplicate.
ppDSBufferDuplicate
Address of a variable that receives the IDirectSoundBuffer interface pointer for the new buffer. The IDirectSoundBuffer8 interface cannot be obtained from duplicate buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_ALLOCATED
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

This method is not valid for buffers created with the DSBCAPS_CTRLFX flag.

Initially, the duplicate buffer will have the same parameters as the original buffer. However, the application can change the parameters of each buffer independently, and each can be played or stopped without affecting the other.

The buffer memory is released when the last object referencing it is released.

Although duplicate buffers often share the same memory, this is not always the case. Changes in the data stored in one buffer are not necessarily reflected in its duplicates.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound8::CreateSoundBuffer


IDirectSound8::GetCaps

Retrieves the capabilities of the hardware device that is represented by the DirectSound object.

HRESULT GetCaps(
  LPDSCAPS pDSCaps
);

Parameters

pDSCaps
Address of a DSCAPS structure that receives the capabilities of this sound device.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

Information retrieved in the DSCAPS structure describes the maximum capabilities of the sound device and those currently available, such as the number of hardware mixing channels and the amount of on-board sound memory. You can use this information to fine-tune performance and optimize resource allocation.

Because of resource-sharing requirements, the maximum capabilities in one area might be available only at the cost of another area.

Requirements

Header: Declared in dsound.h.


IDirectSound8::GetSpeakerConfig

Retrieves the speaker configuration.

HRESULT GetSpeakerConfig(
  LPDWORD pdwSpeakerConfig
);

Parameters

pdwSpeakerConfig
Address of the speaker configuration for this DirectSound object. The speaker configuration is specified with one of the following values:
DSSPEAKER_5POINT1
The audio is played through a speaker arrangement of surround speakers with a subwoofer.
DSSPEAKER_HEADPHONE
The audio is played through headphones.
DSSPEAKER_MONO
The audio is played through a single speaker.
DSSPEAKER_QUAD
The audio is played through quadraphonic speakers.
DSSPEAKER_STEREO
The audio is played through stereo speakers (default value).
DSSPEAKER_SURROUND
The audio is played through surround speakers.
DSSPEAKER_STEREO can be combined with one of the following values:
DSSPEAKER_GEOMETRY_WIDE
The speakers are directed over an arc of 20 degrees.
DSSPEAKER_GEOMETRY_NARROW
The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_MIN
The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_MAX
The speakers are directed over an arc of 180 degrees.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

The value returned at pdwSpeakerConfig can be a packed DWORD containing both configuration and geometry information. Use the DSSPEAKER_CONFIG and DSSPEAKER_GEOMETRY macros to unpack the DWORD, as in the following example:

if (DSSPEAKER_CONFIG(dwSpeakerConfig) == DSSPEAKER_STEREO)
    {
    if (DSSPEAKER_GEOMETRY(dwSpeakerConfig) ==
                      DSSPEAKER_GEOMETRY_WIDE)
       {...}
    }

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound8::SetSpeakerConfig, Speaker Configuration


IDirectSound8::Initialize

Initializes a DirectSound object that was created by using the CoCreateInstance function.

HRESULT Initialize(
  LPCGUID pcGuidDevice
);

Parameters

pcGuidDevice
Address of the globally unique identifier (GUID) specifying the sound driver to which this DirectSound object binds. Pass NULL to select the primary sound driver.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_ALREADYINITIALIZED
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_NODRIVER

Remarks

This method is provided for compliance with the Component Object Model (COM) protocol. If the DirectSoundCreate8 function was used to create the DirectSound object, this method returns DSERR_ALREADYINITIALIZED. If IDirectSound8::Initialize is not called when using CoCreateInstance to create the DirectSound object, any method called afterward returns DSERR_UNINITIALIZED.

Requirements

Header: Declared in dsound.h.


IDirectSound8::SetCooperativeLevel

Sets the cooperative level of the application for this sound device.

HRESULT SetCooperativeLevel(
  HWND hwnd,
  DWORD dwLevel
);

Parameters

hwnd
Handle to the application window.
dwLevel
Requested priority level. Specify one of the following values:
DSSCL_EXCLUSIVE
For DirectX 8.0 and later, has the same effect as DSSCL_PRIORITY. For previous versions, sets the application to the exclusive level. This means that when it has the input focus, the application will be the only one audible; sounds from applications with the DSBCAPS_GLOBALFOCUS flag set will be muted. With this level, it also has all the privileges of the DSSCL_PRIORITY level. DirectSound will restore the hardware format, as specified by the most recent call to the IDirectSoundBuffer8::SetFormat method, after the application gains the input focus.
DSSCL_NORMAL
Sets the application to a fully cooperative status. This level has the smoothest multitasking and resource-sharing behavior, but because it does not allow the primary buffer format to change, output is restricted to the default 8-bit format.
DSSCL_PRIORITY
Sets the application to the priority level. Applications with this cooperative level can call the IDirectSoundBuffer8::SetFormat and IDirectSound8::Compact methods.
DSSCL_WRITEPRIMARY
This is the highest priority level. The application has write access to the primary sound buffers. No secondary sound buffers can be played. This level cannot be set if the DirectSound driver is being emulated for the device; that is, if the IDirectSound8::GetCaps method returns the DSCAPS_EMULDRIVER flag in the DSCAPS structure.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_UNINITIALIZED
DSERR_UNSUPPORTED

Remarks

The application must set the cooperative level by calling this method before its buffers can be played. The recommended cooperative level is DSSCL_PRIORITY. For more information, see Cooperative Levels.

Do not call this method if any buffers are locked.

Requirements

Header: Declared in dsound.h.


IDirectSound8::SetSpeakerConfig

Specifies the speaker configuration of the DirectSound object.

It is not recommended that applications use this method. See Speaker Configuration.

HRESULT SetSpeakerConfig(
  DWORD dwSpeakerConfig
);

Parameters

dwSpeakerConfig
Speaker configuration of the specified DirectSound object. This parameter can be one of the following values:
DSSPEAKER_5POINT1
The audio is played through a speaker arrangement of surround speakers with a subwoofer.
DSSPEAKER_HEADPHONE
The speakers are headphones.
DSSPEAKER_MONO
The speakers are monaural.
DSSPEAKER_QUAD
The speakers are quadraphonic.
DSSPEAKER_STEREO
The speakers are stereo (default value).
DSSPEAKER_SURROUND
The speakers are surround sound.
DSSPEAKER_STEREO can be combined with one of the following values:
DSSPEAKER_GEOMETRY_WIDE
The speakers are directed over an arc of 20 degrees.
DSSPEAKER_GEOMETRY_NARROW
The speakers are directed over an arc of 10 degrees.
DSSPEAKER_GEOMETRY_MIN
The speakers are directed over an arc of 5 degrees.
DSSPEAKER_GEOMETRY_MAX
The speakers are directed over an arc of 180 degrees.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNINITIALIZED

Remarks

If a geometry value is to be used, it must be packed in a DWORD along with the DSSPEAKER_STEREO flag. This can be done by using the DSSPEAKER_COMBINED macro, as in the following C++ example:

lpds->SetSpeakerConfig(DSSPEAKER_COMBINED(
    DSSPEAKER_STEREO, DSSPEAKER_GEOMETRY_WIDE));

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound8::GetSpeakerConfig


IDirectSound8::VerifyCertification

Ascertains whether the DirectSound device is certified for DirectX.

VerifyCertification(
  LPDWORD pdwCertified
);

Parameters

pdwCertified
Address of a DWORD variable that receives one of the following values.
DS_CERTIFIED
Driver is certified for DirectSound.
DS_UNCERTIFIED
Driver is not certified for DirectSound.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNSUPPORTED

Remarks

On emulated devices, the method returns DSERR_UNSUPPORTED. Emulated devices are identified by the DSCAPS_EMULDRIVER flag in the dwFlags member of DSCAPS.

Requirements

Header: Declared in dsound.h.


IDirectSound3DBuffer8

Used to retrieve and set parameters that describe the position, orientation, and environment of a sound buffer in 3-D space.

IDirectSound3DBuffer8 is a define for IDirectSoundBuffer. The two interface names are interchangeable.

The IDirectSound3DBuffer8 interface is obtained from an IDirectSoundBuffer8 interface by using the IDirectSoundBuffer8::QueryInterface method. It can also be retrieved from an audio path.

The methods of the IDirectSound3DBuffer8 interface can be organized into the following groups:

Batch parameter manipulation | GetAllParameters
 | SetAllParameters
Distance | GetMaxDistance
 | GetMinDistance
 | SetMaxDistance
 | SetMinDistance
Operation mode | GetMode
 | SetMode
Position | GetPosition
 | SetPosition
Sound projection cones | GetConeAngles
 | GetConeOrientation
 | GetConeOutsideVolume
 | SetConeAngles
 | SetConeOrientation
 | SetConeOutsideVolume
Velocity | GetVelocity
 | SetVelocity

The IDirectSound3DBuffer8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUND3DBUFFER type is defined as a pointer to the IDirectSound3DBuffer8 interface:

typedef struct IDirectSound3DBuffer    *LPDIRECTSOUND3DBUFFER;

Requirements

Header: Declared in dsound.h.

See Also

Obtaining the 3-D Buffer Object, Retrieving Objects from an Audiopath


IDirectSound3DBuffer8::GetAllParameters

Retrieves information that describes the 3-D characteristics of a sound buffer at a given point in time.

HRESULT GetAllParameters(
  LPDS3DBUFFER pDs3dBuffer
);

Parameters

pDs3dBuffer
Address of a DS3DBUFFER structure that receives the information describing the 3-D characteristics of the sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSound3DBuffer8::GetConeAngles

Retrieves the inside and outside angles of the sound projection cone for this sound buffer.

HRESULT GetConeAngles(
  LPDWORD pdwInsideConeAngle,
  LPDWORD pdwOutsideConeAngle
);

Parameters

pdwInsideConeAngle
Addresses of a variable that receives the inside angle of the sound projection cone, in degrees. This is the angle within which the sound is at its normal volume.
pdwOutsideConeAngle
Addresses of a variable that receives the outside angle of the sound projection cone, in degrees. This is the angle outside of which the sound is at its outside volume.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined in Dsound.h as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DBuffer8::GetConeOutsideVolume, IDirectSound3DBuffer8::SetConeOutsideVolume, IDirectSound3DBuffer8::GetConeOrientation,IDirectSound3DBuffer8::SetConeOrientation


IDirectSound3DBuffer8::GetConeOrientation

Retrieves the orientation of the sound projection cone for this sound buffer.

HRESULT GetConeOrientation(
  D3DVECTOR * pvOrientation
);

Parameters

pvOrientation
Address of a D3DVECTOR structure that receives the orientation of the sound projection cone. The vector information represents the center of the sound cone.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The values returned are not necessarily the same as those set by using the IDirectSound3DBuffer8::SetConeOrientation method. DirectSound adjusts orientation vectors so that they are have a magnitude of less than or equal to 1.0.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DBuffer8::SetConeOrientation, IDirectSound3DBuffer8::SetConeAngles, IDirectSound3DBuffer8::SetConeOutsideVolume


IDirectSound3DBuffer8::GetConeOutsideVolume

Retrieves the cone outside volume for this sound buffer.

HRESULT GetConeOutsideVolume(
  LPLONG plConeOutsideVolume
);

Parameters

plConeOutsideVolume
Address of a variable that receives the cone outside volume for this buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Volume levels are represented by attenuation. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). These values are defined in Dsound.h. Currently DirectSound does not support amplification.

For more information about the concept of outside volume, see Sound Cones.

Requirements

Header: Declared in dsound.h.

See Also

See Also

IDirectSound3DBuffer8::SetConeOutsideVolume, IDirectSound3DBuffer8::GetConeOrientation,IDirectSound3DBuffer8::SetConeOrientation


IDirectSound3DBuffer8::GetMaxDistance

Retrieves the maximum distance for this sound buffer.

HRESULT GetMaxDistance(
  D3DVALUE * pflMaxDistance
);

Parameters

pflMaxDistance
Address of a variable that receives the maximum distance setting.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DBuffer8::GetMinDistance, IDirectSound3DBuffer8::SetMaxDistance


IDirectSound3DBuffer8::GetMinDistance

Retrieves the minimum distance for this sound buffer.

HRESULT GetMinDistance(
  D3DVALUE * pflMinDistance
);

Parameters

pflMinDistance
Address of a variable that receives the minimum distance setting.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, currently defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DBuffer8::SetMinDistance, IDirectSound3DBuffer8::GetMaxDistance


IDirectSound3DBuffer8::GetMode

Retrieves the operation mode for 3-D sound processing.

HRESULT GetMode(
  LPDWORD pdwMode
);

Parameters

pdwMode
Address of a variable that receives the mode setting. This value will be one of the following:
DS3DMODE_DISABLE
Processing of 3-D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSound3DBuffer8::GetPosition

Retrieves the sound buffer's position, in distance units. By default, distance units are meters, but the units can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

HRESULT GetPosition(
  D3DVECTOR * pvPosition
);

Parameters

pvPosition
Address of a D3DVECTOR structure that receives the position of the sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSound3DBuffer8::GetVelocity

Retrieves the velocity for this sound buffer. Velocity is measured in units per second. The default unit is one meter, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

HRESULT GetVelocity(
  D3DVECTOR * pvVelocity
);

Parameters

pvVelocity
Address of a D3DVECTOR structure that receives the sound buffer's velocity.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used for Doppler effects only. It does not actually move the buffer. For more information, see Doppler Factor.

The default unit of measurement is meters per second, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DBuffer8::SetPosition, IDirectSound3DBuffer8::SetVelocity


IDirectSound3DBuffer8::SetAllParameters

Sets all 3-D sound buffer parameters.

HRESULT SetAllParameters(
  LPCDS3DBUFFER pcDs3dBuffer,
  DWORD dwApply
);

Parameters

pcDs3dBuffer
Address of a DS3DBUFFER structure that describes the 3-D characteristics of the sound buffer.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSound3DBuffer8::SetConeAngles

Sets the inside and outside angles of the sound projection cone for this sound buffer.

HRESULT SetConeAngles(
  DWORD dwInsideConeAngle,
  DWORD dwOutsideConeAngle,
  DWORD dwApply
);

Parameters

dwInsideConeAngle
Value that specifies the inside cone angle, in degrees. This is the angle within which the sound is at its normal volume.
dwOutsideConeAngle
Value that specifies the outside cone angle, in degrees. This is the angle outside of which the sound is at its outside volume.
dwApply
Value that indicates when the setting should be applied. Must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The minimum, maximum, and default cone angles are defined in Dsound.h as DS3D_MINCONEANGLE, DS3D_MAXCONEANGLE, and DS3D_DEFAULTCONEANGLE. Each angle must be in the range of 0 degrees (no cone) to 360 degrees (the full sphere). The default value is 360.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DBuffer8::SetConeOutsideVolume, IDirectSound3DBuffer8::SetConeOrientation


IDirectSound3DBuffer8::SetConeOrientation

Sets the orientation of the sound projection cone for this sound buffer. This method has no effect unless the cone angle and cone volume factor have also been set.

HRESULT SetConeOrientation(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z
Values that specify the coordinates of the sound cone orientation vector.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DBuffer8::SetConeAngles, IDirectSound3DBuffer8::SetConeOutsideVolume


IDirectSound3DBuffer8::SetConeOutsideVolume

Sets the cone outside volume for this sound buffer.

HRESULT SetConeOutsideVolume(
  LONG lConeOutsideVolume,
  DWORD dwApply
);

Parameters

lConeOutsideVolume
Cone outside volume for this sound buffer, in hundredths of decibels. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). These values are defined in Dsound.h.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Volume levels are represented by attenuation. Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). The default value is DS3D_DEFAULTCONEOUTSIDEVOLUME (no attenuation). These values are defined in Dsound.h. Currently DirectSound does not support amplification.

For information about the concept of cone outside volume, see Sound Cones.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DBuffer8::SetConeAngles, IDirectSound3DBuffer8::SetConeOrientation, IDirectSoundBuffer8::SetVolume


IDirectSound3DBuffer8::SetMaxDistance

Sets the maximum distance value.

HRESULT SetMaxDistance(
  D3DVALUE flMaxDistance,
  DWORD dwApply
);

Parameters

flMaxDistance
New maximum distance value.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The default maximum distance, defined as DS3D_DEFAULTMAXDISTANCE, is effectively infinite.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DBuffer8::GetMaxDistance, IDirectSound3DBuffer8::SetMinDistance


IDirectSound3DBuffer8::SetMinDistance

Sets the minimum distance value.

HRESULT SetMinDistance(
  D3DVALUE flMinDistance,
  DWORD dwApply
);

Parameters

flMinDistance
New minimum distance value.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

By default, the minimum distance value is DS3D_DEFAULTMINDISTANCE, currently defined as 1.0 (corresponding to 1.0 meter at the default distance factor of 1.0 meters per unit).

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DBuffer8::SetMaxDistance


IDirectSound3DBuffer8::SetMode

Sets the operation mode for 3-D sound processing.

HRESULT SetMode(
  DWORD dwMode,
  DWORD dwApply
);

Parameters

dwMode
Flag specifying the 3-D sound processing mode to be set:
DS3DMODE_DISABLE
Processing of 3-D sound is disabled. The sound seems to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSound3DBuffer8::SetPosition

Sets the sound buffer's position, in distance units. By default, distance units are meters, but the units can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

HRESULT SetPosition(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z
Values that specify the coordinates of the position vector. DirectSound may adjust these values to prevent floating-point overflow.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSound3DBuffer8::SetVelocity

Sets the velocity of the sound source.

HRESULT SetVelocity(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z
Values that specify the coordinates of the velocity vector. DirectSound may adjust these values to prevent floating-point overflow.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for calculating Doppler effect. It does not change the position of the buffer. For more information, see Doppler Factor.

The default unit of measurement is meters per second, but this can be changed by using the IDirectSound3DListener8::SetDistanceFactor method.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DBuffer8::SetPosition, IDirectSound3DBuffer8::GetVelocity


IDirectSound3DListener8

Used to retrieve and set parameters that describe a listener's position, orientation, and listening environment in 3-D space.

The interface can be obtained by calling the IDirectSoundBuffer8::QueryInterface method on a primary buffer created with the DSBCAPS_CTRL3D flag. Applications that use audiopaths can obtain the interface from the audiopath as in the following code example, where pAudiopath is an IDirectMusicAudioPath8 interface pointer.

IDirectSound3DListener8 *pListener;

pAudioPath->GetObjectInPath(0, DMUS_PATH_PRIMARY_BUFFER,
        0, GUID_All_Objects, 0, IID_IDirectSound3DListener,
        (void **)&pListener)));

The methods of the IDirectSound3DListener8 interface can be organized into the following groups:

Batch parameters | GetAllParameters
 | SetAllParameters
Deferred settings | CommitDeferredSettings
Distance factor | GetDistanceFactor
 | SetDistanceFactor
Doppler factor | GetDopplerFactor
 | SetDopplerFactor
Orientation | GetOrientation
 | SetOrientation
Position | GetPosition
 | SetPosition
Rolloff factor | GetRolloffFactor
 | SetRolloffFactor
Velocity | GetVelocity
 | SetVelocity

The IDirectSound3DListener8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUND3DLISTENER type is defined as a pointer to the IDirectSound3DListener interface:

typedef struct IDirectSound3DListener    *LPDIRECTSOUND3DLISTENER;

Requirements

Header: Declared in dsound.h.


IDirectSound3DListener8::CommitDeferredSettings

Commits any deferred settings made since the last call to this method.

HRESULT CommitDeferredSettings();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

For more information about using deferred settings to maximize efficiency, see Deferred Settings.

Requirements

Header: Declared in dsound.h.


IDirectSound3DListener8::GetAllParameters

Retrieves the state of the 3-D world and listener.

HRESULT GetAllParameters(
  LPDS3DLISTENER pListener
);

Parameters

pListener
Address of a DS3DLISTENER structure that receives the state of the 3-D world and listener.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::SetAllParameters


IDirectSound3DListener8::GetDistanceFactor

Retrieves the distance factor, which is the number of meters in a vector unit.

HRESULT GetDistanceFactor(
  D3DVALUE * pflDistanceFactor
);

Parameters

pflDistanceFactor
Address of a variable that receives the distance factor value.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::SetDistanceFactor, Distance Factor


IDirectSound3DListener8::GetDopplerFactor

Retrieves the Doppler effect factor.

HRESULT GetDopplerFactor(
  D3DVALUE * pflDopplerFactor
);

Parameters

pflDopplerFactor
Address of a variable that receives the Doppler factor value.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (as currently defined, 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0). For more information, see Doppler Factor.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::SetDopplerFactor


IDirectSound3DListener8::GetOrientation

Retrieves the listener's orientation in vectors: a front vector and a top vector.

HRESULT GetOrientation(
  D3DVECTOR * pvOrientFront,
  D3DVECTOR * pvOrientTop
);

Parameters

pvOrientFront
Address of a D3DVECTOR structure that receives the listener's front orientation vector.
pvOrientTop
Address of a D3DVECTOR structure that receives the listener's top orientation vector.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points out the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The values returned are not necessarily the same as those set by using the IDirectSound3DListener8::SetOrientation method. DirectSound adjusts orientation vectors so that they are at right angles and have a magnitude of less than or equal to 1.0.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::SetOrientation


IDirectSound3DListener8::GetPosition

Retrieves the listener's position in distance units. By default, these units are meters, but this can be changed by calling the IDirectSound3DListener8::SetDistanceFactor method.

HRESULT GetPosition(
  D3DVECTOR * pvPosition
);

Parameters

pvPosition
Address of a D3DVECTOR structure that receives the listener's position vector.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::SetPosition


IDirectSound3DListener8::GetRolloffFactor

Retrieves the rolloff factor, which determines the rate of attenuation over distance.

HRESULT GetRolloffFactor(
  D3DVALUE * pflRolloffFactor
);

Parameters

pflRolloffFactor
Address of a variable that receives the rolloff factor.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (as currently defined, 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For more information, see Rolloff Factor.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::SetRolloffFactor


IDirectSound3DListener8::GetVelocity

Retrieves the listener's velocity.

HRESULT GetVelocity(
  D3DVECTOR * pvVelocity
);

Parameters

pvVelocity
Address of a D3DVECTOR structure that receives the listener's velocity.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for calculating Doppler effect. It does not change the listener's position. To move the listener, use the IDirectSound3DListener8::SetPosition method.

The default velocity is (0,0,0).

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::SetVelocity


IDirectSound3DListener8::SetAllParameters

Sets all 3-D listener parameters from a given DS3DLISTENER structure that describes all aspects of the 3-D listener at a moment in time.

HRESULT SetAllParameters(
  LPCDS3DLISTENER pcListener,
  DWORD dwApply
);

Parameters

pcListener
Address of a DS3DLISTENER structure that contains information describing all 3-D listener parameters.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::GetAllParameters


IDirectSound3DListener8::SetDistanceFactor

Sets the distance factor, which is the number of meters in a vector unit.

HRESULT SetDistanceFactor(
  D3DVALUE flDistanceFactor,
  DWORD dwApply
);

Parameters

flDistanceFactor
Value that specifies the distance factor.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The distance factor has a range of DS3D_MINDISTANCEFACTOR to DS3D_MAXDISTANCEFACTOR, defined in Dsound.h as FLT_MIN and FLT_MAX respectively. The default value is DS3D_DEFAULTDISTANCEFACTOR, or 1.0.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::GetDistanceFactor, Distance Factor


IDirectSound3DListener8::SetDopplerFactor

Sets the Doppler effect factor.

HRESULT SetDopplerFactor(
  D3DVALUE flDopplerFactor,
  DWORD dwApply
);

Parameters

flDopplerFactor
Value that specifies the Doppler factor.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The Doppler factor has a range of DS3D_MINDOPPLERFACTOR (no Doppler effects) to DS3D_MAXDOPPLERFACTOR (as currently defined, 10 times the Doppler effects found in the real world). The default value is DS3D_DEFAULTDOPPLERFACTOR (1.0). For more information, see Doppler Factor.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::GetDopplerFactor


IDirectSound3DListener8::SetOrientation

Sets the listener's orientation in terms of two vectors: a front vector and a top vector.

HRESULT SetOrientation(
  D3DVALUE xFront,
  D3DVALUE yFront,
  D3DVALUE zFront,
  D3DVALUE xTop,
  D3DVALUE yTop,
  D3DVALUE zTop,
  DWORD    dwApply
);

Parameters

xFront, yFront, zFront
Values that specify the coordinates of the front orientation vector.
xTop, yTop, zTop
Values that specify the coordinates of the top orientation vector.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The front vector points in the direction of the listener's nose, and the top vector points out the top of the listener's head. By default, the front vector is (0,0,1.0) and the top vector is (0,1.0,0).

The top vector must be at right angles to the front vector. If necessary, DirectSound adjusts the front vector after setting the top vector.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::GetOrientation


IDirectSound3DListener8::SetPosition

Sets the listener's position, in distance units. By default, these units are meters, but this can be changed by calling the IDirectSound3DListener8::SetDistanceFactor method.

HRESULT SetPosition(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z
Values that specify the coordinates of the listener's position vector. Note that DirectSound may adjust these values to prevent floating-point overflow.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::GetPosition


IDirectSound3DListener8::SetRolloffFactor

Sets the rolloff factor, which determines the rate of attenuation over distance.

HRESULT SetRolloffFactor(
  D3DVALUE flRolloffFactor,
  DWORD dwApply
);

Parameters

flRolloffFactor
Value that specifies the rolloff factor.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The rolloff factor has a range of DS3D_MINROLLOFFFACTOR (no rolloff) to DS3D_MAXROLLOFFFACTOR (as currently defined, 10 times the rolloff found in the real world). The default value is DS3D_DEFAULTROLLOFFFACTOR (1.0). For more information, see Rolloff Factor.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::GetRolloffFactor


IDirectSound3DListener8::SetVelocity

Sets the listener's velocity.

HRESULT SetVelocity(
  D3DVALUE x,
  D3DVALUE y,
  D3DVALUE z,
  DWORD dwApply
);

Parameters

x, y, and z
Values that specify the coordinates of the listener's velocity vector. DirectSound may adjust these values to prevent floating-point overflow.
dwApply
Value that specifies when the setting should be applied. This value must be one of the following:
DS3D_DEFERRED
Settings are not applied until the application calls the IDirectSound3DListener8::CommitDeferredSettings method. This allows the application to change several settings and generate a single recalculation.
DS3D_IMMEDIATE
Settings are applied immediately, causing the system to recalculate the 3-D coordinates for all 3-D sound buffers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

Velocity is used only for Doppler effects. It does not actually move the listener. To change the listener's position, use the IDirectSound3DListener8::SetPosition method. The default velocity is (0,0,0).

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound3DListener8::GetVelocity


IDirectSoundBuffer8

Used to manage sound buffers.

The IDirectSoundBuffer8 interface supersedes IDirectSoundBuffer and adds new methods.

To obtain the interface, use the IDirectSound8::CreateSoundBuffer method to retrieve IDirectSoundBuffer, and then pass IID_IDirectSoundBuffer8 to IDirectSoundBuffer::QueryInterface.

For primary sound buffers, you must use the IDirectSoundBuffer interface. IDirectSoundBuffer8 is not available. IDirectSoundBuffer is not documented separately. For documentation, see the corresponding IDirectSoundBuffer8 methods.

Not all methods of IDirectSoundBuffer are valid for primary buffers. For example, SetCurrentPosition will fail. See the reference topics for individual methods.

The IDirectSoundBuffer8 methods can be organized into the following groups:

Effects | GetObjectInPath
 | SetFX
Information | GetCaps
 | GetFormat
 | GetStatus
 | SetFormat
Memory management | AcquireResources
 | Initialize
 | Restore
Play management | GetCurrentPosition
 | Lock
 | Play
 | SetCurrentPosition
 | Stop
 | Unlock
Sound management | GetFrequency
 | GetPan
 | GetVolume
 | SetFrequency
 | SetPan
 | SetVolume

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The following table shows which methods are supported for buffer objects obtained from an audiopath; that is, buffers created by a DirectMusic performance. Mix-in buffers accept sends from other buffers.All other buffers in the audiopath are sink-in buffers, which means that they accept data only from the synthesizer sink.

IDirectSoundBuffer8 method | Mix-in | Sink-in
AcquireResources |  |
GetCaps | Yes | Yes
GetCurrentPosition |  |
GetFormat | Yes | Yes
GetFrequency |  |
GetObjectInPath | Yes | Yes
GetPan | Yes | Yes
GetStatus | Yes | Yes
GetVolume | Yes | Yes
Initialize |  |
Lock |  |
Play | Yes |
Restore |  |
SetCurrentPosition |  |
SetFormat |  |
SetFrequency |  |
SetFX | Yes | Yes
SetPan | Yes | Yes
SetVolume | Yes | Yes
Stop | Yes |
Unlock |  |

The LPDIRECTSOUNDBUFFER8 type is defined as a pointer to the IDirectSoundBuffer interface:

typedef struct IDirectSoundBuffer8    *LPDIRECTSOUNDBUFFER8;

Requirements

Header: Declared in dsound.h.


IDirectSoundBuffer8::AcquireResources

Allocates resources for a buffer that was created with the DSBCAPS_LOCDEFER flag in the DSBUFFERDESC structure.

HRESULT AcquireResources(
  DWORD dwFlags,
  DWORD dwEffectsCount,
  LPDWORD pdwResultCodes
);

Parameters

dwFlags
Flags specifying how resources are to be allocated for a buffer created with the DSBCAPS_LOCDEFER flag. For a list of values, see the voice management and voice allocation flags for IDirectSoundBuffer8::Play.
dwEffectsCount
Value that specifies the number of elements in the pdwResultFlags array, or 0 if pdwResultCodes is NULL.
pdwResultCodes
Address of an array of DWORD variables that receives information about the effects associated with the buffer. This array must contain one element for each effect that was assigned to the buffer by IDirectSoundBuffer8::SetFX. For each effect, one of the following values is returned.
DSFXR_LOCHARDWARE
Effect is instantiated in hardware.
DSFXR_LOCSOFTWARE
Effect is instantiated in software.
DSFXR_FAILED
No effect was created because resources weren't available.
DSFXR_PRESENT
The effect is available but was not created because the method failed for some other reason.
DSFXR_UNKNOWN
No effect was created because the effect isn't registered on the system.

This parameter can be NULL if result codes are not wanted.

Return Values

If the method succeeds, the return value is DS_OK or DS_INCOMPLETE.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDCALL
DSERR_INVALIDPARAM

Remarks

Normally, buffers created with DSBCAPS_LOCDEFER are not allocated resources until IDirectSoundBuffer8::Play is called. IDirectSoundBuffer8::AcquireResources can be used to allocate resources for deferred buffers. By doing so, the application can retrieve information about effects processing and set effect parameters before the buffer is played.

If the method fails, check the values in pdwResultCodes to determine which effects caused the failure.

A buffer with acquired resources that is not yet playing is not a candidate for premature termination by the voice management flags passed to the Play method.

Resources that have been acquired by AcquireResources are released when playback is stopped.

If the method is called on a buffer on which it has already been called, the status of the effects is returned but no additional resources are allocated.

The dwEffectsCount parameter to this function must be the same as the one passed in the call to IDirectSoundBuffer8::SetFX.

If an attempt is made to acquire resources for a buffer with the DSBCAPS_LOCHARDWARE flag on a system where hardware acceleration is not available, the method fails with either DSERR_CONTROLUNAVAIL or DSERR_INVALIDCALL, depending on the operating system.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFX, DSBCAPS


IDirectSoundBuffer8::GetCaps

Retrieves the capabilities of the DirectSoundBuffer object.

HRESULT GetCaps(
  LPDSBCAPS pDSBufferCaps
);

Parameters

pDSBufferCaps
Address of a DSBCAPS structure to contain the capabilities of this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The DSBCAPS structure contains similar information to the DSBUFFERDESC structure passed to the IDirectSound8::CreateSoundBuffer method, with some additional information. This additional information can include the buffer's location, either in hardware or software, and performance measures.

The flags specified in the dwFlags member of the DSBCAPS structure are the same flags used by the DSBUFFERDESC structure. The only difference is that in the DSBCAPS structure, either DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE will be specified according to the location of the buffer memory. In the DSBUFFERDESC structure, these flags are optional and, depending on which flag is specified, force the buffer to be located in either hardware or software.

Requirements

Header: Declared in dsound.h.

See Also

DSBCAPS, DSBUFFERDESC, IDirectSound8::CreateSoundBuffer


IDirectSoundBuffer8::GetCurrentPosition

Retrieves the position of the play and write cursors in the sound buffer.

HRESULT GetCurrentPosition(
  LPDWORD pdwCurrentPlayCursor,
  LPDWORD pdwCurrentWriteCursor
);

Parameters

pdwCurrentPlayCursor
Address of a variable that receives the offset, in bytes, of the play cursor. This parameter can be NULL if the value is not wanted.
pdwCurrentWriteCursor
Address of a variable that receives the offset, in bytes, of the write cursor. This parameter can be NULL if the value is not wanted.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The write cursor is the point in the buffer ahead of which it is safe to write data to the buffer. Data should not be written to the part of the buffer after the play cursor and before the write cursor. For more information, see Play and Write Cursors.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetCurrentPosition


IDirectSoundBuffer8::GetFormat

Retrieves a description of the format of the sound data in the buffer, or the buffer size needed to retrieve the format description.

HRESULT GetFormat(
  LPWAVEFORMATEX pwfxFormat,
  DWORD dwSizeAllocated,
  LPDWORD pdwSizeWritten
);

Parameters

pwfxFormat
Address of a WAVEFORMATEX structure that receives a description of the sound data in the buffer. To retrieve the buffer size needed to contain the format description, specify NULL. In this case the variable at pdwSizeWritten receives the size of the structure needed to receive the data.
dwSizeAllocated
Size, in bytes, of the structure at pwfxFormat. If pwfxFormat is not NULL, this value must be equal to or greater than the size of the expected data.
pdwSizeWritten
Address of a variable that receives the number of bytes written to the structure at pwfxFormat. This parameter can be NULL.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Remarks

The WAVEFORMATEX structure can have a variable length that depends on the format. Before retrieving the format description, the application should query the DirectSoundBuffer object for the size of the format by calling this method and specifying NULL for the pwfxFormat parameter. The necessary size of the structure is returned in the pdwSizeWritten parameter. The application can then allocate sufficient memory and call IDirectSoundBuffer8::GetFormat again to retrieve the format description.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFormat


IDirectSoundBuffer8::GetFrequency

Retrieves the frequency, in samples per second, at which the buffer is playing.

HRESULT GetFrequency(
  LPDWORD pdwFrequency
);

Parameters

pdwFrequency
Address of a variable that receives the frequency at which the audio buffer is being played, in hertz.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The frequency value for software buffers will be in the range of DSBFREQUENCY_MIN to DSBFREQUENCY_MAX. These values are defined in Dsound.h as 100 and 100,000 respectively. Hardware buffers can return other values.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFrequency


IDirectSoundBuffer8::GetObjectInPath

Retrieves an interface for an effect object associated with the buffer.

HRESULT GetObjectInPath(
  REFGUID rguidObject,
  DWORD dwIndex,
  REFGUID rguidInterface,
  LPVOID * ppObject
);

Parameters

rguidObject
Value of type REFGUID that specifies the unique class identifier of the object being searched for, such as GUID_DSFX_STANDARD_ECHO. Set this parameter to GUID_All_Objects to search for objects of any class.
dwIndex
Value that specifies the index of the object within objects of that class in the path. See Remarks.
rguidInterface
Value that specifies the unique identifier of the desired interface. See Remarks.
ppObject
Address of a variable that receives the desired interface pointer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_OBJECTNOTFOUND
E_NOINTERFACE

Remarks

Any DMO that has been set on a buffer by using IDirectSoundBuffer8::SetFX can be retrieved, even it has not been allocated resources.

The following interfaces can be retrieved for the various DMOs supplied with DirectX.

rguidInterface | *ppObject
IID_IDirectSoundFXGargle8 | IDirectSoundFXGargle8
IID_IDirectSoundFXChorus8 | IDirectSoundFXChorus8
IID_IDirectSoundFXFlanger8 | IDirectSoundFXFlanger8
IID_IDirectSoundFXEcho8 | IDirectSoundFXEcho8
IID_IDirectSoundFXDistortion8 | IDirectSoundFXDistortion8
IID_IDirectSoundFXCompressor8 | IDirectSoundFXCompressor8
IID_IDirectSoundFXParamEq8 | IDirectSoundFXParamEq8
IID_IDirectSoundFXWavesReverb8 | IDirectSoundFXWavesReverb8
IID_IDirectSoundFXI3DL2Reverb8 | IDirectSoundFXI3DL2Reverb8

In addition, the following interfaces are available for any of the standard DMOs. For information on these interfaces, see the DirectShow Help.

rguidInterface | *ppObject
IID_IMediaObject | IMediaObject
IID_IMediaObjectInPlace | IMediaObjectInPlace
IID_IMediaParams | IMediaParams

The value in dwIndex is the index of the object within the array of effects passed to IDirectSoundBuffer8::SetFX. This is not necessarily the actual position of the object in the effects chain, because some effects might not have been created.

An object is returned solely on the basis of whether it matches rguidObject and dwIndex. It is up to the application to ensure that rguidInterface specifies an interface that can be expected to be found on the object.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundFXChorus8, IDirectSoundFXCompressor8, IDirectSoundFXDistortion8, IDirectSoundFXEcho8, IDirectSoundFXFlanger8, IDirectSoundFXParamEq8, IDirectSoundFXI3DL2Reverb8


IDirectSoundBuffer8::GetPan

Retrieves the relative volume between the left and right audio channels.

HRESULT GetPan(
  LPLONG plPan
);

Parameters

plPan
Address of a variable to contain the relative mix between the left and right speakers.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The returned value is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are currently defined in Dsound.h as –10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is attenuated by 100 dB. The value DSBPAN_RIGHT means the left channel is attenuated by 100 dB. The neutral value is DSBPAN_CENTER, defined as zero. This value of 0 in the plPan parameter means that both channels are at full volume (they are attenuated by 0 decibels). At any setting other than DSBPAN_CENTER, one of the channels is at full volume and the other is attenuated.

A pan of –2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume. A pan of DSBPAN_LEFT means that the right channel is silent and the sound is all the way to the left, while a pan of DSBPAN_RIGHT means that the left channel is silent and the sound is all the way to the right.

The pan control acts cumulatively with the volume control.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::GetVolume, IDirectSoundBuffer8::SetPan, IDirectSoundBuffer8::SetVolume


IDirectSoundBuffer8::GetStatus

Retrieves the status of the sound buffer.

HRESULT GetStatus(
  LPDWORD pdwStatus
);

Parameters

pdwStatus
Address of a variable to contain the status of the sound buffer. The status can be a combination of the following flags:
DSBSTATUS_BUFFERLOST
The buffer is lost and must be restored before it can be played or locked.
DSBSTATUS_LOOPING
The buffer is being looped. If this value is not set, the buffer will stop when it reaches the end of the sound data. This value is returned only in combination with DSBSTATUS_PLAYING.
DSBSTATUS_PLAYING
The buffer is playing. If this value is not set, the buffer is stopped.
DSBSTATUS_LOCSOFTWARE
The buffer is playing in software. Set only for buffers created with the DSBCAPS_LOCDEFER flag.
DSBSTATUS_LOCHARDWARE
The buffer is playing in hardware. Set only for buffers created with the DSBCAPS_LOCDEFER flag.
DSBSTATUS_TERMINATED
The buffer was prematurely terminated by the voice manager and is not playing. Set only for buffers created with the DSBCAPS_LOCDEFER flag.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundBuffer8::GetVolume

Retrieves the volume of the buffer.

HRESULT GetVolume(
  LPLONG plVolume
);

Parameters

plVolume
Address of a variable that receives the attenuation, in hundredths of a decibel. See Remarks.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The return value is between DSBVOLUME_MAX and DSBVOLUME_MIN. These values are defined as 0 and –10,000, respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the sound. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for practical purposes, is silence.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetVolume


IDirectSoundBuffer8::Initialize

Initializes a DirectSoundBuffer object if it has not yet been initialized.

HRESULT Initialize(
  LPDIRECTSOUND pDirectSound,
  LPCDSBUFFERDESC pcDSBufferDesc
);

Parameters

pDirectSound
Address of the DirectSound object associated with this DirectSoundBuffer object.
pcDSBufferDesc
Address of a DSBUFFERDESC structure that contains the values used to initialize this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values.

DSERR_INVALIDPARAM
DSERR_ALREADYINITIALIZED

Remarks

Because the IDirectSound8::CreateSoundBuffer method calls IDirectSoundBuffer8::Initialize internally, it is not needed for the current release of DirectSound. This method is provided for future extensibility.

Requirements

Header: Declared in dsound.h.

See Also

DSBUFFERDESC, IDirectSound8::CreateSoundBuffer, IDirectSoundBuffer8


IDirectSoundBuffer8::Lock

Readies all or part of the buffer for a data write and returns pointers to which data can be written.

HRESULT Lock(
  DWORD dwOffset,
  DWORD dwBytes,
  LPVOID * ppvAudioPtr1,
  LPDWORD pdwAudioBytes1,
  LPVOID * ppvAudioPtr2,
  LPDWORD pdwAudioBytes2,
  DWORD dwFlags
);

Parameters

dwOffset
Value that specifies the offset, in bytes, from the start of the buffer to the point where the lock begins. This parameter is ignored if DSBLOCK_FROMWRITECURSOR is specified in the dwFlags parameter.
dwBytes
Value that specifies the size, in bytes, of the portion of the buffer to lock. The buffer is conceptually circular, so this number can exceed the number of bytes between dwOffset and the end of the buffer.
ppvAudioPtr1
Address of a variable that receives a pointer to the first locked part of the buffer.
pdwAudioBytes1
Address of a variable that receives the number of bytes in the block at ppvAudioPtr1. If this value is less than dwBytes, the lock has wrapped and ppvAudioPtr2 points to a second block of data at the beginning of the buffer .
ppvAudioPtr2
Address of a variable that receives a pointer to the second locked part of the capture buffer. If NULL is returned, the ppvAudioPtr1 parameter points to the entire locked portion of the capture buffer.
pdwAudioBytes2
Address of a variable that receives the number of bytes in the block at ppvAudioPtr2. If ppvAudioPtr2 is NULL, this value is zero.
dwFlags
Flags modifying the lock event. The following flags are defined:
DSBLOCK_FROMWRITECURSOR
Start the lock at the write cursor. The dwOffset parameter is ignored.
DSBLOCK_ENTIREBUFFER
Lock the entire buffer. The dwBytes parameter is ignored.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method accepts an offset and a byte count, and returns two write pointers and their associated sizes. If the locked portion does not extend to the end of the buffer and wrap to the beginning, the second pointer, ppvAudioBytes2, receives NULL. If the lock does wrap, ppvAudioBytes2 points to the beginning of the buffer.

If the application passes NULL for the ppvAudioPtr2 and pdwAudioBytes2 parameters, the lock extends no further than the end of the buffer and does not wrap.

After writing data to the pointers returned by this method, the application must immediately call IDirectSoundBuffer8::Unlock to notify DirectSound that the data is ready for playback. Failure to do so can cause audio breakup or silence on some sound device configurations.

This method returns write pointers only. The application should not try to read sound data from this pointer, because the data might not be valid. For example, if the buffer is located in on-card memory, the pointer might be an address to a temporary buffer in system memory. When IDirectSoundBuffer8::Unlock is called, the contents of this temporary buffer are transferred to the on-card memory.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::GetCurrentPosition


IDirectSoundBuffer8::Play

Causes the sound buffer to play, starting at the play cursor.

HRESULT Play(
  DWORD dwReserved1,
  DWORD dwPriority,
  DWORD dwFlags
);

Parameters

dwReserved1
Reserved. Must be 0.
dwPriority
Priority for the sound, used by the voice manager when assigning hardware mixing resources. The lowest priority is 0, and the highest priority is 0xFFFFFFFF. If the buffer was not created with the DSBCAPS_LOCDEFER flag, this value must be 0.
dwFlags
Flags specifying how to play the buffer. The following flags are defined:
DSBPLAY_LOOPING
After the end of the audio buffer is reached, play restarts at the beginning of the buffer. Play continues until explicitly stopped. This flag must be set when playing a primary sound buffer.
Voice allocation flags
The voice allocation flags are valid only for buffers created with the DSBCAPS_LOCDEFER flag. One of the following flags can be used to force the processing of the sound into hardware or software. If neither DBSPLAY_LOCHARDWARE nor DBSPLAY_LOCSOFTWARE is set, the sound is played in either software or hardware, depending on the availability of resources at the time the method is called. See Remarks.
DSBPLAY_LOCHARDWARE
Play this voice in a hardware buffer only. If the hardware has no available voices and no voice management flags are set, the call to IDirectSoundBuffer8::Play fails. This flag cannot be combined with DSBPLAY_LOCSOFTWARE.
DSBPLAY_LOCSOFTWARE
Play this voice in a software buffer only. This flag cannot be combined with DSBPLAY_LOCHARDWARE or any voice management flag.
Voice management flags
The voice management flags are valid only for buffers created with the DSBCAPS_LOCDEFER flag, and are used for sounds that are to play in hardware. These flags enable hardware resources that are already in use to be yielded to the current sound. Only buffers created with the DSBCAPS_LOCDEFER flag are candidates for premature termination. See Remarks.
DSBPLAY_TERMINATEBY_TIME
If the hardware has no available voices, a currently playing nonlooping buffer will be stopped to make room for the new buffer. The buffer prematurely terminated is the one with the least time left to play.
DSBPLAY_TERMINATEBY_DISTANCE
If the hardware has no available voices, a currently playing buffer will be stopped to make room for the new buffer. The buffer prematurely terminated will be selected from buffers that have the buffer's DSBCAPS_ MUTE3DATMAXDISTANCE flag set and are beyond their maximum distance. If there are no such buffers, the method fails.
DSBPLAY_TERMINATEBY_PRIORITY
If the hardware has no available voices, a currently playing buffer will be stopped to make room for the new buffer. The buffer prematurely terminated will be the one with the lowest priority as set by the dwPriority parameter passed to IDirectSoundBuffer8::Play for the buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

If IDirectSound8::SetCooperativeLevel has not been called, the method returns DS_OK, but no sound will be produced until a cooperative level has been set.

If the buffer specified in the method is already playing, the call to the method succeeds and the buffer continues to play. However, the flags defined in the most recent call supersede flags defined in previous calls.

When called on the primary buffer, this method causes the buffer to start playing to the sound device. If the application has set the DSSCL_WRITEPRIMARY cooperative level, any audio data put in the primary buffer by the application is sent to the sound device. Under any other cooperative level, the primary buffer plays silence if no secondary buffers are playing. Primary buffers must be played with the DSBPLAY_LOOPING flag set. For more information, see Playing the Primary Buffer Continuously.

If the method is called with a voice allocation or voice management flag set on a buffer that was not created with the DSBCAPS_LOCDEFER flag, the call fails with DSERR_INVALIDPARAM.

DSBPLAY_TERMINATEBY_TIME and DSBPLAY_TERMINATEBY_DISTANCE cannot be combined, but either may be combined with DSBPLAY_TERMINATEBY_PRIORITY, in which case the DSBPLAY_TERMINATEBY_TIME or DSBPLAY_TERMINATEBY_DISTANCE flag is used to determine which buffer should be terminated in the event of a priority tie.

The following table shows the behavior of the method under various combinations of the voice allocation and voice management flags when no free hardware voices are available.

 | DSBPLAY_LOCHARDWARE | Neither DSBPLAY_LOCHARDWARE nor DSBPLAY_LOCSOFTWARE | DSBPLAY_LOCSOFTWARE
DSBPLAY_TERMINATEBY_TIME | Sound with least time left to play is terminated and the new sound plays on the released voice. | Sound with least time left to play is terminated and the new sound plays on the released voice. | New sound plays in software.
DSBPLAY_TERMINATEBY_DISTANCE | If any sounds currently playing in hardware are beyond their maximum distance and have the DSBCAPS_MUTE3DATMAXDISTANCE flag set, one of them is terminated and the new sound plays in hardware. Otherwise, the call fails. | If any sounds currently playing in hardware are beyond their maximum distance and have the DSBCAPS_MUTE3DATMAXDISTANCE flag set, one of them is terminated and the new sound plays in hardware. Otherwise, the new sound plays in software. | New sound plays in software.
DSBPLAY_TERMINATEBY_PRIORITY | If the new sound's priority is higher than or equal to that of any sound currently playing in hardware, one of the lowest-priority sounds is terminated and the new sound plays in hardware. Otherwise, the call fails. | If the new sound's priority is higher than or equal to that of any sound currently playing in hardware, one of the lowest-priority sounds is terminated and the new sound plays in hardware. Otherwise, the new sound plays in software. | New sound plays in software.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8, IDirectSound8::SetCooperativeLevel


IDirectSoundBuffer8::Restore

Restores the memory allocation for a lost sound buffer for the specified DirectSoundBuffer object.

HRESULT Restore();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_BUFFERLOST
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

If the application does not have the input focus, IDirectSoundBuffer8::Restore might not succeed. For example, if the application with the input focus has the DSSCL_WRITEPRIMARY cooperative level, no other application will be able to restore its buffers. Similarly, an application with the DSSCL_WRITEPRIMARY cooperative level must have the input focus to restore its primary sound buffer.

After DirectSound restores the buffer memory, the application must rewrite the buffer with valid sound data. DirectSound cannot restore the contents of the memory, only the memory itself.

The application can receive notification that a buffer is lost when it specifies that buffer in a call to the IDirectSoundBuffer8::Lock or IDirectSoundBuffer8::Play method. These methods return DSERR_BUFFERLOST to indicate a lost buffer. The IDirectSoundBuffer8::GetStatus method can also be used to retrieve the status of the sound buffer and test for the DSBSTATUS_BUFFERLOST flag.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::Lock, IDirectSoundBuffer8::Play, IDirectSoundBuffer8::GetStatus


IDirectSoundBuffer8::SetCurrentPosition

Sets the position of the play cursor, which is the point at which the next byte of data is read from the buffer.

HRESULT SetCurrentPosition(
  DWORD dwNewPosition
);

Parameters

dwNewPosition
Offset of the play cursor, in bytes, from the beginning of the buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

This method cannot be called on primary sound buffers.

If the buffer is playing, the cursor immediately moves to the new position and play continues from that point. If it is not playing, playback will begin from the new position the next time the IDirectSoundBuffer8::Play method is called.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::GetCurrentPosition, IDirectSoundBuffer8::Play


IDirectSoundBuffer8::SetFormat

Sets the format of the primary sound buffer for the application. Whenever this application has the input focus, DirectSound will set the primary buffer to the specified format.

Since primary sound buffers do not support the IDirectSoundBuffer8 interface, this method must be called on IDirectSoundBuffer.

HRESULT SetFormat(
  LPCWAVEFORMATEX pcfxFormat
);

Parameters

pcfxFormat
Address of a WAVEFORMATEX structure that describes the new format for the primary sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_BADFORMAT
DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY
DSERR_PRIOLEVELNEEDED
DSERR_UNSUPPORTED

Remarks

The format of the primary buffer should be set before secondary buffers are created.

The method fails if the application has the DSSCL_NORMAL cooperative level.

If the application is using DirectSound at the DSSCL_WRITEPRIMARY cooperative level, the buffer must be stopped before IDirectSoundBuffer8::SetFormat is called. If the format is not supported, the method fails.

If the cooperative level is DSSCL_PRIORITY or DSSCL_EXCLUSIVE, DirectSound stops the primary buffer, changes the format, and restarts the buffer. The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest supported format. To determine whether this has happened, an application can call the IDirectSoundBuffer8::GetFormat method for the primary buffer and compare the result with the format that was requested with the SetFormat method.

This method is not available for secondary sound buffers. If a new format is required, the application must create a new DirectSoundBuffer object.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8, IDirectSoundBuffer8::GetFormat


IDirectSoundBuffer8::SetFrequency

Sets the frequency at which the audio samples are played.

HRESULT SetFrequency(
  DWORD dwFrequency
);

Parameters

dwFrequency
New frequency, in hertz (Hz), at which to play the audio samples. The value must be in the range DSBFREQUENCY_MIN to DSBFREQUENCY_MAX. These values are currently defined in Dsound.h as 100 and 100,000 respectively.

If the value is DSBFREQUENCY_ORIGINAL, the frequency is reset to the default value in the buffer format. This format is specified in the IDirectSound8::CreateSoundBuffer method.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

Increasing or decreasing the frequency changes the perceived pitch of the audio data. This method does not affect the format of the buffer.

This method is not valid for primary sound buffers.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound8::CreateSoundBuffer, IDirectSoundBuffer8::GetFrequency, IDirectSoundBuffer8::Play, IDirectSoundBuffer8::SetFormat


IDirectSoundBuffer8::SetFX

Enables effects on a buffer. The buffer must not be playing or locked.

For this method to succeed, CoInitialize must have been called. This is done automatically in applications that create DirectSound by using IDirectMusicPerformance8::InitAudio. However, applications that create DirectSound by using DirectSoundCreate8 must also call CoInitialize.

HRESULT SetFX(
  DWORD dwEffectsCount,
  LPDSEFFECTDESC pDSFXDesc,
  LPDWORD pdwResultCodes
);

Parameters

dwEffectsCount
Value that specifies the number of elements in the pDSFXDesc and pdwResultCodes arrays. If this value is 0, pDSFXDesc and pdwResultCodes must both be NULL. Set to 0 to remove all effects from the buffer.
pDSFXDesc
Address of an array of DSEFFECTDESC structures, of size dwEffectsCount, that specifies the effects wanted on the buffer. Must be NULL if dwEffectsCount is 0.
pdwResultCodes
Address of an array of DWORD elements, of size dwEffectsCount. Each element receives one of the following values indicating the result of the attempt to create the corresponding effect in the pDSFXDesc array.
DSFXR_LOCHARDWARE
Effect is instantiated in hardware.
DSFXR_LOCSOFTWARE
Effect is instantiated in software.
DSFXR_UNALLOCATED
Effect has not yet been assigned to hardware nor software. This value is returned if the buffer was created with the DSBCAPS_LOCDEFER flag in DSBUFFERDESC.
DSFXR_FAILED
No effect was created because resources weren't available.
DSFXR_PRESENT
The effect is available but was not created because one of the other effects requested could not be created. If any of the effects requested cannot be created, none of them are, and the call fails.
DSFXR_UNKNOWN
The effect is not registered on the system, and the method failed as a result.

This parameter can be NULL is no result values are wanted, and must be NULL if dwEffectsCount is 0

Return Values

If the method succeeds, the return value is DS_OK or DS_INCOMPLETE.

If the method fails, the return value may be one of the following error values:

CO_E_NOTINITIALIZED
DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_INVALIDCALL
DSERR_NOINTERFACE
DSERR_PRIOLEVELNEEDED

In addition, the method can return an error value from DMO methods, including IMediaObject::SetInputType and IMediaObject::SetOutputType. See the DirectShow documentation for possible error values.

Remarks

If the method fails, the value for each effect in pdwResultCodes is either DSFXF_PRESENT or DSFXR_UNKNOWN. Check these values to determine which effects caused the failure.

For the method to succeed, the buffer must have been created with the DSBCAPS_CTRLFX flag and must not be playing or locked.

If the method returns DSERR_NOINTERFACE or another COM error, check the result code array for DSFXR_PRESENT or DSFXR_UNKNOWN to ascertain which effect caused the error. If the method returns DSERR_INVALIDPARAM, check the result codes for DSFXR_FAILED to see which effects failed to acquire resources.

If the buffer is part of an audiopath, the audiopath must be inactive. See IDirectMusicAudioPath8::Activate.

An effect must be set on a buffer before the effect interface can be obtained. To obtain the effect interface, use IDirectSoundBuffer8::GetObjectInPath.

Requirements

Header: Declared in dsound.h.

See Also

DSBCAPS, IDirectSoundBuffer8::AcquireResources


IDirectSoundBuffer8::SetPan

Sets the relative volume of the left and right channels.

HRESULT SetPan(
  LONG lPan
);

Parameters

lPan
Relative volume between the left and right channels.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The value in lPan is measured in hundredths of a decibel (dB), in the range of DSBPAN_LEFT to DSBPAN_RIGHT. These values are currently defined in Dsound.h as –10,000 and 10,000 respectively. The value DSBPAN_LEFT means the right channel is attenuated by 100 dB. The value DSBPAN_RIGHT means the left channel is attenuated by 100 dB. The neutral value is DSBPAN_CENTER, defined as zero. This value of 0 in the plPan parameter means that both channels are at full volume (they are attenuated by 0 decibels). At any setting other than DSBPAN_CENTER, one of the channels is at full volume and the other is attenuated.

A pan of –2173 means that the left channel is at full volume and the right channel is attenuated by 21.73 dB. Similarly, a pan of 870 means that the left channel is attenuated by 8.7 dB and the right channel is at full volume. A pan of DSBPAN_LEFT means that the right channel is silent and the sound is all the way to the left, while a pan of DSBPAN_RIGHT means that the left channel is silent and the sound is all the way to the right.

The pan control acts cumulatively with the volume control.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::GetPan, IDirectSoundBuffer8::GetVolume, IDirectSoundBuffer8::SetVolume


IDirectSoundBuffer8::SetVolume

Sets the sound volume.

HRESULT SetVolume(
  LONG lVolume
);

Parameters

lVolume
New volume requested for this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_GENERIC
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

The volume is specified in hundredths of decibels (dB). Allowable values are between DSBVOLUME_MAX (no attenuation) and DSBVOLUME_MIN (silence). These values are currently defined in Dsound.h as 0 and –10,000 respectively. The value DSBVOLUME_MAX represents the original, unadjusted volume of the stream. The value DSBVOLUME_MIN indicates an audio volume attenuated by 100 dB, which, for all practical purposes, is silence. Currently DirectSound does not support amplification.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::GetPan, IDirectSoundBuffer8::GetVolume, IDirectSoundBuffer8::SetPan


IDirectSoundBuffer8::Stop

Causes the sound buffer to stop playing.

HRESULT Stop();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

For secondary sound buffers, IDirectSoundBuffer8::Stop sets the play cursor to the sample that follows the last sample played. This means that when the IDirectSoundBuffer8::Play method is next called on the buffer, it will continue playing where it left off.

For primary sound buffers, if an application has the DSSCL_WRITEPRIMARY level, this method will stop the buffer and reset the play cursor to 0 (the beginning of the buffer). This is necessary because the primary buffers on most sound cards can play only from the beginning of the buffer.

However, if IDirectSoundBuffer8::Stop is called on a primary buffer and the application has a cooperative level other than DSSCL_WRITEPRIMARY, this method simply reverses the effects of IDirectSoundBuffer8::Play. It configures the primary buffer to stop if no secondary buffers are playing. If other buffers are playing in this or other applications, the primary buffer will not actually stop until they are stopped. This method is useful because playing the primary buffer consumes processing overhead even if the buffer is playing sound data with the amplitude of 0 decibels.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::Play


IDirectSoundBuffer8::Unlock

Releases a locked sound buffer.

HRESULT Unlock(
  LPVOID pvAudioPtr1,
  DWORD dwAudioBytes1,
  LPVOID pvAudioPtr2,
  DWORD dwAudioBytes2
);

Parameters

pvAudioPtr1
Address of the value retrieved in the ppvAudioPtr1 parameter of the IDirectSoundBuffer8::Lock method.
dwAudioBytes1
Value that specifies the number of bytes written to the portion of the buffer at pvAudioPtr1. See Remarks.
pvAudioPtr2
Address of the value retrieved in the ppvAudioPtr2 parameter of the IDirectSoundBuffer8::Lock method.
dwAudioBytes2
Value that specifies the number of bytes written to the portion of the buffer at pvAudioPtr2. See Remarks.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDCALL
DSERR_INVALIDPARAM
DSERR_PRIOLEVELNEEDED

Remarks

An application must pass both pointers, pvAudioPtr1 and pvAudioPtr2, returned by the IDirectSoundBuffer8::Lock method to ensure the correct pairing of IDirectSoundBuffer8::Lock and IDirectSoundBuffer8::Unlock. The second pointer is needed even if nothing was written to the second pointer.

The values in dwAudioBytes1 and dwAudioBytes2 must specify the number of bytes actually written to each part of the buffer, which might be less than the size of the lock. DirectSound uses these values to determine how much data to commit to the device.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::GetCurrentPosition, IDirectSoundBuffer8::Lock


IDirectSoundCapture8

The methods of the IDirectSoundCapture8 interface are used to create sound capture buffers.

The interface is obtained by using the DirectSoundCaptureCreate8 function or DirectSoundFullDuplexCreate8 function, or , or by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSoundCapture8.

IDirectSoundCapture8 is a define for IDirectSoundCapture. The two interface names are interchangeable. However, objects supporting this interface can have different functionality, depending on their class. For more information, see DirectSoundCaptureCreate8 and IDirectSoundCapture8::CreateCaptureBuffer.

This reference section gives information on the following methods of the IDirectSoundCapture8 interface:

Creation | CreateCaptureBuffer
 | Initialize
Capabilities | GetCaps

Like all COM interfaces, the IDirectSoundCapture8 interface inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUNDCAPTURE type is defined as a pointer to the IDirectSoundCapture interface:

typedef struct IDirectSoundCapture   *LPDIRECTSOUNDCAPTURE;

Requirements

Header: Declared in dsound.h.


IDirectSoundCapture8::CreateCaptureBuffer

Creates a capture buffer.

HRESULT CreateCaptureBuffer(
  LPCDSCBUFFERDESC pcDSCBufferDesc,
  LPDIRECTSOUNDCAPTUREBUFFER * ppDSCBuffer,
  LPUNKNOWN pUnkOuter
);

Parameters

pcDSCBufferDesc
Pointer to a DSCBUFFERDESC structure containing values for the capture buffer being created.
ppDSCBuffer
Address of a variable that receives an IDirectSoundCaptureBuffer interface pointer. Use QueryInterface to obtain IDirectSoundCaptureBuffer8. See Remarks.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_BADFORMAT
DSERR_GENERIC
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Remarks

On Microsoft® Windows® 95, Windows® 98, and Windows® 2000, each capture device supports a single buffer.

The IDirectSoundCaptureBuffer8 interface is supported only on buffers created by an object of class CLSID_DirectSoundCapture8. If the IDirectSoundCapture8 interface was obtained from DirectSoundCaptureCreate8, IDirectSoundCaptureBuffer8 is supported. If IDirectSoundCapture8 was obtained from the earlier DirectSoundCaptureCreate function, only IDirectSoundCaptureBuffer is supported.

Requirements

Header: Declared in dsound.h.


IDirectSoundCapture8::GetCaps

Obtains the capabilities of the capture device.

HRESULT GetCaps(
  LPDSCCAPS pDSCCaps
);

Parameters

pDSCCaps
Pointer to a DSCCAPS structure to be receive information about the capture device. When the method is called, the dwSize member must specify the size of the structure in bytes.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_UNINITIALIZED

Requirements

Header: Declared in dsound.h.


IDirectSoundCapture8::Initialize

When CoCreateInstance is used to create a DirectSoundCapture object, the object must be initialized with the IDirectSoundCapture8::Initialize method. Calling this method is not required when the DirectSoundCaptureCreate function is used to create the object.

HRESULT Initialize(
  LPCGUID pcGuidDevice
);

Parameters

pcGuidDevice
Address of the GUID specifying the sound driver to which the DirectSoundCapture object binds. Use NULL to select the primary sound driver.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY
DSERR_ALREADYINITIALIZED

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureBuffer8

Used to manipulate sound capture buffers.

To obtain the IDirectSoundCaptureBuffer8 interface, call the IDirectSoundCapture8::CreateCaptureBuffer method to obtain IDirectSoundCaptureBuffer, then pass IID_IDirectSoundCaptureBuffer8 to IDirectSoundCaptureBuffer::QueryInterface.

Note IDirectSoundCaptureBuffer8 cannot be obtained if the IDirectSoundCapture8 interface was obtained by using the DirectSoundCaptureCreate function. See DirectSoundCaptureCreate8.

The methods of this interface can be grouped as follows:

Capture management | Lock
 | Start
 | Stop
 | Unlock
Effects | GetFXStatus
 | GetObjectInPath
Initialization | Initialize
Information | GetCaps
 | GetCurrentPosition
 | GetFormat
 | GetStatus

Like all COM interfaces, this interface inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUNDCAPTUREBUFFER8 type is defined as a pointer to the IDirectSoundCaptureBuffer8 interface:

typedef struct IDirectSoundCaptureBuffer8 *LPDIRECTSOUNDCAPTUREBUFFER8;

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureBuffer8::GetCaps

Returns the capabilities of the buffer.

HRESULT GetCaps(
  LPDSCBCAPS pDSCBCaps
);

Parameters

pDSCBCaps
Pointer to a DSCBCAPS structure that receives information about the capture buffer. On input, the dwSize member must specify the size of the structure in bytes.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_UNSUPPORTED
DSERR_OUTOFMEMORY

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureBuffer8::GetCurrentPosition

Retrieves the capture and read cursors in the buffer.

The capture cursor is ahead of the read cursor. The data after the read position up to and including the capture position is not necessarily valid data.

HRESULT GetCurrentPosition(
  LPDWORD pdwCapturePosition,
  LPDWORD pdwReadPosition
);

Parameters

pdwCapturePosition
Address of a variable that receives the offset from the start of the buffer, in bytes, of the capture cursor. The parameter can be NULL if this value is not wanted.
pdwReadPosition
Address of a variable that receives the offset from the start of the buffer, in bytes, of the read cursor.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureBuffer8::GetFormat

Retrieves the format of the capture buffer.

HRESULT GetFormat(
  LPWAVEFORMATEX pwfxFormat,
  DWORD dwSizeAllocated,
  LPDWORD pdwSizeWritten
);

Parameters

pwfxFormat
Address of a WAVEFORMATEX structure that receives a description of the sound data in the capture buffer. To retrieve the buffer size needed to contain the format description, specify NULL.; in this case, the DWORD pointed to by the pdwSizeWritten parameter receives the size of the structure needed to receive complete format information.
dwSizeAllocated
Size, in bytes, of the WAVEFORMATEX structure. DirectSoundCapture writes, at most, dwSizeAllocated bytes to the structure; if the structure requires more memory, it is truncated.
pdwSizeWritten
Address of a variable that receives the number of bytes written to the WAVEFORMATEX structure; or, if pwfxFormat is NULL, the size of the WAVEFORMATEX structure that would be necessary to receive the information. This parameter can be NULL if the value is not wanted.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureBuffer8::GetFXStatus

Retrieves the status of effects for the capture buffer.

HRESULT GetFXStatus(
  DWORD dwFXCount,
  LPDWORD pdwFXStatus
);

Parameters

dwFXCount
Value that specifies the number of elements in the pdwFXStatus array.
pdwFXStatus
Address of an array of DWORD variables that receive the status of each effect. This should contain the same number of elements as the array passed in the lpDSCFXDesc parameter of IDirectSoundCapture8::CreateCaptureBuffer.For each effect, one of the following flags is returned.
DSCFXR_LOCHARDWARE
Effect is instantiated in hardware.
DSCFXR_LOCSOFTWARE
Effect is instantiated in software.
DSCFXR_UNALLOCATED
Effect has not yet been assigned to hardware nor software.
DSCFXR_FAILED
No effect was created because resources weren't available.
DSCFXR_UNKNOWN
No effect was created because the effect isn't registered on the system.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureBuffer8::GetObjectInPath

Retrieves an interface for an effect object associated with the buffer.

HRESULT GetObjectInPath(
  REFGUID rguidObject,
  DWORD dwIndex,
  REFGUID rguidInterface,
  LPVOID * ppObject
);

Parameters

rguidObject
Value of type REFGUID that specifies the unique class identifier of the object being searched for, such as GUID_DSCFX_CLASS_AEC. Set this parameter to GUID_All_Objects to search for objects of any class.
dwIndex
Value that specifies the index of the object within objects of that class in the path. See Remarks.
rguidInterface
Value that specifies the unique identifier of the desired interface, such as IID_IDirectSoundCaptureFXAec8.
ppObject
Address of a variable that receives the desired interface pointer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_CONTROLUNAVAIL
DSERR_INVALIDPARAM
E_NOINTERFACE

Remarks

The value in dwIndex is the index of the object within the array of effects passed to IDirectSoundCapture8::CreateCaptureBuffer. This is not necessarily the actual position of the object in the effects chain, because some effects might not have been created.

An object is returned solely on the basis of whether it matches rguidObject and dwIndex. It is up to the application to ensure that rguidInterface specifies an interface that can be expected to be found on the object.

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureBuffer8::GetStatus

Retrieves the status of the capture buffer.

HRESULT GetStatus(
  LPDWORD pdwStatus
);

Parameters

pdwStatus
Address of a variable that receives the status of the capture buffer. The status can be set to one or more of the following:
DSCBSTATUS_CAPTURING
The buffer is currently capturing audio data.
DSCBSTATUS_LOOPING
The buffer is currently looping.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureBuffer8::Initialize

Initializes a DirectSoundCaptureBuffer object if it has not yet been initialized.

HRESULT Initialize(
  LPDIRECTSOUNDCAPTURE pDirectSoundCapture,
  LPCDSCBUFFERDESC pcDSCBufferDesc
);

Parameters

pDirectSoundCapture
Address of the DirectSoundCapture object associated with this DirectSoundCaptureBuffer object.
pcDSCBufferDesc
Address of a DSCBUFFERDESC structure that contains the values used to initialize this sound buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_ALREADYINITIALIZED

Remarks

Because the IDirectSoundCapture8::CreateCaptureBuffer method calls the IDirectSoundCaptureBuffer8::Initialize method internally, it is not needed for the current release of DirectSound. This method is provided for future extensibility.

Requirements

Header: Declared in dsound.h.

See Also

DSBUFFERDESC, IDirectSoundCapture8::CreateCaptureBuffer


IDirectSoundCaptureBuffer8::Lock

Locks the buffer. Locking the buffer returns pointers into the buffer, allowing the application to read or write audio data into that memory.

HRESULT Lock(
  DWORD dwOffset,
  DWORD dwBytes,
  LPVOID *ppvAudioPtr1,
  LPDWORD pdwAudioBytes1,
  LPVOID *ppvAudioPtr2,
  LPDWORD pdwAudioBytes2,
  DWORD dwFlags
);

Parameters

dwOffset
Value that specifies the offset, in bytes, from the start of the buffer to the point where the lock begins.
dwBytes
Value that specifies the size, in bytes, of the portion of the buffer to lock. Because the buffer is conceptually circular, this number can exceed the number of bytes between dwOffset and the end of the buffer.
ppvAudioPtr1
Address of a variable that receives a pointer to the first locked part of the buffer.
pdwAudioBytes1
Address of a variable that receives the number of bytes in the block at ppvAudioPtr1. If this value is less than dwBytes, the lock has wrapped and ppvAudioPtr2 points to a second block of data at the beginning of the buffer.
ppvAudioPtr2
Address of a variable that receives a pointer to the second locked part of the capture buffer. If NULL is returned, the ppvAudioPtr1 parameter points to the entire locked portion of the capture buffer.
pdwAudioBytes2
Address of a variable that receives the number of bytes in the block at ppvAudioPtr2. If ppvAudioPtr2 is NULL, this value is zero.
dwFlags
Flags modifying the lock event. This value can be zero or the following flag:
DSCBLOCK_ENTIREBUFFER
Ignore dwReadBytes and lock the entire capture buffer.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Remarks

This method accepts an offset and a byte count, and returns two read pointers and their associated sizes. If the locked portion does not extend to the end of the buffer and wrap to the beginning, the second pointer, ppvAudioBytes2, receives NULL. If the lock does wrap, ppvAudioBytes2 points to the beginning of the buffer.

If the application passes NULL for the ppvAudioPtr2 and pdwAudioBytes2 parameters, the lock extends no further than the end of the buffer and does not wrap.

The application should read data from the pointers returned by this method and then immediately call IDirectSoundCaptureBuffer8::Unlock. The sound buffer should not remain locked while it is running; if it does, the capture cursor will reach the locked bytes and audio problems may result.

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureBuffer8::Start

Begins capturing data into the buffer. If the buffer is already capturing, the method has no effect.

HRESULT Start(
  DWORD dwFlags
);

Parameters

dwFlags
Flags that specify the behavior of the buffer when capturing sound data. The following flag is defined:
DSCBSTART_LOOPING
After the end of the buffer is reached, capture restarts at the beginning and continues until explicitly stopped.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureBuffer8::Stop

Stops the buffer so that it is no longer capturing data. If the buffer is not capturing, the method has no effect.

HRESULT Stop();

Parameters

None.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_NODRIVER
DSERR_OUTOFMEMORY

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureBuffer8::Unlock

Unlocks the buffer.

HRESULT Unlock(
  LPVOID pvAudioPtr1,
  DWORD dwAudioBytes1,
  LPVOID pvAudioPtr2,
  DWORD dwAudioBytes2
);

Parameters

pvAudioPtr1
Address of the value retrieved in the ppvAudioPtr1 parameter of the IDirectSoundCaptureBuffer8::Lock method.
dwAudioBytes1
Number of bytes read from the pvAudioPtr1 parameter. See Remarks.
pvAudioPtr2
Address of the value retrieved in the ppvAudioPtr2 parameter of the IDirectSoundCaptureBuffer8::Lock method.
dwAudioBytes2
Number of bytes read from the pvAudioPtr2 parameter. See Remarks.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following values:

DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Remarks

An application must pass both pointers, pvAudioPtr1 and pvAudioPtr2, returned by the IDirectSoundCaptureBuffer8::Lock method to ensure the correct pairing of IDirectSoundCaptureBuffer8::Lock and IDirectSoundCaptureBuffer8::Unlock. The second pointer is needed even if zero bytes were written to the second pointer.

The values in dwAudioBytes1 and dwAudioBytes2 must specify the number of bytes actually read from each part of the buffer, which might be less than the size of the lock. DirectSound uses these values to determine how much data to transfer from the device.

Make sure that the capture buffer does not remain locked for long periods of time.

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureFXAec8

Not implemented on current operating systems.

Used to set and retrieve parameters on a capture buffer that supports acoustic echo cancellation.

IDirectSoundCaptureFXAec8 is a define for IDirectSoundCaptureFXAec. The interface names are interchangeable.

This interface is obtained by calling IDirectSoundCaptureBuffer8::GetObjectInPath on the buffer that supports the effect.

The IDirectSoundCaptureFXAec8 interface has the following methods.

Parameters | GetAllParameters
 | SetAllParameters

Like all COM interfaces, the IDirectSoundCaptureFXAec8 interface inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUNDCAPTUREFXAEC8 type is defined as a pointer to the IDirectSoundCaptureFXAec8 interface:

typedef struct IDirectSoundCaptureFXAec8 *LPDIRECTSOUNDCAPTUREFXAEC8;

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureFXAec8::GetAllParameters

Not implemented on current operating systems.

Retrieves the acoustic echo cancellation parameters of a buffer.

HRESULT GetAllParameters(
  LPDSCFXAec pDscFxAec
);

Parameters

pDscFxAec
Address of a DSCFXAec structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureFXAec8::SetAllParameters

Not implemented on current operating systems.

Sets the acoustic echo cancellation parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSCFXAec  pcDscFxAec
);

Parameters

pcDscFxAec
Address of a DSCFXAec structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureFXNoiseSuppress8

Not implemented on current operating systems.

Used to set and retrieve parameters on a capture buffer that supports noise suppression.

IDirectSoundCaptureFXNoiseSuppress8 is a define for IDirectSoundCaptureFXNoiseSuppress. The interface names are interchangeable.

This interface is obtained by calling IDirectSoundCaptureBuffer8::GetObjectInPath on the buffer that supports the effect.

The IDirectSoundCaptureFXNoiseSuppress8 interface has the following methods.

Parameters | GetAllParameters
 | SetAllParameters

Like all COM interfaces, the IDirectSoundNoiseSuppress8 interface inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUNDNOISESUPPRESS8 type is defined as a pointer to the IDirectSoundNoiseSuppress8 interface:

typedef struct IDirectSoundCaptureFXNoiseSuppress8  *LPDIRECTSOUNDCAPTUREFXNOISESUPPRESS8;

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureFXNoiseSuppress8::GetAllParameters

Not implemented on current operating systems.

Retrieves the noise suppression parameters of a buffer.

HRESULT GetAllParameters(
  LPDSCFXNoiseSuppress pDsFxNoiseSuppress
);

Parameters

pDscFxNoiseSuppress
Address of a DSCFXNoiseSuppress structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundCaptureFXNoiseSuppress8::SetAllParameters

Not implemented on current operating systems.

Sets the noise suppression parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSCFXNoiseSuppression  pcDscFxNoiseSuppress
);

Parameters

pcDscFxNoiseSuppress
Address of a DSCFXNoiseSuppress structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundFullDuplex8

Not implemented on current operating systems.

Represents a full-duplex stream.

The interface is obtained by using the DirectSoundFullDuplexCreate8 function. This function initializes DirectSound capture and playback.

The interface can also be obtained by using CoCreateInstance or CoCreateInstanceEx to create an object of class CLSID_DirectSoundFullDuplex8.

IDirectSoundFullDuplex8 is a define for IDirectSoundFullDuplex. The interface names are interchangeable.

This interface has the following method:

Initialization Initialize

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dsound.h.

The LPDIRECTSOUNDFULLDUPLEX type is defined as a pointer to IDirectSoundFullDuplex.

typedef struct IDirectSoundFullDuplex *LPDIRECTSOUNDFULLDUPLEX;


IDirectSoundFullDuplex8::Initialize

Initializes a full duplex object that was created by using CoCreateInstance.

HRESULT Initialize(
  LPCGUID  pCaptureGuid,
  LPCGUID  pRenderGuid,
  LPCDSCBUFFERDESC  lpDscBufferDesc,
  LPCDSBUFFERDESC  lpDsBufferDesc,
  HWND  hWnd,
  DWORD  dwLevel,
  LPLPDIRECTSOUNDCAPTUREBUFFER8  lplpDirectSoundCaptureBuffer8,
  LPLPDIRECTSOUNDBUFFER8  lplpDirectSoundBuffer8
);

Parameters

pCaptureGuid
Address of the GUID that identifies the sound capture device for full duplex input. Must be one of the GUIDs returned by DirectSoundCaptureEnumerate, NULL for the default capture device, or one of the following values:
DSDEVID_DefaultCapture
System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture
Default voice capture device.
pRenderGuid
Address of the GUID that identifies the sound render device for full-duplex output. Must be one of the GUIDs returned by DirectSoundEnumerate, NULL for the default render device, or one of the following values:
DSDEVID_DefaultPlayback
System-wide default audio playback device.
DSDEVID_DefaultVoicePlayback
Default voice playback device.
lpDscBufferDesc
Address of a DSCBUFFERDESC structure that specifies the characteristics of the capture buffer.
lpDsBufferDesc
Address of a DSBUFFERDESC structure that specifies the characteristics of the render buffer.
hWnd
Handle to the application window.
dwLevel
Cooperative level for the DirectSound object. For more information, see IDirectSound8::SetCooperativeLevel.
lplpDirectSoundCaptureBuffer8
Address of a variable that receives the IDirectSoundCaptureBuffer8 interface of the capture buffer.
lplpDirectSoundBuffer8
Address of a variable that receives the IDirectSoundBuffer8 interface of the render buffer.

Requirements

Header: Declared in dsound.h.


IDirectSoundFXChorus8

Used to set and retrieve effect parameters on a buffer that supports chorus.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

The IDirectSoundFXChorus8 interface has the following methods.

Parameters | GetAllParameters
 | SetAllParameters

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFX


IDirectSoundFXChorus8::GetAllParameters

Retrieves the chorus parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXChorus pDsFxChorus
);

Parameters

pDsFxChorus
Address of a DSFXChorus structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundFXChorus8::SetAllParameters

Sets the chorus parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXChorus  pcDsFxChorus
);

Parameters

pcDsFxChorus
Address of a DSFXChorus structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

Effect Parameters


IDirectSoundFXCompressor8

Used to set and retrieve effect parameters on a buffer that supports compression.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

The IDirectSoundFXCompressor8 interface has the following methods.

Parameters | GetAllParameters
 | SetAllParameters

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFX, Compression


IDirectSoundFXCompressor8::GetAllParameters

Retrieves the compression parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXCompressor pDsFxCompressor
);

Parameters

pDsFxCompressor
Address of a DSFXCompressor structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundFXCompressor8::SetAllParameters

Sets the compression parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXCompressor pcDsFxCompressor
);

Parameters

pcDsFxCompressor
Address of a DSFXCompressor structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

Effect Parameters


IDirectSoundFXDistortion8

Used to set and retrieve effect parameters on a buffer that supports distortion.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

The IDirectSoundFXDistortion8 interface has the following methods.

Parameters | GetAllParameters
 | SetAllParameters

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFX


IDirectSoundFXDistortion8::GetAllParameters

Retrieves the distortion parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXDistortion  pDsFxDistortion
);

Parameters

pDsFxDistortion
Address of a DSFXDistortion structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundFXDistortion8::SetAllParameters

Sets the distortion parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXDistortion  pcDsFxDistortion
);

Parameters

pcDsFxDistortion
Address of a DSFXDistortion structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

Effect Parameters


IDirectSoundFXEcho8

Used to set and retrieve effect parameters on a buffer that supports echo.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

The IDirectSoundFXEcho8 interface has the following methods.

Parameters | GetAllParameters
 | SetAllParameters

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFX


IDirectSoundFXEcho8::GetAllParameters

Retrieves the echo parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXEcho pDsFxEcho
);

Parameters

pDsFxEcho
Address of a DSFXEcho structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundFXEcho8::SetAllParameters

Sets the echo parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXEcho  pcDsFxEcho
);

Parameters

pcDsFxEcho
Address of a DSFXEcho structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

Effect Parameters


IDirectSoundFXFlanger8

Used to set and retrieve effect parameters on a buffer that supports flange.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

The IDirectSoundFXFlanger8 interface has the following methods.

Parameters | GetAllParameters
 | SetAllParameters

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFX


IDirectSoundFXFlanger8::GetAllParameters

Retrieves the flange parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXFlanger  pDsFxFlanger
);

Parameters

pDsFxFlanger
Address of a DSFXFlanger structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundFXFlanger8::SetAllParameters

Sets the flange parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXFlanger pcDsFxFlanger
);

Parameters

pcDsFxFlanger
Address of a DSFXFlanger structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

Effect Parameters


IDirectSoundFXGargle8

Used to set and retrieve effect parameters on a buffer that supports amplitude modulation.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

The IDirectSoundFXGargle8 interface has the following methods.

Parameters | GetAllParameters
 | SetAllParameters

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFX


IDirectSoundFXGargle8::GetAllParameters

Retrieves the amplitude modulation parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXGargle  pDsFxGargle
);

Parameters

pDsFxGargle
Address of a DSFXGargle structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value can be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundFXGargle8::SetAllParameters

Sets the amplitude modulation parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXGargle  pcDsFxGargle
);

Parameters

pcDsFxGargle
Address of a DSFXGargle structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value can be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

Effect Parameters


IDirectSoundFXI3DL2Reverb8

Used to set and retrieve effect parameters on a buffer that supports I3DL2 (Interactive 3D Audio Level 2) reverberation effects.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

The IDirectSoundFXI3DL2Reverb8 interface has the following methods.

Parameters | GetAllParameters
 | GetQuality
 | SetAllParameters
 | SetQuality
Presets | GetPreset
 | SetPreset

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFX


IDirectSoundFXI3DL2Reverb8::GetAllParameters

Retrieves the I3DL2 environmental reverberation parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXI3DL2Reverb pDsFxI3DL2Reverb
);

Parameters

pDsFxI3DL2Reverb
Address of a DSFXI3DL2Reverb structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundFXI3DL2Reverb8::GetPreset

Retrieves an identifier for standard reverberation parameters of a buffer.

HRESULT GetPreset(
  LPDWORD  pdwPreset
);

Parameters

pdwPreset

Address of a DWORD that receives one of the preset identifiers. For a list of defined values, see IDirectSoundFXI3DL2Reverb8::SetPreset.Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_INVALIDCALL

Requirements

Header: Declared in dsound.h.


IDirectSoundFXI3DL2Reverb8::GetQuality

Retrieves the quality of the environmental reverberation effect.

HRESULT GetQuality(
  LONG * plQuality
);

Parameters

plQuality
Address of a LONG variable to receive the quality of the effect.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundFXI3DL2Reverb8::SetQuality


IDirectSoundFXI3DL2Reverb8::SetAllParameters

Sets the I3DL2 environmental reverberation parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXI3DL2Reverb  pcDsFxI3DL2Reverb
);

Parameters

pcDsFxI3DL2Reverb
Address of a DSFXI3DL2Reverb structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

Effect Parameters


IDirectSoundFXI3DL2Reverb8::SetPreset

Specifies standard reverberation parameters of a buffer.

HRESULT SetPreset(
  DWORD  dwPreset
);

Parameters

dwPreset
Value that specifies a preset. The following constants are enumerated. See Dsound.h for the default values associated with each preset.
DSFX_I3DL2_ENVIRONMENT_PRESET_DEFAULT
DSFX_I3DL2_ENVIRONMENT_PRESET_GENERIC
DSFX_I3DL2_ENVIRONMENT_PRESET_PADDEDCELL
DSFX_I3DL2_ENVIRONMENT_PRESET_ROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_BATHROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_LIVINGROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_STONEROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_AUDITORIUM
DSFX_I3DL2_ENVIRONMENT_PRESET_CONCERTHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_CAVE
DSFX_I3DL2_ENVIRONMENT_PRESET_ARENA
DSFX_I3DL2_ENVIRONMENT_PRESET_HANGAR
DSFX_I3DL2_ENVIRONMENT_PRESET_CARPETEDHALLWAY
DSFX_I3DL2_ENVIRONMENT_PRESET_HALLWAY
DSFX_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR
DSFX_I3DL2_ENVIRONMENT_PRESET_ALLEY
DSFX_I3DL2_ENVIRONMENT_PRESET_FOREST
DSFX_I3DL2_ENVIRONMENT_PRESET_CITY
DSFX_I3DL2_ENVIRONMENT_PRESET_MOUNTAINS
DSFX_I3DL2_ENVIRONMENT_PRESET_QUARRY
DSFX_I3DL2_ENVIRONMENT_PRESET_PLAIN
DSFX_I3DL2_ENVIRONMENT_PRESET_PARKINGLOT
DSFX_I3DL2_ENVIRONMENT_PRESET_SEWERPIPE
DSFX_I3DL2_ENVIRONMENT_PRESET_UNDERWATER
DSFX_I3DL2_ENVIRONMENT_PRESET_SMALLROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEROOM
DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEHALL
DSFX_I3DL2_ENVIRONMENT_PRESET_PLATE

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

Effect Parameters


IDirectSoundFXI3DL2Reverb8::SetQuality

Sets the quality of the environmental reverberation effect. Higher values produce better quality at the expense of processing time.

HRESULT SetQuality(
  LONG lQuality
);

Parameters

lQuality
Value that specifies the quality of the effect, in the range from DSFX_I3DL2REVERB_QUALITY_MIN to DSFX_I3DL2REVERB_QUALITY_MAX. The default value is 2.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundFXI3DL2Reverb8::GetQuality

See Also

Effect Parameters


IDirectSoundFXParamEq8

Used to set and retrieve effect parameters on a buffer that supports parametric equalizer effects.

The IDirectSoundFXParamEq8 interface has the following methods.

Parameters | GetAllParameters
 | SetAllParameters

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFX


IDirectSoundFXParamEq8::GetAllParameters

Retrieves the parametric equalizer parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXParamEq pDsFxParamEq
);

Parameters

pDsFxParamEq
Address of a DSFXParamEq structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundFXParamEq8::SetAllParameters

Sets the parametric equalizer parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXParamEq  pcDsFxParamEq
);

Parameters

pcDsFxParamEq
Address of a DSFXParamEq structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

Effect Parameters


IDirectSoundFXWavesReverb8

Used to set and retrieve effect parameters on a buffer that supports music reverberation.

This interface is obtained by calling IDirectSoundBuffer8::GetObjectInPath on the buffer that supports the effect.

The IDirectSoundFXWavesReverb8 interface has the following methods.

Parameters | GetAllParameters
 | SetAllParameters

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods.

IUnknown | AddRef
 | QueryInterface
 | Release

Remarks

The Waves reverberation DMO is based on the Waves MaxxVerb technology, which is licenced to Microsoft.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundBuffer8::SetFX


IDirectSoundFXWavesReverb8::GetAllParameters

Retrieves the music reverberation parameters of a buffer.

HRESULT GetAllParameters(
  LPDSFXWavesReverb  pDsFXWavesReverb
);

Parameters

pDsFXWavesReverb
Address of a DSFXWavesReverb structure that receives the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.


IDirectSoundFXWavesReverb8::SetAllParameters

Sets the music reverberation parameters of a buffer.

HRESULT SetAllParameters(
  LPCDSFXWavesReverb  pcDsFXWavesReverb
);

Parameters

pcDsFXWavesReverb
Address of a DSFXWavesReverb structure that specifies the effect parameters.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.

See Also

Effect Parameters


IDirectSoundNotify8

Sets up notification events for a playback or capture buffer.

IDirectSoundNotify8 is a define for IDirectSoundNotify. The two interface names are interchangeable.

The interface is obtained by calling the QueryInterface method of an existing interface on a DirectSoundBuffer object. For an example, see Play Buffer Notification.

The interface has the following method:

SetNotificationPositions

Like all COM interfaces, the IDirectSoundNotify8 interface inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTSOUNDNOTIFY type is defined as a pointer to the IDirectSoundNotify interface:

typedef struct IDirectSoundNotify    *LPDIRECTSOUNDNOTIFY;

Requirements

Header: Declared in dsound.h.


IDirectSoundNotify8::SetNotificationPositions

Sets the notification positions. During capture or playback, whenever the read or play cursor reaches an offset specified in one of the DSBPOSITIONNOTIFY structures in the caller-supplied array, the associated event is signaled.

HRESULT SetNotificationPositions(
  DWORD dwPositionNotifies,
  LPCDSBPOSITIONNOTIFY pcPositionNotifies
);

Parameters

dwPositionNotifies
Number of DSBPOSITIONNOTIFY structures.
pcPositionNotifies
Pointer to an array of DSBPOSITIONNOTIFY structures.

Return Values

If the method succeeds, the return value is DS_OK.

If the method fails, the return value may be one of the following error values:

DSERR_INVALIDPARAM
DSERR_OUTOFMEMORY

Remarks

The value DSBPN_OFFSETSTOP can be specified in the dwOffset member to tell DirectSound to signal the associated event when the IDirectSoundBuffer8::Stop or IDirectSoundCaptureBuffer8::Stop method is called or when the end of the buffer has been reached and the playback is not looping. If it is used, this should be the last item in the position-notify array.

If a position-notify array has already been set, the method replaces the previous array.

The buffer must be stopped when this method is called.

Requirements

Header: Declared in dsound.h.


IKsPropertySet

Allows drivers to provide extended capabilities that can be used without API extensions. DirectSound supports this interface for accessing properties of sound drivers.

The IKsPropertySet interface is part of the WDM KS (Win32® driver model kernel streaming) architecture.

To retrieve this interface, call the QueryInterface method of any interface on a DirectSound buffer.

The IKsPropertySet interface has the following methods:

IKsPropertySet | Get
 | QuerySupport
 | Set

All COM interfaces inherit the IUnknown interface methods. This interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

Requirements

Header: Declared in dsound.h.


IKsPropertySet::Get

Retrieves data for an item in a property set.

HRESULT Get(
  REFGUID rguidPropSet,
  ULONG ulId,
  LPVOID pInstanceData,
  ULONG ulInstanceLength,
  LPVOID pPropertyData,
  ULONG ulDataLength,
  PULONG pulBytesReturned
);

Parameters

rguidPropSet
Reference to (C++) or address of (C) a GUID representing the property set to be accessed.
ulId
Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set GUID.
pInstanceData
Instance data for the get call.
ulInstanceLength
Number of bytes pointed to by pInstanceData.
pPropertyData
Data to set for this item.
ulDataLength
Number of bytes pointed to by pPropertyData
pulBytesReturned
Address of a variable that receives the number of bytes written into pPropertyData.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK.

If it fails, the method may return one E_POINTER.

Remarks

The format of the data in both pInstanceData and pPropertyData is item-specific.

Requirements

Header: Declared in dsound.h.


IKsPropertySet::QuerySupport

Determines whether a property in a property set is supported on the port or device.

HRESULT QuerySupport(
  REFGUID rguidPropSet,
  ULONG ulId,
  PULONG pulTypeSupport
);

Parameters

rguidPropSet
Reference to (C++) or address of (C) a GUID representing the property set to be queried.
ulId
Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set.
pulTypeSupport
Address of a variable that receives information about support for the property. This variable can receive one or both of the following flags. See Remarks:
KSPROPERTY_SUPPORT_GET
The property item may be retrieved.
KSPROPERTY_SUPPORT_SET
The property item may be set.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK. (See Remarks.)

If it fails, the method may return one of the following error values:

E_NOTIMPL (See Remarks.)
E_POINTER

Remarks

Whether it is valid to support some properties within the set but not others depends on the definition of the property set. Consult the hardware manufacturer's specification for the property set of interest.

Some implementations may return S_OK when the property is not supported, and others may return E_NOTIMPL. To be sure that a property is supported, check both the return value of the method and the value returned in pulTypeSupport. If S_OK is returned but pulTypeSupport does not contain a valid flag, the property is not supported.

Requirements

Header: Declared in dsound.h.


IKsPropertySet::Set

Sets the value of a property in a property set.

HRESULT Set(
  REFGUID rguidPropSet,
  ULONG ulId,
  LPVOID pInstanceData,
  ULONG ulInstanceLength,
  LPVOID pPropertyData,
  ULONG ulDataLength
);

Parameters

rguidPropSet
Reference to (C++) or address of (C) a GUID representing the property set to be accessed.
ulId
Item within the property set to be accessed. Items are indexed from 0 and are always the same for a given property set.
pInstanceData
Instance data for the set call. If there are multiple objects within the port that this operation could act on, the instance data specifies which object should be used. No standard property set items at the DirectMusic® API level use instance data; however, vendor-defined extensions are free to use it.
ulInstanceLength
Number of bytes pointed to by pInstanceData.
pPropertyData
Property data to set for this item.
ulDataLength
Number of bytes pointed to by pPropertyData.

Return Values

Return values are determined by the designer of the property set.

If the method succeeds, the return value may be S_OK.

If it fails, the method may return E_POINTER.

Remarks

The format of the data in both pInstanceData and pPropertyData is item-specific.

Requirements

Header: Declared in dsound.h.


DirectSound Callback Function

This section contains reference information for the following DirectSound callback function.

  • DSEnumCallback


DSEnumCallback

Application-defined callback function that enumerates the DirectSound drivers. The system calls this function in response to the application's previous call to the DirectSoundEnumerate or DirectSoundCaptureEnumerate function.

BOOL CALLBACK DSEnumCallback(
  LPGUID lpGuid,
  LPCSTR lpcstrDescription,
  LPCSTR lpcstrModule,
  LPVOID lpContext
);

Parameters

lpGuid
Address of the GUID that identifies the DirectSound driver being enumerated. This value can be passed to the DirectSoundCreate8 function to create a DirectSound object for that driver.
lpcstrDescription
Address of a null-terminated string that provides a textual description of the DirectSound device.
lpcstrModule
Address of a null-terminated string that specifies the module name of the DirectSound driver corresponding to this device.
lpContext
Address of application-defined data. This is the pointer passed to DirectSoundEnumerate or DirectSoundCaptureEnumerate as the lpContext parameter.

Return Values

Returns TRUE to continue enumerating drivers, or FALSE to stop.

Remarks

The application can save the strings passed in the lpcstrDescription and lpcstrModule parameters by copying them to memory allocated from the heap. The memory used to pass the strings to this callback function is valid only while this callback function is running.

Requirements

Header: Declared in dsound.h.

See Also

DirectSoundEnumerate


DirectSound Functions

This section contains reference information for the following DirectSound and DirectSoundCapture global functions:

  • DirectSoundCaptureCreate8
  • DirectSoundFullDuplexCreate8
  • DirectSoundCaptureEnumerate
  • DirectSoundCreate8
  • DirectSoundEnumerate
  • GetDeviceID


DirectSoundCaptureCreate8

Creates and initializes an object that supports the IDirectSoundCapture8 interface.

This function creates an object that supports capture effects. Although the older DirectSoundCaptureCreate function can also be used to obtain the IDirectSoundCapture8 interface, the object created by that function cannot be used to create capture buffers that support the IDirectSoundCaptureBuffer8 interface.

HRESULT WINAPI DirectSoundCaptureCreate8(
  LPCGUID lpcGUID,
  LPDIRECTSOUNDCAPTURE8 *lplpDSC,
  LPUNKNOWN pUnkOuter
);

Parameters

lpcGUID
Address of the GUID that identifies the sound capture device. The value of this parameter must be one of the GUIDs returned by DirectSoundCaptureEnumerate, NULL for the default device, or one of the following values:
DSDEVID_DefaultCapture
System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture
Default voice capture device.
lplpDSC
Address of a variable to receive an IDirectSoundCapture8 interface pointer.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be one of the following error values:

DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_OUTOFMEMORY

Remarks

On sound cards that do not support full duplex, this method will fail and return DSERR_ALLOCATED.

Requirements

Header: Declared in dsound.h.
Import Library: Use dsound.lib.


DirectSoundCaptureEnumerate

Enumerates the DirectSoundCapture objects installed in the system.

HRESULT WINAPI DirectSoundCaptureEnumerate(
  LPDSENUMCALLBACK lpDSEnumCallback,
  LPVOID lpContext
);

Parameters

lpDSEnumCallback
Address of the DSEnumCallback function that will be called for each DirectSoundCapture object installed in the system.
lpContext
Address of the user-defined context passed to the enumeration callback function every time that function is called.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.
Import Library: Use dsound.lib.


DirectSoundCreate8

Creates and initializes an object that supports the IDirectSound8 interface.

HRESULT WINAPI DirectSoundCreate8(
  LPCGUID lpcGuidDevice,
  LPDIRECTSOUND8 * ppDS8,
  LPUNKNOWN  pUnkOuter
);

Parameters

lpcGuidDevice
Address of the GUID that identifies the sound device. The value of this parameter must be one of the GUIDs returned by DirectSoundEnumerate, NULL for the default device, or one of the following values:
DSDEVID_DefaultPlayback
System-wide default audio playback device. Equivalent to NULL.
DSDEVID_DefaultVoicePlayback
Default voice playback device.
ppDS8
Address of a variable to receive an IDirectSound8 interface pointer.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be one of the following error values:

DSERR_ALLOCATED
DSERR_INVALIDPARAM
DSERR_NOAGGREGATION
DSERR_NODRIVER
DSERR_OUTOFMEMORY

Remarks

The application must call the IDirectSound8::SetCooperativeLevel method immediately after creating a DirectSound object.

Requirements

Header: Declared in dsound.h.
Import Library: Use dsound.lib.

See Also

IDirectSound8::GetCaps, IDirectSound8::SetCooperativeLevel


DirectSoundEnumerate

Enumerates the DirectSound drivers installed in the system.

HRESULT WINAPI DirectSoundEnumerate(
  LPDSENUMCALLBACK lpDSEnumCallback,
  LPVOID lpContext
);

Parameters

lpDSEnumCallback
Address of the DSEnumCallback function that will be called for each DirectSound object installed in the system.
lpContext
Address of the user-defined context passed to the enumeration callback function every time that function is called.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be DSERR_INVALIDPARAM.

Requirements

Header: Declared in dsound.h.
Import Library: Use dsound.lib.


DirectSoundFullDuplexCreate8

Creates the DirectSound and DirectSoundCapture objects and returns the IDirectSoundFullDuplex8 interface.

The IDirectSoundFullDuplex8 object is not supported on current operating systems. However, this function can be used for convenience to set up the other objects necessary for full-duplex operations.

HRESULT WINAPI DirectSoundFullDuplexCreate8(
  LPCGUID pcGuidCaptureDevice,
  LPCGUID pcGuidRenderDevice,
  LPCDSCBUFFERDESC pcDSCBufferDesc,
  LPCDSBUFFERDESC pcDSBufferDesc,
  HWND hWnd,
  DWORD dwLevel,
  LPDIRECTSOUNDFULLDUPLEX* ppDSFD,
  LPDIRECTSOUNDCAPTUREBUFFER8 *ppDSCBuffer8,
  LPDIRECTSOUNDBUFFER8 *ppDSBuffer8,
  LPUNKNOWN pUnkOuter
);

Parameters

pcGuidCaptureDevice
Address of the GUID that identifies the sound capture device for full duplex input. Must be one of the GUIDs returned by DirectSoundCaptureEnumerate, NULL for the default capture device, or one of the following values:
DSDEVID_DefaultCapture
System-wide default audio capture device.
DSDEVID_DefaultVoiceCapture
Default voice capture device.
pcGuidRenderDevice
Address of the GUID that identifies the sound render device for full-duplex output. Must be one of the GUIDs returned by DirectSoundEnumerate, or NULL for the default render device, or one of the following values:
DSDEVID_DefaultPlayback
System-wide default audio playback device.
DSDEVID_DefaultVoicePlayback
Default voice playback device.
pcDSCBufferDesc
Address of a DSCBUFFERDESC structure that specifies the characteristics of the capture buffer.
pcDSBufferDesc
Address of a DSBUFFERDESC structure that specifies the characteristics of the render buffer.
hWnd
Handle to the application window.
dwLevel
Cooperative level for the DirectSound object. For more information, see IDirectSound8::SetCooperativeLevel.
ppDSFD
Address of a variable that receives the IDirectSoundFullDuplex8 interface pointer.
ppDSCBuffer8
Address of a variable that receives the IDirectSoundCaptureBuffer8 interface of the capture buffer.
ppDSBuffer8
Address of a variable that receives the IDirectSoundBuffer8 interface of the render buffer.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL, because aggregation is not supported.

Requirements

Header: Declared in dsound.h.
Import Library: Use dsound.lib.


GetDeviceID

Retrieves the unique device identifier of the default playback and capture devices selected by the user under Sounds and Multimedia in Control Panel.

HRESULT GetDeviceID(
  LPCGUID pGuidSrc,
  LPGUID pGuidDest
);

Parameters

pGuidSrc
Address of a variable of type GUID that specifies a valid device identifier, or the address of one of the following predefined variables.
DSDEVID_DefaultPlayback
System-wide default audio playback device.
DSDEVID_DefaultCapture
System-wide default audio capture device.
DSDEVID_DefaultVoicePlayback
Default voice playback device.
DSDEVID_DefaultVoiceCapture
Default voice capture device.
pGuidDest
Address of a variable of type GUID that receives the unique identifier of the device.

Return Values

If the function succeeds, the return value is DS_OK.

If the function fails, the return value may be DSERR_INVALIDPARAM.

Remarks

If pGuidSrc points to a valid device identifier, the same value is returned in pGuidDest. If pGuidSrc is one of the listed constants, pGuidDest returns the address of the corresponding device GUID.

Requirements

Header: Declared in dsound.h.
Import Library: Use dsound.lib.


DirectSound Structures

This section contains reference information for the following structures used with DirectSound:

  • DS3DBUFFER
  • DS3DLISTENER
  • DSBCAPS
  • DSBPOSITIONNOTIFY
  • DSBUFFERDESC
  • DSCAPS
  • DSCBCAPS
  • DSCBUFFERDESC
  • DSCCAPS
  • DSCEFFECTDESC
  • DSCFXAec
  • DSCFXNoiseSuppress
  • DSEFFECTDESC
  • DSFXI3DL2Reverb
  • DSFXChorus
  • DSFXCompressor
  • DSFXDistortion
  • DSFXEcho
  • DSFXFlanger
  • DSFXGargle
  • DSFXParamEq
  • DSFXWavesReverb
  • WAVEFORMATEX
  • WAVEFORMATEXTENSIBLE

Note The memory for all DirectX structures must be initialized to zero before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use. The following example performs these tasks on a common structure, DSCAPS:

DSCAPS dscaps; // Can't use this yet.

ZeroMemory(&dscaps, sizeof(dscaps));
dscaps.dwSize = sizeof(dscaps);

// Now the structure can be used.
.
.
.


DS3DBUFFER

Contains all information necessary to uniquely describe the location, orientation, and motion of a 3-D sound buffer. This structure is used with the IDirectSound3DBuffer8::GetAllParameters and IDirectSound3DBuffer8::SetAllParameters methods.

typedef struct {
    DWORD      dwSize;
    D3DVECTOR  vPosition;
    D3DVECTOR  vVelocity;
    DWORD      dwInsideConeAngle;
    DWORD      dwOutsideConeAngle;
    D3DVECTOR  vConeOrientation;
    LONG       lConeOutsideVolume;
    D3DVALUE   flMinDistance;
    D3DVALUE   flMaxDistance;
    DWORD      dwMode;
} DS3DBUFFER, *LPDS3DBUFFER;

typedef const DS3DBUFFER *LPCDS3DBUFFER;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
vPosition
A D3DVECTOR structure that describes the current position of the 3-D sound buffer.
vVelocity
A D3DVECTOR structure that describes the current velocity of the 3-D sound buffer.
dwInsideConeAngle
The angle of the inside sound projection cone.
dwOutsideConeAngle
The angle of the outside sound projection cone.
vConeOrientation
A D3DVECTOR structure that describes the current orientation of this 3-D buffer's sound projection cone.
lConeOutsideVolume
The cone outside volume.
flMinDistance
The minimum distance.
flMaxDistance
The maximum distance.
dwMode
The 3-D sound processing mode to be set.
DS3DMODE_DISABLE
3-D sound processing is disabled. The sound will appear to originate from the center of the listener's head.
DS3DMODE_HEADRELATIVE
Sound parameters (position, velocity, and orientation) are relative to the listener's parameters. In this mode, the absolute parameters of the sound are updated automatically as the listener's parameters change, so that the relative parameters remain constant.
DS3DMODE_NORMAL
Normal processing. This is the default mode.

Requirements

Header: Declared in dsound.h.


DS3DLISTENER

Describes the 3-D world parameters and position of the listener. This structure is used with the IDirectSound3DListener8::GetAllParameters and IDirectSound3DListener8::SetAllParameters methods.

typedef struct {
    DWORD      dwSize;
    D3DVECTOR  vPosition;
    D3DVECTOR  vVelocity;
    D3DVECTOR  vOrientFront;
    D3DVECTOR  vOrientTop;
    D3DVALUE   flDistanceFactor;
    D3DVALUE   flRolloffFactor;
    D3DVALUE   flDopplerFactor;
} DS3DLISTENER, *LPDS3DLISTENER;

typedef const DS3DLISTENER *LPCDS3DLISTENER;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
vPosition, vVelocity, vOrientFront, vOrientTop
D3DVECTOR structures that describe the listener's position, velocity, front orientation, and top orientation, respectively.
flDistanceFactor, flRolloffFactor, flDopplerFactor
The current distance, rolloff, and Doppler factors, respectively.

Requirements

Header: Declared in dsound.h.


DSBCAPS

Describes the capabilities of a DirectSound buffer object. Used by the IDirectSoundBuffer8::GetCaps method.

typedef struct {
    DWORD  dwSize;
    DWORD  dwFlags;
    DWORD  dwBufferBytes;
    DWORD  dwUnlockTransferRate;
    DWORD  dwPlayCpuOverhead;
} DSBCAPS, *LPDSBCAPS;

typedef const DSBCAPS *LPCDSBCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Flags that specify buffer-object capabilities.
DSBCAPS_CTRL3D
The buffer has 3-D control capability.
DSBCAPS_CTRLFREQUENCY
The buffer has frequency control capability.
DSBCAPS_CTRLFX
The buffer supports effects processing.
DSBCAPS_CTRLPAN
The buffer has pan control capability.
DSBCAPS_CTRLVOLUME
The buffer has volume control capability.
DSBCAPS_CTRLPOSITIONNOTIFY
The buffer has position notification capability. See the Remarks for DSBUFFERDESC.
DSBCAPS_GETCURRENTPOSITION2
Indicates that IDirectSoundBuffer8::GetCurrentPosition should use the new behavior of the play cursor. In DirectSound in DirectX 1, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play cursor. If this flag is not specified, the old behavior is preserved for compatibility. Note that this flag affects only emulated sound cards; if a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS
The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCDEFER
The buffer can be assigned to a hardware or software resource at play time, or when IDirectSoundBuffer8::AcquireResources is called.
DSBCAPS_LOCHARDWARE
The buffer uses hardware mixing.
DSBCAPS_LOCSOFTWARE
The buffer is in software memory and uses software mixing.
DSBCAPS_MUTE3DATMAXDISTANCE
The sound is reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted.
DSBCAPS_PRIMARYBUFFER
The buffer is a primary sound buffer.
DSBCAPS_STATIC
The buffer is in on-board hardware memory.
DSBCAPS_STICKYFOCUS
The buffer has sticky focus. If the user switches to another application not using DirectSound, the buffer is still audible. However, if the user switches to another DirectSound application, the buffer is muted.
dwBufferBytes
Size of this buffer, in bytes.
dwUnlockTransferRate
Specifies the rate, in kilobytes per second, at which data is transferred to the buffer memory when IDirectSoundBuffer8::Unlock is called. High-performance applications can use this value to determine the time required for IDirectSoundBuffer8::Unlock to execute. For software buffers located in system memory, the rate will be very high because no processing is required. For hardware buffers, the rate might be slower because the buffer might have to be downloaded to the sound card, which might have a limited transfer rate.
dwPlayCpuOverhead
Specifies the processing overhead as a percentage of main processing cycles needed to mix this sound buffer. For hardware buffers, this member will be 0 because the mixing is performed by the sound device. For software buffers, this member depends on the buffer format and the speed of the system processor.

Remarks

The DSBCAPS structure contains information similar to that found in the DSBUFFERDESC structure passed to the IDirectSound8::CreateSoundBuffer method, with some additional information. Additional information includes the location of the buffer (hardware or software) and some cost measures (such as the time to download the buffer if located in hardware, and the processing overhead to play the buffer if it is mixed in software).

The dwFlags member contains the same flags used by the DSBUFFERDESC structure. The only difference is that in the DSBCAPS structure, either the DSBCAPS_LOCHARDWARE or DSBCAPS_LOCSOFTWARE flag is specified, according to the location of the buffer. In the DSBUFFERDESC structure, these flags are optional and are used to force the buffer to be located in either hardware or software.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound8::CreateSoundBuffer, IDirectSoundBuffer8::GetCaps


DSBPOSITIONNOTIFY

Describes a notification position. Used by the IDirectSoundNotify8::SetNotificationPositions method.

typedef struct {
    DWORD   dwOffset;
    HANDLE  hEventNotify;
} DSBPOSITIONNOTIFY, *LPDSBPOSITIONNOTIFY;

typedef const DSBPOSITIONNOTIFY *LPCDSBPOSITIONNOTIFY;

Members

dwOffset
Offset from the beginning of the buffer where the notify event is to be triggered, or DSBPN_OFFSETSTOP.
hEventNotify
Handle to the event to be signaled when the offset has been reached.

Remarks

The DSBPN_OFFSETSTOP value in the dwOffset member causes the event to be signaled when playback or capture stops, either because the end of the buffer has been reached (and playback or capture is not looping) or because the application called the IDirectSoundBuffer8::Stop or IDirectSoundCaptureBuffer8::Stop method.

When using DSBCAPS_LOCDEFER and DSBCAPS_NOTIFY along with any voice management flag, it is possible that a sound that has notifications set, but not yet reached, may be terminated by the voice manager. In this event, the notification event will not occur.

Requirements

Header: Declared in dsound.h.


DSBUFFERDESC

Describes the characteristics of a new DirectSoundBuffer object. Used by the IDirectSound8::CreateSoundBuffer method.

An earlier version of this structure, DSBUFFERDESC1, is maintained in Dsound.h for compatibility with DirectX 7 and earlier.

typedef struct {
    DWORD           dwSize;
    DWORD           dwFlags;
    DWORD           dwBufferBytes;
    DWORD           dwReserved;
    LPWAVEFORMATEX  lpwfxFormat;
    GUID            guid3DAlgorithm;
} DSBUFFERDESC, *LPDSBUFFERDESC;

typedef const DSBUFFERDESC *LPCDSBUFFERDESC;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Flags specifying the capabilities to include when creating a new DirectSoundBuffer object. The following values are defined. See also Remarks.
DSBCAPS_CTRL3D
The buffer has 3-D control capability. Cannot be combined with DSBCAPS_CTRLPAN, and cannot be set for a buffer with a stereo format in lpwfxFormat.
DSBCAPS_CTRLFREQUENCY
The buffer has frequency control capability. Cannot be combined with DSBCAPS_CTRLFX.
DSBCAPS_CTRLFX
The buffer supports effects processing. Cannot be combined with DSBCAPS_CTRLFREQUENCY. The wave format in lpwfxFormat must be an 8-bit or 16-bit PCM format with no more than two channels, and the buffer must be large enough to hold at least DSBSIZE_FX_MIN milliseconds of data.
DSBCAPS_CTRLPAN
The buffer has pan control capability. Cannot be combined with DSBCAPS_CTRL3D.
DSBCAPS_CTRLPOSITIONNOTIFY
The buffer has position notification capability. See Remarks.
DSBCAPS_CTRLVOLUME
The buffer has volume control capability.
DSBCAPS_GETCURRENTPOSITION2
The IDirectSoundBuffer8::GetCurrentPosition method uses the new behavior of the play cursor. In DirectSound in DirectX 1, the play cursor was significantly ahead of the actual playing sound on emulated sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the application can get a more accurate play cursor. If this flag is not specified, the old behavior is preserved for compatibility. Note that this flag affects only emulated sound cards. If a DirectSound driver is present, the play cursor is accurate for DirectSound in all versions of DirectX.
DSBCAPS_GLOBALFOCUS
The buffer is a global sound buffer. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to another application, even if the new application uses DirectSound. The one exception is if you switch focus to a DirectSound application that uses the DSSCL_WRITEPRIMARY flag for its cooperative level. In this case, the global sounds from other applications will not be audible.
DSBCAPS_LOCDEFER
The buffer can be assigned to a hardware or software resource at play time. This flag must be set for buffers that use voice management.
DSBCAPS_LOCHARDWARE
The buffer must use hardware mixing, If the device does not support hardware mixing or if the required hardware memory is not available, the call to IDirectSound8::CreateSoundBuffer method will fail. The application must ensure that a mixing channel is available for this buffer; this condition is not guaranteed.
DSBCAPS_LOCSOFTWARE
The buffer must be in software memory and use software mixing, even if DSBCAPS_STATIC is specified and hardware resources are available.
DSBCAPS_MUTE3DATMAXDISTANCE
The sound is reduced to silence at the maximum distance. The buffer will stop playing when the maximum distance is exceeded, so that processor time is not wasted.
DSBCAPS_PRIMARYBUFFER
The buffer is a primary sound buffer. If this value is not specified, a secondary sound buffer is created. Cannot be combined with DSBCAPS_CTRLFX.
DSBCAPS_STATIC
The buffer is placed in on-board hardware memory, if available. No error occurs if such memory is not available. Compare this flag with DSBCAPS_LOCHARDWARE, which forces the buffer into hardware memory (probably system memory used by the driver for its mixing buffers) and causes an error if no such memory is available. This flag cannot be combined with DSBCAPS_CTRLFX.
DSBCAPS_STICKYFOCUS
The buffer has sticky focus. If the user switches to another application not using DirectSound, the application's normal buffers are muted, but sticky focus buffers are still audible.
dwBufferBytes
Size of the new buffer, in bytes. This value must be 0 when creating a buffer with the DSBCAPS_PRIMARYBUFFER flag. For secondary buffers, the minimum and maximum sizes allowed are specified by DSBSIZE_MIN and DSBSIZE_MAX, defined in Dsound.h.
dwReserved
Reserved. Must be 0.
lpwfxFormat
Address of a WAVEFORMATEX or WAVEFORMATEXTENSIBLE structure specifying the waveform format for the buffer. This value must be NULL for primary buffers. The application can use IDirectSoundBuffer8::SetFormat to set the format of the primary buffer.
guid3DAlgorithm
Unique identifier of the two-speaker virtualization algorithm to be used by the DirectSound3D HEL. If DSBCAPS_CTRL3D is not set in dwFlags, this member must be GUID_NULL (DS3DALG_DEFAULT). See also Remarks.

The following algorithm identifiers are defined:

DS3DALG_DEFAULT
DirectSound uses the default algorithm. In most cases this is DS3DALG_NO_VIRTUALIZATION. On WDM drivers, if the user has selected surround sound in Control Panel, the sound is panned among the left, center, right, and surround channels.

Applies to Software Mixing Only. Available on WDM or Vxd Drivers.

DS3DALG_NO_VIRTUALIZATION
3-D output is mapped onto normal left and right stereo panning. At 90 degrees to the left, the sound is coming out of only the left speaker; at 90 degrees to the right, sound is coming out of only the right speaker. The vertical axis is ignored except for scaling of volume due to distance. Doppler shift and volume scaling are still applied, but the 3-D filtering is not performed on this buffer. This is the most efficient software implementation, but provides no virtual 3-D audio effect. When the DS3DALG_NO_VIRTUALIZATION flag is specified, HRTF processing will not be done. Note: Since DS3DALG_NO_VIRTUALIZATION uses only normal stereo panning, a buffer created with this algorithm may be accelerated by a 2-D hardware voice if no free 3-D hardware voices are available.

Applies to Software Mixing Only. Available on WDM or Vxd Drivers.

DS3DALG_HRTF_FULL
The 3-D API is processed with the high quality 3-D audio algorithm. This flag applies only to the software HEL. This algorithm gives the highest quality 3-D audio effect, but uses more CPU. See Remarks.

Applies to Software Mixing Only. Available on Microsoft® Windows® 98 Second Edition and Windows 2000 when using WDM drivers.

Note: If a sound buffer is created using one of the HRTF algorithms, and the HRTF algorithm is not available on the system (for example, a non-WDM system), a success code, DS_NO_VIRTUALIZATION, is returned. The sound buffer created will use DS3DALG_NO_VIRTUALIZATION instead. For this reason, applications should use the SUCCEEDED or FAILED macros rather than checking explicitly for DS_OK when calling CreateSoundBuffer.

DS3DALG_HRTF_LIGHT
The 3-D API is processed with the efficient 3-D audio algorithm. This flag applies only to the software HEL. This algorithm gives a good 3-D audio effect, but uses less CPU than DS3DALG_HRTF_FULL.

Applies to Software Mixing Only. Available on Windows 98 Second Edition and Windows 2000 when using WDM drivers.

Note: If a sound buffer is created using one of the HRTF algorithms, and the HRTF algorithm is not available on the system (for example, a non-WDM system), a success code, DS_NO_VIRTUALIZATION, is returned. The sound buffer created will use DS3DALG_NO_VIRTUALIZATION instead. For this reason, applications should use the SUCCEEDED or FAILED macros rather than checking explicitly for DS_OK when calling CreateSoundBuffer.

Remarks

When creating a primary buffer, applications must set the dwBufferBytes member to 0. DirectSound will determine the best buffer size for the particular sound device in use. To determine the size of a created primary buffer, call IDirectSoundBuffer8::GetCaps.

The DSBCAPS_CTRLDEFAULT flag is no longer supported. This flag was defined as DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY. By specifying only the flags you need, you cut down on unnecessary resource usage.

Sound buffers created with the DSBCAPS_CTRLPOSITIONNOTIFY flag must set a notification event. If you create a sound buffer with this flag but don't actually set any notifications, the behavior is undefined, and you might experience sounds being played back twice.

On VxD drivers, a sound buffer created with DSBCAPS_CTRLPOSITIONNOTIFY is always a software buffer, because the VxD driver model does not support notifications. With WDM drivers, a notification-enabled buffer can be in hardware, if hardware is available. Calling IDirectSoundBuffer8::Play with the DSBPLAY_LOCHARDWARE flag will fail when playing a buffer created with this flag set.

The DSBCAPS_LOCHARDWARE and DSBCAPS_LOCSOFTWARE flags are optional and mutually exclusive. DSBCAPS_LOCHARDWARE forces the buffer to reside in hardware, meaning that it will be mixed by the sound card. DSBCAPS_LOCSOFTWARE forces the buffer to reside in software, where it is mixed by the CPU. These flags are also defined for the dwFlags member of the DSBCAPS structure, where they indicate the actual location of the buffer.

The 3-D algorithms represent selection of the software emulation layer only—that is, the software algorithm that is used when no hardware is present for acceleration. In order to maximize hardware utilization, DS3DALG_NO_VIRTUALIZATION is treated as a special case. If no free 3-D hardware voices are available, the buffer is then treated as a 2-D buffer, but with 3-D API control. Specifically, when a sound buffer is created with DS3DALG_NO_VIRTUALIZATION, or when the buffer is played if the buffer was created with DSBPLAY_LOCDEFER, the following procedure is followed:

  • If a free hardware 3-D voice is available, that 3-D hardware voice is used.
  • If no free hardware 3-D voices are available and a 2-D hardware voice is available, that 2-D hardware voice will be used. This is possible because the DS3DALG_NO_VIRTUALIZATION algorithm is a simple stereo pan algorithm
  • If no free 2-D or 3-D hardware voices are available, the voice will be played in software using the DS3DALG_NO_VIRTUALIZATION algorithm.

If a speaker configuration other than DSSPEAKER_HEADPHONE or DSSPEAKER_STEREO is in effect, the processing will be done as if for a two-speaker configuration.

If a buffer is created using one of the HRTF algorithms, and the HRTF algorithm is not available on the system (for example, a non-WDM system), a success code, DS_NO_VIRTUALIZATION, is returned. The sound buffer created will use DS3DALG_NO_VIRTUALIZATION instead. For this reason, applications should use the SUCCEEDED or FAILED macros rather than checking explicitly for DS_OK when calling CreateSoundBuffer.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound8::CreateSoundBuffer, DirectSound Buffers, Hardware Acceleration on ISA and PCI Cards


DSCAPS

Describes the capabilities of a DirectSound device. Used by the IDirectSound8::GetCaps method.

typedef {
    DWORD  dwSize;
    DWORD  dwFlags;
    DWORD  dwMinSecondarySampleRate;
    DWORD  dwMaxSecondarySampleRate;
    DWORD  dwPrimaryBuffers;
    DWORD  dwMaxHwMixingAllBuffers;
    DWORD  dwMaxHwMixingStaticBuffers;
    DWORD  dwMaxHwMixingStreamingBuffers;
    DWORD  dwFreeHwMixingAllBuffers;
    DWORD  dwFreeHwMixingStaticBuffers;
    DWORD  dwFreeHwMixingStreamingBuffers;
    DWORD  dwMaxHw3DAllBuffers;
    DWORD  dwMaxHw3DStaticBuffers;
    DWORD  dwMaxHw3DStreamingBuffers;
    DWORD  dwFreeHw3DAllBuffers;
    DWORD  dwFreeHw3DStaticBuffers;
    DWORD  dwFreeHw3DStreamingBuffers;
    DWORD  dwTotalHwMemBytes;
    DWORD  dwFreeHwMemBytes;
    DWORD  dwMaxContigFreeHwMemBytes;
    DWORD  dwUnlockTransferRateHwBuffers;
    DWORD  dwPlayCpuOverheadSwBuffers;
    DWORD  dwReserved1;
    DWORD  dwReserved2;
} DSCAPS, *LPDSCAPS;

typedef const DSCAPS *LPCDSCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Flags describing device capabilities. Can include the following values.
DSCAPS_CERTIFIED
The driver has been tested and certified by Microsoft. This flag is always set for WDM drivers. To test for certification, use IDirectSound8::VerifyCertification.
DSCAPS_CONTINUOUSRATE
The device supports all sample rates between the dwMinSecondarySampleRate and dwMaxSecondarySampleRate member values. Typically, this means that the actual output rate will be within +/- 10 hertz (Hz) of the requested frequency.
DSCAPS_EMULDRIVER
The device does not have a DirectSound driver installed, so it is being emulated through the waveform-audio functions. Performance degradation should be expected.
DSCAPS_PRIMARY16BIT
The device supports primary sound buffers with 16-bit samples.
DSCAPS_PRIMARY8BIT
The device supports primary buffers with 8-bit samples.
DSCAPS_PRIMARYMONO
The device supports monophonic primary buffers.
DSCAPS_PRIMARYSTEREO
The device supports stereo primary buffers.
DSCAPS_SECONDARY16BIT
The device supports hardware-mixed secondary sound buffers with 16-bit samples.
DSCAPS_SECONDARY8BIT
The device supports hardware-mixed secondary buffers with 8-bit samples.
DSCAPS_SECONDARYMONO
The device supports hardware-mixed monophonic secondary buffers.
DSCAPS_SECONDARYSTEREO
The device supports hardware-mixed stereo secondary buffers.
dwMinSecondarySampleRate, dwMaxSecondarySampleRate
Minimum and maximum sample rate specifications that are supported by this device's hardware secondary sound buffers.
dwPrimaryBuffers
Number of primary buffers supported. This value will always be 1.
dwMaxHwMixingAllBuffers
Number of buffers that can be mixed in hardware. This member can be less than the sum of dwMaxHwMixingStaticBuffers and dwMaxHwMixingStreamingBuffers. Resource tradeoffs frequently occur.
dwMaxHwMixingStaticBuffers
Maximum number of static buffers.
dwMaxHwMixingStreamingBuffers
Maximum number of streaming sound buffers.
dwFreeHwMixingAllBuffers
Number of unallocated buffers. On WDM drivers, this includes dwFreeHw3DAllBuffers.
dwFreeHwMixingStaticBuffers
Number of unallocated static buffers.
dwFreeHwMixingStreamingBuffers
Number of unallocated streaming buffers.
dwMaxHw3DAllBuffers
Maximum number of 3-D buffers.
dwMaxHw3DStaticBuffers
Maximum number of static 3-D buffers.
dwMaxHw3DStreamingBuffers
Maximum number of streaming 3-D buffers.
dwFreeHw3DAllBuffers
Number of unallocated 3-D buffers.
dwFreeHw3DStaticBuffers
Number of unallocated static 3-D buffers.
dwFreeHw3DStreamingBuffers
Number of unallocated streaming 3-D buffers.
dwTotalHwMemBytes
Size, in bytes, of the amount of memory on the sound card that stores static sound buffers.
dwFreeHwMemBytes
Size, in bytes, of the free memory on the sound card.
dwMaxContigFreeHwMemBytes
Size, in bytes, of the largest contiguous block of free memory on the sound card.
dwUnlockTransferRateHwBuffers
Description of the rate, in kilobytes per second, at which data can be transferred to hardware static sound buffers. This and the number of bytes transferred determines the duration of a call to the IDirectSoundBuffer8::Unlock method.
dwPlayCpuOverheadSwBuffers
Description of the processing overhead, as a percentage of the central processing unit, needed to mix software buffers (those located in main system memory). This varies according to the bus type, the processor type, and the clock speed.

The unlock transfer rate for software buffers is 0 because the data need not be transferred anywhere. Similarly, the play processing overhead for hardware buffers is 0 because the mixing is done by the sound device.

dwReserved1
Not used.
dwReserved2
Not used.

Remarks

Some audio cards may be unable to report accurately the number of available or free hardware buffers. This can happen, for example, when the card can play more sounds at lower sampling rates than at higher rates. In general, a nonzero value in any of the members relating to number of free hardware buffers signifies that at least one hardware resource of the appropriate type is available.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSound8::GetCaps


DSCBCAPS

Describes the capabilities of a capture buffer. Used by the IDirectSoundCaptureBuffer8::GetCaps method.

typedef struct {
    DWORD  dwSize;
    DWORD  dwFlags;
    DWORD  dwBufferBytes;
    DWORD  dwReserved;
} DSCBCAPS, *LPDSCBCAPS;

typedef const DSCBCAPS *LPCDSCBCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Specifies device capabilities. Can be zero or the following flag:
DSCBCAPS_WAVEMAPPED
The Win32 wave mapper will be used for formats not supported by the device.
dwBufferBytes
The size, in bytes, of the capture buffer.
dwReserved
Reserved for future use.

Requirements

Header: Declared in dsound.h.


DSCBUFFERDESC

Describes a capture buffer. Used by the IDirectSoundCapture8::CreateCaptureBuffer method.

An earlier version of this structure, DSCBUFFERDESC1, is maintained in Dsound.h for compatibility with DirectX 7 and earlier.

typedef struct {
    DWORD           dwSize;
    DWORD           dwFlags;
    DWORD           dwBufferBytes;
    DWORD           dwReserved;
    LPWAVEFORMATEX  lpwfxFormat;
    DWORD           dwFXCount;
    LPDSCEFFECTDESC lpDSCFXDesc;
} DSCBUFFERDESC, *LPDSCBUFFERDESC;

typedef const DSCBUFFERDESC *LPCDSCBUFFERDESC;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Specifies device capabilities. Can be zero or one or more of the following flag:
DSCBCAPS_CTRLFX
The buffer supports effects. See Remarks.
DSCBCAPS_WAVEMAPPED
The Win32 wave mapper will be used for formats not supported by the device.
dwBufferBytes
Size of capture buffer to create, in bytes.
dwReserved
Reserved for future use.
lpwfxFormat
Pointer to a WAVEFORMATEX structure containing the format in which to capture the data.
dwFXCount
Number of elements in the array pointed to by lpDSCFXDesc. Must be zero unless DSCBCAPS_CTRLFX is present in dwFlags.
lpDSCFXDesc
Address of an array of DSCEFFECTDESC structures that describe effects supported by hardware for the buffer. User-mode DMOs are not supported.

Remarks

The DSCBCAPS_CTRLFX flag is supported only on buffers created by an object of class CLSID_DirectSoundCapture8. If the IDirectSoundCapture8 interface was obtained from DirectSoundCaptureCreate8, this flag is supported; if it was obtained from the earlier DirectSoundCaptureCreate function, it is not.

Capture effects are not supported on current operating systems.

Requirements

Header: Declared in dsound.h.


DSCCAPS

Describes the capabilities of the capture device. Used by the IDirectSoundCapture8::GetCaps method.

typedef struct {
    DWORD  dwSize;
    DWORD  dwFlags;
    DWORD  dwFormats;
    DWORD  dwChannels;
} DSCCAPS, *LPDSCCAPS;

typedef const DSCCAPS *LPCDSCCAPS;

Members

dwSize
Size of the structure, in bytes. This member must be initialized before the structure is used.
dwFlags
Specifies device capabilities. Can be 0 or the following flags:
DSCCAPS_EMULDRIVER
There is no DirectSoundCapture driver for the device, so the standard wave audio functions are being used.
DSCCAPS_CERTIFIED
The driver for the device is a certified WDM driver.
DSCCAPS_MULTIPLECAPTURE
The capture device can be opened by multiple applications which can all receive valid capture data simultaneously.
dwFormats
Standard formats that are supported. These are equivalent to the values in the WAVEINCAPS structure used in the Win32 waveform audio functions, and are reproduced here for convenience.
Value | Meaning
WAVE_FORMAT_1M08 | 11.025 kHz, mono, 8-bit
WAVE_FORMAT_1M16 | 11.025 kHz, mono, 16-bit
WAVE_FORMAT_1S08 | 11.025 kHz, stereo, 8-bit
WAVE_FORMAT_1S16 | 11.025 kHz, stereo, 16-bit
WAVE_FORMAT_2M08 | 22.05 kHz, mono, 8-bit
WAVE_FORMAT_2M16 | 22.05 kHz, mono, 16-bit
WAVE_FORMAT_2S08 | 22.05 kHz, stereo, 8-bit
WAVE_FORMAT_2S16 | 22.05 kHz, stereo, 16-bit
WAVE_FORMAT_4M08 | 44.1 kHz, mono, 8-bit
WAVE_FORMAT_4M16 | 44.1 kHz, mono, 16-bit
WAVE_FORMAT_4S08 | 44.1 kHz, stereo, 8-bit
WAVE_FORMAT_4S16 | 44.1 kHz, stereo, 16-bit

dwChannels
Number specifying the number of channels supported by the device, where 1 is mono, 2 is stereo, and so on.

Requirements

Header: Declared in dsound.h.


DSCEFFECTDESC

Contains parameters for an effect associated with a capture buffer.

typedef struct _DSCEFFECTDESC {
    DWORD       dwSize;
    DWORD       dwFlags;
    GUID        guidDSCFXClass;
    GUID        guidDSCFXInstance;
    DWORD       dwReserved1;
    DWORD       dwReserved2;
} DSCEFFECTDESC, *LPDSCEFFECTDESC;

typedef const DSCEFFECTDESC *LPCDSCEFFECTDESC;

Members

dwSize
Size of the structure, in bytes.
dwFlags
Flags that specify desired parameters of the effect. When this structure is passed to IDirectSoundCapture8::CreateCaptureBuffer, this member can be zero or one or more of the following values.
DSCFX_LOCHARDWARE
Effect specified by guidDSCFXInstance must be in hardware.
DSCFX_LOCSOFTWARE
Effect specified by guidDSCFXInstance must be in software.
On return, this member can contain one or more of the following values.
DSCFXR_LOCHARDWARE
Effect was created in hardware.
DSCFXR_LOCSOFTWARE
Effect was created in software.
DSCFXR_UNALLOCATED
The effect was not created.
DSCFXR_FAILED
Effect creation failed.
DSCFXR_UNKNOWN
Result of effect creation is unknown.
guidDSCFXClass
Value of type GUID that specifies the class identifier of the effect. The following standard identifiers are defined.
DSCFX_CLASS_AEC
Acoustic echo cancellation.
DSCFX_CLASS_NS
Noise suppression.
guidDSCFXInstance
Value of type GUID that specifies the unique identifier of the preferred effect. The following standard identifiers are defined.
DSCFX_MS_AEC
Microsoft acoustic echo cancellation. Available in software only.
DSCFX_MS _NS
Microsoft noise suppression. Available in software only.
DSCFX_SYSTEM_AEC
System default acoustic echo cancellation.
DSCFX_SYSTEM_NS
System default noise suppression.
DSCFX_NOP
No effect.

dwReserved1
Reserved. Must be 0.
dwReserved2
Reserved. Must be 0.

Requirements

Header: Declared in dsound.h.


DSCFXAec

Contains parameters for acoustic echo cancellation in a capture buffer.

typedef struct _DSCFXAec {
    BOOL  fEnable;
    BOOL  fReset;
} DSCFXAec, *LPDSCFXAec;

typedef const DSCFXAec *LPCDSCFXAec;

Members

fEnable
Boolean value that specifies whether the effect is enabled.
fReset
Boolean value that specifies whether to reset the effect to the default state.

Remarks

Applications should not reset an effect except when necessary because it has entered an incorrect state. This might be done in response to user input. The fReset flag must not be set arbitrarily at startup, because another application might be using the same effect.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundCaptureFXAec8::GetAllParameters, IDirectSoundCaptureFXAec8::SetAllParameters


DSCFXNoiseSuppress

Contains parameters for noise suppression in a capture buffer.

typedef struct _DSCFXNoiseSuppress {
    BOOL  fEnable;
    BOOL  fReset;
} DSCFXNoiseSuppress, *LPDSCFXNoiseSuppress;

typedef const DSCFXNoiseSuppress *LPCDSCFXNoiseSuppress;

Members

fEnable
Boolean value that specifies whether the effect is enabled.
fReset
Boolean value that specifies whether to reset the effect to the default state.

Remarks

Applications should not reset an effect except when necessary because it has entered an incorrect state. This might be done in response to user input. The fReset flag must not be set arbitrarily at startup, because another application might be using the same effect.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundCaptureFXNoiseSuppress8::GetAllParameters, IDirectSoundCaptureFXNoiseSuppress8::SetAllParameters


DSEFFECTDESC

Describes an effect associated with a buffer.

typedef struct _DSEFFECTDESC {
    DWORD  dwSize;
    DWORD  dwFlags;
    GUID   guidDSFXClass;
    DWORD  dwReserved1;
    DWORD  dwReserved2
} DSEFFECTDESC, *LPDSEFFECTDESC;

typedef const DSEFFECTDESC *LPCDSEFFECTDESC;

Members

dwSize
Size of the structure, in bytes.
dwFlags
Flags. Can be 0 or one of the following values:
DSFX_LOCHARDWARE
Effect must be in hardware. If the effect is not available in hardware, IDirectSoundBuffer8::SetFX raises an error. Because DirectX 8.0 does not support hardware acceleration of effects, this flag should not be used.
DSFX_LOCSOFTWARE
Effect must be in software, even if the hardware supports acceleration of guidDSFXClass. If the effect is not available in software, SetFX raises an error. In DirectX 8.0, all effects are in software regardless of whether this flag is set.
guidDSFXClass
Class identifier of the effect. The following standard effect classes are defined.
GUID_DSFX_STANDARD_CHORUS
GUID_DSFX_STANDARD_COMPRESSOR
GUID_DSFX_STANDARD_DISTORTION
GUID_DSFX_STANDARD_ECHO
GUID_DSFX_STANDARD_FLANGER
GUID_DSFX_STANDARD_GARGLE
GUID_DSFX_STANDARD_I3DL2REVERB
GUID_DSFX_STANDARD_PARAMEQ
GUID_DSFX_STANDARD_WAVES_REVERB
dwReserved1
Reserved for future use.
dwReserved2
Reserved for future use.

Remarks

If dwFlags is zero, the effect is placed in hardware if possible. If the hardware does not support the effect, software is used. If the effect is not available at all, the call to SetFX fails.

An effect of class GUID_DSFX_STANDARD_WAVES_REVERB can be set only on a buffer that has a 16-bit audio format.

Requirements

Header: Declared in dsound.h.

See Also

DSBCAPS, IDirectSoundBuffer8::SetFX, Using Effects


DSFXI3DL2Reverb

Contains parameters for an I3DL2 (Interactive 3D Audio Level 2) reverberation effect.

typedef struct _DSFXI3DL2Reverb {
    LONG    lRoom;
    LONG    lRoomHF;
    FLOAT   flRoomRolloffFactor;
    FLOAT   flDecayTime;
    FLOAT   flDecayHFRatio;
    LONG    lReflections;
    FLOAT   flReflectionsDelay;
    LONG    lReverb;
    FLOAT   flReverbDelay;
    FLOAT   flDiffusion;
    FLOAT   flDensity;
    FLOAT   flHFReference;
} DSFXI3DL2Reverb, *LPDSFXI3DL2Reverb;

typedef const DSFXI3DL2Reverb *LPCDSFXI3DL2Reverb;

Members

lRoom
Attenuation of the room effect, in millibels (mB), in the range from DSFX_I3DL2REVERB_ROOM_MIN to DSFX_I3DL2REVERB_ROOM_MAX. The default value is DSFX_I3DL2REVERB_ROOM_DEFAULT, or -1000 mB.
lRoomHF
Attenuation of the room high-frequency effect, in mB, in the range from DSFX_I3DL2REVERB_ROOMHF_MIN to DSFX_I3DL2REVERB_ROOMHF_MAX. The default value is DSFX_I3DL2REVERB_ROOMHF_DEFAULT, or 0 mB.
flRoomRolloffFactor
Rolloff factor for the reflected signals, in the range from DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MIN to DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MAX. The default value is DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_DEFAULT, or 0.0. The rolloff factor for the direct path is controlled by the DirectSound listener.
flDecayTime
Decay time, in seconds, in the range from DSFX_I3DL2REVERB_DECAYTIME_MIN to DSFX_I3DL2REVERB_DECAYTIME_MAX. The default value is DSFX_I3DL2REVERB_DECAYTIME_DEFAULT, or 1.49 second.
flDecayHFRatio
Ratio of the decay time at high frequencies to the decay time at low frequencies, in the range from DSFX_I3DL2REVERB_DECAYHFRATIO_MIN to DSFX_I3DL2REVERB_DECAYHFRATIO_MAX. The default value is DSFX_I3DL2REVERB_DECAYHFRATIO_DEFAULT, or 0.83.
lReflections
Attenuation of early reflections relative to lRoom, in mB, in the range from DSFX_I3DL2REVERB_REFLECTIONS_MIN to DSFX_I3DL2REVERB_REFLECTIONS_MAX. The default value is DSFX_I3DL2REVERB_REFLECTIONS_DEFAULT, or -2602 mB.
flReflectionsDelay
Delay time of the first reflection relative to the direct path, in seconds, in the range from DSFX_I3DL2REVERB_REFLECTIONSDELAY_MIN to DSFX_I3DL2REVERB_REFLECTIONSDELAY_DEFAULT. The default value is 0.007 seconds.
lReverb
Attenuation of late reverberation relative to lRoom, in mB, in the range -from DSFX_I3DL2REVERB_REVERB_MIN to DSFX_I3DL2REVERB_REVERB_MAX. The default value is DSFX_I3DL2REVERB_REVERB_DEFAULT, or 200 mB.
flReverbDelay
Time limit between the early reflections and the late reverberation relative to the time of the first reflection, in seconds, in the range from DSFX_I3DL2REVERB_REVERBDELAY_MIN to DSFX_I3DL2REVERB_REVERBDELAY_MAX. The default value is DSFX_I3DL2REVERB_REVERBDELAY_DEFAULT, or 0.011 seconds.
flDiffusion
Echo density in the late reverberation decay, in percent, in the range from DSFX_I3DL2REVERB_DIFFUSION_MIN to DSFX_I3DL2REVERB_DIFFUSION_MAX. The default value is DSFX_I3DL2REVERB_DIFFUSION_DEFAULT, or 100.0 percent.
flDensity
Modal density in the late reverberation decay, in percent, in the range from DSFX_I3DL2REVERB_DENSITY_MIN to DSFX_I3DL2REVERB_DENSITY_MAX. The default value is DSFX_I3DL2REVERB_DENSITY_DEFAULT, or 100.0 percent.
flHFReference
Reference high frequency, in hertz, in the range from DSFX_I3DL2REVERB_HFREFERENCE_MIN to DSFX_I3DL2REVERB_HFREFERENCE_MAX. The default value is DSFX_I3DL2REVERB_HFREFERENCE_DEFAULT, or 5000.0 Hz.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundFXI3DL2Reverb8


DSFXChorus

Contains parameters for a chorus effect.

typedef struct _DSFXChorus {
    FLOAT       fWetDryMix;
    FLOAT       fDepth;
    FLOAT       fFeedback;
    FLOAT       fFrequency;
    LONG        lWaveform;
    FLOAT       fDelay;
    LONG        lPhase;
} DSFXChorus, *LPDSFXChorus;

typedef const DSFXChorus *LPCDSFXChorus;

Members

fWetDryMix
Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXCHORUS_WETDRYMIX_MIN through DSFXCHORUS_WETDRYMIX_MAX (all wet).
fDepth
Percentage by which the delay time is modulated by the low-frequency oscillator, in hundredths of a percentage point. Must be in the range from DSFXCHORUS_DEPTH_MIN through DSFXCHORUS_DEPTH_MAX. The default value is 25.
fFeedback
Percentage of output signal to feed back into the effect's input, in the range from DSFXCHORUS_FEEDBACK_MIN to DSFXCHORUS_FEEDBACK_MAX. The default value is 0.
fFrequency
Frequency of the LFO, in the range from DSFXCHORUS_FREQUENCY_MIN to DSFXCHORUS_FREQUENCY_MAX. The default value is 0.
lWaveform
Waveform of the LFO. Defined values are DSFXCHORUS_WAVE_TRIANGLE and DSFXCHORUS_WAVE_SIN. By default, the waveform is a sine.
fDelay
Number of milliseconds the input is delayed before it is played back, in the range from DSFXCHORUS_DELAY_MIN to DSFXCHORUS_DELAY_MAX. The default value is 0 ms.
lPhase
Phase differential between left and right LFOs, in the range from DSFXCHORUS_PHASE_MIN through DSFXCHORUS_PHASE_MAX. Possible values are defined as follows:
DSFXCHORUS_PHASE_NEG_180
DSFXCHORUS_PHASE_NEG_90
DSFXCHORUS_PHASE_ZERO
DSFXCHORUS_PHASE_90
DSFXCHORUS_PHASE_180

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundFXChorus8, Chorus


DSFXCompressor

Contains parameters for a compression effect.

typedef struct _DSFXCompressor {
    FLOAT   fGain;
    FLOAT   fAttack;
    FLOAT   fRelease;
    FLOAT   fThreshold;
    FLOAT   fRatio;
    FLOAT   fPredelay;
} DSFXCompressor, *LPDSFXCompressor;

typedef const DSFXCompressor *LPCDSFXCompressor;

Members

fGain
Output gain of signal after compression, in the range from DSFXCOMPRESSOR_GAIN_MIN to DSFXCOMPRESSOR_GAIN_MAX. The default value is 0 dB.
fAttack
Time before compression reaches its full value, in the range from DSFXCOMPRESSOR_ATTACK_MIN to DSFXCOMPRESSOR_ATTACK_MAX. The default value is 0.01 ms.
fRelease
Speed at which compression is stopped after input drops below fThreshold, in the range from DSFXCOMPRESSOR_RELEASE_MIN to DSFXCOMPRESSOR_RELEASE_MAX. The default value is 50 ms.
fThreshold
Point at which compression begins, in decibels, in the range from DSFXCOMPRESSOR_THRESHOLD_MIN to DSFXCOMPRESSOR_THRESHOLD_MAX. The default value is -10 dB.
fRatio
Compression ratio, in the range from DSFXCOMPRESSOR_RATIO_MIN to DSFXCOMPRESSOR_RATIO_MAX. The default value is 10, which means 10:1 compression.
fPredelay
Time after lThreshold is reached before attack phase is started, in milliseconds, in the range from DSFXCOMPRESSOR_PREDELAY_MIN to DSFXCOMPRESSOR_PREDELAY_MAX. The default value is 0 ms.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundFXCompressor8, Compression


DSFXDistortion

Contains parameters for a distortion effect.

typedef struct _DSFXDistortion {
    FLOAT   fGain;
    FLOAT   fEdge;
    FLOAT   fPostEQCenterFrequency;
    FLOAT   fPostEQBandwidth;
    FLOAT   fPreLowpassCutoff;
} DSFXDistortion, *LPDSFXDistortion;

typedef const DSFXDistortion *LPCDSFXDistortion;

    Members

    fGain
    Amount of signal change after distortion, in the range from DSFXDISTORTION_GAIN_MIN through DSFXDISTORTION_GAIN_MAX. The default value is 0 dB.
    fEdge
    Percentage of distortion intensity, in the range in the range from DSFXDISTORTION_EDGE_MIN through DSFXDISTORTION_EDGE_MAX. The default value is 50 percent.
    fPostEQCenterFrequency
    Center frequency of harmonic content addition, in the range from DSFXDISTORTION_POSTEQCENTERFREQUENCY_MIN through DSFXDISTORTION_POSTEQCENTERFREQUENCY_MAX. The default value is 4000 Hz.
    fPostEQBandwidth
    Width of frequency band that determines range of harmonic content addition, in the range from DSFXDISTORTION_POSTEQBANDWIDTH_MIN through DSFXDISTORTION_POSTEQBANDWIDTH_MAX. The default value is 4000 Hz.
    fPreLowpassCutoff
    Filter cutoff for high-frequency harmonics attenuation, in the range from DSFXDISTORTION_PRELOWPASSCUTOFF_MIN through DSFXDISTORTION_PRELOWPASSCUTOFF_MAX. The default value is 4000 Hz.

    Remarks

    The values in fPostEQBandwidth, fPostEQCenterFrequency, and fPreLowpassCutoff cannot exceed one-third of the frequency of the buffer.

    Requirements

    Header: Declared in dsound.h.

    See Also

    IDirectSoundFXDistortion8, Distortion


DSFXEcho

Contains parameters for an echo effect.

typedef struct _DSFXEcho {
    FLOAT   fWetDryMix;
    FLOAT   fFeedback;
    FLOAT   fLeftDelay;
    FLOAT   fRightDelay;
    LONG    lPanDelay;
} DSFXEcho, *LPDSFXEcho;

typedef const DSFXEcho *LPCDSFXEcho;

    Members

    fWetDryMix
    Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXECHO_WETDRYMIX_MIN through DSFXECHO_WETDRYMIX_MAX (all wet).
    fFeedback
    Percentage of output fed back into input, in the range from DSFXECHO_FEEDBACK_MIN through DSFXECHO_FEEDBACK_MAX. The default value is 0.
    fLeftDelay
    Delay for left channel, in milliseconds, in the range from DSFXECHO_LEFTDELAY_MIN through DSFXECHO_LEFTDELAY_MAX. The default value is 333 ms.
    fRightDelay
    Delay for right channel, in milliseconds, in the range from DSFXECHO_RIGHTDELAY_MIN through DSFXECHO_RIGHTDELAY_MAX. The default value is 333 ms.
    lPanDelay
    Value that specifies whether to swap left and right delays with each successive echo. The default value is zero, meaning no swap. Possible values are defined as DSFXECHO_PANDELAY_MIN (equivalent to FALSE) and DSFXECHO_PANDELAY_MAX (equivalent to TRUE).

    Requirements

    Header: Declared in dsound.h.

    See Also

    IDirectSoundFXEcho8, Echo


DSFXFlanger

Contains parameters for a flange effect.

typedef struct _DSFXFlanger {
    FLOAT   fWetDryMix;
    FLOAT   fDepth;
    FLOAT   fFeedback;
    FLOAT   fFrequency;
    LONG    lWaveform;
    FLOAT   fDelay;
    LONG    lPhase;
} DSFXFlanger, *LPDSFXFlanger;

typedef const DSFXFlanger *LPCDSFXFlanger;

Members

fWetDryMix
Ratio of wet (processed) signal to dry (unprocessed) signal. Must be in the range from DSFXFLANGER_WETDRYMIX_MIN through DSFXFLANGER_WETDRYMIX_MAX (all wet).
fDepth
Percentage by which the delay time is modulated by the low-frequency oscillator (LFO), in hundredths of a percentage point. Must be in the range from DSFXFLANGER_DEPTH_MIN through DSFXFLANGER_DEPTH_MAX. The default value is 25.
fFeedback
Percentage of output signal to feed back into the effect's input, in the range from DSFXFLANGER_FEEDBACK_MIN to DSFXFLANGER_FEEDBACK_MAX. The default value is 0.
fFrequency
Frequency of the LFO, in the range from DSFXFLANGER_FREQUENCY_MIN to DSFXFLANGER_FREQUENCY_MAX. The default value is 0.
lWaveform
Waveform of the LFO. By default, the waveform is a sine. Possible values are defined as follows:
DSFXFLANGER_WAVE_TRIANGLE
Triangle.
DSFXFLANGER_WAVE_SIN
Sine.
fDelay
Number of milliseconds the input is delayed before it is played back, in the range from DSFXFLANGER_DELAY_MIN to DSFXFLANGER_DELAY_MAX. The default value is 0 ms.
lPhase
Phase differential between left and right LFOs, in the range from DSFXFLANGER_PHASE_MIN through DSFXFLANGER_PHASE_MAX. Possible values are defined as follows:
DSFXFLANGER_PHASE_NEG_180
DSFXFLANGER_PHASE_NEG_90
DSFXFLANGER_PHASE_ZERO
DSFXFLANGER_PHASE_90
DSFXFLANGER_PHASE_180

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundFXFlanger8, Flange


DSFXGargle

Contains parameters for an amplitude modulation effect.

typedef struct _DSFXGargle {
    DWORD  dwRateHz;
    DWORD  dwWaveShape;
} DSFXGargle, *LPDSFXGargle;

typedef const DSFXGargle *LPCDSFXGargle;

Members

dwRateHz
Rate of modulation, in Hertz. Must be in the range from DSFXGARGLE_RATEHZ_MIN through DSFXGARGLE_RATEHZ_MAX.
dwWaveShape
Shape of the modulation wave. The following values are defined.
DSFXGARGLE_WAVE_TRIANGLE
Triangular wave.
DSFXGARGLE_WAVE_SQUARE
Square wave.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundFXGargle8, Gargle


DSFXParamEq

Contains parameters for a parametric equalizer effect.

typedef struct _DSFXParamEq {
    FLOAT fCenter;
    FLOAT fBandwidth;
    FLOAT fGain;
} DSFXParamEq, *LPDSFXParamEq;

Members

fCenter
Center frequency, in hertz, in the range from DSFXPARAMEQ_CENTER_MIN to DSFXPARAMEQ_CENTER_MAX. This value cannot exceed one-third of the frequency of the buffer.
fBandwidth
Bandwidth, in semitones, in the range from DSFXPARAMEQ_BANDWIDTH_MIN to DSFXPARAMEQ_BANDWIDTH_MAX.
fGain
Gain, in the range from DSFXPARAMEQ_GAIN_MIN to DSFXPARAMEQ_GAIN_MAX.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundFXParamEq8, Parametric Equalizer


DSFXWavesReverb

Contains parameters for a wave reverberation effect.

typedef struct _DSFXWavesReverb {
    FLOAT   fInGain;
    FLOAT   fReverbMix;
    FLOAT   fReverbTime;
    FLOAT   fHighFreqRTRatio;
} DSFXWavesReverb, *LPDSFXWavesReverb;

typedef const DSFXWavesReverb *LPCDSFXWavesReverb;

Members

fInGain
Input gain of signal, in decibels (dB), in the range from DSFX_WAVESREVERB_INGAIN_MIN through DSFX_WAVESREVERB_INGAIN_MAX. The default value is DSFX_WAVESREVERB_INGAIN_DEFAULT, or 0 dB.
fReverbMix
Reverb mix, in dB, in the range from DSFX_WAVESREVERB_REVERBMIX_MIN through DSFX_WAVESREVERB_REVERBMIX_MAX. The default value is DSFX_WAVESREVERB_REVERBMIX_DEFAULT, or 0 dB.
fReverbTime
Reverb time, in milliseconds, in the range from DSFX_WAVESREVERB_REVERBTIME_MIN through DSFX_WAVESREVERB_REVERBTIME_MAX. The default value is DSFX_WAVESREVERB_REVERBTIME_DEFAULT, or 1000.
fHighFreqRTRatio
In the range from DSFX_WAVESREVERB_HIGHFREQRTRATIO_MIN through DSFX_WAVESREVERB_HIGHFREQRTRATIO_MAX. The default value is DSFX_WAVESREVERB_HIGHFREQRTRATIO_DEFAULT, or 0.001.

Requirements

Header: Declared in dsound.h.

See Also

IDirectSoundFXWavesReverb8


WAVEFORMATEX

Defines the format of waveform-audio data. Only format information common to all waveform-audio data formats is included in this structure. For formats that require additional information, this structure is included as the first member in another structure, along with the additional information.

This structure is part of the Platform SDK and is not declared in Dsound.h. It is documented here for convenience.

typedef struct {
    WORD  wFormatTag;
    WORD  nChannels;
    DWORD nSamplesPerSec;
    DWORD nAvgBytesPerSec;
    WORD  nBlockAlign;
    WORD  wBitsPerSample;
    WORD  cbSize;
} WAVEFORMATEX;

Members

wFormatTag
Waveform-audio format type. Format tags are registered with Microsoft Corporation for many compression algorithms. A complete list of format tags can be found in the Mmreg.h header file. For one- or two-channel PCM data, this value should be WAVEFORMAT_PCM.
nChannels
Number of channels in the waveform-audio data. Monaural data uses one channel and stereo data uses two channels.
nSamplesPerSec
Sample rate, in samples per second (hertz). If wFormatTag is WAVE_FORMAT_PCM, then common values for nSamplesPerSec are 8.0 kHz, 11.025 kHz, 22.05 kHz, and 44.1 kHz. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.
nAvgBytesPerSec
Required average data-transfer rate, in bytes per second, for the format tag. If wFormatTag is WAVE_FORMAT_PCM, nAvgBytesPerSec should be equal to the product of nSamplesPerSec and nBlockAlign. For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.
nBlockAlign
Block alignment, in bytes. The block alignment is the minimum atomic unit of data for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM or WAVE_FORMAT_EXTENSIBLE, nBlockAlign must be equal to the product of nChannels and wBitsPerSample divided by 8 (bits per byte). For non-PCM formats, this member must be computed according to the manufacturer's specification of the format tag.

Software must process a multiple of nBlockAlign bytes of data at a time. Data written and read from a device must always start at the beginning of a block. For example, it is illegal to start playback of PCM data in the middle of a sample (that is, on a non-block-aligned boundary).

wBitsPerSample
Bits per sample for the wFormatTag format type. If wFormatTag is WAVE_FORMAT_PCM, then wBitsPerSample should be equal to 8 or 16. If wFormatTag is WAVE_FORMAT_EXTENSIBLE, this value can be any integer multiple of 8.
cbSize
Size, in bytes, of extra format information appended to the end of the WAVEFORMATEX structure. This information can be used by non-PCM formats to store extra attributes for the wFormatTag. If no extra information is required by the wFormatTag, this member must be set to zero. For WAVE_FORMAT_PCM formats, this member is ignored.

Requirements

Header: Declared in Mmreg.h.

See Also

WAVEFORMATEXTENSIBLE


WAVEFORMATEXTENSIBLE

Defines the format of waveform-audio data for formats having more than two channels.

This structure is part of the Platform SDK and is not declared in Dsound.h. It is documented here for convenience.

typedef struct {
    WAVEFORMATEX  Format;
    union {
        WORD      wValidBitsPerSample;
        WORD      wSamplesPerBlock;
        WORD      wReserved;
    } Samples;
    DWORD         dwChannelMask;
    GUID          SubFormat;
} WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE;

Members

Format
WAVEFORMATEX structure that specifies the basic format. The wFormatTag member must be WAVE_FORMAT_EXTENSIBLE, defined in Mmreg.h. The cbSize member must be at least 22.
wValidBitsPerSample
How many bits of precision are present in the signal. Usually equal to WAVEFORMATEX.wBitsPerSample.
wSamplesPerBlock
How many samples are contained in one compressed block of audio data. If zero, the number of samples in each block is variable.
wReserved
Set to zero if neither wValidBitsPerSample nor wSamplesPerBlock applies to the format.
dwChannelMask
Bitmask specifying which channels are present. See Remarks.
SubFormat
Subformat of the data. Must be KSDATAFORMAT_SUBTYPE_PCM, defined in Ksmedia.h.

Remarks

The dwChannelMask member indicates which channels are present in the multichannel stream. The least significant bit corresponds with the front left speaker, the next least significant bit corresponds to the front right speaker, and so on. The bits, in order of significance, are defined in Ksmedia.h and Mmreg.h as follows:

SPEAKER_FRONT_LEFT
SPEAKER_FRONT_RIGHT
SPEAKER_FRONT_CENTER
SPEAKER_LOW_FREQUENCY
SPEAKER_BACK_LEFT
SPEAKER_BACK_RIGHT
SPEAKER_FRONT_LEFT_OF_CENTER
SPEAKER_FRONT_RIGHT_OF_CENTER
SPEAKER_BACK_CENTER
SPEAKER_SIDE_LEFT
SPEAKER_SIDE_RIGHT
SPEAKER_TOP_CENTER
SPEAKER_TOP_FRONT_LEFT
SPEAKER_TOP_FRONT_CENTER
SPEAKER_TOP_FRONT_RIGHT
SPEAKER_TOP_BACK_LEFT
SPEAKER_TOP_BACK_CENTER
SPEAKER_TOP_BACK_RIGHT

For more information on this structure, see the document "Enhanced Audio Formats for Multi-Channel Configurations and High-Bit Resolution", available at http://www.microsoft.com/hwdev/audio/multichaud.htm.

Requirements

Header: Declared in Mmreg.h, Ksproxy.h.


DirectSound Return Values

This section provides a brief explanation of the various error codes that can be returned by DirectSound methods. For a list of the specific codes that each method can return, see the individual method descriptions. The lists given there are not necessarily comprehensive.

Error codes are presented in the following sections:

  • DirectSound Return Values By Number
  • DirectSound Return Values By Name


DirectSound Return Values By Number

The following table lists DirectSound return values sorted by hexadecimal value. For a description, click on the constant.

Hexadecimal | Constant
0x00000000 | DS_OK
0x00000007 | DSERR_OUTOFMEMORY
0x000001AE | DSERR_NOINTERFACE
0x0878000A | DS_NO_VIRTUALIZATION
0x08780014 | DS_INCOMPLETE
0x80004001 | DSERR_UNSUPPORTED
0x80004005 | DSERR_GENERIC
0x80070005 | DSERR_ACCESSDENIED
0x80070057 | DSERR_INVALIDPARAM
0x8878000A | DSERR_ALLOCATED
0x8878001E | DSERR_CONTROLUNAVAIL
0x88780032 | DSERR_INVALIDCALL
0x88780046 | DSERR_PRIOLEVELNEEDED
0x88780064 | DSERR_BADFORMAT
0x88780078 | DSERR_NODRIVER
0x88780082 | DSERR_ALREADYINITIALIZED
0x88780096 | DSERR_BUFFERLOST
0x887800A0 | DSERR_OTHERAPPHASPRIO
0x887800AA | DSERR_UNINITIALIZED
0x887810B4 | DSERR_BUFFERTOOSMALL
0x887810BE | DSERR_DS8_REQUIRED
0x88781161 | DSERR_OBJECTNOTFOUND


DirectSound Return Values by Name

The following list describes all DirectSound return values. To find a constant from its value, see DirectSound Return Values By Number.

DS_OK
The method succeeded.
DS_NO_VIRTUALIZATION
The buffer was created, but another 3-D algorithm was substituted.
DS_INCOMPLETE
The method succeeded, but not all the optional effects were obtained.
DSERR_ACCESSDENIED
The request failed because access was denied.
DSERR_ALLOCATED
The request failed because resources, such as a priority level, were already in use by another caller.
DSERR_ALREADYINITIALIZED
The object is already initialized.
DSERR_BADFORMAT
The specified wave format is not supported.
DSERR_BUFFERLOST
The buffer memory has been lost and must be restored.
DSERR_BUFFERTOOSMALL
The buffer size is not great enough to enable effects processing.
DSERR_CONTROLUNAVAIL
The buffer control (volume, pan, and so on) requested by the caller is not available.
DSERR_DS8_REQUIRED
A DirectSound object of class CLSID_DirectSound8 or later is required for the requested functionality. For more information, see IDirectSound8.
DSERR_GENERIC
An undetermined error occurred inside the DirectSound subsystem.
DSERR_INVALIDCALL
This function is not valid for the current state of this object.
DSERR_INVALIDPARAM
An invalid parameter was passed to the returning function.
DSERR_NOAGGREGATION
The object does not support aggregation.
DSERR_NODRIVER
No sound driver is available for use, or the given GUID is not a valid DirectSound device ID.
DSERR_NOINTERFACE
The requested COM interface is not available.
DSERR_OBJECTNOTFOUND
The requested object was not found.
DSERR_OTHERAPPHASPRIO
Another application has a higher priority level, preventing this call from succeeding.
DSERR_OUTOFMEMORY
The DirectSound subsystem could not allocate sufficient memory to complete the caller's request.
DSERR_PRIOLEVELNEEDED
The caller does not have the priority level required for the function to succeed.
DSERR_UNINITIALIZED
The IDirectSound8::Initialize method has not been called or has not been called successfully before other methods were called.
DSERR_UNSUPPORTED
The function called is not supported at this time.


DirectInput

This section provides information about the Microsoft® DirectInput® component of the Microsoft DirectX® application programming interface (API). The DirectInput API is used to process data from a keyboard, mouse, joystick, or other game controller.

For an overview of the documentation, see Roadmap.


Roadmap

Information on using Microsoft® DirectInput® is presented in the following sections. Use this page to guide you through the documentation based on your level of experience as a DirectInput developer.

What's New in DirectInput. Summary of features new to this version of Microsoft® DirectX®. Read this section if you've used Microsoft DirectInput® before but want to take advantage of the new capabilities.

Introduction to DirectInput. High-level overview of the capabilities of DirectInput and the steps you'll take to implement it. Start with this section if you're new to DirectInput.

Understanding DirectInput. Introduction to the objects and interfaces of DirectInput and how they are related to the Microsoft Windows® message system. Read this section if you're new to DirectInput.

Using DirectInput. Guide to the application programming interface (API). This section contains more detailed conceptual information than the previous two sections, as well as information about the API elements you'll use for setting up devices, retrieving data, and implementing force-feedback effects. If you're a novice, at least familiarize yourself with the contents of this section. Later, you can refer to topics as you need them. Use this section in conjunction with the DirectInput C/C++ Reference.

Programming Tips and Tools. Advanced programming topics and a guide to the DirectInput tools provided with the DirectX software development kit (SDK).

DirectInput C/C++ Tutorials. Step-by-step tutorials, often based on samples in the SDK. If you learn best from sample code, this is a good place to start after reading Introduction to DirectInput and Understanding DirectInput.

DirectInput C/C++ Samples. A guide to the DirectInput C/C++ samples included in the SDK, illustrating the use and capabilities of DirectInput.

DirectInput C/C++ Reference

Reference information for the API. Use this section when you need to know the details of an interface, method, structure, macro, or other element.


What's New in DirectInput

The following are some of the new features in Microsoft® DirectInput®.

Action mapping
Microsoft DirectInput for Microsoft DirectX® 8.0 introduces a major new feature: action mapping. Action mapping enables you to establish a connection between input actions and input devices that does not depend on the existence of particular device objects (such as specific buttons or axes). Action mapping simplifies the input loop and reduces the need for custom game drivers, custom device profilers, and custom configuration user interfaces in games.

For more information, see Action Mapping.

New DirectInput object features
The DirectInput object is now represented by the IDirectInput8 interface. A new helper function, DirectInput8Create, creates the object and retrieves this interface. IDirectInput8 has a new CLSID and cannot be obtained by calling QueryInterface on an interface to objects of the class CLSID_DirectInput used in earlier DirectX versions.
New keyboard properties
Two keyboard properties have been added: DIPROP_KEYNAME, which retrieves a localized key name, and DIPROP_SCANCODE, which retrieves the scan code.
Joystick slider data in rglSlider array
Joystick slider data which was assigned to the Z axis of a DIJOYSTATE or DIJOYSTATE2 structure under earlier DirectX versions will now be found in the rglSlider array of those same structures.


Introduction to DirectInput

Microsoft® DirectInput® is an API for input devices including the mouse, keyboard, joystick, and other game controllers, as well as for force-feedback (input/output) devices.

This section provides a brief overview of the capabilities of DirectInput and how to set it up in an application. Information is contained in the following topics.

  • The Power of DirectInput
  • Getting Started with DirectInput

For a more comprehensive view of how DirectInput works, see Understanding DirectInput.

For a step-by-step guide to using the DirectInput application programming interface (API), see the following topics.

  • Using DirectInput
  • DirectInput C/C++ Tutorials


The Power of DirectInput

Apart from providing services for devices not supported by the Microsoft® Win32® API, Microsoft DirectInput® gives faster access to input data by communicating directly with the hardware drivers rather than relying on Microsoft Windows® messages.

DirectInput enables an application to retrieve data from input devices even when the application is in the background. It also provides full support for any type of input device, as well as for force feedback.

Through action mapping, applications can retrieve input data without needing to know what kind of device is being used to generate it.

The extended services and improved performance of DirectInput make it a valuable tool for games, simulations, and other real-time interactive applications running under Windows.

DirectInput does not provide any advantages for applications that use the keyboard for text entry or the mouse for navigation. For more information, see Interaction with Windows.


Getting Started with DirectInput

This topic is an overview of what is involved in setting up and using Microsoft® DirectInput® in a simple application.

For details and examples of these steps, see Using DirectInput and DirectInput C/C++ Tutorials.

Note To understand DirectInput, it is essential to understand the following terms.

  • DirectInput object: The root DirectInput interface.
  • Device: A keyboard, mouse, joystick, or other input device.
  • DirectInputDevice object: Code representing a keyboard, mouse, joystick, or other input device.
  • Device object: Code representing a key, button, trigger, and so on found on a DirectInput device object. Also called device object instance.

The following steps represent a simple implementation of DirectInput in which the application takes responsibility for ascertaining what device object (button, axis, and so on) generated each item of data.

  1. Create the DirectInput object. You use methods of this object to enumerate devices and create DirectInput device objects.
  2. Enumerate devices. This is not an essential step if you intend to use only the system mouse or keyboard. To ascertain what other input devices are available on the user's system, have DirectInput enumerate them. Each time DirectInput finds a device that matches the criteria you set, it gives you the opportunity to examine the device's capabilities. It also retrieves a unique identifier that you can use to create a DirectInput device object representing the device.
  3. Create a DirectInputDevice object for each device you want to use. To do this, you need the unique identifier retrieved during enumeration. For the system mouse or keyboard, you can use a standard GUID.
  4. Set up the device. For each device, first set the cooperative level, which determines the way the device is shared with other applications or the system. You must also set the data format used for identifying device objects, such as buttons and axes, within data packets. If you intend to retrieve buffered data—that is, events rather than states—you also need to set a buffer size. Optionally, at this stage you can retrieve information about the device and tailor the application's behavior accordingly. You can also set properties such as the range of values returned by joystick axes.
  5. Acquire the device. At this stage you tell DirectInput that you are ready to receive data from the device.
  6. Retrieve data. At regular intervals, typically on each pass through the message loop or rendering loop, get either the current state of each device or a record of events that have taken place since the last retrieval. If you prefer, you can have DirectInput notify you whenever an event occurs.
  7. Act on the data. The application can respond either to the state of buttons and axes or to events such as a key being pressed or released.
  8. Close DirectInput. Before exiting, your application should unacquire all devices and release them, then release the DirectInput object.

This is not the only approach to implementing DirectInput. To take advantage of the great variety of input devices available now and in the future, and to simplify configuration for the user, you can use action mapping.

By setting an action map for a device, you let DirectInput decide which device object to use for each application action. For example, instead of specifying that the throttle in your racing game must always be controlled by the y-axis, you can create an action called AXIS_THROTTLE and have DirectInput assign that action to the most appropriate axis available on the device. When you retrieve events, you identify them by their associated actions rather than by the device objects that generated them.

For more information, see Action Mapping.


Understanding DirectInput

This section covers the underlying structure of Microsoft® DirectInput® and its relationship to the Microsoft Windows® message system.

  • DirectInput Objects
  • Interaction with Windows

For practical information on how to implement the elements of DirectInput introduced here, see Using DirectInput.


DirectInput Objects

An input-only Microsoft® DirectInput® implementation consists of the DirectInput object, which supports the IDirectInput8 COM interface, and a DirectInputDevice object for each input device that provides data. Each DirectInputDevice object in turn has device objects, which are individual controls or switches such as keys, buttons, or axes. Device objects are also called device object instances.

Each DirectInputDevice object represents one input device, such as a mouse, keyboard, or joystick. In the DirectInput API, the word joystick means any type of input device other than a mouse or keyboard. A piece of hardware that is really a combination of different types of input devices, such as a keyboard with a touchpad, can be represented by two or more DirectInputDevice objects. A force-feedback device is represented by a single joystick object that handles both input and output.

DirectInputDevice objects instantiate the IDirectInputDevice8 interface. The application ascertains the number and type of device objects available by using the IDirectInputDevice8::EnumObjects method. Individual device objects are not encapsulated as code objects, but are described in DIDEVICEOBJECTINSTANCE structures.

Force-feedback effects are represented by the IDirectInputEffect interface. Methods of this interface are used to create, modify, start, and stop effects.

All DirectInput interfaces are available in ANSI and Unicode versions. If "UNICODE" is defined during compilation, the Unicode versions are used.


Interaction with Windows

Because Microsoft® DirectInput® works directly with the device drivers, it either suppresses or ignores Microsoft Windows® mouse and keyboard messages. It also ignores mouse and keyboard settings made by the user in Control Panel. It does, however, use the calibrations set for a joystick or other game controller.

DirectInput does not recognize keyboard character repeat settings. When using buffered data, DirectInput interprets each press and release as a single event with no repetition. When using immediate data, DirectInput is concerned only with the present physical state of the keys, not with keyboard events as interpreted by Windows.

DirectInput does not perform any character conversion or translation. For example, the SHIFT key is treated like any other key, not as a modifier of another keypress. Keys return the same identifiers regardless of the user's system language settings.

Under Windows 2000, acquiring the keyboard in exclusive mode prevents any applications that are subsequently launched from receiving keyboard data.

Because DirectInput works directly with the mouse driver, it bypasses the subsystem of Windows that interprets mouse data for windowed applications. Applications that rely on the Windows cursor for navigation should continue to use the standard Windows mouse messages and Microsoft® Win32® functions.

When using the system mouse in exclusive mode, DirectInput suppresses mouse messages, and therefore Windows is unable to show the standard cursor.

DirectInput ignores Control Panel settings such as acceleration and swapped buttons. However, DirectInput recognizes settings in the driver itself. For example, if the user has a three-button mouse and uses the driver-utility software to make the middle button a double-click shortcut, DirectInput reports a click of the middle button as two clicks of the primary button.


Using DirectInput

This section is a guide to implementing Microsoft® DirectInput®. For a broader overview, see Understanding DirectInput.

The following topics are discussed.

  • Creating DirectInput
  • DirectInput Device Enumeration
  • DirectInput Devices
  • DirectInput Device Data
  • Action Mapping
  • Force Feedback


Creating DirectInput

The first step in any Microsoft® DirectInput® application is obtaining the IDirectInput8 interface. You can do this most easily by calling the DirectInput8Create function.

You should create a single Microsoft® DirectInput object and not release it until the application terminates.


DirectInput Device Enumeration

Microsoft® DirectInput® can query the system for all available input devices, determine whether they are connected, and return information about them. This process is called enumeration.

If your application is using only the standard keyboard or mouse, or both, you do not need to enumerate the available input devices. As explained under Creating a DirectInput Device, you can use predefined global variables when calling the IDirectInput8::CreateDevice method.

For all other input devices, and for systems with multiple keyboards or mouse devices, call IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics to enumerate available devices and find one that is suitable. You might also want to enumerate in order to give the user a choice of available devices.

The following is a sample implementation of the IDirectInput8::EnumDevices method:

/* lpdi is a valid IDirectInput8 interface pointer. */

GUID KeyboardGUID = GUID_SysKeyboard;

lpdi->EnumDevices(DIDEVTYPE_KEYBOARD,
                  DIEnumDevicesCallback,
                  &KeyboardGUID,
                  DIEDFL_ATTACHEDONLY);

The first parameter determines what types of devices are to be enumerated. It is NULL if you want to enumerate all devices, regardless of type; otherwise it is one of the DIDEVTYPE_* values described in DIDEVICEINSTANCE.

The second parameter is a pointer to a callback function to be called once for each device enumerated. This function can be declared by any name; the documentation uses the placeholder name DIEnumDevicesCallback.

The third parameter to the EnumDevices method is any 32-bit value that you want to pass into the callback function. In this example, it is a pointer to a variable of type GUID, passed in so that the callback can assign a keyboard instance identifier to this variable.

The fourth parameter is a flag to request enumeration of either all devices or only those that are attached (DIEDFL_ALLDEVICES or DIEDFL_ATTACHEDONLY).

If your application is using more than one input device, the callback function is a good place to initialize each device as it is enumerated. (For an example, see Tutorial 3: Using the Joystick.) You obtain the instance GUID of the device from the callback function. You can also perform other processing here, such as looking for particular subtypes of devices or adding the device name to a list box.

The following sample callback function checks for the presence of an enhanced keyboard and stops the enumeration as soon as it finds one. It assigns the instance GUID of the last keyboard found to the KeyboardGUID variable (the address of which was passed in the pvRef variable by the call to EnumDevices in the previous example), which can then be passed to IDirectInput8::CreateDevice.

BOOL  hasEnhanced;

BOOL CALLBACK DIEnumKbdCallback(LPCDIDEVICEINSTANCE lpddi,
                                LPVOID pvRef)
{
  *(GUID*) pvRef = lpddi->guidInstance;
  if (GET_DIDEVICE_SUBTYPE(lpddi->dwDevType) ==
                       DIDEVTYPEKEYBOARD_PCENH)
  {
    hasEnhanced = TRUE;
    return DIENUM_STOP;
  }
  return DIENUM_CONTINUE;
} // End of callback

The first parameter points to a DIDEVICEINSTANCE structure containing information about the device. This structure is created by DirectInput.

The second parameter points to data passed in from EnumDevices. In this case, it is a pointer to the variable KeyboardGUID. This variable was assigned a default value earlier, but it is given a new value each time a device is enumerated. It is not important what instance GUID you use for a single keyboard, but the code does illustrate a technique for retrieving an instance GUID from the callback.

Rather than saving the instance GUID so that you can create the DirectInputDevice later, you can save the device created by DirectInput during enumeration. For more information, see Creating a DirectInput Device.

The return value in the example indicates that enumeration is to stop if the sought-for device has been found, or continue otherwise. Enumeration automatically stops as soon as all devices have been enumerated.

For more information on enumerating devices by using IDirectInput8::EnumDevicesBySemantics, see Action Mapping.


DirectInput Devices

This section contains information about the code objects that represent devices such as a mouse, keyboards, or joysticks. The following topics are covered:

  • Device Setup
  • Creating a DirectInput Device
  • Device Capabilities
  • Cooperative Levels
  • Device Object Enumeration
  • Device Data Formats
  • Device Properties
  • Acquiring Devices

For information on how to retrieve and interpret data from devices, see DirectInput Device Data.


Device Setup

Your application must obtain a Microsoft® DirectInput® device object for each device from which it expects input. It must also prepare each device for use, which requires, at the very least, setting the data format and acquiring the device. You might also want to carry out other preparatory tasks such as getting information about the devices and changing their properties.

The following tasks are part of the setup process. Certain steps are always required. Other steps may be necessary if you need further information about devices or need to change default values.

  1. Create the DirectInput device (required). See Creating a DirectInput Device.
  2. Get the device capabilities (optional).
  3. Enumerate the keys, buttons, and axes on the device (optional). See Device Object Enumeration.
  4. Set the cooperative level (highly recommended).
  5. Set the data format (required).
  6. Set the device properties (you must at least set the buffer size if you intend to get buffered data).
  7. When ready to read data, acquire the device (required). See Acquiring Devices.


Creating a DirectInput Device

To get input data from a device, you first have to create an object to represent that device.

The IDirectInput8::CreateDevice method is used to obtain a pointer to the IDirectInputDevice8 interface. Methods of this interface are then used to manipulate the device and obtain data.

The following code example, where lpdi is a pointer to the IDirectInput8 interface, creates a keyboard device:

LPDIRECTINPUTDEVICE8  lpdiKeyboard;
lpdi->CreateDevice(GUID_SysKeyboard, &lpdiKeyboard, NULL);

The first parameter in CreateDevice is an instance GUID that identifies the instance of the device for which the interface is to be created. Microsoft® DirectInput® has two predefined GUIDs, GUID_SysMouse and GUID_SysKeyboard, which represent the system mouse and keyboard. You can pass one of these identifiers into the CreateDevice method. The global variable GUID_Joystick should not be used as a parameter for CreateDevice because it is a product GUID, not an instance GUID.

Note If the computer has more than one mouse, input from all of them is combined to form the system device. The same is true for multiple keyboards.

DirectInput provides four other predefined GUIDs primarily for testing.

• GUID_SysKeyboardEm

• GUID_SysKeyboardEm2

• GUID_SysMouseEm

• GUID_SysMouseEm2.

Passing one of these GUIDs to CreateDevice grants access to the system keyboard or mouse through an emulation layer, at either level 1 or level 2. These GUIDs always represent the system mouse or keyboard. They are aliases for GUID_SysKeyboard and GUID_SysMouse, so they are not enumerated by IDirectInput8::EnumDevices or IDirectInput8::EnumDevicesBySemantics unless the DIEDFL_INCLUDEALIASES flag is passed.

For devices other than the system mouse or keyboard, use the instance GUID for the device returned by EnumDevices or EnumDevicesBySemantics. The instance GUID for a device is always the same. You can allow the user to select a device from a list of those enumerated, then save the GUID to a configuration file and use it again in future sessions.


Device Capabilities

Before you begin asking for input from a device, you need to know something about its capabilities. Does the joystick have a point-of-view hat? Is the mouse currently attached to the user's computer?

Such questions are answered with a call to the IDirectInputDevice8::GetCapabilities method, which returns the data in a DIDEVCAPS structure. As with other such structures in Microsoft® DirectX®, you must initialize the dwSize member before passing this structure to the method.

Note To optimize speed or memory usage, you can use the smaller DIDEVCAPS_DX3 structure instead. For structure details, see Dinput.h in the Microsoft Software Development Kit (SDK).

The following code example checks whether the mouse is attached and whether it has a third axis (presumably a wheel). Assume that lpdiMouse is a valid Microsoft DirectInput® device.

DIDEVCAPS  DIMouseCaps;
HRESULT    hr;
BOOLEAN    WheelAvailable;

DIMouseCaps.dwSize = sizeof(DIDEVCAPS);
hr = lpdiMouse->GetCapabilities(&DIMouseCaps);
WheelAvailable = ((DIMouseCaps.dwFlags & DIDC_ATTACHED)
        && (DIMouseCaps.dwAxes > 2));

Another way to check for a button or axis is to call IDirectInputDevice8::GetObjectInfo for that object. If the call returns DIERR_OBJECTNOTFOUND, the object is not present. The following code determines whether there is a z-axis, even if it is not the third axis:

DIDEVICEOBJECTINSTANCE  didoi;

didoi.dwSize = sizeof(DIDEVICEOBJECTINSTANCE);
hr = lpdiMouse->GetObjectInfo(&didoi, DIMOFS_Z, DIPH_BYOFFSET);
WheelAvailable = SUCCEEDED(hr);


Cooperative Levels

The cooperative level of a device determines how the input is shared with other applications and with the Microsoft® Windows® system. You set it by using the IDirectInputDevice8::SetCooperativeLevel method, as in the following code example:

/* hwnd is the top-level window handle. */
lpdiDevice->SetCooperativeLevel(hwnd,
        DISCL_NONEXCLUSIVE | DISCL_FOREGROUND)

The parameters are the handle to the top-level window associated with the device (generally the application window) and one or more flags.

Although DirectInput provides a default setting, you should still explicitly set the cooperative level because this is the only way to give DirectInput the window handle. Without this handle, DirectInput cannot react to situations that involve window messages, such as joystick recalibration.

The valid flag combinations are shown in the following table.

Flags | Notes
DISCL_NONEXCLUSIVE DISCL_BACKGROUND | The default setting
DISCL_NONEXCLUSIVE DISCL_FOREGROUND |
DISCL_EXCLUSIVE DISCL_FOREGROUND |
DISCL_EXCLUSIVE DISCL_BACKGROUND | Not valid for keyboard or mouse

For the keyboard, you can also include DISCL_NOWINKEY in combination with DISCL_NONEXCLUSIVE. This flag disables the Windows logo key so that users cannot inadvertently break out of the application. In exclusive mode, the Windows logo key is always disabled.

Note Even if the cooperative level for the application is disabling the Windows logo key passively through an exclusive cooperative level, or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping UI is displayed.

The cooperative level has two main components: whether the device is being used in the foreground or the background, and whether it is being used exclusively or nonexclusively.

Foreground vs. Background

A foreground cooperative level means that the input device is available only when the application is in the foreground or, in other words, has the input focus. If the application moves to the background, the device is automatically unacquired, or made unavailable.

A background cooperative level really means foreground and background. A device with a background cooperative level can be acquired and used by an application at any time.

You will usually want to have foreground access only because most applications are not designed to respond to input that takes place when another program is in the foreground.

While developing an application, it is useful to employ conditional compilation so that the background cooperative level is always set for debugging. This prevents your application from losing access to the device every time it moves to the background as you switch to the debugging environment.

Exclusive vs. Nonexclusive

In most cases, the fact that your application is using a device at the exclusive level does not mean that other applications cannot get data from the device. However, it does mean that no other application can also acquire the device exclusively.

Consider the example of a music player that accepts input from a hand-held remote-control device, even when the application is running in the background. Now suppose you run a similar application that plays movies in response to signals from the same remote control. What happens when the user presses Play? Both programs start playing, which is probably not what the user wants. To prevent this from happening, each application should have the DISCL_EXCLUSIVE flag set so that only one of them can be running at a time.

To use force-feedback effects, an application must have exclusive access to the device.

Windows itself requires exclusive access to the system mouse. The reason is that system mouse events such as a click on an inactive window could force an application to unacquire the device, with potentially harmful results such as a loss of data from the input buffer. So when an application has exclusive access to the system mouse, created by passing GUID_SysMouse to IDirectInput8::CreateDevice, Windows is not allowed any access and no mouse messages are generated. A further side effect is that the cursor disappears.

When an application has exclusive access to the keyboard, DirectInput suppresses all keyboard messages except CTRL+ALT+DEL and, on Windows 95 and Windows 98, ALT+TAB. Under Windows 2000, no application launched subsequently to the exclusive-mode DirectInput application can get keyboard data.


Device Object Enumeration

It might be necessary for your application to determine what buttons or axes are available on a given device. To do this, you enumerate the device objects in much the same way as you enumerate devices.

Note Because of limitations imposed by device drivers, enumeration of keyboard keys and indicator lights is not reliable. Objects might falsely be reported as present. You can get basic information about available keys from the device subtype, but there is no way to determine whether extra objects such as the menu key are available, other than asking the user for input.

To some extent, IDirectInputDevice8::EnumObjects overlaps the functionality of IDirectInputDevice8::GetCapabilities. Either method can be used to determine how many buttons or axes are available. However, EnumObjects is intended for cataloging all the available objects rather than checking for a particular one.

Like IDirectInput8::EnumDevices, the EnumObjects method has a callback function that enables you to do other processing on each object—for example, adding it to a list or creating a corresponding element on a user interface.

The following sample callback simply extracts the name of each object so that it can be added to a string list or array. This standard callback is documented under the placeholder name DIEnumDeviceObjectsCallback, but you can give it any name you like. Remember, this function is called once for each object enumerated.

char  szName[MAX_PATH];

BOOL CALLBACK DIEnumDeviceObjectsCallback(
                      LPCDIDEVICEOBJECTINSTANCE lpddoi,
                      LPVOID pvRef)
{
  lstrcpy(szName, lpddoi->tszName);
  // Now add szName to a list or array.
  .
  .
  .
  return DIENUM_CONTINUE;
}

The first parameter points to a structure containing information about the object. This structure is created for you by Microsoft® DirectInput®.

The second parameter is an application-defined pointer to data, equivalent to the second parameter to EnumObjects. In the example, this parameter is not used.

The return value in this case indicates that enumeration is to continue as long as there are objects to be enumerated.

Now here's the call to the EnumObjects method, which puts the callback function to work.

lpdiMouse->EnumObjects(DIEnumDeviceObjectsCallback,
                       NULL, DIDFT_ALL);

The first parameter is the address of the callback function. The second parameter can be a pointer to any data you want to use or modify in the callback. The example does not use this parameter and so passes NULL. The third parameter is a flag to indicate which type or types of objects are to be included in the enumeration. In the example, all objects are to be enumerated. To restrict the enumeration, you can use one or more of the other DIDFT_* flags listed at IDirectInputDevice8::EnumObjects.

Note Some of the DIDFT_* flags are combinations of others; for example, DIDFT_AXIS is equivalent to DIDFT_ABSAXIS | DIDFT_RELAXIS.


Device Data Formats

If you are not using Action Mapping, setting the data format for a device is an essential step before you can acquire and begin using the device. This is true even if you do not intend to retrieve immediate (state) data from the device. Microsoft® DirectInput® uses the data format in many methods to identify particular device objects.

The IDirectInputDevice8::SetDataFormat method tells DirectInput what device objects will be used and how the data will be arranged.

The examples in the reference for the DIDATAFORMAT and DIOBJECTDATAFORMAT structures show how to set up custom data formats for nonstandard devices. Fortunately, this step is not necessary for the joystick, keyboard, and mouse. DirectInput provides five global variables, c_dfDIJoystick, c_dfDIJoystick2, c_dfDIKeyboard, c_dfDIMouse, and c_dfDIMouse2, which can be passed in to SetDataFormat to create a standard data format for these devices.

In the following code example, lpdiMouse is an initialized pointer to a DirectInputDevice object:

lpdiMouse->SetDataFormat(&c_dfDIMouse);

Note You cannot change the dwFlags member in the predefined DIDATAFORMAT global variables (for example, to change the property of an axis), because they are const variables. To change properties, use the IDirectInputDevice8::SetProperty method after setting the data format, but before acquiring the device.


Device Properties

Properties of Microsoft® DirectInput® devices include the size of the data buffer, the range and granularity of values returned from an axis, whether axis data is relative or absolute, and the dead zone and saturation values for a joystick axis. Specialized devices can have other properties as well. For a list of properties defined by DirectInput, see IDirectInputDevice8::GetProperty.

With one exception—the gain property of a force-feedback device—properties can be changed only when the device is in an unacquired state.

Before calling the IDirectInputDevice8::SetProperty or the IDirectInputDevice8::GetProperty method you must set up a property structure that consists of a DIPROPHEADER structure and one or more elements for data. There is potentially a great variety of properties for input devices, and SetProperty must be able to work with all sorts of structures defining those properties. The purpose of the DIPROPHEADER structure is to define the size of the property structure and how the data is to be interpreted.

DirectInput includes the following predefined property structures:

  • DIPROPDWORD defines a structure containing a DIPROPHEADER and a DWORD data member for properties that require a single value, such as a buffer size.
  • DIPROPRANGE is for range properties, which require two values (maximum and minimum). It consists of a DIPROPHEADER and two LONG data members.
  • DIPROPGUIDANDPATH is a specialized property structure enabling applications to perform operations on a Human Interface Device (HID) that are not supported by DirectInput. The structure consists of a DIPROPHEADER, a GUID, and a Unicode string for the path.
  • DIPROPSTRING is for Unicode string properties. The structure comprises a DIPROPHEADER and a Unicode string.

For SetProperty, the data members of the property structure are the values that you want to set. For GetProperty, the current value is returned in these members.

Before the call to GetProperty or SetProperty, the DIPROPHEADER structure must be initialized with the following:

  • The size of the property structure.
  • The size of the DIPROPHEADER structure itself.
  • An object identifier.
  • A value indicating how the object identifier should be interpreted.

When getting or setting properties for a whole device, the object identifier dwObj is 0, and the dwHow member is DIPH_DEVICE. If you want to get or set properties for a device object (for example, a particular axis), the combination of dwObj and dwHow values identifies the object. For details, see DIPROPHEADER.

After setting up the property structure, pass the address of its header into GetProperty or SetProperty, along with an identifier for the property that you want to obtain or change.

The following values are used to identify the property passed to SetProperty and GetProperty. For more information, see IDirectInputDevice8::GetProperty.

  • DIPROP_BUFFERSIZE. See also Buffered and Immediate Data. The buffer size can also be set by using the IDirectInputDevice8::SetActionMap method.
  • DIPROP_AXISMODE. See also Relative and Absolute Axis Coordinates.
  • DIPROP_CALIBRATIONMODE
  • DIPROP_GRANULARITY
  • DIPROP_FFGAIN
  • DIPROP_FFLOAD
  • DIPROP_AUTOCENTER
  • DIPROP_RANGE
  • DIPROP_DEADZONE
  • DIPROP_SATURATION

For more information about the last three properties, see also Interpreting Joystick Axis Data.

The following code example sets the buffer size for a device to hold up to 10 data items:

DIPROPDWORD  dipdw;
HRESULT      hr;
dipdw.diph.dwSize = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj = 0;
dipdw.diph.dwHow = DIPH_DEVICE;
dipdw.dwData = 10;
hr = lpdiDevice->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);


Acquiring Devices

Acquiring a Microsoft® DirectInput® device means giving your application access to it. As long as a device is acquired, DirectInput is making its data available to your application. If the device is not acquired, you can manipulate its characteristics but not obtain any data.

Acquisition is not permanent. Your application might acquire and unacquire a device many times.

In certain cases, depending on the cooperative level, a device is unacquired automatically whenever the application moves to the background. The mouse is automatically unacquired when the user clicks a menu, because at this point Microsoft Windows® assumes control of the device.

You must unacquire a device before changing its properties. The only exception is that you can change the gain for a force-feedback device while it is in an acquired state.

The acquisition mechanism is needed for two reasons:

First, DirectInput must be able to tell the application when the flow of data from the device has been interrupted by the system. For instance, if the user has switched to another application with ALT+TAB and has used the input device in that application, your application needs to know that the input no longer belongs to it and that the state of the buffers might have changed. Or consider an application with the DISCL_FOREGROUND cooperative level. The user holds down the SHIFT key and switches to another application. Then the user releases the key and switches back to the first application. As far as the first application is concerned, the SHIFT key is still down. The acquisition mechanism, by telling the application that input was lost, enables it to recover from these conditions.

Second, because your application can alter the properties of the device, without safeguards DirectInput would have to check the properties each time you wanted to retrieve data. This would be very inefficient. Even worse, a potential disaster could happen such as a hardware interrupt accessing a data buffer just as you were changing the buffer size. Therefore DirectInput requires your application to unacquire the device before changing properties. When you reacquire it, DirectInput checks the properties and decides on the optimal way of transferring data from the device to the application. This is done only once, so the data retrieval methods can be very fast.

Because the most common cause of losing a device is that your application moves to the background, you may want to reacquire devices whenever your application is activated. Be careful, though, about relying on a WM_ACTIVATE handler at startup time. The first WM_ACTIVATE message will likely arrive when your window is being initialized before DirectInput has been set up. To ensure that the device is acquired at startup, call IDirectInputDevice8::Acquire as soon as the device has been initialized.

Even acquiring the device on activation of your program window might not cover all cases in which a device is unacquired, especially for devices other than the standard mouse or keyboard. Because your application might unacquire a device unexpectedly, you need a mechanism for checking the acquisition state before attempting to get data from the device. The Scrawl Sample does this in the OnMouseInput function, in which a DIERR_INPUTLOST error triggers a message to reacquire the mouse. (See also Tutorial 2: Using the Mouse.)

Attempting to reacquire a device that is already acquired does no harm. Redundant calls to Acquire are ignored, and the device can always be unacquired with a single call to Unacquire.

Windows does not have access to the mouse when your application is using it in exclusive mode. If you want Windows to acquire the mouse, you must release it. The Scrawl Sample responds to a right-click by unacquiring the mouse, putting the Windows cursor in the same spot as its own, displaying a shortcut menu, and letting Windows handle the input until a menu choice is made.


DirectInput Device Data

This section covers the following basic concepts of getting data from Microsoft® DirectInput® devices.

  • Buffered and Immediate Data
  • Time Stamps and Sequence Numbers
  • Polling and Event Notification
  • Relative and Absolute Axis Coordinates

The following topics describe specific details about output data and mouse, keyboard, and joystick input data.

  • Mouse Data
  • Keyboard Data
  • Joystick Data
  • Output Data

DirectInput provides two mechanisms for identifying data retrieved from devices. Using the traditional mechanism, the application identifies the data as coming from a particular device object, such as a the x-axis on a mouse or the F1 key on a keyboard. With the newer system, available for the first time in Microsoft DirectX® 8.0, DirectInput associates application-defined values (for instance, identifiers for particular game actions such as moving or shooting) with the most suitable device objects available. When data is retrieved, the application does not concern itself with the actual device or device object from which the data comes. It acts only on the meaning of that data.

Most of the information in this section applies to both mechanisms. For more information on the newer way of identifying device data, see Action Mapping.


Buffered and Immediate Data

Microsoft® DirectInput® supplies two types of data: buffered and immediate. Buffered data is a record of events that are stored until an application retrieves them. Immediate data is a snapshot of the current state of a device.

You might use immediate data in an application that is concerned only with the current state of a device—for example, a flight combat simulation that responds to the current position of the joystick and the state of one or more buttons. Buffered data might be the better choice where events are more important than states—for example, in an application that responds to movement of the mouse and button clicks. You can also use both types of data, as you might, for example, if you wanted to get immediate data for joystick axes but buffered data for the buttons.

Note If you are using Action Mapping, you will want to retrieve buffered data because the buffered data packets contain the application-defined data associated with the input. Doing so means that you are responsible for tracking the position of absolute axes, since events but not states are reported in buffered data packets.

An application retrieves immediate data by calling the IDirectInputDevice8::GetDeviceState method. As the name implies, this method returns the current state of the device—for example, whether each button is up or down. The method provides no data about what has happened with the device since the last call, apart from implicit information that you can derive by comparing the current state with the last one. For example, if a user presses and releases a button between two calls to GetDeviceState, your application will never be given this input. On the other hand, if the user is holding a button down, GetDeviceState continues reporting that fact until the user releases it.

This way of reporting the device state is different from the way Microsoft Windows® reports events with one-time messages such as WM_LBUTTONDOWN. It is more like the results from the Microsoft Win32® GetKeyboardState function. If you are polling a device with GetDeviceState, you are responsible for determining what constitutes a button click, a double-click, a single keystroke, and so on, and for ensuring that your application does not keep responding to a button-down or key-down state when it's not appropriate to do so.

With buffered data, events are stored until you are ready to deal with them. Every time a button or key is pressed or an axis is moved, information about the event is placed in a DIDEVICEOBJECTDATA structure in the buffer. If the buffer overflows, new data is lost. Your application reads the buffer with a call to IDirectInputDevice8::GetDeviceData. You can read any number of items at a time.

Reading an item normally deletes it from the buffer, but you also have the choice of peeking without deleting.

To get buffered data, you must first set the buffer size with the IDirectInputDevice8::SetProperty or IDirectInputDevice8::SetActionMap method. (See the example under Device Properties.) Set the buffer size before acquiring the device for the first time. For reasons of efficiency, the default size of the buffer is 0, and you cannot obtain buffered data unless you change this value. The size of the buffer is measured in items of data for that type of device, not in bytes.

Check the value of the pdwInOut parameter after a call to the GetDeviceData method. The number of items retrieved from the buffer is returned in this variable.

Note For devices that do not generate interrupts, such as analog joysticks, DirectInput does not obtain any data until you call the IDirectInputDevice8::Poll method. For more information, see Polling and Event Notification.

For examples of retrieving buffered data, see IDirectInputDevice8::GetDeviceData.

See also:

  • Time Stamps and Sequence Numbers
  • Mouse Data
  • Keyboard Data
  • Joystick Data


Time Stamps and Sequence Numbers

When Microsoft® DirectInput® input data is buffered (see Buffered and Immediate Data), each DIDEVICEOBJECTDATA structure contains not only information about the type of event and the device object associated with it. It also contains a time stamp and a sequence number.

The dwTimeStamp member contains the system time, in milliseconds, at which the event took place. This is equivalent to the value that would have been returned by the Microsoft Win32® GetTickCount function, but at a higher resolution.

The dwSequence member contains a sequence number assigned by DirectInput. The DirectInput system keeps a single sequence counter, which is incremented by each buffered event from any device. (Simultaneous events on the same device, such as diagonal mouse movements, increment the count only once.) Use this number to compare events from different devices and see which came first. The DISEQUENCE_COMPARE macro, used for comparing DirectInput sequence numbers, takes wraparound into account.

Note Events are always placed in the buffer in chronological order, so you don't need to check the sequence numbers to sort the events from a single device.


Polling and Event Notification

There are two ways to find out whether input data is available: polling and event notification.

Polling a device means regularly getting the current state of the device objects or checking the contents of the event buffer. Polling is typically used by real-time games that are never idle, but instead are constantly updating and rendering the game world.

Polling

In a C++ application, polling would typically be done within the message loop.

Some joysticks and other game devices, or particular objects on them, do not generate hardware interrupts and do not return any data or signal any events until you call the IDirectInputDevice8::Poll method. (This behind-the-scenes polling is not to be confused with the kind of application polling just discussed. Poll does not retrieve any data, but merely makes data available.)

To find out whether it is necessary to call Poll each time you want to retrieve data, first set the data format for the device, then call the IDirectInputDevice8::GetCapabilities method and check for the DIDC_POLLEDDATAFORMAT flag in the DIDEVCAPS structure.

Do not confuse the DIDC_POLLEDDATAFORMAT flag with the DIDC_POLLEDDEVICE flag. The latter is set if any object on the device requires polling, regardless of data format. You can then find out whether this is the case for a particular object by calling the IDirectInputDevice8::GetObjectInfo method and checking for the DIDOI_POLLED flag in the DIDEVICEOBJECTINSTANCE structure.

The DIDC_POLLEDDEVICE flag describes the worst case for the device, not the actual situation. For example, a Human Interface Device (HID) mouse with software-controllable resolution might be marked as DIDC_POLLEDDEVICE because reading the resolution information requires polling. If you want to retrieve only the standard button and axis data, polling the device under these conditions is not necessary. However, there is no harm in calling the IDirectInputDevice8::Poll method for any input device. If the call is unnecessary, it has no effect and is very fast.

Event Notification

Event notification is suitable for applications such as the Scrawl Sample that wait for input before doing anything.

To use event notification, set up a thread-synchronization object with the Microsoft® Win32® CreateEvent function, and then associate this event with the device by passing its handle to the IDirectInputDevice8::SetEventNotification method. The event is then signaled by Microsoft DirectInput® whenever the state of the device changes. Your application can receive notification of the event with a Win32 function such as WaitForSingleObject, and then respond by checking the input buffer to find out what the event was. For code examples, see the Scrawl sample and IDirectInputDevice8::SetEventNotification.


Relative and Absolute Axis Coordinates

Axis coordinates can be returned as relative values—that is, the amount by which they have changed since the application last retrieved the device state or, in the case of buffered input, since the last item was put in the buffer.

Absolute axis coordinates are a running total of all the relative coordinates returned by the system since the device was acquired. In other words, they show the position of the axis in relation to a fixed point.

By default, mouse axes are reported as relative coordinates and joystick axes as absolute coordinates. You can change the coordinate system for a device by setting a property. For more information, see Device Properties.


Mouse Data

To set up the mouse device for data retrieval, first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIMouse or c_dfDIMouse2 global variable as the parameter value. Use c_dfDIMouse2 if you want to support more than four mouse buttons.

For maximum performance in a full-screen application, set the cooperative level to DISCL_EXCLUSIVE | DISCL_FOREGROUND. Note that the exclusive setting causes the Microsoft® Windows® cursor to disappear. The DISCL_FOREGROUND setting causes the application to lose access to the mouse when you switch to a debugging window. Changing to DISCL_BACKGROUND enables you to debug the application more easily, but at a cost in performance.

The following sections give more information about retrieval and interpretation of immediate and buffered mouse data:

  • Immediate Mouse Data
  • Buffered Mouse Data
  • Interpreting Mouse Axis Data
  • Checking for Lost Mouse Input

See Also

Device Data Formats, Cooperative Levels


Immediate Mouse Data

To retrieve the current state of the mouse, call IDirectInputDevice8::GetDeviceState with a pointer to a DIMOUSESTATE or a DIMOUSESTATE2 structure, depending on the data format. The mouse state returned in the structure includes axis data and the state of each of the buttons.

The first three members of the structure hold the axis coordinates. (See Interpreting Mouse Axis Data.)

The rgbButtons member is an array of bytes, one for each of four or eight buttons. For a traditional mouse, the first element in the array is generally the left button, the second is the right button, and the third is the middle button. The high bit is set if the button is down, and it is clear if the button is up or not present.

See also

Buffered and Immediate Data


Buffered Mouse Data

To retrieve buffered data from the mouse, you must first set the buffer size (see Device Properties). The default size of the buffer is 0, so this step is essential.

You must also declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush events in the buffer at any time by using the IDirectInputDevice8::GetDeviceData method. (See Buffered and Immediate Data.) On return, each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the mouse. For example, if the user presses button 0 and moves the mouse diagonally, the array passed to GetDeviceData (if it has at least three elements, and pdwInOut is at least 3) will have three elements filled in—an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis—and the value of pdwInOut will be set to 3.

You can determine which object an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the values returned by the following macros:

  • DIMOFS_BUTTON0 to DIMOFS_BUTTON7
  • DIMOFS_X
  • DIMOFS_Y
  • DIMOFS_Z

Each of these values is derived from the offset of the data for the object in a DIMOUSESTATE or DIMOUSESTATE2 structure. For example, DIMOFS_BUTTON0 is equivalent to the offset of rgbButtons[0] in the DIMOUSESTATE structure. DIMOFS_BUTTON4 to DIMOFS_BUTTON7 are supported only for DIMOUSESTATE2. With the macros you can use simple comparisons to determine which device object is associated with an item in the buffer. For example:

DIDEVICEOBJECTDATA  *lpdidod;
int                 n;
.
.
.
/* MouseBuffer is an array of DIDEVICEOBJECTDATA structures
   that has been set by a call to GetDeviceData.
   n is incremented in a loop that examines all filled elements
   in the array. */
lpdidod = &MouseBuffer[n];
if (( (int) lpdidod->dwOfs == DIMOFS_BUTTON0)
      && (lpdidod->dwData & 0x80))
{
 ;  // Do something in response to left button press.
}

The data for the change of state of the device object is located in the dwData member of the DIDEVICEOBJECTDATA structure. For axes, the coordinate value is returned in this member. For button objects, only the low byte of dwData is significant. The high bit of this byte is set if the button was pressed, and it is clear if the button was released. In other words, the button was pressed if (dwData & 0x80) is nonzero.

If you are using Action Mapping, ignore the value in dwOfs and instead retrieve the application-defined data associated with the event from the uAppData member.

For more information on the other members of the DIDEVICEOBJECTDATA structure, see Time Stamps and Sequence Numbers.


Interpreting Mouse Axis Data

The data returned for the x-axis and y-axis of a mouse indicates the movement of the mouse itself, not the cursor. The units of measurement are based on the values returned by the mouse hardware and have nothing to do with pixels or any other form of screen measurement. Because Microsoft® DirectInput® communicates directly with the mouse driver, the values for mouse speed and acceleration set by the user in Control Panel do not affect this data.

Axis data returned from the mouse can be either relative or absolute. (See Relative and Absolute Axis Coordinates.) Because a mouse is a relative device—unlike a joystick, it does not have a home position—relative data is returned by default.

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to absolute, call IDirectInputDevice8::SetProperty with the DIPROP_AXISMODE value in the rguidProp parameter and with DIPROPAXISMODE_ABS in the dwData member of the DIPROPDWORD structure.

When the axis mode for the mouse is set to relative, the axis coordinate represents the number of units that the device has been moved along the axis since the last value was returned. A negative value indicates that the mouse was moved to the left for the x-axis, or away from the user for the y-axis, or that the z-axis (the wheel) was rotated toward the user. Positive values indicate movement in the opposite direction.

When the axis mode is set to absolute, the coordinates are simply a running total of all relative motions received by DirectInput. The axis coordinates are not initialized to any particular value when the device is acquired, so your application should treat absolute values as relative to an unknown origin. You can record the current absolute position whenever the device is acquired and save it as the virtual origin. This virtual origin can then be subtracted from subsequent absolute coordinates retrieved from the device to compute the relative distance that the mouse has moved from the point of acquisition.

The data returned for the axis coordinates is also affected by the granularity property of the device. For the x-axis and y-axis of the mouse, granularity is normally 1. In other words, the minimum change in value is 1. For the wheel axis, it might be larger.


Checking for Lost Mouse Input

When you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application (or even to the menu in your own application), Microsoft® Windows® might force your application to unacquire the mouse. For this reason, you should check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or the IDirectInputDevice8::GetDeviceState method, and attempt to reacquire the mouse if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the mouse on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop—acquisition would again fail, you would get another DIERR_NOTACQUIRED error, and so on.


Keyboard Data

When using Microsoft® DirectInput®, consider the keyboard not as a text input device but as a game pad with many buttons. When your application requires text input, do not use DirectInput methods. It is far easier to retrieve the data from the normal Microsoft Windows® messages, which enable you take advantage of services such as character repeat and translation of physical keys to virtual keys. This is particularly important for languages other than English, which can require special translations of key presses.

To set up the keyboard device for data retrieval, you must first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIKeyboard global variable as the parameter. (See Device Data Formats.)

The following sections give more information about obtaining and interpreting keyboard data:

  • Immediate Keyboard Data
  • Buffered Keyboard Data
  • Interpreting Keyboard Data
  • Checking for Lost Keyboard Input


Immediate Keyboard Data

To retrieve the current state of the keyboard, call the IDirectInputDevice8::GetDeviceState method with a pointer to an array of 256 bytes that will hold the returned data.

The GetDeviceState method behaves in the same way as the Microsoft® Win32® GetKeyboardState function. It returns a snapshot of the current state of the keyboard. Each key is represented by a byte in the array of 256 bytes whose address was passed as the lpvData parameter. If the high bit of the byte is set, the key is down. The array is most conveniently indexed with the Microsoft® DirectInput® Keyboard Device Constants. (See also Interpreting Keyboard Data.)

The following code example calls a function in response to the ESC key being down. Assume that lpdiKeyboard is an acquired DirectInput device.

BYTE  diKeys[256];
if (lpdiKeyboard->GetDeviceState(256, diKeys) == DI_OK)
{
  if (diKeys[DIK_ESCAPE] & 0x80) DoSomething();
}


Buffered Keyboard Data

To retrieve buffered data from the keyboard, you must first set the buffer size (see Device Properties). This step is essential because the default size of the buffer is 0.

You must also declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the keyboard device, you can examine and flush the buffer at any time by using the IDirectInputDevice8::GetDeviceData method. (See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single key—that is, a press or release. Because Microsoft® DirectInput® gets the data directly from the keyboard, any settings for character repeat in Control Panel are ignored. This means that a keystroke is counted only once, no matter how long the key is held down.

You can determine which key an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the DirectInput Keyboard Device Constants. (See also Interpreting Keyboard Data.)

If you are using Action Mapping, ignore the value in dwOfs and instead retrieve the application-defined data associated with the key event from the uAppData member.

The data for the change of state of the key is located in the dwData member of the DIDEVICEOBJECTDATA structure. Only the low byte of dwData is significant. The high bit of this byte is set if the key was pressed, and it is clear if it was released. In other words, the key was pressed if (dwData & 0x80) is nonzero.


Interpreting Keyboard Data

This topic covers the identification of keys for which data is reported by the IDirectInputDevice8::GetDeviceState and IDirectInputDevice8::GetDeviceData methods. For more information on interpreting the data from GetDeviceData, see Time Stamps and Sequence Numbers.

In one important respect, Microsoft® DirectInput® applications read the keyboard differently from the way Microsoft Windows® does. For DirectInput applications, keyboard data refers not to virtual keys but to the actual physical keys—that is, the scan codes. DIK_ENTER, for example, refers only to the ENTER key on the main keyboard, not to the ENTER key on the numerical keypad.

Additionally, differences among keyboards can affect the way DirectInput applications interpret keyboard data. For example, DirectInput defines a constant for each key on the enhanced keyboard, as well as the additional keys on international keyboards. Because NEC keyboards support different scan codes than the PC-enhanced keyboards, DirectInput translates NEC key-scan codes into PC-enhanced scan codes where possible.

Other keyboard differences to consider are:

  • Not all PC-enhanced keyboards have the Windows logo keys (DIK_LWIN, DIK_RWIN, and DIK_APPS), there is no way to determine whether the keys are physically available.
  • Laptops and other small computers often do not implement a full set of keys. Instead, some keys (typically numeric keypad keys) are multiplexed with other keys, which are selected by an auxiliary mode key that does not generate a separate scan code.
  • If the keyboard subtype indicates a PC XT or PC AT keyboard, the following keys are not available: DIK_F11, DIK_F12, and all the extended keys (DIK_* values greater than 0x7F). Furthermore, the PC XT keyboard lacks DIK_SYSRQ.
  • Japanese keyboards, particularly the NEC PC-98 keyboards, contain a substantially different set of keys than U.S. keyboards. For more information, see DirectInput and Japanese Keyboards.


Checking for Lost Keyboard Input

When you have set the cooperative level to DISCL_FOREGROUND and the focus switches to another application, Microsoft® Windows® might force your application to unacquire the keyboard. For this reason, you should check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or IDirectInputDevice8::GetDeviceState methods and attempt to reacquire the keyboard, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the keyboard on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would again fail, you would get another DIERR_NOTACQUIRED error, and so on.


Joystick Data

To set up the joystick device for data retrieval, first call the IDirectInputDevice8::SetDataFormat method with the c_dfDIJoystick or the c_dfDIJoystick2 global variable as the parameter value. (See Device Data Formats.)

Because some device drivers do not notify Microsoft® DirectInput® of changes in state until explicitly asked to do so, you should always call the IDirectInputDevice8::Poll method before attempting to retrieve data from the joystick. For more information, see Polling and Event Notification.

The following sections cover retrieval and interpretation of data from a joystick or other similar input device such as a game pad or steering wheel:

  • Immediate Joystick Data
  • Buffered Joystick Data
  • Interpreting Joystick Axis Data
  • Checking for Lost Joystick Input


Immediate Joystick Data

To retrieve the current state of the joystick, call the IDirectInputDevice8::GetDeviceState method with a pointer to a DIJOYSTATE or a DIJOYSTATE2 structure, depending on whether the data format was set with c_dfDIJoystick or c_dfDIJoystick2. (See Device Data Formats.) The joystick state returned in the structure includes the coordinates of the axes, the state of the buttons, and the state of the point-of-view controllers.

The first seven members of the DIJOYSTATE structure hold the axis coordinates. The last of these seven, rglSlider, is an array of two values. (See Interpreting Joystick Axis Data.)

The rgdwPOV member contains the position of up to four point-of-view controllers in hundredths of a degree clockwise from north (or forward). The center (neutral) position is reported as –1. For controllers that have only five positions, the position is one of the following values:

  • –1
  • 0
  • 90 * DI_DEGREES
  • 180 * DI_DEGREES
  • 270 * DI_DEGREES.

Some drivers report a value of 65,535, instead of –1, for the center position. You should check for a centered POV indicator as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

The rgbButtons member is an array of bytes, one for each of 32 or 128 buttons, depending on the data format. For each button, the high bit is set if the button is down and it is clear if the button is up or not present.

The DIJOYSTATE2 structure has additional members for information about the velocity, acceleration, force, and torque of the axes.

See also

Buffered and Immediate Data


Buffered Joystick Data

To retrieve buffered data from the joystick, first set the buffer size (see Device Properties) and declare an array of DIDEVICEOBJECTDATA structures. This array can have up to the same number of elements as the buffer size. You do not have to retrieve the entire contents of the buffer with a single call. You can have just one element in the array and retrieve events one at a time until the buffer is empty.

After acquiring the device, you can examine and flush the buffer at any time with the IDirectInputDevice8::GetDeviceData method. (See Buffered and Immediate Data.)

Each element in the DIDEVICEOBJECTDATA array represents a change in state for a single object on the joystick. For instance, if the user presses button 0 and moves the stick diagonally, the array passed to GetDeviceData (if it has at least three elements, and pdwInOut is at least 3) will have three elements filled in—an element for button 0 being pressed, an element for the change in the x-axis, and an element for the change in the y-axis—and the value of pdwInOut will be set to 3.

You can determine which object an element in the array refers to by checking the dwOfs member of the DIDEVICEOBJECTDATA structure against the following values:

  • DIJOFS_X
  • DIJOFS_Y
  • DIJOFS_Z
  • DIJOFS_Rx
  • DIJOFS_Ry
  • DIJOFS_Rz
  • DIJOFS_BUTTON0 to DIJOFS_BUTTON31 or DIJOFS_BUTTON(n)
  • DIJOFS_POV(n)
  • DIJOFS_SLIDER(n)

Each of these values is equivalent to the offset of the data for the object in a DIJOYSTATE structure. For example, DIJOFS_BUTTON0 is equivalent to the offset of rgbButtons[0] in the DIJOYSTATE structure. You can use simple comparisons to determine which device object is associated with an item in the buffer. For example:

DIDEVICEOBJECTDATA  *lpdidod;
int                 n;
.
.
.
/* JoyBuffer is an array of DIDEVICEOBJECTDATA structures
   that has been set by a call to GetDeviceData.
   n is incremented in a loop that examines all filled elements
   in the array. */
lpdidod = &JoyBuffer[n];
if (( (int) lpdidod->dwOfs == DIJOFS_BUTTON0)
   && (lpdidod->dwData & 0x80))
{
 ;  // Do something in response to press of primary button.
}

If the data format was set with c_dfDIJoystick2, you can use the predefined offsets for all the device objects that exist in DIJOYSTATE, but you must supply your own offsets for device objects represented in the extra members of DIJOYSTATE2.

If you are using Action Mapping, ignore the value in dwOfs and instead retrieve the application-defined data associated with the event from the uAppData member.

The data for the change of state of the device object is located in the dwData member of the DIDEVICEOBJECTDATA structure. For axes, the coordinate value is returned in this member. For button objects, only the low byte of dwData is significant. The high bit of this byte is set if the button is pressed, and it is clear if the button is released.

For the other members, see Time Stamps and Sequence Numbers.


Interpreting Joystick Axis Data

Axis values for the joystick are like those for the mouse. The value returned for the x-axis is greater as the stick moves to the right, and the value for the y-axis increases as the stick moves toward the user.

Data is in arbitrary units determined by the range property of the axis. For example, if the range for the stick's x-axis is from 0 through 10,000, a unit is one ten-thousandth of the stick's left-right travel, and the center position is 5,000. For some axes, the granularity property might be greater than 1. In this case, values are rounded off. For example, if the granularity is 10, values are reported as 0, 10, 20, and so on.

Axis data is also affected by the dead zone, a region around the center position in which motion is ignored. The dead zone provides tolerance for a slight deviation from the true center position for either or both axes of the stick. An axis value within the range of the dead zone is reported as true center.

The saturation property of an axis is a zone of tolerance at the minimum and maximum of the range. An axis value within this zone is reported as the minimum or maximum value. The purpose of the saturation property is to allow for slight differences between, for example, the minimum x-axis value reported at the top-left and bottom-left positions of the stick.

The following illustration shows the effect of the dead zone and the saturation zones. The vertical axis represents the returned axis values, where min and max are the lower and upper limits of the reported range and ctr is the reported center. The horizontal axis shows the physical position of the stick, where pmin and pmax are the extremes of the physical range, pctr is neutral position of the axis, dmin and dmax are the limits of the dead zone, and smin and smax are the boundaries of the lower and upper saturation zones. The lower saturation zone lies between pmin and smin, the upper saturation zone lies between smax and pmax, and the dead zone lies between dmin and dmax.

For more information on joystick properties, see the following:

  • IDirectInputDevice8::GetProperty
  • IDirectInputDevice8::SetProperty
  • DIPROPRANGE
  • DIACTIONFORMAT

Axis coordinates from the joystick can be either relative or absolute. (See Relative and Absolute Axis Coordinates.) Because a joystick is an absolute device—unlike a mouse, it cannot travel infinitely far along any axis—absolute data is returned by default. When the axis mode for the joystick is set to relative, the axis coordinate represents the number of units of movement along the axis since the last value was returned.

The axis mode, which specifies whether relative or absolute data should be returned, is a property that can be changed before the device is acquired. (See Device Properties.) To set the axis mode to relative, call the IDirectInputDevice8::SetProperty method with the DIPROP_AXISMODE value in the rguidProp parameter and with DIPROPAXISMODE_REL in the dwData member of the DIPROPDWORD structure.


Using CPOINTs

The CPOINT structure is used to calibrate segments of the response curve of a device axis. Up to eight CPOINTs can be set through the DIPROPCPOINTS structure. Each CPOINT structure contains a raw data value representing the position of the joystick along the axis, and a logical value. When your application receives the raw value, the logical value is used to calculate the returned value that is actually used. Raw values that fall between specific CPOINT raw data values are interpolated to logical values based on a line drawn between the CPOINTs to either side of the value.

The following is an example of the effect of five CPOINTs applied to the response curve of a joystick's X axis. Before application of the DIPROPCPOINTS structure, the response graph for the example axis would appear as shown below, including saturation and dead zones.

A DIPROPCPOINTS structure is initialized as follows, assuming the physical range to be -500 to 500.

DIPROPCPOINTS dipcp;

dipcp.diph.dwSize = sizeof(DIPROPCPOINTS);
dipcp.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipcp.diph.dwObj = GUID_XAxis;
dipcp.diph.dwHow = DIPH_BYID;
dipcp.dwCPointsNum = 5;
dipcp.cp[0].lP = -500
dipcp.cp[0].dwLog = 0
dipcp.cp[1].lP = -300
dipcp.cp[1].dwLog = 1000
dipcp.cp[2].lP = -100
dipcp.cp[2].dwLog = 5000
dipcp.cp[3].lP = 200
dipcp.cp[3].dwLog = 9000
dipcp.cp[4].lP = 500
dipcp.cp[4].dwLog = 10000

Note that you do not need to know the actual maximum returned value as the values in the dwLog member of the CPOINT structure are expressed as a percentage of the total, multiplied by 10000 (the number of discrete divisions in the total range). For instance, the example sets the curve so that 10% of the maximum value is returned at the -300 point in the joystick's range. 0.10 * 10000 = 1000, so that value is given to the dwLog member while -300 is assigned to the corresponding lP member.

After applying this DIPROPCPOINTS structure through IDirectInputDevice8::SetProperty, the curve responds as seen below.


Checking for Lost Joystick Input

If your application is using the joystick in foreground mode (see Cooperative Levels), it will lose the device when the focus shifts to another application.

Check for the DIERR_INPUTLOST return value from the IDirectInputDevice8::GetDeviceData or the IDirectInputDevice8::GetDeviceState method and attempt to reacquire the joystick, if necessary. (See Acquiring Devices.)

Note You should not attempt to reacquire the joystick on getting a DIERR_NOTACQUIRED error. If you do, you could get caught in an infinite loop: acquisition would fail again, you would get another DIERR_NOTACQUIRED error, and so on.

Because access to the joystick is not lost except when your application moves to the background—unlike the mouse and keyboard, the joystick is never used by the Microsoft® Windows® system—an alternative method is to reacquire the device in response to a WM_ACTIVATE message.


Output Data

Some Human Interface Devices both generate input and accept output. The IDirectInputDevice8::SendDeviceData method is used to send packets of data to such devices.

SendDeviceData may be viewed as IDirectInputDevice8::GetDeviceData in reverse. As with that method, it uses the DIDEVICEOBJECTDATA structure as the basic unit of data. In this case, however, the dwOfs member contains the instance ID of the device object associated with the data rather than its offset in the data format for the device. (Because offset identifiers exist only for device objects that provide input in the selected data format, an object that accepts only output might not even have an offset.) The dwData member contains whatever data is appropriate for the object. The dwTimeStamp and dwSequence members are not used and must be set to 0.

To send data to the device, set up an array of DIDEVICEOBJECTDATA structures, fill the required number of elements with data, and then pass the array address and the number of elements used to SendDeviceData. Data for different device objects is combined into a single packet that is then sent to the device.

The form of the data packet is specific to the device, as is the treatment of unused fields in the packet. Some devices may treat fields as optional. In other words, if no data is supplied, the state of the object remains unchanged. More commonly, all fields are significant, even when you do not specifically supply data for them. For example, if you send data to a single keyboard LED, it is assumed that the data for the other two LEDs is 0 and that they are turned off. However, you can override this behavior by using the DISDD_CONTINUE flag. In this case, the data for the other two LEDs is the value you most recently sent them.

The device object type identifiers are obtained from the dwType member of the DIDEVICEOBJECTINSTANCE structure after passing the HID usage page and usage code to IDirectInputDevice8::GetObjectInfo. For example, the type identifier of the Scroll Lock LED can be obtained by using the following code, where pdev is an IDirectInputDevice8 interface pointer representing the keyboard.

DIDEVICEOBJECTINSTANCE didoi;
DWORD NumLockID;

HRESULT hr = pdev->GetObjectInfo(&didoi,
        DIMAKEUSAGEDWORD(0x07,0x53), DIPH_BYUSAGE);
NumLockID = didoi.dwType;

The following sample function, when called repeatedly, causes the LEDs on the keyboard to flash in a recurring pattern. It is assumed that the high bit of the data byte determines the state of the LED. The DWORDs NumLockID, CapsLockID, and ScrollLockID have all been obtained as shown above.

#define ARRAYSIZE 4
void FlashLEDs(void)
    {
    static int         rgiBits[] = { 1, 2, 4, 2 };
    static int         iLooper = 0;
    DWORD              cdod = 3;                  // Number of items
    DIDEVICEOBJECTDATA rgdod[ARRAYSIZE-1];
    HRESULT            hres;

    // Must clear dwTimeStamp and dwSequence
    ZeroMemory(rgdod, sizeof(rgdod));

    rgdod[0].dwOfs = NumLockID;
    rgdod[1].dwOfs = CapsLockID;
    rgdod[2].dwOfs = ScrollLockID;

    rgdod[0].dwData = (rgiBits[iLooper] & 1) ? 0x80 : 0;
                                           // NumLock light on/off
    rgdod[1].dwData = (rgiBits[iLooper] & 2) ? 0x80 : 0;
                                           // CapsLock light on/off
    rgdod[2].dwData = (rgiBits[iLooper] & 4) ? 0x80 : 0;
                                           // ScrollLock light on/off

    iLooper = (iLooper + 1) % ARRAYSIZE; // Loops from 0 to 3

    hres = pdev->SendDeviceData(sizeof(DIDEVICEOBJECTDATA),
            rgdod, &cdod, 0);
    }


Action Mapping

Traditionally, applications have done their own mapping of events to particular buttons and axes. A car-racing game, for example, might assume that the x-axis on the user's joystick or mouse was the most suitable control for steering the car. The only way to accommodate new or unusual devices was to provide configuration options so that the user could specify some other axis, such as a rotational axis, to use for steering. Moreover, the application had no way of knowing which installed device was the best fit for the game, so the user typically had to choose a device from a menu or make sure only the preferred device was attached.

Using action mapping, you no longer need to make assumptions about the best use of devices and device objects. Instead, your application binds actions to virtual controls wherever possible. Rather than getting data from the x-axis and steering the car to the left or the right accordingly, the application might get data from a virtual control called DIAXIS_DRIVINGR_STEER. Microsoft® DirectInput® assigns the virtual control to a physical control—that is, a device object. It does so by taking into account the application genre, user preferences, information from the device manufacturer, and the user's configuration of the device.

Action mapping also simplifies the input loop by returning data for all devices in a form independent of the particular device. A single action can be mapped to more than one device, and the input loop can respond to the action the same way regardless of which device is being read.

The following topics contain more information on the steps required to implement action mapping.

  • Preparing the Action Map
  • Finding Matching Devices
  • Configuring the Action Map
  • User Configuration of the Device
  • Retrieving Action Data
  • Maintaining Files During Development


Preparing the Action Map

The action map is a DIACTIONFORMAT structure containing information about application actions and their mapping to virtual controls or device objects. The structure is passed back and forth between the application and Microsoft® DirectInput® to establish the final mapping. This section explains how to initialize the map.

1. Define Application Actions

The first step in implementing DirectInput action mapping is to determine what input-driven actions in your application need to be mapped to device objects. For actions that can be performed either by an axis or by a button, you must define separate actions for both input types. It is recommended that you define button actions for all important functions, in case the device does not have the appropriate axes.

The following sample enumeration of action values might be defined by a car-racing game. Axis actions begin with "eA" and button actions with "eB".

enum eGameActions
{
    eA_STEER,       // Steering
    eB_STEER_LEFT,  // Steer left
    eB_STEER_RIGHT, // Steer right
    eA_ACCELERATE,  // Change speed
    eB_ACCELERATE,  // Speed up
    eB_DECELERATE,  // Slow down
    eA_BRAKE,       // Brake
    eB_BRAKE,       // Brake
    eB_UPSHIFT,     // Shift to higher gear
    eB_DOWNSHIFT,   // Shift to lower gear
    eB_CYCLEVIEW,   // Cycle to next view
    eB_COURSEVIEW,  // Toggle course view
    eB_DRIVERVIEW,  // View from driver's seat
    eB_BRAKEBIAS,   // Brake bias
    eA_VOLUME,      // Sound volume
    eB_MUTE         // Toggle sound
};

#define NUM_MY_ACTIONS 16

In the example, actions are defined as enumerated values. However, they could be other 32-bit data types, such as pointers to functions. When you retrieve device data, you get whatever action value you have defined, and you can handle it in any way you like.

2. Define the Genre

The next step is to decide what genre your application belongs to. A genre defines a set of virtual controls. By selecting the proper genre, you can obtain the best possible fit of virtual controls to application actions. Manufacturers who choose to supply default mappings for their devices must support one or more of the genres defined by DirectInput. See Action Mapping Constants for a list of these genres.

For the game in the example, the obvious choice is the DIVIRTUAL_DRIVING_RACE genre, which contains the following virtual controls.

Priority 1 Controls

DIAXIS_DRIVINGR_STEER
DIAXIS_DRIVINGR_ACCELERATE
DIAXIS_DRIVINGR_BRAKE
DIBUTTON_DRIVINGR_SHIFTUP
DIBUTTON_DRIVINGR_SHIFTDOWN
DIBUTTON_DRIVINGR_VIEW
DIBUTTON_DRIVINGR_MENU

Priority 2 Controls

DIAXIS_DRIVINGR_ACCEL_AND_BRAKE
DIHATSWITCH_DRIVINGR_GLANCE
DIBUTTON_DRIVINGR_ACCELERATE_LINK
DIBUTTON_DRIVINGR_AIDS
DIBUTTON_DRIVINGR_BOOST
DIBUTTON_DRIVINGR_BRAKE
DIBUTTON_DRIVINGR_DASHBOARD
DIBUTTON_DRIVINGR_DEVICE
DIBUTTON_DRIVINGR_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGR_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGR_MAP
DIBUTTON_DRIVINGR_PAUSE
DIBUTTON_DRIVINGR_PIT
DIBUTTON_DRIVINGR_STEER_LEFT_LINK
DIBUTTON_DRIVINGR_STEER_RIGHT_LINK

There is no difference in functionality between Priority 1 and Priority 2 controls. Priority 1 controls are those most likely to be supported by device manufacturers in their default mappings. However, there is no guarantee that any virtual control will be supported by a device.

3. Assign Actions to Controls or Device Objects

The next step in creating the action map is to associate each application action with one or more of the virtual controls defined for the genre. You do this by declaring and initializing an array of DIACTION structures. Each structure in the array specifies the action value, the virtual control to associate with it, and a friendly name that describes the action. Leave other members as zero; they will be filled in later by DirectInput.

You can also use elements of the DIACTION array to map actions to particular keys or buttons on the keyboard or mouse or to channels on a Microsoft DirectPlay® voice device. By doing so, you can take advantage of the simplified input loop for all input, not just that from virtual controls. For example, suppose you map the application-defined action eB_UPSHIFT to both the DIBUTTON_DRIVINGR_SHIFTUP virtual control and to the Page Up key. When retrieving data, you get back eB_UPSHIFT whether the input came from a joystick button or the keyboard.

The following example declares an action map for the car-racing game.

DIACTION rgActions[]=
{
//Genre-defined virtual axes

  {eA_STEER,       DIAXIS_DRIVINGR_STEER,        0, "Steer",      },
  {eA_ACCELERATE,  DIAXIS_DRIVINGR_ACCELERATE,   0, "Accelerate", },
  {eA_BRAKE,       DIAXIS_DRIVINGR_BRAKE,        0, "Brake",      },

//Genre-defined virtual buttons

  {eB_UPSHIFT,     DIBUTTON_DRIVINGR_SHIFTUP,    0, "Upshift",    },
  {eB_DOWNSHIFT,   DIBUTTON_DRIVINGR_SHIFTDOWN,  0, "DownShift",  },
  {eB_CYCLEVIEW,   DIBUTTON_DRIVINGR_VIEW,       0, "Change View",},

// Actions not defined in the genre that can be assigned to any
// button or axis

  {eA_VOLUME,      DIAXIS_ANY_1,                 0, "Volume",      },
  {eB_MUTE,        DIBUTTON_ANY(0),              0, "Toggle Sound",},

// Actions not defined in the genre that must be assigned to
// particular keys

  {eB_DRIVERVIEW,  DIKEYBOARD_1,                 0, "Driver View",},
  {eB_COURSEVIEW,  DIKEYBOARD_C,                 0, "Course View",},
  {eB_BRAKEBIAS,   DIKEYBOARD_B,                 0, "Brake Bias", },

// Actions mapped to keys as well as to virtual controls

  {eB_UPSHIFT,     DIKEYBOARD_PRIOR,              0, "Upshift",    },
  {eB_DOWNSHIFT,   DIKEYBOARD_NEXT,               0, "Downshift",  },
  {eB_STEER_LEFT,  DIKEYBOARD_LEFT,               0, "Steer Left", },
  {eB_STEER_RIGHT, DIKEYBOARD_RIGHT,              0, "Steer Right",},
  {eB_ACCELERATE,  DIKEYBOARD_UP,                 0, "Accelerate", },
  {eB_DECELERATE,  DIKEYBOARD_DOWN,               0, "Decelerate", },
  {eB_BRAKE,       DIKEYBOARD_END,                0, "Brake",      },

// Actions mapped to buttons as well as to virtual controls and keys

  {eB_UPSHIFT,     DIMOUSE_BUTTON0,              0, "Upshift",   },
  {eB_DOWNSHIFT,   DIMOUSE_BUTTON1,              0, "Downshift", },
};

In the example, some actions are mapped to actual keys by using Keyboard Mapping Constants. Similar mappings to the mouse buttons and axes can be made by using Mouse Mapping Constants.

The DIACTION array is contained within a DIACTIONFORMAT structure that also contains information about the genre, the application, and the desired scaling of axis data. Use the same instance of this structure throughout the action mapping process. Some members will not be used immediately, but you can fill in the entire structure before the next step, Finding Matching Devices.


Finding Matching Devices

After you define the application actions and the virtual controls or device objects to which these actions are to be mapped, the next step is to enumerate devices on the system to find those that best support the desired virtual controls.

To do so, pass the DIACTIONFORMAT structure to IDirectInput8::EnumDevicesBySemantics. This method works in much the same way as IDirectInput8::EnumDevices and takes a similar callback function.

Devices that have been configured by the user to match certain controls are always enumerated first. For example, if a user has configured a wheel as the primary steering device for driving games, then the wheel is enumerated first whenever devices that support DIAXIS_DRIVINGR_STEER are requested, taking precedence over other capable devices such as joysticks that have not been configured by the user. Otherwise, the order in which available devices are enumerated is determined by the degree to which they match the requested controls.

In the enumeration callback, you can retrieve the default action mapping for each device, change any mappings you don't like, give the user an opportunity to reconfigure the device, and apply the action map. These steps are covered in Configuring the Action Map. Flags returned in the DIEnumDevicesBySemanticsCallback will provide information about why a particular device was enumerated. These flags will indicate whether a device has been used recently, is newly installed, or will accept mappings of priority 1 or priority 2 controls.


Configuring the Action Map

As each device is enumerated, you can obtain a pointer to it, retrieve the default action map, make changes in the default map, and apply the final mappings.

1. Obtaining the Device

Obtain the IDirectInputDevice8 interface pointer for each enumerated device from the lpdid parameter of the enumeration callback. See DIEnumDevicesBySemanticsCallback. If you want to save the device interface for use in your application, call AddRef on the pointer and assign it to a global variable.

2. Obtaining the Default Action Map

To obtain the default action map for the device, call IDirectInputDevice8::BuildActionMap. Microsoft® DirectInput® takes the list of virtual controls specified in your DIACTIONFORMAT structure and attempts to map these to physical device objects, returning the results in the same structure. You should examine the dwHow member of each DIACTION element to determine whether the control was successfully mapped. If it was, you can also ascertain what criterion was used in choosing the object—for example, configuration by the user or by the device manufacturer.

3. Making Changes to the Action Map

You now have the option of changing the default mappings, although it is not recommended that you do so. After examining the dwSemantic member of the DIACTION structure to determine which device object was mapped to an action, you can change that value. For example, if an action is mapped to DIJOFS_BUTTON9, but you want that action to be mapped to the trigger button instead, change the value to DIJOFS_BUTTON0 before applying the action map.

4. Applying the Action Map

When you are satisfied that the DIACTIONFORMAT structure contains suitable mappings for the device, call IDirectInputDevice8::SetActionMap. The value you assigned to the uAppData member of each DIACTION structure now becomes bound to the control specified in the dwSemantic member, which in turn is bound to a particular device object.

5. Mapping More than One Device

Repeat steps 1 though 4 for each device you want to use in your application. Suppose you want to map actions to both a joystick and the keyboard. In the racing-game example, the action defined in the game as eB_DRIVERVIEW was mapped to a keyboard key in the following element of the DIACTION array.

{eB_DRIVERVIEW, DIKEYBOARD_1, "Driver View", },

In that example, when BuildActionMap is called on any device that is not a keyboard, the lHow member of the DIACTION structure for that element is set to DIAH_UNMAPPED. Continue examining the lHow member as each device in turn is enumerated, until a value other than DIAH_UNMAPPED is returned. This indicates that the device being currently mapped is a keyboard and the action has been successfully mapped to the requested key.

Even actions that have been successfully mapped can be mapped to another device. In the example, eB_UPSHIFT is given two DIACTION structures, as follows:

{eB_UPSHIFT, DIBUTTON_DRIVINGR_SHIFTUP, 0, "Upshift", },
...
{eB_UPSHIFT, DIKEYBOARD_PRIOR,          0, "Upshift", },

As devices are successively enumerated, the eB_UPSHIFT action is mapped to a suitable button on one or more joysticks or other game controllers, and then again to the keyboard.

6. Displaying the Configuration

To show the user how actions have been mapped to devices, pass the DICD_DEFAULT flag to IDirectInput8::ConfigureDevices. The property sheet for the device, containing a graphical representation of mappings, is displayed in view-only mode as in the following diagram. For more information on the mechanics of displaying the image, refer to the Using Action Mapping tutorial.

If the device manufacturer has not provided a device image, the mapping will be presented in text mode as in the following diagram.

Note Even if the cooperative level for the application is disabling the Microsoft® Windows® logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping UI is displayed.

For more information about this property sheet, see User Configuration of the Device.


User Configuration of the Device

Microsoft® DirectInput® provides a property sheet that can be called from an application, enabling the user to configure devices for the application and view the current configuration. This property sheet can display various views of the device as provided by the manufacturer.

To enable user configuration, pass a DICONFIGUREDEVICESPARAMS structure containing a pointer to the DIACTIONFORMAT structure describing the desired mapping, along with the DICD_EDIT flag, to the IDirectInput8::ConfigureDevices method. Normally you would do this after calling IDirectInputDevice8::BuildActionMap on all devices that will be used in the application.

The following illustration shows a typical property sheet in edit mode.

If the device manufacturer has not provided a device image, the mapping will be presented in text mode as in the following diagram.

Note Even if the cooperative level for the application is disabling the Microsoft® Windows® logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping UI is displayed.

The property page for a device lists the friendly names that were provided by you in the lptszActionName member of each DIACTION structure. If you have already called BuildActionMap for a device, the page also shows these names as callouts on the image of the device, with lines pointing to the device objects to which the actions have been mapped.

The user now has the opportunity to reassign game actions by first choosing a control then choosing an action from the menu. When the user closes the property sheet, the method returns and the modifications are stored in the DIACTIONFORMAT structure that you passed in. You can now pass the same structure to IDirectInputDevice8::SetActionMap in order to implement the new mapping scheme.


Retrieving Action Data

You retrieve buffered data from action-mapped devices just as you would from unmapped devices: by calling IDirectInputDevice8::GetDeviceData. However, instead of identifying device objects by examining the dwOfs member of the DIDEVICEOBJECTDATA structure, you obtain the action associated with the object from the uAppData member. This is the same value you passed to the device in the DIACTION structure. It can be a simple identifier or a pointer to a function designed to handle the action.

Remember that an action can be associated with more than one device. You still have to obtain data from both devices independently, but you can use the same routine to handle the data regardless of where it comes from.

The following sample code, which might be part of the game loop in a driving simulation, retrieves data from all devices in the g_lpIdiDevices array. This array contains g_nDevices elements.

for (int iDevice = 0x0; iDevice < g_nDevices; iDevice++)
{
    DIDEVICEOBJECTDATA didod;
    DWORD dwObjCount = 1;

    // Poll the device for data.
    g_lpDiDevices[iDevice]->Poll();

    // Retrieve the data.
    g_lpDiDevices[iDevice]->GetDeviceData( sizeof(didod),
                                           &didod,
                                           &dwObjCount, 0 );

    // Handle the actions regardless of what device returned them.
    switch(didod.uAppData)
    {
        case eA_STEER:
            SteerCar(didod.dwData);
            break;
        case eB_UPSHIFT
            if (didod.dwData & 0x80) ShiftGears(UPSHIFT);
            break;
        .
        .
        .

        default:
            break;
    }
}

Note Axis constants for specific genres, such as DIAXIS_DRIVINGR_STEER or DIAXIS_SPACESIM_LATERAL, are used for absolute joystick data. The action mapper attempts to map this virtual control to a device object that returns absolute data. The data returned from that device should be processed accordingly in the application. Device constants such as DIMOUSE_XAXIS, however, are expected to return relative data.

When retrieving data, each potential source of data should be processed separately to keep one device object from possibly overwriting the data from another. For instance, the following DIACTION structures are used in an action map to control direction.

{INPUT_LEFTRIGHT_ABS_AXIS, DIAXIS_SPACESIM_LATERAL, 0,   _T("Turn"),},
{INPUT_LEFTRIGHT_REL_AXIS, DIMOUSE_XAXIS,           0,   _T("Turn"),},
{INPUT_TURNLEFT,           DIKEYBOARD_LEFT,     0,  _T("Turn left"),},
{INPUT_TURNRIGHT,          DIKEYBOARD_RIGHT,    0, _T("Turn right"),},

The application's input loop processes data from these actions in the following case statement.

switch (adod[j].uAppData)
{
    case INPUT_LEFTRIGHT_ABS_AXIS:
        g_dwAbsLR = adod[j].dwData
        break;
    case INPUT_LEFTRIGHT_REL_AXIS:
        g_dwRelLR = adod[j].dwData;
        break;
    case INPUT_TURNLEFT:
        g_bLeft = (adod[j].dwData != 0);
        break;
    case INPUT_TURNRIGHT:
        g_bRight = (adod[j].dwData != 0)
        break;
}

Note that each data source is assigned to a separate variable rather than all data sources being assigned a generic "turn" variable. If they were to share a generic variable, holding down the LEFT ARROW key and then moving the joystick would cause the keyboard information to be lost. This is because the joystick data would overwrite the variable.

In addition to individual variables, there are many ways to process the data. Whatever method is used, care should be taken in the processing of data to avoid unexpectedly lost information.


Maintaining Files During Development

During a development cycle, unused and out of date .ini files may accumulate due to frequent action map changes, Microsoft® DirectX® reinstallations, multiple users, and other normal development situations. These files could possibly cause unexpected mappings or reports of "recent" (DIEDBS_RECENTDEVICE) for devices that would not be expected to return that value. For this reason, it is good practice to occasionally delete any unused .ini files. These files can be found in C:\Program Files\Common Files\DirectX\DirectInput\User Maps.

Note The procedure suggested above is meant to be performed only manually during a development cycle to ensure that the development environment is in a cleaner state. A shipping application should never delete user maps as this could result in the loss of a user's preferred settings.


Force Feedback

Force feedback is the generation of push or resistance in an input/output device—for example, by motors mounted in the base of a joystick. Microsoft® DirectInput® enables you to generate force-feedback effects for devices that have compatible drivers.

The following sections introduce the elements of force feedback.

  • Basic Concepts of Force Feedback
  • Effect Enumeration
  • Loading Effects from a File
  • Information About a Supported Effect
  • Creating an Effect
  • Effect Direction
  • Envelopes and Offsets
  • Effect Playback
  • Downloading and Unloading Effects
  • Changing an Effect
  • Gain
  • Force-Feedback State
  • Effect Object Enumeration
  • Effect Types


Basic Concepts of Force Feedback

A particular instance of force feedback is called an effect, and the push or resistance is called the force. Most effects fall into one of the following categories:

  • Constant force. A steady force in a single direction.
  • Ramp force. A force that steadily increases or decreases in magnitude.
  • Periodic effect. A force that pulsates according to a defined wave pattern.
  • Condition. A reaction to motion or position along an axis. Two examples are a friction effect that generates resistance to movement of the joystick, and a spring effect that pushes the stick back toward a certain position after it has been moved from that position.

The strength of the force is called its magnitude. Magnitude is measured in units ranging from 0 (no force) through 10,000 (maximum force for the device, defined for C/C++ and Visual Basic as DI_FFNOMINALMAX). A negative value indicates force in the opposite direction. Magnitudes are linear: a force of 10,000 is twice as great as one of 5,000.

Ramp forces have a beginning and ending magnitude. For a periodic effect, the basic magnitude is the force at the peak of the wave.

The direction of a force is the direction from which it comes. A positive force on a given axis pushes from the positive toward the negative.

Effects also have duration, measured in microseconds. Periodic effects have a period, or the duration of one cycle, also measured in microseconds. The phase of a periodic effect is the point along the wave at which playback begins.

The following illustration represents a sawtooth periodic effect with a magnitude of 5,000, or half the maximum force for the device. The horizontal axis represents the duration of the effect, and the vertical axis represents the magnitude. Points above the center line represent positive force in the direction defined for the effect, and points below the center line represent negative force, or force in the opposite direction.

A force may be further shaped by an envelope. An envelope defines an attack value and a fade value, which modify the beginning and ending magnitude of the effect. Attack and fade also have duration, which determines how long the magnitude takes to reach or fall away from the sustain value, the magnitude in the middle portion of the effect.

The following diagram shows an envelope. The attack level is set to 8,000 and the fade level to 1,000. The sustain level is defined by the basic magnitude of the force to which the envelope is being applied; in the example, it is 5,000. In this case, the attack is greater than the sustain, giving the effect an initial strong kick. Both the attack and the fade level can be either greater or less than the sustain level.

The next diagram shows the result of the envelope being applied to the periodic effect in the first diagram. The envelope is mirrored on the negative side of the magnitude. An attack value of 8,000 means that the initial magnitude of the force in either direction is 80 percent of the maximum possible.

Periodic effects and conditions can also be modified by the addition of an offset, which defines the amount by which the waveform is shifted up or down from the base level. The practical effect of applying a positive offset to the sawtooth example would be to strengthen the positive force and weaken the negative one—in other words, the force would peak more strongly in one direction than in the other.

Finally, the overall magnitude of an effect can be scaled by gain, which is analogous to a volume control in audio. A single gain value can be applied to all effects for a device. You might want to do this to compensate for stronger or weaker forces on different hardware or to accommodate the user's preferences.


Effect Enumeration

The IDirectInputDevice8::EnumEffects method returns information about the support offered by the device for various kinds of effects.

It is important to distinguish between supported effects and created effects, or effect objects. A supported effect is a basic type which a device is capable of playing, such as a constant force. However, a constant force by itself has no properties such as magnitude, direction, duration, attack, or fade. These properties are set when you create a specific effect object in your application by shaping the raw effect type with an envelope or setting the values of a DIEFFECT structure. A supported effect can be represented by many effect objects, each with different parameters—for example, several constant forces, each with different duration, magnitude, and direction.

For information on enumerating created effects, see Effect Object Enumeration.

Like other Microsoft® DirectInput® enumerations, the IDirectInputDevice8::EnumEffects method requires a callback function. This is documented with the placeholder name DIEnumEffectsCallback, but you can use a different name if you prefer. This function is called for each effect enumerated. Within the function you can obtain the GUID for each effect, get information about the extent of hardware support, and create one or more effect objects whose methods you can use to manipulate the effect.

The following code example sets the enumeration in motion. Assume that g_lpdid is an initialized pointer to the IDirectInputDevice8 interface of the device.

HRESULT hr = g_lpdid->EnumEffects(&DIEnumEffectsCallback,
        g_lpdid, DIEFT_ALL);

A skeletal callback is shown in the following code. The pvRef parameter of the callback could be any 32-bit value, but in this case it is a pointer to the device interface (the global g_lpdid in the previous example), which is used for getting information about effects supported by the device and for creating effect objects.

BOOL CALLBACK DIEnumEffectsCallback(LPCDIEFFECTINFO pdei,
                                LPVOID pvRef)
{
    HRESULT              hr;
    LPDIRECTINPUTDEVICE8 lpdid = (LPDIRECTINPUTDEVICE8)pvRef;
// Pointer to calling device
    LPDIRECTINPUTEFFECT  lpdiEffect;      // Pointer to created effect
    DIEFFECT             diEffect;        // Params for created effect
    DICONSTANTFORCE      diConstantForce; // Type-specific parameters

    if (DIEFT_GETTYPE(pdei->dwEffType) == DIEFT_CONSTANTFORCE)
    {
       /* Here you can extract information about support for the
          effect type (from pdei), and tailor your effects
          accordingly. For example, the device might not support
          envelopes for this type of effect. */
       .
       .
       .
       // Create one or more constant force effects.
       // For each, you have to initialize a DICONSTANTFORCE
       // and a DIEFFECT structure.
       .
       .
       .
        hr = lpdid->CreateEffect(pdei->guid,
                                &diEffect,
                                &lpdiEffect,
                                NULL);
       .
       .
       .
    }
    // And so on for other types of effect
   .
   .
   .

    return DIENUM_CONTINUE;
}  // End of callback

For a detailed example of creating an effect, and for more information on how to initialize an effect, see Creating an Effect.


Loading Effects from a File

Using the Force Editor supplied with the Microsoft® DirectX® SDK, or another application that uses the same file format, you can design effects and save them in a file. You can then use these effects in any application by loading them at run time.

To load effects, call the IDirectInputDevice8::EnumEffectsInFile method. By default, the enumeration is limited to the standard Microsoft DirectInput® effects, but you can enumerate other effects by setting the DIFEF_INCLUDENONSTANDARD flag. By setting the DIFEF_MODIFYIFNEEDED flag, you can also instruct DirectInput to modify the parameters of effects, if necessary, so that they work on the device. (For example, an effect authored for two axes can be made to work on a single-axis steering wheel.)

In the following code example, the first three standard effects are loaded from a file and created as DirectInputEffect objects.

// g_lpdid is a valid IDirectInputDevice8 pointer to a
// force feedback device.

// The array of effect pointers is declared globally.
LPDIRECTINPUTEFFECT pEff[3];
.
.
.
g_lpdid->EnumEffectsInFile("FEdit1.ffe",
                            EnumEffectsInFileProc,
                            NULL,
                            DIFEF_MODIFYIFNEEDED);
.
.
.

The following callback function is called once for each effect in the file or until it returns DIENUM_STOP. Note that because the DIFEF_MODIFYIFNEEDED flag was passed, the effect parameters may have been modified in lpdife->lpDiEffect. The callback creates the effect with these modified parameters.

BOOL CALLBACK EnumEffectsInFileProc(LPCDIFILEEFFECT lpdife,
        LPVOID pvRef)

{
    HRESULT     hr;
    static int  i;

    hr = g_lpdid->CreateEffect(lpdife->GuidEffect,
                               lpdife->lpDiEffect,
                               &pEff[i],
                               NULL);
    if (FAILED(hr))
    {
        // Error handling
    }
    if (++i > 2) return DIENUM_STOP;
    else return DIENUM_CONTINUE;
}


Information About a Supported Effect

The IDirectInputDevice8::GetEffectInfo method can be used to retrieve information about the device's support for an effect whose GUID is known. It retrieves the same information that is returned in the DIEFFECTINFO structure during enumeration. For more information, see Effect Enumeration.

The following code fetches information about an effect whose GUID is stored in the EffectGuid variable, and determines whether the direction of the effect can be changed without stopping and restarting it:

DIEFFECTINFO diEffectInfo;
diEffectInfo.dwSize = sizeof(DIEFFECTINFO);
g_lpdid->GetEffectInfo(&diEffectInfo, EffectGuid);
if (diEffectInfo.dwDynamicParams & DIEP_DIRECTION)
{
  // Can reset parameter dynamically
}


Creating an Effect

Create an effect object by using the IDirectInputDevice8::CreateEffect method, as in the following code example, where g_lpdid points to an instance of the interface. This example creates a very simple effect that pulls the joystick away from the user at full force for half a second.

HRESULT  hr;
LPDIRECTINPUTEFFECT lpdiEffect;  // receives pointer to created effect
DIEFFECT diEffect;               // parameters for created effect

DWORD    dwAxes[2] = { DIJOFS_X, DIJOFS_Y };
LONG     lDirection[2] = { 18000, 0 };

DICONSTANTFORCE diConstantForce;

diConstantForce.lMagnitude = DI_FFNOMINALMAX;   // Full force

diEffect.dwSize          = sizeof(DIEFFECT);
diEffect.dwFlags         = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;
diEffect.dwDuration      = (DWORD)(0.5 * DI_SECONDS);
diEffect.dwSamplePeriod  = 0;                 // = default
diEffect.dwGain          = DI_FFNOMINALMAX;   // No scaling
diEffect.dwTriggerButton = DIEB_NOTRIGGER;    // Not a button response
diEffect.dwTriggerRepeatInterval = 0;         // Not applicable
diEffect.cAxes                   = 2;
diEffect.rgdwAxes                = &dwAxes[0];
diEffect.rglDirection            = &lDirection[0];
diEffect.lpEnvelope              = NULL;
diEffect.cbTypeSpecificParams    = sizeof(DICONSTANTFORCE);
diEffect.lpvTypeSpecificParams   = &diConstantForce;

hr = g_lpdid->CreateEffect(GUID_ConstantForce,
                           &diEffect,
                           &lpdiEffect,
                           NULL);

In the method call, the first parameter identifies the supported effect with which the created effect is to be associated. The example uses one of the predefined GUIDs found in Dinput.h. If you use a predefined GUID, the call fails if the device does not support the effect.

The second parameter sets the parameters as specified in the DIEFFECT structure.

The third parameter receives a pointer to the effect object if the call is successful.

The DIEFF_POLAR flag specifies the type of coordinates used for the direction of the force. (See Effect Direction.) It is combined with DIEFF_OBJECTOFFSETS, which indicates that any buttons or axes used in other members are identified by their offsets within the DIDATAFORMAT structure for the device. The alternative is to use the DIEFF_OBJECTIDS flag, signifying that buttons and axes are identified by the dwType member of the DIDEVICEOBJECTINSTANCE structure returned for the object when it was enumerated with the IDirectInputDevice8::EnumObjects method.

For more information on the members of the DIEFFECT structure, see Effect Direction.

Effects are automatically downloaded to the device when created, provided the device is not full and is acquired at the exclusive cooperative level.


Effect Direction

Directions can be defined for one or more axes. As with the mouse and joystick, the x-axis increases from left to right, and the y-axis increases from far to near. For three-dimensional devices, the z-axis increases from up to down.

The direction of an effect is the direction from which it comes. An effect with a direction along the negative y-axis tends to push the stick along the positive y-axis (toward the user). If the user must push the stick toward the left to counteract an effect, the effect has a left direction; that is, it lies on the negative x-axis.

Direction can be expressed in polar, spherical, or Cartesian coordinates.

Polar coordinates are expressed as a single angle, in hundredths of a degree clockwise from whatever zero-point, or true north, has been established for the effect. Normally this is the negative y-axis; that is, away from the user. Thus an effect with a polar coordinate of 9,000 has a direction of east, or to the user's right, and the user must exert force to the right to counteract it.

Spherical coordinates are also in hundredths of a degree but can contain two or more angles For each angle, the direction is rotated in the positive direction of the next axis. For a 3-D device, the first angle would normally be rotated from the positive x-axis toward the positive y-axis (clockwise from east), and the second angle would be rotated toward the positive z-axis (down). Thus a force with a direction of (0, 0) would be to the user's right and parallel to the tabletop. A direction of 27,000 for the first angle and 4,500 for the second would be directly away from the user (270 degrees clockwise from east) and angling toward the floor (45 degrees downward from the tabletop); to counteract a force with this direction, the user would have to push forward and down.

Cartesian coordinates are similar to 3-D vectors. If you draw a straight line on graph paper with an origin of (0, 0) at the center of the page, the direction of the line can be defined by the coordinates of any intersection that it crosses, regardless of the distance from the origin. A direction of (1, –2) and a direction of (5, –10) are exactly the same.

Note The coordinates used in creating force-feedback effects define only direction, not magnitude or distance.

When an effect is created or modified, the cAxes, rgdwAxes, and rglDirection members of the DIEFFECT structure are used to specify the direction of the force.

The cAxes member specifies the number of axes involved in the effect. This will also be the number of elements in each of the arrays pointed to by the next two members.

The array pointed to by rgdwAxes identifies the axes to which the effects will be applied. If the DIEFF_OBJECTOFFSETS flag has been set, the axes are identified by the offsets within the data format structure. These offsets are most readily identified by using the DIJOFS_* defines. (For a list of these values, see Joystick Device Constants.)

Finally, the rglDirection member specifies the direction of the force.

Note The cAxes and rgdwAxes members cannot be modified once they have been set. An effect always has the same axis list.

Regardless of whether you are using Cartesian, polar, or spherical coordinates, you must provide exactly as many elements in rglDirection as there are axes in the array pointed to by rgdwAxes.

In the polar coordinate system, north (0 degrees) lies along the vector (0, –1), where the elements of the vector correspond to the elements in the axis list pointed to by rgdwAxes. Normally those axes are x and y, so north is directly along the negative y-axis; that is, away from the user. The last element of rglDirection must be 0.

In the example in Creating an Effect, the direction of a two-dimensional force is defined in polar coordinates. The force has a south direction—it comes from the direction of the user, so the user has to pull the stick to counteract it. The direction is 180 degrees clockwise from north, and can be assigned as follows:

LONG  lDirection[2] = { 18000, 0 };

For greater clarity, the assignment could also be expressed this way:

LONG  lDirection[2] = { 180 * DI_DEGREES, 0 };

For spherical coordinates, presuming that you are working with a three-axis device, the same direction is assigned as follows:

LONG  lDirection[3] = { 90 * DI_DEGREES, 0, 0 }

The first angle is measured in hundredths of a degree from the (1, 0) direction, rotated in the direction of (0, 1); the second angle is measured in hundredths of a degree toward (0, 0, 1). The elements of the vector notation again correspond to elements in the array pointed to by the rgdwAxes member. Assume that the elements of this array represent the x, y, and z axes, in that order. The point of origin is at x = 1 and y = 0; that is, to the user's right. The direction of rotation is toward the positive y-axis (0, 1); that is, toward the user, or clockwise. The force in the example is 90 degrees clockwise from the right; that is, south. Because the second element of lDirection is 0, there is no rotation on the third axis.

How do you accomplish the same thing with Cartesian coordinates? Presuming that you have used the DIEFF_CARTESIAN flag in the dwFlags member, you would specify the direction like this:

LONG  lDirection[2] = { 0, 1 };

Here again, the elements of the array correspond to the axes listed in the array pointed to by rgdwAxes. The example sets the x-axis to 0 and the y-axis to 1; that is, the direction lies directly along the positive y-axis, or to the south.

The theory of effect directions can be difficult to grasp, but the practice is fairly straightforward. For code examples, see Examples of Setting Effect Direction.


Examples of Setting Effect Direction

Single-Axis Effects

Setting up the direction for a single-axis effect is easy because there is nothing to specify. Put the DIEFF_CARTESIAN flag in the dwFlags member of the DIEFFECT structure and set rglDirection to point to a single LONG containing the value 0.

The following code example sets up the direction and axis parameters for an x-axis effect:

DIEFFECT eff;
LONG     lZero  = 0;                       // No direction
DWORD    dwAxis = DIJOFS_X;                // X-axis effect

ZeroMemory(&eff, sizeof(DIEFFECT));
eff.cAxes        = 1;                                     // One axis
eff.dwFlags      = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; // Flags
eff.rglDirection = &lZero;                                // Direction
eff.rgdwAxes     = &dwAxis;                         // Axis for effect

Two-Axis Effects with Polar Coordinates

Setting up the direction for a polar two-axis effect is only a little more complicated. Set the DIEFF_POLAR flag in dwFlags and set rglDirection to point to an array of two LONGs. The first element in this array is the direction from which you want the effect to come. The second element in the array must be 0.

The following example sets up the direction and axis parameters for a two-axis effect coming from the east:

DIEFFECT eff;
LONG     rglDirection[2] = { 90 * DI_DEGREES, 0 };
DWORD    rgdwAxes[2]     = { DIJOFS_X, DIJOFS_Y };   // X- and y-axis

ZeroMemory(&eff, sizeof(DIEFFECT));
eff.cAxes        = 2;                                  // Two axes
eff.dwFlags      = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;  // Flags
eff.rglDirection = rglDirection;                       // Direction
eff.rgdwAxes     = rgdwAxes;                     // Axis for effect

Two-Axis Effects with Cartesian Coordinates

Setting up the direction for a Cartesian two-axis effect is a bit trickier. Set the DIEFF_CARTESIAN flag in dwFlags, and again set rglDirection to point to an array of two LONGs. This time the first element in the array is the x-coordinate of the direction vector, and the second is the y-coordinate.

The following code example sets up the direction and axis parameters for a two-axis effect coming from the east:

DIEFFECT eff;
LONG     rglDirection[2] = { 1, 0 };            // Positive x = east
DWORD    rgdwAxes[2]     = { DIJOFS_X, DIJOFS_Y };  // X- and y-axis

ZeroMemory(&eff, sizeof(DIEFFECT));
eff.cAxes = 2;                                       // Two axes
eff.dwFlags = DIEFF_CARTESIAN | DIEFF_OBJECTOFFSETS; // Flags
eff.rglDirection = rglDirection;                     // Direction
eff.rgdwAxes = rgdwAxes;                       // Axis for effect


Envelopes and Offsets

You can modify the basic magnitude of some effects by applying an envelope and an offset. For an overview, see Basic Concepts of Force Feedback.

To apply an envelope when creating or modifying an effect, initialize a DIENVELOPE structure and put a pointer to it in the lpEnvelope member of the DIEFFECT structure.

The device driver determines which effects support envelopes. Typically, you can apply an envelope to a constant force, a ramp force, or a periodic effect, but not to a condition. To determine whether a particular effect supports an envelope, call the IDirectInputDevice8::GetEffectInfo method and check for the DIEP_ENVELOPE flag in the dwStaticParams member of the DIEFFECTINFO structure.

To apply an offset, set the lOffset member of the DIPERIODIC or DICONDITION structure pointed to by the lpvTypeSpecificParams member of the DIEFFECT structure. For periodic effects, the absolute value of the offset plus the magnitude of the effect must not exceed DI_FFNOMINALMAX.

You cannot apply an offset to a constant force or ramp force. In these cases, you can achieve the same effect by altering the magnitude.


Effect Playback

There are two principal ways to start playback of an effect: manually by a call to the IDirectInputEffect::Start method, or automatically in response to a button press. Playback also starts when you change an effect by calling the IDirectInputEffect::SetParameters method with the DIEP_START flag.

Passing INFINITE in the dwIterations parameter of the IDirectInputEffect::Start method has the effect of playing the effect repeatedly, with the envelope being applied each time. If you want to repeat an effect without repeating the envelope—for example, to begin with a strong kick, then settle down to a steady throb—set dwIterations to 1, and set the dwDuration member of the DIEFFECT structure to INFINITE. (This is the structure passed to the IDirectInputDevice8::CreateEffect method.)

Note Some devices do not support multiple iterations of an effect, and they accept only the value 1 in the dwIterations parameter to the Start method. Always check the return value from Start to be sure the effect played successfully.

To associate an effect with a button press, set the dwTriggerButton member of the DIEFFECT structure. Also set the dwTriggerRepeatInterval member to the desired delay between playbacks when the button is held down. This is the interval, in microseconds, between the end of one playback and the start of the next.

Note On some devices, multiple effects cannot be triggered by the same button. If you associate more than one effect with a button, the last effect downloaded is the one triggered. Also, trigger repeat interval might not be supported.

To dissociate an effect from its trigger button, either call the IDirectInputEffect::Unload method or set the parameters for the effect with dwTriggerButton set to DIEB_NOTRIGGER.

Triggered effects, like all others, are lost when the application loses access to the device. To make them active again, download them as soon as the application reacquires the device. See Downloading and Unloading Effects. This step is not necessary for effects not associated with a trigger, because they are automatically downloaded if necessary whenever the Start method is called.

If an effect has a finite duration and is started by a call to the Start method, it stops playing when the time has elapsed. If its duration was set to INFINITE, playback ends only when the IDirectInputEffect::Stop method is called. An effect associated with a trigger button starts when the button is pressed and stops when the button is released or the duration has elapsed, whichever comes sooner.


Downloading and Unloading Effects

Before an effect can be played, it must be downloaded to the device. Downloading an effect means telling the driver to prepare the effect for playback. It is entirely up to the driver to determine how this is done. Generally, the driver places the parameters of the effect in hardware memory to minimize the subsequent transfer of data between the device and the system. The consequent reduction in latency is particularly important for conditions and for effects played in response to a trigger, such as a fire button. Ideally the device does not have to communicate with the system at all in order to respond to axis movements and button presses.

Downloading is done automatically when you create an effect, provided the device is not full and is acquired at the exclusive cooperative level. By default, it is also done when you start the effect or change its parameters.

If you specify the DIEP_NODOWNLOAD flag when changing parameters, you must subsequently use the IDirectInputEffect::Download method to download or update the effect.

When the device is unacquired—for example, when it has been acquired with the exclusive foreground cooperative level and the application moves to the background—effects are unloaded and must be downloaded again when the application regains the foreground. This is done automatically when you call the IDirectInputEffect::Start method, but you can choose to download all effects immediately on reacquiring the device. You always have to download effects associated with a trigger button because the Start method is not normally called for such effects.

If your application gets the DIERR_DEVICEFULL error when downloading an effect, you must make room for the new effect by unloading an old one. You can remove an effect from the device by calling the IDirectInputEffect::Unload method. You can also remove all effects by resetting the device through a call to the IDirectInputDevice8::SendForceFeedbackCommand method.

When you create a force-feedback device, the hardware and driver are reset, so any existing effects are cleared.


Changing an Effect

You can modify the parameters of an effect, in some cases even while the effect is playing. Do this by using the IDirectInputEffect::SetParameters method.

The dwDynamicParams member of the DIEFFECTINFO structure tells you which effect parameters can be changed while an effect is playing. If you attempt to modify an effect parameter that cannot be modified while the effect is playing, and the effect is still playing, Microsoft® DirectInput® normally stops the effect, updates the parameters, and restarts the effect. You can override this default behavior by passing the DIEP_NORESTART flag.

The following code example changes the magnitude of the constant force that was set in the example under Creating an Effect.

DIEFFECT        diEffect;           // Parameters for effect
DICONSTANTFORCE diConstantForce;    // Type-specific parameters

diConstantForce.lMagnitude = 5000;
diEffect.dwSize = sizeof(DIEFFECT);
diEffect.cbTypeSpecificParams = sizeof(DICONSTANTFORCE);
diEffect.lpvTypeSpecificParams = &diConstantForce;
hr = lpdiEffect->SetParameters(&diEffect, DIEP_TYPESPECIFICPARAMS);

The DIEP_TYPESPECIFICPARAMS flag ensures that the transfer of data from the DIEFFECT structure is restricted to the relevant members, so that you do not have to initialize the entire structure and so that the minimum possible amount of data needs to be sent to the device.


Gain

You might want to scale the force of your effects according to the force exerted by different devices. For example, if an application's effects feel right on a device that puts out a maximum force of n newtons on a given axis, you might want to adjust the gain for a device that puts out more force. (You cannot use the gain to increase the maximum force of the axis, so you should set the basic effect magnitudes to values suitable for devices that put out less force.)

Gain can also be used to decrease the magnitude of a hardware-defined effect.

The actual force generated by a device object such as an axis or button is returned in the dwFFMaxForce member of the DIDEVICEOBJECTINSTANCE structure when objects are enumerated. (See Device Object Enumeration.)

You can set the gain for the entire device by using the IDirectInputDevice8::SetProperty method.

You must set the gain for individual effects when creating them by putting a value in the dwGain member of the DIEFFECT structure. (If dwGain is 0, the effect will not be felt.) You can change this value later by using IDirectInputEffect::SetParameters, passing DIEP_GAIN in the dwFlags parameter.

The purpose of setting the device gain is to allow your application to have control over the strength of all effects all at once. For example, you might have a slider control in your application to enable the user to specify how strong the force-feedback effects should be, such as the master volume control on a sound mixer. When the device gain is set, your application does not need to adjust the gain of each individual effect to suit the user's preferences.

A gain value can be in the range from 0 through 10,000, where 10,000 indicates that magnitudes are not to be scaled, 7,500 means that forces are to be scaled to 75 percent of their nominal magnitudes, and so on.


Force-Feedback State

The IDirectInputDevice8::SendForceFeedbackCommand method enables you to turn off the device's actuators (effectively causing it to ignore any effects that are being played), pause, stop, or continue playback of effects, and reset the device so that all downloaded effects are removed.

To retrieve the current force-feedback state, use the IDirectInputDevice8::GetForceFeedbackState method. This method returns information about whether the actuators are active, whether playback is paused, and whether the device has been reset. It also retrieves information about various switches and whether the device is currently powered.


Effect Object Enumeration

When you need to examine or manipulate all the effects you have created, you can use the IDirectInputDevice8::EnumCreatedEffectObjects method. As no flags are currently defined for this method, you cannot restrict the enumeration to particular kinds of effects; all effects will be enumerated.

Note This method enumerates created effects, not effects supported by a device. For more information on the distinction between the two, see Effect Enumeration.

Like other Microsoft® DirectInput® enumerations, the EnumCreatedEffectObjects method requires a callback function. This standard callback is documented with the placeholder name DIEnumCreatedEffectObjectsCallback, but you can use a different name. The function is called for each effect enumerated. Within the function, you can perform any processing you want. However, it is not safe to create a new effect while enumeration is going on.

The following is a skeletal example of the callback function. The pvRef parameter of the callback can be any 32-bit value; in this case, it is a pointer to the IDirectInputDevice8 interface that is performing the enumeration.

HRESULT  hr;

BOOL CALLBACK DIEnumCreatedEffectObjectsCallback(
                             LPDIRECTINPUTEFFECT peff, LPVOID pvRef);
{
    LPDIRECTINPUTDEVICE pdid = (IDirectInputDevice*)pvRef;
                                        // Pointer to calling device
    DIEFFECT            diEffect;      // Params for created effect

    diEffect.dwSize = sizeof(DIEFFECTINFO);
    peff->GetParameters(&diEffect, DIEP_ALLPARAMS);
    // Check or set parameters, or do anything else.
    .
    .
    .
}  // End of callback

Here's the call that sets the enumeration in motion, passing in the DirectInputDevice pointer lpdid:

hr = lpdid->EnumCreatedEffectObjects(
         &DIEnumCreatedEffectObjectsCallback,
         &lpdid, 0);


Effect Types

This section contains information specific to the following types of force-feedback effects:

  • Constant Forces
  • Ramp Forces
  • Periodic Effects
  • Conditions
  • Custom Forces
  • Device-Specific Effects


Constant Forces

A constant force is a force with a defined magnitude and duration.

You can apply an envelope to a constant force to give it shape. For example, suppose you have an effect with a nominal magnitude of 2,000 and a duration of 2 seconds. Then you apply an envelope with the following values:

Parameter | Value
Attack time | 0.5 second
Initial attack level | 5,000
Fade time | 1 second
Fade level | 0

When you play the effect, you get the following:

Elapsed time | Magnitude
0.0 | 5,000
0.1 | 4,400
0.2 | 3,800
0.3 | 3,200
0.4 | 2,600
0.5 | 2,000
(Duration of sustain) | 2,000
1.0: | 2,000
1.1 | 1,800
1.2 | 1,600
1.3 | 1,400
1.4 | 1,200
1.5 | 1,000
1.6 | 800
1.7 | 600
1.8 | 400
1.9 | 200
2.0 | 0

You cannot apply an offset to a constant force.

To create a constant force, pass GUID_ConstantForce to the IDirectInputDevice8::CreateEffect method. You can also pass any other GUID obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEfftype)) is equal to DIEFT_CONSTANTFORCE. In this way, you can use hardware-specific forces designed by the manufacturer such as a "constant" force that actually varies in magnitude in a seemingly random fashion to simulate turbulence.

A constant force uses a DICONSTANTFORCE structure to define the magnitude. A negative magnitude has the effect of reversing the direction of the force.


Ramp Forces

A ramp force is a force with defined starting and ending magnitudes and a finite duration. A ramp force can continue in a single direction, or it can start as a strong push in one direction, weaken, stop, and then strengthen in the opposite direction.

The following illustration shows a ramp force that starts at a magnitude of -5,000 and ends at 5,000:

You can apply an envelope to a ramp force to shape it further. The following diagram shows the effect of applying an envelope, shown in green, to the ramp force in the previous diagram.

Note that during the sustain portion of the envelope, the magnitude of the effect follows the same straight line as before the envelope was applied. For the duration of the attack and fade, the slope of the ramp is modified by the attack and fade levels.

You cannot apply an offset to a ramp force.

To create a ramp force, pass GUID_RampForce to the IDirectInputDevice8::CreateEffect method. You can also pass any other GUID obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEfftype)) is equal to DIEFT_RAMPFORCE. In this way, you can use hardware-specific ramp forces designed by the manufacturer.

A ramp force uses a DIRAMPFORCE structure to define the starting and ending magnitude of the force, whereas the duration is taken from the DIEFFECT structure. Duration must never be set to INFINITE.


Periodic Effects

Periodic effects are waveform effects. Microsoft® DirectInput® defines the following waveforms:

  • Square.
  • Sine.
  • Cosine.
  • Triangle.
  • SawtoothUp. The waveform drops vertically after it reaches maximum positive force. See Basic Concepts of Force Feedback for an example.
  • SawtoothDown. The waveform rises vertically after it reaches maximum negative force.

An envelope can be applied to periodic effects. See the example in Basic Concepts of Force Feedback.

The phase of a periodic effect is the point along the waveform where the effect begins. Phase is measured in hundredths of a degree, from 0 to 35,999. The following table indicates where selected phase values (in degrees) lie along the various waveforms. Max is the top (+) or bottom (–) of the wave, and Mid is the midpoint, where no force is applied in either direction.

Waveform | 0 | 90 | 180 | 270
Square | +Max | +Max | –Max | –Max
Sine | Mid | +Max | Mid | –Max
Triangle | +Max | Mid | –Max | Mid
SawtoothUp | –Max | –Max/2 | Mid | +Max/2 (reaches +Max just before the cycle repeats)
SawtoothDown | +Max | +Max/2 | Mid | –Max/2 (reaches –Max just before the cycle repeats)

A driver may round off a phase value to the nearest supported value. For example, for a sine effect some drivers support only values of 0 and 9,000 (to create a cosine); for other effects, only values of 0 and 18,000 are supported.

To create a periodic force, pass one of the following values in the rguid parameter of the IDirectInputDevice8::CreateEffect method:

  • GUID_Square
  • GUID_Sine
  • GUID_Triangle
  • GUID_SawtoothUp
  • GUID_SawtoothDown

You can also pass any other GUID obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEfftype)) is equal to DIEFT_PERIODIC. In this way, you can use hardware-specific forces designed by the manufacturer. For example, a hardware device might support a periodic effect that rotates the stick in a small circle.

The type-specific structure for periodic effects is DIPERIODIC.

Do not confuse the period of a periodic effect (DIPERIODIC.dwPeriod) with the sample period (DIEFFECT.dwSamplePeriod). The period is the length of time that it takes to go through a complete wave cycle. The sample period, as for all effects, is the minimum time between actual adjustments of magnitude.


Conditions

Conditions are forces applied in response to current sensor values within the device. In other words, conditions require information about device motion, such as position or velocity of a joystick handle.

In general, conditions are not associated with individual events during a game or other application. They represent ambient phenomena, such as the stiffness or looseness of a flight stick, or the tendency of a steering wheel to return to a straight-ahead position.

A condition does not have a predefined magnitude. The magnitude is scaled in proportion to the movement or position of the input object.

Microsoft® DirectInput® defines the following types of condition effects:

  • Friction. The force is applied when the axis is moved and depends on the defined friction coefficient.
  • Damper. The force increases in proportion to the velocity with which the user moves the axis.
  • Inertia. The force increases in proportion to the acceleration of the axis.
  • Spring. The force increases in proportion to the distance of the axis from a defined neutral point.

Most hardware devices do not support the application of envelopes to conditions.

Conditions have the following type-specific parameters:

Offset
The offset from the zero reading of the appropriate sensor value at which the condition begins to be applied. For a spring effect, the neutral point—that is, the point along the axis at which the spring would be considered at rest—would be defined by the offset for the condition. For a damper, the offset would define the greatest velocity value for which damping force is zero. Offset is not normally used for inertia or friction effects.
Coefficient
A multiplier that scales the effect. For some devices, you can set separate coefficients for the positive and negative direction along the axis associated with the condition. For example, a flight stick controlling a damaged aircraft might move more easily to the right than to the left.
Saturation
In force feedback, saturation is an expression of the maximum possible force for an effect. For example, suppose a flight stick has a spring condition on the x-axis. The offset is 0 and the coefficient is 10,000, so the maximum force is normally exerted when the stick is furthest from the center. But if you define a positive and negative saturation of 5,000, the force does not increase after the stick has been moved halfway to the right or left.

Not all devices support saturation.

Deadband
The deadband is a zone around the offset of an axis at which the condition is not active. In the case of a spring that is at rest in the middle of an axis, the deadband enlarges this area of rest.

Not all devices support deadband.

Conditions can have duration, although in most cases you would probably want to set the duration to infinite (–1) and stop the effect only in response to some event in the application.

To create a condition, pass one of the following values in the rguid parameter of the IDirectInputDevice8::CreateEffect method:

  • GUID_Spring
  • GUID_Damper
  • GUID_Inertia
  • GUID_Friction

You can also pass any other GUID obtained by the IDirectInputDevice8::EnumEffects method, provided the low byte of the dwEffType member of the DIEFFECTINFO structure (DIEFT_GETTYPE(dwEfftype)) is equal to DIEFT_CONDITION. In this way, you can use hardware-specific conditions designed by the manufacturer.

The type-specific structure for conditions is DICONDITION. For multiple-axis conditions, you can provide an array of such structures, one for each axis, or a single structure that defines the condition in the specified direction. In either case, you must set the cbTypeSpecificParams member of the DIEFFECT structure to the number of bytes used; that is, to sizeof(DICONDITION) * n, where n is the number of structures provided. For more information on how to use either single or multiple structures, see the DICONDITION structure.

An application should call the IDirectInputDevice8::GetEffectInfo method or the IDirectInputDevice8::EnumEffects method and examine the dwEffectType member of the DIEFFECTINFO structure to determine whether both a positive and a negative coefficient and saturation for the effect are supported on the device. If the effect does not return the DIEFT_POSNEGCOEFFICIENTS flag, it ignores the value in the lNegativeCoefficient member, and the value in lPositiveCoefficient is applied to the entire axis. Likewise, if the effect does not return the DIEFT_POSNEGSATURATION flag, it ignores the value in dwNegativeSaturation, and the value in dwPositiveSaturation is used as the negative saturation level. Finally, if the effect does not return the DIEFT_SATURATION flag, it ignores both the dwPositiveSaturation and dwNegativeSaturation values, and no saturation is applied.

You should also check DIEFFECTINFO.dwEffectType for the DIEFT_DEADBAND flag, to see if deadband is supported for the condition. If it is not supported, the value in the lDeadBand member of the DICONDITION structure will be ignored.

You can set a coefficient to a negative value, and this has the effect of generating the force in the opposite direction. For example, for a spring effect, it would cause the spring to push away from the offset point rather than pulling toward it.


Custom Forces

Application writers can create their own effects by creating a custom force. A custom force is an array of constant force values played back by the device.

The type-specific structure for custom waveform effects is DICUSTOMFORCE.

Set the dwSamplePeriod member of the DICUSTOMFORCE structure and the dwSamplePeriod member of the DIEFFECT structure to the same value. This is the length of time, in milliseconds, for which each element in the array of forces is played.

The custom force is played repeatedly until the time set in the dwDuration member of the DIEFFECT structure has elapsed.


Device-Specific Effects

Hardware drivers can support special effects that do not fit into the categories defined by Microsoft® DirectInput®. The type-specific parameters for these effects may be either hard-coded or modifiable by the application.

If type-specific parameters are modifiable, the application developer must obtain a header file declaring the data structure required by the effect.

The hardware vendor must provide a GUID identifying the device-specific effect and might provide a custom structure for the type-specific parameters of the effect. Your application then must initialize a DIEFFECT structure and a type-specific structure, as with any other effect. You then call the IDirectInputDevice8::CreateEffect method, passing the device-specific GUID and a pointer to the DIEFFECT structure.

When you obtain information about a device-specific effect in a DIEFFECTINFO structure, the low byte of the dwEffType member (DIEFT_GETTYPE(dwEfftype)) indicates into which of the predefined DirectInput effect categories (constant force, ramp force, periodic, or condition) the effect falls. If it does not fall into any of the predefined categories, the value is DIEFT_HARDWARE.

If a device-specific effect falls into one of the predefined categories, the lpvTypeSpecificParams member of the DIEFFECT structure must point to the corresponding DICONSTANTFORCE, DIRAMPFORCE, DIPERIODIC, or DICONDITION structure, and the cbTypeSpecificParams member must be equal to the size of that structure.

If (DIEFT_GETTYPE(dwEfftype) == DIEFT_HARDWARE), the values of the lpvTypeSpecificParams and cbTypeSpecificParams members depend on whether the effect requires custom type-specific parameters. If it does, these values must refer to the appropriate structure defined in the manufacturer's header file and declared and initialized by your application. If the effect does not require custom parameters—that is, if the dwStaticParams member of the DIEFFECTINFO structure for the hardware effect does not have the DIEP_TYPESPECIFICPARAMS flag—lpvTypeSpecificParams must be NULL and cbTypeSpecificParams must be 0.

DirectInput passes the GUID and the DIEFFECT structure to the device driver for verification. If the GUID is unknown, the device returns DIERR_DEVICENOTREG. If the GUID is known but the type-specific data is incorrect for that effect, the device returns DIERR_INVALIDPARAM.


Programming Tips and Tools

This section covers specialized programming topics and an overview of tools provided with the Microsoft® DirectX® SDK that can help in understanding Microsoft DirectInput® data and in designing force-feedback effects.

Information is contained in the following topics.

  • Designing for Previous Versions of DirectInput
  • Preventing Response Delays During Debugging
  • Force Editor


Designing for Previous Versions of DirectInput

In the DirectInput8Create, IDirectInput8::Initialize, IDirectInputDevice8::Initialize, and IDirectInputEffect::Initialize methods, you are required to pass the Microsoft® DirectInput® version number. This parameter specifies which version of Microsoft DirectX® the DirectInput subsystem should emulate.

Applications designed for the latest version of DirectInput should pass the value DIRECTINPUT_VERSION as defined in Dinput.h.

Applications designed to run under previous versions should pass a value corresponding to the version of DirectInput for which they were designed, with the main version number in the high-order byte. For example, an application designed to run on DirectInput 3.0 should pass a value of 0x0300.

If you define DIRECTINPUT_VERSION as 0x0300 before including the Dinput.h header file, the header file generates structure definitions compatible with DirectInput 3.0.

If you do not define DIRECTINPUT_VERSION before including the Dinput.h header file, the header file generates structure definitions compatible with the current version of DirectInput. However, the DirectX 3–compatible structures are available under the same names with "_DX3" appended. For example, the DirectX 3–compatible DIDEVCAPS structure is called DIDEVCAPS_DX3.

You must also use the appropriate versions of the DirectInput and DirectInputDevice interfaces. For versions of DirectX prior to DirectX 7.0, you must use IDirectInput and either IDirectInputDevice or IDirectInputDevice2 (the latter is available for DirectX 5.0 or later.)


Preventing Response Delays During Debugging

When using the keyboard or mouse with Microsoft® DirectInput® under Microsoft Windows® 2000, you might notice short delays in response when you are stepping through code during a debugging session. This behavior occurs only in debug mode, so it is not seen by your application's end users. However, this behavior can be eliminated in debug mode as well by adding the Emulation value to the following registry key.

HKEY_LOCAL_MACHINE
    SOFTWARE
        Microsoft
            DirectInput

Name | Type | Data
Emulation | DWORD | 0x08 (for the mouse) 0x10 (for the keyboard) 0x18 (for both)

Without changing how DirectInput returns data, this value invokes an emulation mode that is not susceptible to those delays. The Microsoft Software Development Kit (SDK) includes two registry files—Mouse and Keyboard Emulation On.reg and Mouse and Keyboard Emulation Off.reg—to activate and deactivate this emulation mode. The files are located under (SDK root)\Samples\Multimedia\DirectInput\Bin.

Note The Emulation value is supported only in debug mode when your device is using an Exclusive and Foreground cooperative level.


Force Editor

Description

The Force Editor application enables you to design force-feedback effects and test them singly or in combination. Effects can be saved to file and then loaded into Microsoft® DirectInput® applications.

Path

Executable: (SDK root)\Bin\Dxutils\Fedit.exe

User's Guide

The Force Editor has its own documentation. Once you've launched Fedit.exe, press F1 for online Help. The Help file can also be launched directly.

(SDK root)\Bin\Dxutils\Fedit.chm


DirectInput C/C++ Tutorials

This section contains five tutorials, each providing step-by-step instructions for implementing basic Microsoft® DirectInput® functionality in a C or C++ application.

  • Tutorial 1: Using the Keyboard

    The first tutorial shows how to add DirectInput keyboard support to an existing application.

  • Tutorial 2: Using the Mouse

    The next tutorial takes you through the steps of providing DirectInput mouse support in an application. The tutorial is based on the Scrawl sample, and focuses on buffered data.

  • Tutorial 3: Using the Joystick

    This tutorial shows how to enumerate a joystick connected to a system, how to create and initialize a DirectInputDevice object in a callback function, and how to retrieve immediate data. Sample code is based on the JoyStick sample.

  • Tutorial 4: Using Force Feedback

    This tutorial illustrates the creation and manipulation of a simple effect on a force-feedback joystick.

  • Tutorial 5: Using Action Mapping

    The final tutorial takes you through the creation and application of an action map.

Note These tutorials are written using C++ style function calls. For instructions on writing Microsoft DirectX® function calls in a C environment, see Using C to Access COM Objects.


Tutorial 1: Using the Keyboard

To prepare for keyboard input, first create an instance of a Microsoft® DirectInput® object. You then use the IDirectInput8::CreateDevice method to create an instance of an IDirectInputDevice8 interface. The IDirectInputDevice8 interface methods are used to manipulate the device, set its behavior, and retrieve data.

This tutorial divides the required tasks into the following steps.

  • Step 1: Creating the DirectInput Object
  • Step 2: Creating the DirectInput Keyboard Device
  • Step 3: Setting the Keyboard Data Format
  • Step 4: Setting the Keyboard Behavior
  • Step 5: Gaining Access to the Keyboard
  • Step 6: Retrieving Data from the Keyboard
  • Step 7: Closing Down the DirectInput System

Adding DirectInput keyboard support to an application is relatively simple, so this tutorial is not based on the complete Keyboard sample application. All of the tutorial steps are illustrated by code fragments within the text. All related steps for initializing the system are gathered in Sample Function 1: DI_Init. Another function, Sample Function 2: DI_Term, is called whenever the system needs to be closed down. Much of the content of these functions are reused in subsequent tutorials.


Step 1: Creating the DirectInput Object

The first step in setting up the Microsoft® DirectInput® system is to create a single DirectInput object as overall manager. This is done with a call to the DirectInput8Create function.

// HINSTANCE  g_hinst; // initialized earlier
HRESULT         hr;
LPDIRECTINPUT8  g_lpDI;

hr = DirectInput8Create(g_hinst, DIRECTINPUT_VERSION,
        IID_IDirectInput8, (void**)&g_lpDI, NULL);
if FAILED(hr)
{
    // DirectInput not available; take appropriate action
}

The first parameter for DirectInput8Create is the instance handle to the application or DLL that is creating the object.

The second parameter tells the DirectInput object which version of the DirectInput system should be used. You can design your application to be compatible with earlier versions of DirectInput. For more information, see Designing for Previous Versions of DirectInput.

The third parameter determines which interface is returned. Most applications obtain the most recent version, by passing IID_IDirectInput8.

The fourth parameter is the address of a variable that is initialized with a valid interface pointer if the call succeeds.

The last parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

After creating a single DirectInput object as overall manager, go to Step 2: Creating the DirectInput Keyboard Device.


Step 2: Creating the DirectInput Keyboard Device

After creating the Microsoft® DirectInput® object, your application must create the keyboard object—the device—and retrieve a pointer to an IDirectInputDevice8 interface. The device performs most of the keyboard-related tasks, using the methods of the interface.

To do this your application must call the IDirectInput8::CreateDevice method, as shown in Sample Function 1: DI_Init. CreateDevice accepts three parameters.

The first parameter is the GUID for the device being created. Because the system keyboard is used, your application should pass the GUID_SysKeyboard predefined global variable.

The second parameter is the address of a variable that is initialized with the interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

The following example attempts to retrieve a pointer to an IDirectInputDevice8 interface. If this fails, it calls the DI_Term application-defined sample function to deallocate existing DirectInput objects, if any.

Note In all the examples, g_lpdi is the initialized pointer to the DirectInput object.

HRESULT               hr;
LPDIRECTINPUTDEVICE8  g_lpDIDevice

hr = g_lpDI->CreateDevice(GUID_SysKeyboard, &g_lpDIDevice, NULL);
if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After creating the DirectInput keyboard device, go to Step 3: Setting the Keyboard Data Format.


Step 3: Setting the Keyboard Data Format

After retrieving an IDirectInputDevice8 pointer, your application must set the device's data format, as shown in Sample Function 1: DI_Init. For keyboards, this is a very simple task. Call the IDirectInputDevice8::SetDataFormat method, specifying the data format provided by Microsoft® DirectInput® in the c_dfDIKeyboard global variable.

The following example attempts to set the data format. If this fails, it calls the DI_Term sample function to deallocate existing DirectInput objects, if any.

hr = g_lpDIDevice->SetDataFormat(&c_dfDIKeyboard);

if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After setting the keyboard data format, go to Step 4: Setting the Keyboard Behavior.


Step 4: Setting the Keyboard Behavior

Before your application can gain access to the keyboard, it must set the device's behavior using the IDirectInputDevice8::SetCooperativeLevel method, as shown in Sample Function 1: DI_Init. This method accepts the handle to the window to be associated with the device and a combination of flags that determine the cooperative level. In this case the application is requesting foreground, nonexclusive access.

The following example attempts to set the device's cooperative level. If this fails, it calls the DI_Term application-defined sample function to deallocate existing Microsoft® DirectInput® objects, if any.

// Set the cooperative level
hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
                   DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);

if FAILED(hr) {
    DI_Term();
    return FALSE;
}

After setting the keyboard behavior, go to Step 5: Gaining Access to the Keyboard.


Step 5: Gaining Access to the Keyboard

After your application sets the keyboard's behavior, it can acquire access to the device by calling the IDirectInputDevice8::Acquire method. The application must acquire the device before retrieving data from it. The Acquire method accepts no parameters.

The following line of sample code acquires the keyboard device that was created in Step 2: Creating the DirectInput Keyboard Device.

if (g_lpDIDevice) g_lpDIDevice->Acquire();

Now that your application has acquired access to the keyboard, go to Step 6: Retrieving Data from the Keyboard.


Step 6: Retrieving Data from the Keyboard

Once a device is acquired, your application can start retrieving data from it. The simplest way to do this is to call the IDirectInputDevice8::GetDeviceState method, which takes a snapshot of the device's state at the time of the call.

The GetDeviceState method accepts two parameters: the size of a buffer to be filled with device state data, and a pointer to that buffer. For keyboards, always declare a buffer of 256 unsigned bytes.

The following sample attempts to retrieve the state of the keyboard. If this fails, it calls an application-defined sample function to deallocate existing Microsoft® DirectInput® objects, if any. See Sample Function 2: DI_Term.

After retrieving the keyboard's current state, your application can respond to specific keys that were pressed down at the time of the call. Each element in the buffer represents a key. If an element's high bit is 1, the key was down at the moment of the call; otherwise, the key was up. To check the state of a given key, use the DirectInput Keyboard Device Constants to index the buffer for a given key.

The following skeleton function, called from the main loop of a hypothetical spaceship game, uses the IDirectInputDevice8::GetDeviceState method to poll the keyboard. It then checks to see if the LEFT ARROW, RIGHT ARROW, UP ARROW or DOWN ARROW keys were pressed when the device state was retrieved. This is accomplished with the KEYDOWN macro defined in the body of the function. The macro accepts a buffer's variable name and an index value, then checks the byte at the specified index to see if the high bit is set and returns TRUE if it is.

void WINAPI ProcessKBInput()
{
    #define KEYDOWN(name, key) (name[key] & 0x80)

    char     buffer[256];
    HRESULT  hr;

    hr = g_lpDIDevice->GetDeviceState(sizeof(buffer),(LPVOID)&buffer);
    if FAILED(hr)
    {
         // If it failed, the device has probably been lost.
         // Check for (hr == DIERR_INPUTLOST)
         // and attempt to reacquire it here.
         return;
    }

    // Turn the spaceship right or left
    if (KEYDOWN(buffer, DIK_RIGHT));
        // Turn right.
    else if(KEYDOWN(buffer, DIK_LEFT));
        // Turn left.

    // Thrust or stop the spaceship
    if (KEYDOWN(buffer, DIK_UP)) ;
        // Move the spaceship forward.
    else if (KEYDOWN(buffer, DIK_DOWN));
        // Stop the spaceship.
}

Now that your application can retrieve data from the keyboard, go to Step 7: Closing Down the DirectInput System.


Step 7: Closing Down the DirectInput System

When an application is about to close, it should destroy all Microsoft® DirectInput® objects. This is a three-step process.

  • Unacquire all DirectInput devices (IDirectInputDevice8::Unacquire)
  • Release all DirectInput devices (IDirectInputDevice8::Release)
  • Release the DirectInput object (IDirectInput8::Release)

For a sample function that closes down the DirectInput system, see Sample Function 2: DI_Term.


Sample Function 1: DI_Init

This application-defined sample function creates a Microsoft® DirectInput® object, initializes it, and retrieves the necessary interface pointers, assigning them to global variables. When initialization is complete, it acquires the device.

If any part of the initialization fails, this function calls the DI_Term application-defined sample function to deallocate DirectInput objects and interface pointers in preparation for terminating the program. See Sample Function 2: DI_Term.

In addition to creating the DirectInput object, the DI_Init function performs the tasks discussed in the following tutorial steps.

  • Step 2: Creating the DirectInput Keyboard Device
  • Step 3: Setting the Keyboard Data Format
  • Step 4: Setting the Keyboard Behavior
  • Step 5: Gaining Access to the Keyboard

The following is the DI_Init function.

/* The following variables are presumed to be initialized:
HINSTANCE             g_hinst;    // application instance
HWND                  g_hwndMain; // application window
*/

LPDIRECTINPUT8        g_lpDI;
LPDIRECTINPUTDEVICE8  g_lpDIDevice;

BOOL WINAPI DI_Init()
{
    HRESULT hr;

    // Create the DirectInput object.
    hr = DirectInput8Create(g_hinst, DIRECTINPUT_VERSION,
                            IID_IDirectInput8, (void**)&g_lpDI, NULL);

    if FAILED(hr) return FALSE;

    // Retrieve a pointer to an IDirectInputDevice8 interface
    hr = g_lpDI->CreateDevice(GUID_SysKeyboard, &g_lpDIDevice, NULL);

    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Now that you have an IDirectInputDevice8 interface, get
    // it ready to use.

    // Set the data format using the predefined keyboard data
    // format provided by the DirectInput object for keyboards.

    hr = g_lpDIDevice->SetDataFormat(&c_dfDIKeyboard);

    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Set the cooperative level
    hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
                             DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    // Get access to the input device.
    hr = g_lpDIDevice->Acquire();
    if FAILED(hr)
    {
        DI_Term();
        return FALSE;
    }

    return TRUE;
}


Sample Function 2: DI_Term

This application-defined sample function deallocates existing Microsoft® DirectInput® interface pointers in preparation for program shutdown or in the event of a failure to properly initialize a device.

/* The following variables are presumed initialized:
LPDIRECTINPUT8        g_lpDI;
LPDIRECTINPUTDEVICE8  g_lpDIDevice;
*/

void WINAPI DI_Term()
{
    if (g_lpDI)
    {
        if (g_lpDIDevice)
        {
        // Always unacquire device before calling Release().
            g_lpDIDevice->Unacquire();
            g_lpDIDevice->Release();
            g_lpDIDevice = NULL;
        }
        g_lpDI->Release();
        g_lpDI = NULL;
    }
}

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.


Tutorial 2: Using the Mouse

This tutorial guides you through the process of setting up a mouse device and retrieving buffered input data. The examples are based on the Scrawl sample.

To prepare for mouse input, you first create an instance of a Microsoft® DirectInput® object. Then you use the IDirectInput8::CreateDevice method to create an instance of an IDirectInputDevice8 interface. The IDirectInputDevice8 interface methods are used to manipulate the device, set its behavior, and retrieve data.

The preliminary step of setting up the DirectInput system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard.

This tutorial divides the required tasks into the following steps.

  • Step 1: Creating the DirectInput Mouse Device
  • Step 2: Setting the Mouse Data Format
  • Step 3: Setting the Mouse Behavior
  • Step 4: Preparing for Buffered Input from the Mouse
  • Step 5: Managing Access to the Mouse
  • Step 6: Retrieving Buffered Data from the Mouse

Note When an application acquires the mouse at the exclusive cooperative level, Microsoft Windows® does not show a mouse pointer on the screen. For this, your application needs a simple sprite engine. The Scrawl sample application uses the Microsoft Win32® function DrawIcon to display a crosshair cursor.


Step 1: Creating the DirectInput Mouse Device

After creating the Microsoft® DirectInput® object, your application should retrieve a pointer to an IDirectInputDevice8 interface, which is used to perform most mouse-related tasks. To do this, call the IDirectInput8::CreateDevice method.

The first parameter of CreateDevice is the globally unique identifier (GUID) for the device your application is creating. In this case, because the system mouse is used, your application should pass the predefined global variable GUID_SysMouse.

The second parameter is the address of a variable that is initialized with a valid IDirectInputDevice8 interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. Because most applications do not use aggregation, the value of this parameter is usually NULL.

The following sample code attempts to retrieve a pointer to an IDirectInputDevice8 interface. If the call fails, FALSE is returned. It is assumed that g_pDI is a valid pointer to IDirectInput8.

LPDIRECTINPUTDEVICE g_pMouse;
HRESULT             hr;

hr = g_pDI->CreateDevice(GUID_SysMouse, &g_pMouse, NULL);

if (FAILED(hr)) {
    return FALSE;
}

After creating the DirectInput mouse device, go to Step 2: Setting the Mouse Data Format.


Step 2: Setting the Mouse Data Format

After retrieving an IDirectInputDevice8 pointer, your application must set the device's data format. For mouse devices, this is a very simple task. Call the IDirectInputDevice8::SetDataFormat method, specifying the data format provided for your convenience by Microsoft® DirectInput® in the c_dfDIMouse global variable.

The following code fragment attempts to set the device's data format. If the call fails, FALSE is returned.

hr = g_pMouse->SetDataFormat(&c_dfDIMouse);

if (FAILED(hr)) {
    return FALSE;
}

After setting the mouse data format, go to Step 3: Setting the Mouse Behavior.


Step 3: Setting the Mouse Behavior

Before it can gain access to the mouse, your application must set the mouse device's behavior using the IDirectInputDevice8::SetCooperativeLevel method. This method accepts the handle to the window to be associated with the device. In Scrawl, the DISCL_EXCLUSIVE flag is included to ensure that this application is the only one that can have exclusive access to the device. This flag is combined with DISCL_FOREGROUND because Scrawl should not allow data input when another application is in the foreground.

The following code sample attempts to set the device's cooperative level. If this attempt fails, FALSE is returned. It is assumed that hWnd is a valid window handle.

hr = g_pMouse->SetCooperativeLevel(hWnd,
               DISCL_EXCLUSIVE | DISCL_FOREGROUND);

if (FAILED(hr)) {
    return FALSE;
}

After setting the mouse behavior, go to Step 4: Preparing for Buffered Input from the Mouse.


Step 4: Preparing for Buffered Input from the Mouse

The Scrawl application demonstrates how to use event notification to find out about mouse activity, and how to read buffered input from the mouse. Both of these techniques require some setup. You can perform these steps at any time after creating the mouse device and before acquiring it.

First, create an event and associate it with the mouse device. You are instructing Microsoft® DirectInput® to notify the mouse device object whenever a hardware interrupt indicates that new data is available.

This is how it is done in Scrawl, where g_hevtMouse is a global HANDLE.

g_hMouseEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

if (g_hMouseEvent == NULL) {
    return FALSE;
}

hr = g_pMouse->SetEventNotification(g_hMouseEvent);

if (FAILED(hr)) {
    return FALSE;
}

Now set the buffer size so that DirectInput can store any input data until you are ready to look at it. Note that by default the buffer size is zero, so this step is essential if you want to use buffered data.

It is not necessary to used buffered data with event notification. If you prefer, you can retrieve immediate data when an event is signaled.

To set the buffer size, initialize a DIPROPDWORD structure with information about itself and about the property you wish to set. Most of the values are boilerplate. The key value is the last one, dwData, which is initialized with the number of items you want the buffer to hold.

#define SAMPLE_BUFFER_SIZE  16

DIPROPDWORD dipdw;
    // the header
    dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
    dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    dipdw.diph.dwObj        = 0;
    dipdw.diph.dwHow        = DIPH_DEVICE;
    // the data
    dipdw.dwData            = SAMPLE_BUFFER_SIZE;

You then pass the address of the header (the DIPROPHEADER structure within the DIPROPDWORD structure), along with the identifier of the property you want to change, to the IDirectInputDevice8::SetProperty method, as follows:

hr = g_pMouse->SetProperty(DIPROP_BUFFERSIZE, &dipdw.diph);

if (FAILED(hr)) {
    return FALSE;
}

The setup is now complete, and you are ready to acquire the mouse and start collecting data.

After preparing your application for buffered input from the mouse, go to Step 5: Managing Access to the Mouse.


Step 5: Managing Access to the Mouse

Microsoft® DirectInput® provides the IDirectInputDevice8::Acquire and IDirectInputDevice8::Unacquire methods to manage device access. Your application must call the Acquire method to gain access to the device before requesting mouse information with the IDirectInputDevice8::GetDeviceState and IDirectInputDevice8::GetDeviceData methods.

Most of the time your application has the device in an acquired state. However, if you have only foreground access, the mouse is automatically unacquired whenever your application moves to the background. You are responsible for reacquiring it when you get the focus back again. This can be done in response to a WM_ACTIVATE message.

Scrawl handles this message by setting a global variable, g_bActive, according to whether the application is gaining or losing the focus. It then calls a helper function, SetAcquire, which acquires the mouse if g_bActive is TRUE and unacquires it otherwise.

case WM_ACTIVATE:
    if (WA_INACTIVE == wParam)
        g_bActive = FALSE;
    else
        g_bActive = TRUE;

    // Set exclusive mode access to the mouse based on active state
    SetAcquire();
    return 0;

If you have exclusive access, your application might need to unacquire the mouse to enable the user to interact with Microsoft Windows®—for example, to access a menu or a dialog box. In Scrawl this can happen when the user opens the system menu with ALT+SPACEBAR.

The Scrawl window procedure has a handler for WM_ENTERMENULOOP that responds by setting the global variable g_bActive to FALSE and calling the SetAcquire function. This handler enables Windows to have the mouse and display its own cursor.

When the user is done using a menu, Windows sends the application a WM_EXITSIZEMOVE message. In this case, the Scrawl window process sets g_bActive appropriately and calls SetAcquire.

Scrawl also unacquires the mouse in response to a right-button click, which displays a shortcut menu. Although the mouse would get unacquired later, in the WM_ENTERMENULOOP handler, it is unacquired here first so that the position of the Windows cursor can be set before the menu appears.

Finally, Scrawl tries to reacquire the mouse if it receives a DIERR_INPUTLOST error after an attempt to retrieve data. This is in case the device has been unacquired by some mechanism not covered elsewhere; for instance, if the user has pressed CTRL+ALT+DEL.

In summary, your application needs to acquire the mouse before it can get data from it. This needs to be done only once, as long as nothing happens to force your application to surrender access to it. In exclusive mode, you are responsible for giving up control of the mouse when Windows needs it. You are also responsible for reacquiring the mouse whenever your program needs access to it after losing it to Windows or another application.

Once your application can manage access to the mouse, go to Step 6: Retrieving Buffered Data from the Mouse.


Step 6: Retrieving Buffered Data from the Mouse

Once the mouse is acquired, your application can begin to retrieve data from it.

In the Scrawl sample, retrieval is triggered by a signaled event. In the WinMain function, the application sleeps until MsgWaitForMultipleObjects indicates that there is either a signal or a message. If there is a signal associated with the mouse, the OnMouseInput function is called. This function is a good illustration of how buffered input is handled, as shown in the following process.

First, the function makes sure that the old cursor position is cleaned up. Note that Scrawl is maintaining its own cursor and is wholly responsible for drawing and erasing it.

VOID OnMouseInput(HWND hWnd)
{
    /* Invalidate the old cursor so that it will be erased */
    InvalidateCursorRect(hWnd);

Next, the function enters a loop to read and respond to the entire contents of the buffer. Because it retrieves just one item at a time, it needs only a single DIDEVICEOBJECTDATA structure to hold the data.

    while (!bDone) {
        DIDEVICEOBJECTDATA od;
        DWORD dwElements = 1;   // number of items to be retrieved

Note Another way to go about handling input would be to read the entire buffer at once and then loop through the retrieved items, responding to each one in turn. In that case, dwElements would be the size of the buffer, and od would be an array with the same number of elements.

The application calls the IDirectInputDevice8::GetDeviceData method in order to fetch the data. The second parameter tells Microsoft® DirectInput® where to put the data, and the third tells it how many items are wanted. The final parameter would be DIGDD_PEEK if the data was to be left in the buffer, but in this case the data is not needed again, and so it is removed.

        hr = g_pMouse->GetDeviceData(sizeof(DIDEVICEOBJECTDATA),
                                     &od, &dwElements, 0);

Next, the application checks to see if access to the device has been lost and, if so, attempts to reacquire the mouse at the first opportunity. This step was discussed in Step 5: Managing Access to the Mouse.

        if (hr == DIERR_INPUTLOST)
        {
            SetAcquire();
            break;
        }

Next, the application makes sure the call to the GetDeviceData method succeeded and that there was actually data to be retrieved. Note that after the call to GetDeviceData the dwElements variable shows how many items were actually retrieved.

        /* Unable to read data or no data available */
        if (FAILED(hr) || dwElements == 0)
        {
            break;
        }

If execution has proceeded to this point, the call succeeded and there is an item of data in the buffer. Now the application looks at the dwOfs member of the DIDEVICEOBJECTDATA structure to determine which object on the device reported a change of state, and it calls helper functions to respond appropriately. The value of the dwData member, which contains information about what occurred with the device object, is passed to these functions.

        /* Look at the element to see what occurred */

        switch (od.dwOfs)
        {
            // Mouse horizontal motion
            case DIMOFS_X:
                UpdateCursorPosition(od.dwData, 0);
                break;

            // Mouse vertical motion
            case DIMOFS_Y:
                UpdateCursorPosition(0, od.dwData);
                break;

            // DIMOFS_BUTTON0: Right button pressed or released
            case DIMOFS_BUTTON0:
            // DIMOFS_BUTTON1: Left button pressed or released
            case DIMOFS_BUTTON1:
                // Is the right button or a swapped left button down?
                if((g_bSwapMouseButtons &&
                               DIMOFS_BUTTON1 == od.dwOfs) ||
                   (!g_bSwapMouseButtons &&
                               DIMOFS_BUTTON0 == od.dwOfs))
                {
                    if (od.dwData & 0x80)  // Left button pressed, so
                                           // go into button-down mode
                    {
                        bDone = TRUE;
                        OnLeftButtonDown(hWnd);
                    }
                // Is the left button or a swapped right button down?
                if((g_bSwapMouseButtons &&
                               DIMOFS_BUTTON0 == od.dwOfs) ||
                   (!g_bSwapMouseButtons &&
                               DIMOFS_BUTTON1 == od.dwOfs))
                {
                    if(!(od.dwData & 0x80))  // button release, so
                                             // check shortcut menu
                    {
                        bDone = TRUE;
                        OnRightButtonUp(hWnd);
                    }
                }
                break;
        }

Finally, in the event that the cursor has been moved by one of the helper functions, the OnMouseInput sample function invalidates the screen rectangle occupied by the cursor.

    // Invalidate the new cursor so that it will be drawn
    InvalidateCursorRect(hWnd);
}

Scrawl also collects mouse data in the OnLeftButtonDown function. This is where the application keeps track of mouse movements while the primary button is being held down—that is, while the user is drawing. This function does not rely on event notification, but repeatedly polls the DirectInput buffer until the button is released.

Note that in the OnLeftButtonDown function no drawing is done until all pending data has been read. This is because each horizontal or vertical movement of the mouse is reported as a separate event. (Both events are, however, placed in the buffer at the same time.) If a line were immediately drawn in response to each separate axis movement, a diagonal mouse movement would produce two lines at right angles.

Another way you can be sure that the movement in both axes is taken into account before responding in your application is to check the sequence numbers of the x-axis item and the y-axis item. If the numbers are the same, the two events took place simultaneously. For more information, see Time Stamps and Sequence Numbers.

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.


Tutorial 3: Using the Joystick

This tutorial shows you how to enumerate a joystick attached to a system and set it up for input. Code samples are based on the JoyStick sample.

The preliminary step of setting up the Microsoft® DirectInput® system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard.

The first step in this tutorial is to enumerate devices; that is, to see what joysticks are available. As part of this process you initialize each joystick device and set its desired characteristics. You then use the IDirectInputDevice8 interface methods to retrieve data from each joystick.

This tutorial divides the required tasks into the following steps.

  • Step 1: Enumerating the Joysticks
  • Step 2: Creating the DirectInput Joystick Device
  • Step 3: Setting the Joystick Data Format
  • Step 4: Setting the Joystick Behavior
  • Step 5: Gaining Access to the Joystick
  • Step 6: Retrieving Data from the Joystick


Step 1: Enumerating the Joysticks

After creating the Microsoft® DirectInput® system, call the IDirectInput8::EnumDevices method to enumerate the joysticks, as in the following sample code.

//g_pDI is an initialized pointer to IDirectInput8

g_pDI->EnumDevices(DI8DEVCLASS_GAMECTRL, EnumJoysticksCallback,
                       NULL, DIEDFL_ATTACHEDONLY)

The DI8DEVCLASS_GAMECTRL constant, passed as the first parameter, specifies the class of device to be enumerated.

EnumJoysticksCallback is the address of a callback function to be called each time a joystick is found. This is where the individual devices are created in Step 2: Creating the DirectInputJoystick Device.

The third parameter can be any 32-bit value that you want to make available to the callback function. In this case, nothing is being sent.

The last parameter, DIEDFL_ATTACHEDONLY, is a flag that restricts enumeration to devices that are attached to the computer.

When your application can enumerate the joysticks, go to Step 2: Creating the DirectInput Joystick Device.


Step 2: Creating the DirectInput Joystick Device

After creating the Microsoft® DirectInput® object, the application must retrieve a pointer to an IDirectInputDevice8 interface, which is used to perform most joystick-related tasks. In the JoyStick sample, this is done in the callback function EnumJoysticksCallback, which is called each time a joystick is enumerated.

The following sample code is the first part of the callback function.

BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE*
                                       pdidInstance, VOID* pContext)
{
    HRESULT hr;

    // Obtain an interface to the enumerated joystick.
    hr = g_pDI->CreateDevice(pdidInstance->guidInstance,
                                &g_pJoystick, NULL);
    if(FAILED(hr))
        return DIENUM_CONTINUE;

    return DIENUM_STOP;

The EnumJoysticksCallback callback function parameters are as follows:

  • A pointer to the device instance, supplied by the DirectInput system when the device is enumerated.
  • A pointer to a 32-bit value that you supplied as a parameter to IDirectInput8::EnumDevices. This parameter could be any 32-bit value such as a pointer to an interface so that you could use its methods. In this case, however, NULL was passed.

The first task of the callback function is to create the device. The IDirectInput8::CreateDevice method accepts three parameters.

The first parameter is a reference to the globally unique identifier (GUID) for the instance of the device. In this case, the GUID is taken from the DIDEVICEINSTANCE structure supplied by DirectInput when it enumerated the device.

The second parameter is the address of the variable that is initialized with a valid interface pointer if the call succeeds.

The third parameter specifies the address of the controlling object's IUnknown interface for use in COM aggregation. The JoyStick sample does not use aggregation, so the parameter is NULL.

Note that if the device interface cannot be created, DIENUM_CONTINUE is returned from the callback function. This flag instructs DirectInput to keep enumerating as long as there are devices to be enumerated.

After creating the DirectInput joystick device, go to Step 3: Setting the Joystick Data Format.


Step 3: Setting the Joystick Data Format

Now that the application has a pointer to a Microsoft® DirectInput® device, it can call the IDirectInputDevice8 methods to manipulate that device. The first step, which is essential, is to set the data format for the joystick. This step tells DirectInput how to format the input data.

if (FAILED(hr = g_pJoystick->SetDataFormat(&c_dfDIJoystick2)))
    return hr;

The IDirectInputDevice8::SetDataFormat method takes one parameter, a pointer to a DIDATAFORMAT structure containing information about how the data for the device is to be formatted. For the joystick, you can use the predefined global variable c_dfDIJoystick2, which signifies use of the DIJOYSTATE2 structure to retrieve data.

After setting the joystick data format, go to Step 4: Setting the Joystick Behavior.


Step 4: Setting the Joystick Behavior

The joystick device has been created, and its data format has been set. The next step is to set its cooperative level. As in the previous step, g_pJoystick is a pointer to the device interface.

if (FAILED(hr = g_pJoystick->SetCooperativeLevel(hDlg,
                    DISCL_EXCLUSIVE | DISCL_FOREGROUND)))
    return hr;

The first parameter to IDirectInputDevice8::SetCooperativeLevel is a window handle. In this case, the handle to the dialog box serving as the main program window is passed to the function.

The final parameter is a combination of flags describing the desired cooperative level. The Joystick sample requires input from the joystick only when it is the foreground application. Also, when the joystick sample is in the foreground, it should be the only application with exclusive access to the joystick. Therefore, the flags are set to DISCL_EXCLUSIVE | DISCL_FOREGROUND. See Cooperative Levels for a full explanation of these flags.

The next step is to gather information about the capabilities of the joystick. This information includes the number of axes, buttons, and other controllers, whether the device supports force feedback, and other details about the joystick's behavior and supported options.

A DIDEVCAPS structure is used to hold the capability information. The dwSize member of the DIDEVCAPS structure must first be initialized, then the address of the structure sent to IDirectInputDevice8::GetCapabilities. In the example below, g_diDevCaps is a previously declared DIDEVCAPS structure.

g_diDevCaps.dwSize = sizeof(DIDEVCAPS);
if (FAILED(hr = g_pJoystick->GetCapabilities(&g_diDevCaps)))
    return hr;

At this point, you could proceed using the device defaults or you could customize the device properties. The Joystick sample enumerate the axes on the joystick and sets a range for each by calling IDirectInputDevice8::EnumObjects.

if (FAILED(hr = g_pJoystick->EnumObjects(EnumAxesCallback,
                                       (VOID*)hDlg, DIDFT_AXIS)))
    return hr;

The first parameter to the EnumObjects method, EnumAxesCallback, is the address of a callback function which processes the enumerated objects as desired.

The second parameter can be any 32-bit value that you might want to provide to the callback function. Here, the handle to the main dialog window is passed so that it can update the display to indicate which axes are found on the joystick.

The last parameter, DIDFT_AXIS, tells the callback function to enumerate only device axes.

In the sample, the properties changed will be the range for any axis or slider detected (a slider is considered an axis).

By setting the range, you are telling DirectInput what maximum and minimum values you want returned for an axis. If you set a range of -1,000 to +1,000 for the x-axis, as in the example, you are asking that a value of -1,000 be returned when the stick is at the extreme left, +1,000 when it is at the extreme right, and zero when it is in the middle.

The following sample code sets the range of an enumerated axis. The pdidoi variable is the address of a DIDEVICEOBJECTINSTANCE structure passed by the system to the callback function. This variable contains information about the object currently being enumerated.

DIPROPRANGE diprg;

diprg.diph.dwSize       = sizeof(DIPROPRANGE);
diprg.diph.dwHeaderSize = sizeof(DIPROPHEADER);
diprg.diph.dwHow        = DIPH_BYID;
diprg.diph.dwObj        = pdidoi->dwType;
diprg.lMin              = -1000;
diprg.lMax              = +1000;
.
.
hr = g_pJoystick->SetProperty(DIPROP_RANGE, &diprg.diph);
if (FAILED(hr))
    return DIENUM_STOP;

The first task here is to set up the DIPROPRANGE structure diprg, whose address is passed into the IDirectInputDevice8::SetProperty method. Note that it is not the address of the structure itself that is passed but rather the address of its first member, which is a DIPROPHEADER structure. For more information, see Device Properties.

The property header is initialized with the following values.

  • The size of the property structure
  • The size of the header structure
  • A flag to indicate how the dwObj member is to be interpreted.
  • The value found in the dwType member of the DIDEVICEOBJECTINSTANCE structure indicating the object whose property is being changed.

The lmin and lmax members of the DIPROPRANGE structure are assigned the desired range values.

The application now calls the IDirectInputDevice8::SetProperty method. The first parameter is a flag indicating which property is being changed. The second parameter is the address of the DIPROPHEADER member of the property structure.

After setting the joystick behavior, go to Step 5: Gaining Access to the Joystick.


Step 5: Gaining Access to the Joystick

After your application sets a joystick's behavior, it can acquire access to the device by calling the IDirectInputDevice8::Acquire method. The application must acquire the device before retrieving data from it. The Acquire method accepts no parameters.

The Joystick sample performs initial acquisition in the message loop as the application is activated. This loop also automatically reacquires the device whenever the application regains focus after having lost it. Acquisition is also performed if access to the joystick is lost or a DIERR_INPUTLOST error is returned when the application attempts to get input data. This is shown in the following code sample.

hr = g_pJoystick->Poll();
if (FAILED(hr))
{
    hr = g_pJoystick->Acquire();
    while(hr == DIERR_INPUTLOST)
        hr = g_pJoystick->Acquire();
    return S_OK;
}

Once your application can gain access to the joystick go to Step 6: Retrieving Data from the Joystick.


Step 6: Retrieving Data from the Joystick

Because your application is more likely concerned with the position of the joystick axes than with their movement, you probably want to retrieve immediate rather than buffered data from the device. You can do this by polling with IDirectInputDevice8::GetDeviceState. Note that not all device drivers notify Microsoft® DirectInput® when the state of the device changes. Therefore, it is always good policy to call the IDirectInputDevice8::Poll method before checking the device state.

The Joystick application calls the following function from the Microsoft® Windows—> message loop.

HRESULT UpdateInputState(HWND hDlg)
{
    HRESULT     hr;
    CHAR        strText[128]; // Device state text
    DIJOYSTATE2 js;           // Direct Input joystick state
    CHAR*       str;

    if (NULL == g_pJoystick)
        return S_OK;

    // Poll the device to read the current state
    hr = g_pJoystick->Poll();
    if (FAILED(hr))
    {
        // Attempt to reacquire joystick
    }
    hr = g_pJoystick->GetDeviceState(sizeof(DIJOYSTATE2), &js);
    if (FAILED(hr))
        return hr;

Note the call to GetDeviceState. The first parameter is the size of the structure in which the data is returned, and the second parameter is the address of this structure, which is of type DIJOYSTATE2. This structure holds data for up to six axes, 128 buttons, and four point-of-view hats. The sample program proceeds to look at the state of all axes and buttons, and one slider. This information is then displayed in the main dialog window.

Joystick buttons work just like keys or mouse buttons. If the high bit of the returned byte is 1, the button is pressed.

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.


Tutorial 4: Using Force Feedback

This tutorial takes you through the process of creating, playing, and modifying a simple effect on a force-feedback joystick. The effect is based on the feel of running a chain saw. Effects are created that simulate a chain saw starting with some difficulty, running normally, and cutting into wood.

The preliminary step of setting up the Microsoft® DirectInput® system and the final step of closing it down are essentially the same for any application and are covered in Tutorial 1: Using the Keyboard. However, when closing down the DirectInput force-feedback system, you are required to take the additional step of releasing any effects you have created.

This tutorial divides the required tasks into the following steps.

  • Step 1: Enumerating Force-Feedback Devices
  • Step 2: Creating the DirectInput Force-Feedback Device
  • Step 3: Enumerating Supported Effects
  • Step 4: Creating an Effect
  • Step 5: Playing an Infinite Effect
  • Step 6: Changing an Effect


Step 1: Enumerating Force-Feedback Devices

The first step is to ensure that a force-feedback device is available on the system. You do this by calling the IDirectInput8::EnumDevices method. In the following example, the global pointer to the game device interface is initialized only if the enumeration has succeeded in finding at least one suitable device:

LPDIRECTINPUTDEVICE8  g_lpDIDevice = NULL;

hr = g_lpDI->EnumDevices(DI8DEVTYPE_GAMECTRL,
                         DIEnumDevicesProc,
                         NULL,
                         DIEDFL_FORCEFEEDBACK | DIEDFL_ATTACHEDONLY);
if (FAILED(hr))
{
  // No force-feedback joystick available; take appropriate action.
}

In the example, g_lpDI is an initialized pointer to the IDirectInput8 interface. The first parameter to EnumDevices restricts the enumeration to joystick-type devices. The second parameter is the callback function that is called whenever Microsoft® DirectInput® identifies a device that qualifies for enumeration. The third parameter is for user-defined data to be passed in or out of the callback function; in this case it is not used. Finally, the flags further restrict the enumeration to devices attached to the system that support force feedback.

The callback function is a convenient place to initialize the device as soon as it has been found. (It is assumed that the first device found is the one you want to use.) You do this in Step 2: Creating the DirectInput Force-Feedback Device.


Step 2: Creating the DirectInput Force-Feedback Device

To have Microsoft® DirectInput® enumerate devices, create a callback function of the same type as DIEnumDevicesCallback. In Step 1 you passed the address of this function to the IDirectInput8::EnumDevices method.

DirectInput passes into the callback, as the first parameter, a pointer to a DIDEVICEINSTANCE structure that tells you what you need to know about the device. The structure member of most interest in the example is guidInstance, the unique identifier for the particular piece of hardware on the user's system. You must pass this GUID to the IDirectInput8::CreateDevice method.

The following code fragment is the first part of the callback, which extracts the GUID and creates the device object.

BOOL CALLBACK DIEnumDevicesProc( LPCDIDEVICEINSTANCE lpddi,
                                 LPVOID pvRef )
{
    HRESULT hr;
    GUID DeviceGuid = lpddi->guidInstance;

    // Create game device.

    hr = g_lpDI->CreateDevice(DeviceGuid, &g_lpDIDevice, NULL);

    if (FAILED(hr))
        // Continue enumerating until successful or finished
        return DIENUM_CONTINUE;

The next steps of the callback function are similar to those for setting up any input device. Note that you need the exclusive cooperative level for any force-feedback device.

    // Set cooperative level.
    hr = g_lpDIDevice->SetCooperativeLevel(g_hwndMain,
                                  DISCL_EXCLUSIVE | DISCL_FOREGROUND);
    if (FAILED(hr))
        return hr;

    // set game data format
    hr = g_lpDIDevice->SetDataFormat(&c_dfDIJoystick);
    if (FAILED(hr))
        return hr;

Finally, you might want to turn off the device's autocenter feature. Autocenter is essentially a condition effect that uses the motors to simulate the springs in a standard joystick. It is a good idea to turn it off so that it does not interfere with other effects.

    DIPROPDWORD DIPropAutoCenter;

    DIPropAutoCenter.diph.dwSize       = sizeof(DIPropAutoCenter);
    DIPropAutoCenter.diph.dwHeaderSize = sizeof(DIPROPHEADER);
    DIPropAutoCenter.diph.dwObj        = 0;
    DIPropAutoCenter.diph.dwHow        = DIPH_DEVICE;
    DIPropAutoCenter.dwData            = DIPROPAUTOCENTER_OFF;

    hr = g_lpDIDevice->SetProperty(DIPROP_AUTOCENTER,
                                   &DIPropAutoCenter.diph);
    if (FAILED(hr))
    {
        // Handle the failure as appropriate
    }

    return DIENUM_STOP;   // One is enough.
}   // end DIEnumDevicesProc

Before using the device, you must acquire it. See Step 5: Gaining Access to the Joystick in Tutorial 3: Using the Joystick for an example of how to handle acquisition. Note that unlike other property changes, force-feedback effects can be downloaded to a device when it is in an acquired state.

After you have created the DirectInput force-feedback device, go to Step 3: Enumerating Supported Effects.


Step 3: Enumerating Supported Effects

Now that you have successfully enumerated and created a force-feedback device, you can enumerate the effect types it supports.

Effect enumeration is not strictly necessary if you want to create only standard effects that will be available on any device, such as constant forces. When creating the effect object, you can identify the desired effect type simply by using one of the predefined GUIDs, such as GUID_ConstantForce. For a complete list of these identifiers, see IDirectInputDevice8::CreateEffect.

Another more flexible approach is to enumerate supported effects of a particular type, then obtain the GUID for the effect from the callback function. You could use the callback to obtain more information about the device's support for the effect— for example, whether it supports an envelope—but in this tutorial you obtain only the effect GUID.

First, create the callback function that Microsoft® DirectInput® calls for each effect enumerated. For information on this standard callback, see DIEnumEffectsCallback. You can give the function any name you like.

BOOL  EffectFound = FALSE;  // global flag

BOOL CALLBACK DIEnumEffectsProc(LPCDIEFFECTINFO pei, LPVOID pv)
{
    *((GUID *)pv) = pei->guid;
    EffectFound = TRUE;
    return DIENUM_STOP;  // one is enough
}

The GUID variable pointed to by the application-defined value pv is assigned the value passed in the DIEFFECTINFO structure created by DirectInput for the effect.

To obtain the effect GUID, set the callback in motion by calling the IDirectInputDevice8::EnumEffects method, as follows:

HRESULT  hr;
GUID     guidEffect;

hr = g_lpDIDevice->EnumEffects(
                         (LPDIENUMEFFECTSCALLBACK) DIEnumEffectsProc,
                          &guidEffect,
                          DIEFT_PERIODIC);
if (FAILED(hr))
{
    // Note that success does not mean that any effects were found,
    // only that the process went smoothly.
}

Note that you pass the address of a GUID variable, guidEffect, to the EnumEffects method. This address is passed in turn to the callback as the pv parameter. You also restrict the enumeration to periodic effects by setting the flag DIEFT_PERIODIC.

Once your application can enumerate supported effects, go to Step 4: Creating an Effect.


Step 4: Creating an Effect

If the EffectFound value is no longer FALSE after effect enumeration, you can safely assume that Microsoft® DirectInput® has found support for at least one effect of the periodic type you requested by passing the DIEFT_PERIODIC flag. Knowing the effect GUID, you can now create the effect object.

Before calling the IDirectInputDevice8::CreateEffect method, you set up the following arrays and structures.

  • An array of axes that will be involved in the effect. For a joystick, this array normally consists of the identifiers for the x-axis and the y-axis.
  • An array of values for setting the direction. The values differ according to both the number of axes and whether you want to use polar, spherical, or Cartesian coordinates. For a full explanation, see Effect Direction.
  • A structure of type-specific parameters. In the example, because you are creating a periodic effect, this is of type DIPERIODIC.
  • A DIENVELOPE structure for defining an envelope to be applied to the effect.
  • A DIEFFECT structure to contain the basic parameters for the effect.

Arrays can be initialized when they, along with the structures, are declared.

DWORD      dwAxes[2] = {DIJOFS_X, DIJOFS_Y};
LONG       lDirection[2] = {0, 0};

DIPERIODIC diPeriodic;      // type-specific parameters
DIENVELOPE diEnvelope;      // envelope
DIEFFECT   diEffect;        // general parameters

Next, initialize the type-specific parameters. The values in this example create a full-force periodic effect with a period of one-twentieth of a second.

diPeriodic.dwMagnitude = DI_FFNOMINALMAX;
diPeriodic.lOffset = 0;
diPeriodic.dwPhase = 0;
diPeriodic.dwPeriod = (DWORD)(0.05 * DI_SECONDS);

To produce an effect of the chain-saw motor trying to start, briefly coughing into life, and then slowly dying, you set an envelope with an attack time of one-half second and a fade time of one second.

diEnvelope.dwSize = sizeof(DIENVELOPE);
diEnvelope.dwAttackLevel = 0;
diEnvelope.dwAttackTime = (DWORD)(0.5 * DI_SECONDS);
diEnvelope.dwFadeLevel = 0;
diEnvelope.dwFadeTime = (DWORD)(1.0 * DI_SECONDS);

Next, set up the basic effect parameters. These include flags to determine how the directions and device objects (buttons and axes) are identified, the sample period and gain for the effect, and pointers to the other data that you have just prepared. You also associate the effect with the joystick's fire button so that it is automatically played whenever that button is pressed.

diEffect.dwSize = sizeof(DIEFFECT);
diEffect.dwFlags = DIEFF_POLAR | DIEFF_OBJECTOFFSETS;
diEffect.dwDuration = (DWORD)(2 * DI_SECONDS);

diEffect.dwSamplePeriod = 0;               // = default
diEffect.dwGain = DI_FFNOMINALMAX;         // no scaling
diEffect.dwTriggerButton = DIJOFS_BUTTON0;
diEffect.dwTriggerRepeatInterval = 0;
diEffect.cAxes = 2;
diEffect.rgdwAxes = dwAxes;
diEffect.rglDirection = &lDirection[0];
diEffect.lpEnvelope = &diEnvelope;
diEffect.cbTypeSpecificParams = sizeof(diPeriodic);
diEffect.lpvTypeSpecificParams = &diPeriodic;

Finally, you can create the effect.

LPDIRECTINPUTEFFECT  g_lpdiEffect;  // global effect object

hr = g_lpDIDevice->CreateEffect(
                     guidEffect,     // GUID from enumeration
                     &diEffect,      // where the data is
                     &g_lpdiEffect,  // where to put interface pointer
                     NULL);          // no aggregation
if (FAILED(hr))
{
    return hr;
}

Note that, by default, the effect is downloaded to the device as soon as it has been created, provided that the device is in an acquired state at the exclusive cooperative level. You should now be able to compile, run, press the fire button, and feel the sputtering of a chain saw that's out of gas.

After creating an effect object, go to Step 5: Playing an Infinite Effect.


Step 5: Playing an Infinite Effect

The effect created in the previous step starts in response to the press of a button. To create an effect that is to be played in response to an explicit call, return to Step 4: Creating an Effect and modify the dwTriggerButton member of the DIEFFECT structure as follows:

diEffect.dwTriggerButton = DIEB_NOTRIGGER;

To make a chain saw that starts and keeps going, change the dwDuration member as follows:

diEffect.dwDuration = INFINITE;

Next, start the effect.

g_lpdiEffect->Start(1, 0);

The effect keeps running until you stop it.

g_lpdiEffect->Stop();

Note that it is not necessary to change the envelope you created in the previous step. The attack is played as the effect starts, but the fade value is ignored.

Once your application can play an infinite effect, go to Step 6: Changing an Effect.


Step 6: Changing an Effect

Next, you modify the effect to simulate the slowing down of the engine as the saw bites into wood. Microsoft® DirectInput® enables you to modify the parameters of an effect while it is playing.

To change the effect, set up a new DIEFFECT structure or have access to the one you used to create the effect. If you are setting up a new structure with local scope, initialize only the dwSize member and any members that contain or point to data that is to be changed.

In this case, you want to change a type-specific parameter—the period of the effect—so you need to have access to the DIPERIODIC structure you used when creating the effect. Alternatively, you can create a local copy with all members initialized. Make sure that the address of the DIPERIODIC structure is in the lpvTypeSpecificParams member of the DIEFFECT structure.

First, set the new period of the effect.

diPeriodic.dwPeriod = (DWORD)(0.08 * DI_SECONDS);

Next, call the IDirectInputEffect::SetParameters method to make the changes.

hr = g_lpdiEffect->SetParameters(&diEffect, DIEP_TYPESPECIFICPARAMS);

Note the DIEP_TYPESPECIFICPARAMS flag that restricts the changes to a single member of the DIEFFECT structure.

You can control the way changes are handled by using other flags. For example, by using the DIEP_NODOWNLOAD flag you could change the parameters immediately after starting the effect but delay the implementation until a specific call to the IDirectInputEffect::Download method. For more information concerning use of the various control flags, see IDirectInputEffect::SetParameters.

For additional DirectInput tutorials, see DirectInput C/C++ Tutorials.


Tutorial 5: Using Action Mapping

This tutorial guides you through the setup, modification, and application of an action map. Examples are based written as though they were to be used in a space combat game.

The preliminary step of setting up the Microsoft® DirectInput® system and the final step of closing it down are the same for any application and are covered in Tutorial 1: Using the Keyboard. The keyboard, a mouse, and a joystick are all used in the sample, so each of those devices needs to be set up.

This tutorial divides the required tasks into the following steps.

  • Step 1: Defining the Game Actions
  • Step 2: Defining the Action Map
  • Step 3: Mapping Actions to Devices
  • Step 4: Configuring and Applying the Action Map
  • Step 5: Displaying the Action Map
  • Step 6: User Configuration of the Action Map
  • Step 7: Retrieval of Action Mapped Data


Step 1: Defining the Game Actions

The first step toward creating an action map is the definition of the game actions. These actions are specific to the application and are defined by the developer. In the case of this example, the actions chosen reflect its needs as a space combat simulator. These values can be defined in many ways as the developer sees fit. They could be defined as an enumeration, as in the Preparing the Action Map overview, or they could be defined as constants as in this code fragment.

#define INPUT_LEFTRIGHT_AXIS   1L
#define INPUT_UPDOWN_AXIS      2L
#define INPUT_TURNLEFT         3L
#define INPUT_TURNRIGHT        4L
#define INPUT_FORWARDTHRUST    5L
#define INPUT_REVERSETHRUST    6L
#define INPUT_FIREWEAPONS      7L
#define INPUT_ENABLESHIELD     8L
#define INPUT_DISPLAYGAMEMENU  9L
#define INPUT_QUITGAME        10L

Once these values are defined, they can be assigned to genre-specific action-mapping constants. This is done in Step 2: Defining the Action Map.


Step 2: Defining the Action Map

Next, each game action should be assigned to at least one virtual control or device object. These controls are defined as action-mapping constants and are defined by genre and subgenre. In this case, the best choice is the Space Combat subgenre of the flight-games genre. This subgenre makes the following constants available.

Priority 1 Controls

DIAXIS_SPACESIM_LATERAL
DIAXIS_SPACESIM_MOVE
DIAXIS_SPACESIM_THROTTLE
DIBUTTON_SPACESIM_FIRE
DIBUTTON_SPACESIM_MENU
DIBUTTON_SPACESIM_TARGET
DIBUTTON_SPACESIM_WEAPONS

Priority 2 Controls

DIAXIS_SPACESIM_CLIMB
DIAXIS_SPACESIM_ROTATE
DIBUTTON_SPACESIM_BACKWARD_LINK
DIBUTTON_SPACESIM_DEVICE DIBUTTON_SPACESIM_DISPLAY
DIBUTTON_SPACESIM_FASTER_LINK
DIBUTTON_SPACESIM_FIRESECONDARY
DIBUTTON_SPACESIM_FORWARD_LINK
DIBUTTON_SPACESIM_GEAR
DIBUTTON_SPACESIM_GLANCE_DOWN_LINK
DIBUTTON_SPACESIM_GLANCE_LEFT_LINK
DIBUTTON_SPACESIM_GLANCE_RIGHT_LINK
DIBUTTON_SPACESIM_GLANCE_UP_LINK
DIBUTTON_SPACESIM_LEFT_LINK DIBUTTON_SPACESIM_LOWER
DIBUTTON_SPACESIM_PAUSE DIBUTTON_SPACESIM_RAISE
DIBUTTON_SPACESIM_RIGHT_LINK
DIBUTTON_SPACESIM_SLOWER_LINK
DIBUTTON_SPACESIM_TURN_LEFT_LINK
DIBUTTON_SPACESIM_TURN_RIGHT_LINK
DIBUTTON_SPACESIM_VIEW
DIHATSWITCH_SPACESIM_GLANCE

Priority 1 controls are those controls that, at the minimum, should be mapped to a device object if possible. Priority 2 controls are less critical to basic game operation and may be mapped as needed.

Game actions are assigned to action-mapping constant controls in an array of DIACTION structures. Each DIACTION structure contains at least one game action, its associated action-mapping constant, any necessary flags, and either a friendly name or ID string for the action. The remaining DIACTION members are not used at this point. The following code sample shows definition of the array of DIACTION structures.

#define NUMBER_OF_ACTIONS 18

DIACTION g_rgGameAction[NUMBER_OF_ACTIONS] =
{
    // Device input pre-defined by DInput, according to genre
    {INPUT_LEFTRIGHT_AXIS, DIAXIS_SPACESIM_LATERAL, 0, "Turn",},
    {INPUT_UPDOWN_AXIS, DIAXIS_SPACESIM_MOVE, 0, "Move",},
    {INPUT_FIREWEAPONS, DIBUTTON_SPACESIM_FIRE, 0, "Shoot",},
    {INPUT_ENABLESHIELD, DIBUTTON_SPACESIM_GEAR, 0, "Shield",},
    {INPUT_DISPLAYGAMEMENU, DIBUTTON_SPACESIM_DISPLAY, 0, "Display",},
    {INPUT_QUITGAME, DIBUTTON_SPACESIM_MENU, 0, "Quit Game",},

    // Keyboard input mappings
    {INPUT_TURNLEFT, DIKEYBOARD_LEFT, 0, "Turn left", },
    {INPUT_TURNRIGHT, DIKEYBOARD_RIGHT, 0, "Turn right", },
    {INPUT_FORWARDTHRUST, DIKEYBOARD_UP, 0, "Forward thrust", },
    {INPUT_REVERSETHRUST, DIKEYBOARD_DOWN, 0, "Reverse thrust", },
    {INPUT_FIREWEAPONS, DIKEYBOARD_F, 0, "Fire weapons", },
    {INPUT_ENABLESHIELD, DIKEYBOARD_S, 0, "Enable shields", },
    {INPUT_DISPLAYGAMEMENU, DIKEYBOARD_D, DIA_APPFIXED,
                                      "Display game menu"), },
    {INPUT_QUITGAME, DIKEYBOARD_ESCAPE, DIA_APPFIXED, "Quit game", },

    // Mouse input mappings
    {INPUT_LEFTRIGHT_AXIS, DIMOUSE_XAXIS, 0, "Turn", },
    {INPUT_UPDOWN_AXIS, DIMOUSE_YAXIS, 0, "Move", },
    {INPUT_FIREWEAPONS, DIMOUSE_BUTTON0, 0, "Fire weapons", },
    {INPUT_ENABLESHIELD, DIMOUSE_BUTTON1, 0, "Enable shields", },
};

A DIACTIONFORMAT structure is then initialized to contain the DIACTION array g_rgGameAction defined above. The DIACTIONFORMAT structure also defines the genre, buffer size, axis scaling, and a friendly name for the action map. The g_AppGuid value is a GUID defined in the application to identify the action map. For more information on creating GUIDs, see Using GUIDS.

DIACTIONFORMAT diaf;
diaf.dwSize        = sizeof(DIACTIONFORMAT);
diaf.dwActionSize  = sizeof(DIACTION);
diaf.dwDataSize    = NUMBER_OF_ACTIONS * sizeof(DWORD);
diaf.dwNumActions  = NUMBER_OF_ACTIONS;
diaf.guidActionMap = g_AppGuid;
diaf.dwGenre       = DIVIRTUAL_SPACESIM;
diaf.rgoAction     = g_rgGameAction;
diaf.dwBufferSize  = 16;
diaf.lAxisMin      = -100;
diaf.lAxisMax      = 100;
diaf.tszActionMap  = "DI Test";

This DIACTIONFORMAT structure is matched against enumerated devices to find the best match in Step 3: Mapping Actions to Devices.


Step 3: Mapping Actions to Devices

Once the desired mapping has been defined, it must be applied to physical devices. IDirectInput8::EnumDevicesBySemantics begins this process in the following code fragment, where m_pDI is a previously defined IDirectInput8 object.

HRESULT hr;

hr = m_pDI->EnumDevicesBySemantics(m_strUserName, &m_diaf,
                                EnumSuitableDevicesCB, this, 0L);

The first parameter, m_strUserName is useful in the case of multiple users who might have different mapping preferences. However, in the case of this example, this value is NULL, indicating the user currently logged onto the system.

The second parameter is the address of the DIACTIONFORMAT structure containing the mapping information.

The third parameter is the address of a callback function that is called for each device found on the system. The function used in the sample is based on the DIEnumDevicesBySemanticsCallback function.

The fourth parameter could be any 32-bit value that you want to make available to the callback function. Here, this is a this pointer to the class object used by the MultiMapper sample for the various action-mapping setup and manipulation functions. This gives the callback function access to the class' functions.

The final parameter is used for flags. None are used in this example.

The EnumSuitableDevicesCB callback function calls the application-defined function AddDevices, which in turn calls the IDirectInputDevice8::BuildActionMap function on the device pdidDevice currently being enumerated. This call is shown in the following code fragment.

hr = pdidDevice->BuildActionMap( &m_diaf, m_strUserName, 0L );

The first parameter is once again the address of the DIACTIONFORMAT structure containing the action map.

The second parameter is again the name of the user if desired, though NULL in this case.

The final parameter holds control flags, with none being passed in this case.

BuildActionMap takes the list of control assignments specified in the DIACTIONFORMAT structure and attempts to map them to specific device objects on the device being enumerated. The results of the mapping are returned in the same structure. Each pass maps different controls depending on the nature of the currently enumerated device. A keyboard, for instance, maps controls that specify a mapping to a particular key, but leaves controls that specify buttons, sliders, or axes unmapped. If a joystick is enumerated next, BuildActionMap ignores those controls mapped to keyboard keys, but it attempts to map the buttons, sliders, and axes to the joystick's device objects.

The results of this default mapping can be examined and manipulated. This is done in Step 4: Configuring and Applying the Action Map.


Step 4: Configuring and Applying the Action Map

Once the mapping has been returned in the DIACTIONFORMAT structure, it can be manipulated before being applied by IDirectInputDevice8::SetActionMap.

The dwHow member of each DIACTION structure might be examined at this point to determine both whether the mapping was successful and what the criteria were in selecting the device object to which that action was mapped. For instance, you can determine if the mapping was specified by the hardware manufacturer or requested by the user.

The actual mapping itself may be changed as well by editing the dwSemantic member of the appropriate DIACTION structure returned in the default mapping. You can choose to make those changes, but it is not recommended that you do so.

Once the action map configuration is finalized, it must be applied to the device to bind the physical controls to the game actions. This is done by calling SetActionMap as follows:

    hr = pdidDevice->SetActionMap( &m_diaf, m_strUserName, 0L );

Action maps, once created, can be displayed for and easily altered by the user. This is explained in Step 5: Displaying the Action Map.


Step 5: Displaying the Action Map

In addition to the advantage of action mapping in enabling the developer to define game actions independently of specific controller hardware, action mapping also benefits the user by providing a user interface (UI) for easy reconfiguration.

The UI can be displayed in two forms, text-only or graphics. In addition, each of those two options can be viewed in two modes: view-only or edit.

To display the UI, some preliminary setup is involved. First, a DICOLORSET structure is declared and initialized. This structure, as its name implies, describes the color set used to display the UI. The following code fragment shows the setup of this structure.

    DICOLORSET dics;
    ZeroMemory(&dics, sizeof(DICOLORSET));
    dics.dwSize = sizeof(DICOLORSET);

By using the ZeroMemory function to set the memory block to zeroes, it indicates that the default color scheme should be used. Beyond this, the only element that requires initialization is the dwSize member, which is set equal to the size of the DICOLORSET structure.

The DICOLORSET structure is then included as part of a larger DICONFIGUREDEVICESPARAMS structure as seen in this code fragment.

    DICONFIGUREDEVICESPARAMS dicdp;
    ZeroMemory(&dicdp, sizeof(dicdp));
    dicdp.dwSize = sizeof(dicdp);
    dicdp.dwcUsers       = 1;
    dicdp.lptszUserNames = m_strUserName;

    dicdp.dwcFormats     = 1;
    dicdp.lprgFormats    = &m_diaf;
    dicdp.hwnd           = m_hWnd;
    dicdp.lpUnkDDSTarget = NULL;

The DICONFIGUREDEVICESPARAMS structure is declared and its allotted memory is set to contain nothing but zeroes. Once again, the dwSize member is set to the size of the structure. Only the currently logged user is being used in this example, so dwcUsers is set to 1. Recall that the m_strUserName variable is set to NULL so that the user's name is the name of the user currently logged onto the system.

Only one DIACTIONFORMAT structure containing the action map is being passed, so dwcFormats is set to 1 and the address of the DIACTIONFORMAT structure is passed as lprgFormats.

The hwnd variable is assigned the handle of the application window and the lpUnkDDSTarget is set to NULL to indicate that the Microsoft® Windows® Graphics Device Interface (GDI) functions should be used to draw the configuration user interface image.

The initialized DICONFIGUREDEVICESPARAMS structure is then passed to IDirectInput8::ConfigureDevices as illustrated in this code fragment.

    hr = m_pDI->ConfigureDevices(NULL, &dicdp, dwFlags, NULL);

The first and last parameters, which are used with an optional callback function, are set to NULL as they are not used in this sample.

The second parameter is the address of the DICONFIGUREDEVICESPARAMS structure containing the data to be displayed and other auxiliary information.

The third parameter is used for flags that determine whether the display is in read-only or edit mode. If you want to display the configuration for informational purposes without giving the user the option of changing it, you use the DICD_DEFAULT flag in this parameter. However, in this sample the dwFlags variable had been set earlier to DICD_EDIT, so the display allows user configuration. This is discussed in Step 6: User Configuration of the Action Map.


Step 6: User Configuration of the Action Map

At this point, the user configuration interface is displayed. If the device manufacturer has provided a graphic, users see an image of the device with labels indicating the action assigned to each device object. If no graphic is available, a simple text list of available device objects with their associated actions is displayed. An example of the former is shown here.

Users can now reassign controllers to actions as they see fit. Any changes made will be reflected in the DIACTIONFORMAT structure. Once the user interface is closed, the new action map must be sent to IDirectInputDevice8::SetActionMap before it can be implemented.

Using the data associated with the controls in an action map is described in Step 7: Retrieval of Action Mapped Data.


Step 7: Retrieval of Action Mapped Data

Action mapping was designed with buffered data in mind and will most often be used in that manner. The only difference between retrieving data from an action-mapped device and a device with no mapping is where you get it. Without action mapping, you would look to the dwOfs member of the DIDEVICEOBJECTDATA structure to determine which device object reported a change. However, with action mapping, you look to the uAppData member. Data is found in the dwData member.

For more detailed information on the retrieval of action-mapped data, see Retrieving Action Data.


DirectInput C/C++ Samples

The following sample programs demonstrate the use and capabilities of Microsoft® DirectInput®:

  • DIConfig Sample
  • FFConst Sample
  • JoyStick Sample
  • Keyboard Sample
  • Mouse Sample
  • MultiMapper Sample
  • ReadFFE Sample
  • Scrawl Sample

Although Microsoft DirectX® samples include Microsoft Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.


DIConfig Sample

Description

The DIConfig code demonstrates the implementation of a configuration user interface based upon the Microsoft® DirectInput® Mapper technology. This sample code is very complex and is intended to be used more as a reference implementation than as a learning tool.

Path

Source: (SDK root)\Samples\Multimedia\DirectInput\DIConfig

Executable: None (see Programming Notes).

User's Guide

This sample does not create an executable file, so there are no end-user instructions.

Programming Notes

This code generates Diconfig.dll, a binary file that contains all of the functionality used in the default Mapper UI. This code is very complex and is intended as a reference implementation of a DirectInput-based configuration user interface.

For more information about this sample, see the comments within the sample code itself. The following major features are supported.

  • Display of device images.
  • Reconfiguration of devices.
  • Support for multiple device views to illustrate alternate viewing angles.
  • Support for control activation overlays.
  • Use of the GetImageInfo method.
  • Device ownership for multiuser applications on the same computer.
  • Persistence of user settings through the SetActionMap method.


FFConst Sample

Description

The FFConst sample program applies raw forces to a force-feedback input device, illustrating how a simulator-type application can use force feedback to generate forces computed by a physics engine.

You must have a force-feedback device connected to your system in order to run the application.

Path

Source: (SDK root)\Samples\Multimedia\DirectInput\FFConst

Executable: (SDK root)\Samples\Multimedia\DirectInput\Bin\FFConst.exe

User's Guide

When you run the application, it displays a window with a crosshair and a black spot in it. Click anywhere within the window's client area to move the black spot. (Note that moving the device itself does not do anything.) FFConst exerts a constant force on the device from the direction of the spot, in proportion to the distance from the crosshair. You can also hold down the mouse button and move the spot continuously.

Programming Notes

This sample program enumerates the input devices and acquires the first force-feedback device that it finds. If none are detected, it displays a message and terminates.

When the user moves the black spot, the joySetForcesXY function converts the cursor coordinates to a force direction and magnitude. This data is used to modify the parameters of the constant force effect.


Joystick Sample

Description

The Joystick sample program obtains and displays joystick data.

Path

Source: (SDK root)\Samples\Multimedia\DirectInput\Joystick

Executable: (SDK root)\Samples\Multimedia\DirectInput\Bin\Joystick.exe

User's Guide

Observe how the displayed data changes when you move and twist the stick, rotate the throttle wheel, and press buttons in various combinations.

Programming Notes

The application polls the joystick for immediate data in response to a timer set inside the dialog procedure.


Keyboard Sample

Description

The Keyboard sample program enables the exploration of Foreground versus Background and Exclusive versus Non-Exclusive cooperative levels, and Buffered versus Immediate data retrieval from the keyboard.

Path

Source: (SDK root)\Samples\Multimedia\DirectInput\Keyboard

Executable: (SDK root)\Samples\Multimedia\DirectInput\Bin\Keyboard.exe

User's Guide

Through the user interface, any combination of cooperative level and data styles can be created and the resulting keyboard behavior observed. Each setting is explained as it is selected, and the expected behavior is predicted when the device is created.

Programming Notes

Note that holding down a key in immediate mode holds that key indefinitely as subsequent snapshots of the keyboard are taken by Microsoft® DirectInput®. This is an optical illusion because DirectInput is taking individual snapshots at the rate of twelve times a second, but it demonstrates that, in immediate mode, only the state of the keyboard at that time is considered, while anything that has happened between snapshots is ignored.

Holding down a key in buffered mode briefly displays the data indicating that the key has been pressed, then quickly clears that data as it is flushed from the buffer. Releasing the key generates another briefly displayed key-up event. This is a significant difference from immediate mode.


Mouse Sample

Description

The Mouse sample program enables the exploration of Foreground versus Background and Exclusive versus Non-Exclusive cooperative levels, and Buffered versus Immediate data retrieval from the mouse.

Path

Source: (SDK root)\Samples\Multimedia\DirectInput\Mouse

Executable: (SDK root)\Samples\Multimedia\DirectInput\Bin\Mouse.exe

User's Guide

Through the user interface, any combination of cooperative level and data styles can be created and the resulting keyboard behavior observed. Each setting is explained as it is selected, and the expected behavior is predicted when the device is created.

Programming Notes

To release the mouse, press ENTER.

Note that in immediate mode, all device objects are visible and you can see the data change as the mouse is moved. This is an optical illusion because Microsoft® DirectInput® is taking individual snapshots at the rate of twelve times a second, but it demonstrates that, in immediate mode, only the state of the device at that time is considered, while anything that has happened between device snapshots is ignored.

Holding down a button in buffered mode briefly displays the data indicating that the button has been pressed, then quickly clears that data as it is flushed from the buffer. Releasing the button generates another briefly displayed button up event. This is a significant difference from immediate mode.


MultiMapper Sample

Description

The MultiMapper sample program shows how to set up, apply, and retrieve data using the Action Mapping functionality. It also demonstrates remapping through the user interface.

Path

Source: (SDK root)\Samples\Multimedia\DirectInput\MultiMapper

Executable: (SDK root)\Samples\Multimedia\DirectInput\MultiMapper.exe

User's Guide

First, assign a number of players. The MultiMapper sample program accepts up to four. There must be one device, including the keyboard and the mouse, for each player. If more players are chosen than there are devices available, the program automatically scales back to the maximum number of players based on the devices attached.

The MultiMapper sample program is designed as though it were a space combat application. Each player is assigned a basic set of actions such as turning, firing, and activating thrusters. These actions are then mapped to device controls. Activation of those controls is then reflected by data in the display window.

To activate the action mapping user interface, press D. Each device has a separate tab for mapping that particular device. Double-clicking a device object label activates the list of possible actions to be assigned to that device object. Make a selection from the action list to map that action to the selected device object. You can also reassign devices among players.

Programming Notes

If a controller such as a joystick or a wheel is attached to the system, it displays a graphic of the device with actions as callouts to each device object. The display of this graphic depends on the presence of a provided bitmap for that device.


ReadFFE Sample

Description

The ReadFFE sample program enumerates and plays all of the Microsoft® DirectInput® Force Feedback effects stored in a DirectInput effects file created by the Force Editor.

Path

Source: (SDK root)\Samples\Multimedia\DirectInput\ReadFFE

Executable: (SDK root)\Samples\Multimedia\DirectInput\ReadFFE.exe

Media: (SDK root)\Samples\Multimedia\Media\*.ffe

User's Guide

Click Read File and open an existing Force Feedback Effects (FFE) file. If it was successfully read, click Play Effects to play the effects on the force-feedback device. FFE files can be authored using the Force Feedback Editor utility packaged with the Microsoft DirectX® SDK.

Programming Notes

For each file effect enumerated, the EnumAndCreateEffectsCallback function initializes an IDirectInputEffect pointer and adds it to a linked list. The OnPlayEffects function traverses this list and plays all effects.


Scrawl Sample

Description

The Scrawl application demonstrates using the mouse in exclusive mode in a windowed application. It functions in the same way as a pencil tool in a paint program.

Path

Source: (SDK root)\Samples\Multimedia\DirectInput\Scrawl

Executable: (SDK root)\Samples\Multimedia\DirectInput\Bin\Scrawl.exe

User's Guide

To draw, hold down the left mouse button and move the mouse. Click the right mouse button to invoke a shortcut menu. From the shortcut menu you can clear the client window, set the mouse sensitivity, or close the application. If the mouse buttons have been switched through Control Panel settings, Scrawl will detect and mimic this behavior. Note that Microsoft® DirectInput® ignores Control Panel settings and the application itself must make the switch.

Programming Notes

The Scrawl sample program demonstrates many aspects of DirectInput programming, including the following:

  • Using the mouse in non-exclusive mode in a windowed application.
  • Releasing the mouse when Microsoft Windows® needs to use it for menu access.
  • Reacquiring the mouse when Windows no longer needs it.
  • Reading buffered device data.
  • Deferring screen updates until movement on both axes has been fully processed.
  • Displaying event notifications of device activity.
  • Restricting the cursor to an arbitrary region.
  • Scaling raw mouse coordinates before using them.
  • Using relative axis mode.


DirectInput C/C++ Reference

Reference material for the Microsoft® DirectInput® C/C++ application programming interface (API) is divided into the following categories.

  • Interfaces
  • Callback Functions
  • Functions
  • Macros
  • Structures
  • Device Constants
  • Action Mapping Constants
  • Return Values


Interfaces

This section contains references for methods of the following Microsoft® DirectInput® interfaces.

  • IDirectInput8
  • IDirectInputDevice8
  • IDirectInputEffect

Note All DirectInput methods have corresponding macros that expand to C or C++ syntax depending on which language is defined. These macros are found in the Dinput.h header file and are not documented separately.


IDirectInput8

Applications use the methods of the IDirectInput8 interface to enumerate, create, and retrieve the status of Microsoft® DirectInput® devices, initialize the DirectInput object, and invoke an instance of the Microsoft Windows® Control Panel.

IDirectInput8 supersedes the IDirectInput, IDirectInput2, and IDirectInput7 interfaces used in earlier versions of Microsoft DirectX®.

IDirectInput8 is an interface to a new class of object, represented by the class identifier CLSID_DirectInput8, and cannot be obtained by calling QueryInterface on an interface to objects of class CLSID_DirectInput. Instead, obtain the IDirectInput8 interface by using the DirectInput8Create function.

The methods of the IDirectInput8 interface can be organized into the following groups.

Device Management | ConfigureDevices
 | CreateDevice
 | EnumDevices
 | EnumDevicesBySemantics
 | FindDevice
 | GetDeviceStatus
Miscellaneous | Initialize
 | RunControlPanel

The IDirectInput interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTINPUT8 type is defined as a pointer to the IDirectInput8 interface:

typedef struct IDirectInput8    *LPDIRECTINPUT8;

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInput8::ConfigureDevices

Displays property pages for connected input devices and enables the user to map actions to device controls.

HRESULT IDirectInput8::ConfigureDevices(
   LPDICONFIGUREDEVICESCALLBACK lpdiCallback,
   LPDICONFIGUREDEVICESPARAMS   lpdiCDParams,
   DWORD  dwFlags,
   LPVOID pvRefData
);

Parameters

lpdiCallback
Address of a callback function to be called each time the contents of the surface change. See DIConfigureDevicesCallback. Pass NULL if the application does not handle the display of the property sheet. In this case, Microsoft® DirectInput® displays the property sheet and returns control to the application when the user closes the property sheet. If you supply a callback pointer, you must also supply a valid surface pointer in the lpUnkDDSTarget member of the DICONFIGUREDEVICESPARAMS structure.
lpdiCDParams
Address of a DICONFIGUREDEVICESPARAMS structure that contains information about users and genres for the game, as well as information about how the user interface is displayed.
dwFlags
DWORD value that specifies the mode in which the control panel should be invoked. DwFlags must be one of the following values.
DICD_DEFAULT
Open the property sheet in view-only mode.
DICD_EDIT
Open the property sheet in edit mode. This mode enables the user to change action-to-control mappings. After the call returns, the application should assume current devices are no longer valid, release all device interfaces, and reinitialize them by calling IDirectInput8::EnumDevicesBySemantics.
pvRefData
Application-defined value to pass to the callback function.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following.

DIERR_INVALIDPARAM
DIERR_OUTOFMEMORY

Remarks

Hardware vendors provide bitmaps and other display information for their device.

Before calling the method, an application can modify the text labels associated with each action by changing the value in the lptszActionName member of the DIACTION structure.

Configuration is stored for each user of each device for each game. The information can be retrieved by the IDirectInputDevice8::BuildActionMap method.

By default, acceleration is supported for these pixel formats:

A1R5G5B5
16-bit pixel format with 5 bits reserved for each color and 1 bit reserved for alpha (transparent texel).
A8R8G8B8
32-bit ARGB pixel format with alpha.
R9G8B8
24-bit RGB pixel format.
X1R5G5B5
16-bit pixel format with 5 bits reserved for each color.
X8R8G8B8
32-bit RGB pixel format with 8 bits reserved for each color.

Other formats will result in color conversion and dramatically slow the frame rate.

Note Even if the cooperative level for the application is disabling the Microsoft Windows® logo key passively through an exclusive cooperative level or actively through use of the DISCL_NOWINKEY flag, that key will be active while the default action mapping UI is displayed.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInput8::CreateDevice

Creates and initializes an instance of a device based on a given GUID, and obtains an IDirectInputDevice8 interface.

HRESULT CreateDevice(
  REFGUID rguid,
  LPDIRECTINPUTDEVICE *lplpDirectInputDevice,
  LPUNKNOWN pUnkOuter
);

Parameters

rguid
Reference to (C++) or address of (C) the instance GUID for the desired input device (see Remarks). The GUID is retrieved through the IDirectInput8::EnumDevices method, or it can be one of the following predefined GUIDs:
GUID_SysKeyboard
The default system keyboard.
GUID_SysMouse
The default system mouse.

For the preceding GUID values to be valid, your application must define INITGUID before all other preprocessor directives at the beginning of the source file, or link to Dxguid.lib.

lplpDirectInputDevice
Address of a variable to receive the IDirectInputDevice8 interface pointer if successful.
pUnkOuter
Address of the controlling object's IUnknown interface for COM aggregation, or NULL if the interface is not aggregated. Most callers pass NULL.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following:

DIERR_DEVICENOTREG
DIERR_INVALIDPARAM
DIERR_NOINTERFACE
DIERR_NOTINITIALIZED
DIERR_OUTOFMEMORY

Remarks

Calling this method with pUnkOuter = NULL is equivalent to creating the object by CoCreateInstance(&CLSID_DirectInputDevice, NULL, CLSCTX_INPROC_SERVER, riid, lplpDirectInputDevice) and then initializing it with Initialize.

Calling this method with pUnkOuter != NULL is equivalent to creating the object by CoCreateInstance(&CLSID_DirectInputDevice, punkOuter, CLSCTX_INPROC_SERVER, &IID_IUnknown, lplpDirectInputDevice). The aggregated object must be initialized manually.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInput8::EnumDevices

Enumerates available devices.

HRESULT EnumDevices(
  DWORD dwDevType,
  LPDIENUMCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD dwFlags
);

Parameters

dwDevType
Device type filter.

To restrict the enumeration to a particular type of device, set this parameter to a DI8DEVTYPE_* value. See DIDEVICEINSTANCE.

To enumerate a class of devices, use one of the following values.

DI8DEVCLASS_ALL
All devices.
DI8DEVCLASS_DEVICE
All devices that do not fall into another class.
DI8DEVCLASS_GAMECTRL
All game controllers.
DI8DEVCLASS_KEYBOARD
All keyboards. Equivalent to DI8DEVTYPE_KEYBOARD.
DI8DEVCLASS_POINTER
All devices of type DI8DEVTYPE_MOUSE and DI8DEVTYPE_SCREENPOINTER.
lpCallback
Address of a callback function to be called once for each device enumerated. See DIEnumDevicesCallback.
pvRef
Application-defined 32-bit value to be passed to the enumeration callback each time it is called.
dwFlags
Flag value that specifies the scope of the enumeration. This parameter can be one or more of the following values:
DIEDFL_ALLDEVICES
All installed devices are enumerated. This is the default behavior.
DIEDFL_ATTACHEDONLY
Only attached and installed devices.
DIEDFL_FORCEFEEDBACK
Only devices that support force feedback.
DIEDFL_INCLUDEALIASES
Include devices that are aliases for other devices.
DIEDFL_INCLUDEHIDDEN
Include hidden devices. For more information about hidden devices, see DIDEVCAPS.
DIEDFL_INCLUDEPHANTOMS
Include phantom (placeholder) devices.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

All installed devices can be enumerated, even if they are not present. For example, a flight stick might be installed on the system but not currently plugged into the computer. Set the dwFlags parameter to indicate whether only attached or all installed devices should be enumerated. If the DIEDFL_ATTACHEDONLY flag is not present, all installed devices are enumerated.

A preferred device type can be passed as a dwDevType filter so that only the devices of that type are enumerated.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInput8::EnumDevicesBySemantics


IDirectInput8::EnumDevicesBySemantics

Enumerates devices that most closely match the application-specified action map.

HRESULT EnumDevicesBySemantics(
  LPCTSTR ptszUserName,
  LPDIACTIONFORMAT lpdiActionFormat,
  LPDIENUMDEVICESBYSEMANTICSCB lpCallback,
  LPVOID pvRef,
  DWORD dwFlags
);

Parameters

ptszUserName
String identifying the current user, or NULL to specify the user logged onto the system. The user name is taken into account when enumerating devices. A device with user mappings is preferred to a device without any user mappings. By default, devices in use by other users are not enumerated for this user.
lpdiActionFormat
Address of a DIACTIONFORMAT structure that specifies the action map for which suitable devices are enumerated.
lpCallback
Address of a callback function to be called once for each device enumerated. See DIEnumDevicesBySemanticsCallback.
pvRef
Application-defined 32-bit value to pass to the enumeration callback each time it is called.
dwFlags
Flag value that specifies the scope of the enumeration. This parameter can be one or more of the following values.
DIEDBSFL_ATTACHEDONLY
Only attached and installed devices are enumerated.
DIEDBSFL_AVAILABLEDEVICES
Only unowned, installed devices are enumerated.
DIEDBSFL_FORCEFEEDBACK
Only devices that support force feedback are enumerated.
DIEDBSFL_MULTIMICEKEYBOARDS
Only secondary (non-system) keyboard and mouse devices.
DIEDBSFL_NONGAMINGDEVICES
Only HID-compliant devices whose primary purpose is not as a gaming device. Devices such as USB speakers and multimedia buttons on some keyboards would fall within this value.
DIEDBSFL_THISUSER
All installed devices for the user identified by ptszUserName, and all unowned devices, are enumerated.

DIEDBSFL_VALID is also defined in Dinput.h, but is not used by applications.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

The keyboard and mouse are enumerated last.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInput8::EnumDevices, Action Mapping.


IDirectInput8::FindDevice

Retrieves the instance GUID of a device that has been newly attached to the system. It is called in response to a Microsoft® Win32® device management notification.

HRESULT FindDevice(
  REFGUID rguidClass,
  LPCTSTR ptszName,
  LPGUID pguidInstance
);

Parameters

rguidClass
Unique identifier of the device class for the device that the application is to locate. The application obtains the class GUID from the device arrival notification. For more information, see the documentation on the DBT_DEVICEARRIVAL event in the Microsoft Platform Software Development Kit (SDK).
ptszName
Name of the device. The application obtains the name from the device arrival notification.
pguidInstance
Address of a variable to receive the instance GUID for the device, if the device is found. This value can be passed to IDirectInput8::CreateDevice.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be DIERR_DEVICENOTREG. Failure results if the GUID and name do not correspond to a device class that is registered with Microsoft® DirectInput®. For example, they might refer to a storage device, rather than an input device.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInput8::GetDeviceStatus

Retrieves the status of a specified device.

HRESULT GetDeviceStatus(
  REFGUID rguidInstance
);

Parameters

rguidInstance
Reference to (C++) or address of (C) the GUID identifying the instance of the device whose status is being checked.

Return Values

If the method succeeds, the return value is DI_OK if the device is attached to the system, or DI_NOTATTACHED otherwise.

If the method fails, the return value can be one of the following error values:

DIERR_GENERIC
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInput8::Initialize

Initializes a Microsoft® DirectInput® object. Applications normally do not need to call this method. The DirectInput8Create function automatically initializes the DirectInput object after creating it.

HRESULT Initialize(
  HINSTANCE hinst,
  DWORD dwVersion
);

Parameters

hinst
Instance handle to the application or dynamic-link library (DLL) that is creating the DirectInput object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backwards compatibility.

It is an error for a DLL to pass the handle of the parent application. For example, a Microsoft ActiveX® control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle of the Web browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that might be necessary.

dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_BETADIRECTINPUTVERSION
DIERR_OLDDIRECTINPUTVERSION

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInput8::RunControlPanel

Runs Control Panel to enable the user to install a new input device or modify configurations.

HRESULT RunControlPanel(
  HWND hwndOwner,
  DWORD dwFlags
);

Parameters

hwndOwner
Handle of the window to be used as the parent window for the subsequent user interface. If this parameter is NULL, no parent window is used.
dwFlags
Currently not used and must be set to 0.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::RunControlPanel


IDirectInputDevice8

Applications use the methods of the IDirectInputDevice8 interface to gain and release access to Microsoft® DirectInput® devices, manage device properties and information, set behavior, perform initialization, create and play force-feedback effects, and invoke a device's control panel.

The IDirectInputDevice8 interface is obtained by using the IDirectInput8::CreateDevice method. For an example, see Creating a DirectInput Device.

IDirectInputDevice8 supersedes the IDirectInputDevice, IDirectInputDevice2, and IDirectInputDevice7 interfaces used in previous versions of Microsoft® DirectX®, but does not inherit from them. Methods that share names with those from older interfaces perform similar services, but may not have exactly the same functionality or behavior. You cannot obtain the earlier interfaces by using QueryInterface.

The methods of the IDirectInputDevice8 interface can be organized into the following groups.

Accessing input devices | Acquire
 | Unacquire
Action mapping | BuildActionMap
 | GetImageInfo
 | SetActionMap
Device information | GetCapabilities
 | GetDeviceData
 | GetDeviceInfo
 | GetDeviceState
 | Poll
 | SetDataFormat
 | SetEventNotification
Device objects | EnumObjects
 | GetObjectInfo
Device properties | GetProperty
 | SetCooperativeLevel
 | SetProperty
Force feedback | CreateEffect
 | EnumCreatedEffectObjects
 | EnumEffects
 | EnumEffectsInFile
 | Escape
 | GetEffectInfo
 | GetForceFeedbackState
 | SendForceFeedbackCommand
 | WriteEffectToFile
Miscellaneous | Initialize
 | RunControlPanel
 | SendDeviceData

The IDirectInputDevice8 interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTINPUTDEVICE8 type is defined as a pointer to the IDirectInputDevice8 interface:

typedef struct IDirectInputDevice8    *LPDIRECTINPUTDEVICE8;

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8

Built on Wednesday, October 04, 2000


IDirectInputDevice8::Acquire

Obtains access to the input device.

HRESULT Acquire();

Parameters

None.

Return Values

If the method succeeds, the return value is DI_OK, or S_FALSE if the device was already acquired.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
DIERR_OTHERAPPHASPRIO

Remarks

Before a device can be acquired, a data format must be set by using the IDirectInputDevice8::SetDataFormat method or IDirectInputDevice8::SetActionMap method. If the data format has not been set, Acquire returns DIERR_INVALIDPARAM.

Devices must be acquired before calling the IDirectInputDevice8::GetDeviceState or IDirectInputDevice8::GetDeviceData methods for that device.

Device acquisition does not use a reference count. Therefore, if an application calls the IDirectInputDevice8::Acquire method twice, then calls the IDirectInputDevice8::Unacquire method once, the device is unacquired.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::BuildActionMap

Builds an action map for the device and retrieves information about it.

HRESULT BuildActionMap(
  LPDIACTIONFORMAT lpdiaf,
  LPCWSTR lpszUserName
  DWORD  dwFlags
);

Parameters

lpdiaf
Address of a DIACTIONFORMAT structure that receives information about the action map.
lpszUserName
Pointer to a string that specifies the name of the user for whom mapping is requested. If NULL, the current user is assumed.
dwFlags
Flags to control the mapping. This can be one of the following values.
DIDBAM_DEFAULT
Overwrite all mappings except application-specified mappings; that is, mappings that have the DIA_APPMAPPED flag in the DIACTION structure.
DIDBAM_HWDEFAULTS
Overwrite all mappings, including application-specified mappings. This flag is similar to DIDBAM_INITIALIZE, but automatically overrides user-mapped actions with the defaults specified by the device driver or Microsoft® DirectInput®.
DIDBAM_INITIALIZE
Overwrite all mappings, including application-specified mappings.
DIDBAM_PRESERVE
Preserve current mappings assigned for this device or any other configured device.

Return Values

If the method succeeds, the return value is DI_OK, DI_NOEFFECT, or DI_WRITEPROTECT. See Remarks.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM
DIERR_MAPFILEFAIL

Remarks

The method returns DI_NOEFFECT if no mappings were created for the device. For example, a keyboard or mouse will not provide mappings for genre-specific actions.

If DIERR_INVALIDPARAM is returned, one or more of the mappings was not valid. The dwHow member of the DIACTION structure is set to DIAH_ERROR. The application can iterate through the action map to find and correct errors.

If DIEFF_MAPFILEFAIL is returned, an error has occurred either reading the vendor supplied file for the device or reading or writing the user configuration file for the device.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::SetActionMap, IDirectInputDevice8::SetDataFormat


IDirectInputDevice8::CreateEffect

Creates and initializes an instance of an effect identified by the effect GUID.

HRESULT CreateEffect(
  REFGUID rguid,
  LPCDIEFFECT lpeff,
  LPDIRECTINPUTEFFECT *ppdeff,
  LPUNKNOWN punkOuter
);

Parameters

rguid
Reference to (C++) or address of (C) the GUID identifying the effect to be created. This can be a predefined effect GUID, or it can be a GUID obtained from IDirectInputDevice8::EnumEffects.

The following standard effect GUIDs are defined:

  • GUID_ConstantForce
  • GUID_RampForce
  • GUID_Square
  • GUID_Sine
  • GUID_Triangle
  • GUID_SawtoothUp
  • GUID_SawtoothDown
  • GUID_Spring
  • GUID_Damper
  • GUID_Inertia
  • GUID_Friction
  • GUID_CustomForce
lpeff
DIEFFECT structure that provides parameters for the created effect. This parameter is optional. If it is NULL, the effect object is created without parameters. The application must then call the IDirectInputEffect::SetParameters method to set the parameters of the effect before it can download the effect.
ppdeff
Address of a variable to receive a pointer to the IDirectInputEffect interface if successful.
punkOuter
Controlling unknown for COM aggregation. The value is NULL if the interface is not aggregated. Most callers pass NULL.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICEFULL
DIERR_DEVICENOTREG
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

If the return value is S_OK, the effect was created, and the parameters of the effect were updated, but the effect was not necessarily downloaded. For it to be downloaded, the device must be acquired in exclusive mode.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::EnumCreatedEffectObjects

Enumerates all the currently created effects for this device. Effects created by IDirectInputDevice8::CreateEffect are enumerated.

HRESULT EnumCreatedEffectObjects(
  LPDIENUMCREATEDEFFECTOBJECTSCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD fl
);

Parameters

lpCallback
Address of an application-defined callback function. Microsoft® DirectInput® provides the prototype function DIEnumCreatedEffectObjectsCallback.
pvRef
Reference data (context) for callback.
fl
No flags are currently defined. This parameter must be 0.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

The results are unpredictable if you create or destroy an effect while an enumeration is in progress. However, the callback function can safely release the effect passed to it.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::EnumEffects

Enumerates all the effects supported by the force-feedback system on the device. The enumerated GUIDs can represent predefined effects, as well as effects peculiar to the device manufacturer.

HRESULT EnumEffects(
  LPDIENUMEFFECTSCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD dwEffType
);

Parameters

lpCallback
Address of an application-defined callback function. The declaration of this function must conform to that of the DIEnumEffectsCallback prototype.
pvRef
A 32-bit application-defined value to be passed to the callback function. This parameter can be any 32-bit type; it is declared as LPVOID for convenience.
dwEffType
Effect type filter. Use one of the DIEFT_* values to indicate the effect type to be enumerated, or DIEFT_ALL to enumerate all effect types. For a list of these values, see DIEFFECTINFO.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

If the callback stops the enumeration prematurely, the enumeration is considered to have succeeded.

Remarks

An application can use the dwEffType member of the DIEFFECTINFO structure to obtain general information about the effect, such as its type and which envelope and condition parameters are supported by the effect.

To exploit an effect to its fullest, contact the device manufacturer to obtain information on the semantics of the effect and its effect-specific parameters.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::EnumEffectsInFile

Enumerates all the effects in a file created by the Force Editor utility or another application using the same file format.

HRESULT EnumEffectsInFile(
  LPCSTR lpszFileName,
  LPENUMEFFECTSINFILECALLBACK pec,
  LPVOID pvRef,
  DWORD dwFlags
);

Parameters

lpszFileName
Name of the RIFF file.
pec
Address of an application-defined callback function. The declaration of this function must conform to that of the DIEnumEffectsInFileCallback prototype.
pvRef
Application-defined value to be passed to the callback function. This parameter can be any 32-bit type.
dwFlags
Can be DIFEF_DEFAULT ( = 0) or one or both of the following values:
DIFEF_INCLUDENONSTANDARD
Include effect types that are not defined by Microsoft® DirectInput®.
DIFEF_MODIFYIFNEEDED
Instruct DirectInput to modify the authored effect, if necessary, so that it plays on the current device. For example, by default, an effect authored for two axes does not play on a single-axis device. Setting this flag allows the effect to play on a single axis. The parameters are modified in the DIEFFECT structure pointed to by the lpDiEffect member of the DIFILEEFFECT structure passed to the callback.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

If the callback stops the enumeration prematurely, the enumeration is considered to have succeeded.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::WriteEffectToFile, Loading Effects from a File


IDirectInputDevice8::EnumObjects

Enumerates the input and output objects available on a device.

HRESULT EnumObjects(
  LPDIENUMDEVICEOBJECTSCALLBACK lpCallback,
  LPVOID pvRef,
  DWORD dwFlags
);

Parameters

lpCallback
Address of a callback function that receives DirectInputDevice objects. Microsoft® DirectInput® provides a prototype of this function as DIEnumDeviceObjectsCallback.
pvRef
Reference data (context) for callback.
dwFlags
Flags that specify the types of object to be enumerated. Each of the following values restricts the enumeration to objects of the described type:
DIDFT_ABSAXIS
An absolute axis.
DIDFT_ALIAS
Controls identified by a Human Interface Device usage alias. This flag applies only to HID-compliant USB devices.
DIDFT_ALL
All objects.
DIDFT_AXIS
An axis, either absolute or relative.
DIDFT_BUTTON
A push button or a toggle button.
DIDFT_COLLECTION
A Human Interface Device (HID) link collection. HID link collections do not generate data of their own.
DIDFT_ENUMCOLLECTION(n)
An object that belongs to HID link collection number n.
DIDFT_FFACTUATOR
An object that contains a force-feedback actuator. In other words, forces can be applied to this object.
DIDFT_FFEFFECTTRIGGER
An object that can be used to trigger force-feedback effects.
DIDFT_NOCOLLECTION
An object that does not belong to any HID link collection; in other words, an object for which the wCollectionNumber member of the DIDEVICEOBJECTINSTANCE structure is 0.
DIDFT_NODATA
An object that does not generate data.
DIDFT_OUTPUT
An object to which data can be sent by using the IDirectInputDevice8::SendDeviceData method.
DIDFT_POV
A point-of-view controller.
DIDFT_PSHBUTTON
A push button. A push button is reported as down when the user presses it and as up when the user releases it.
DIDFT_RELAXIS
A relative axis.
DIDFT_TGLBUTTON
A toggle button. A toggle button is reported as down when the user presses it and remains so until the user presses the button a second time.
DIDFT_VENDORDEFINED
An object of a type defined by the manufacturer.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

The DIDFT_FFACTUATOR and DIDFT_FFEFFECTTRIGGER flags in the dwFlags parameter restrict enumeration to objects that meet all the criteria defined by the included flags. For all the other flags, an object is enumerated if it meets the criterion defined by any included flag in this category. For example, (DIDFT_FFACTUATOR | DIDFT_FFEFFECTTRIGGER) restricts enumeration to force-feedback trigger objects, and (DIDFT_FFEFFECTTRIGGER | DIDFT_TGLBUTTON | DIDFT_PSHBUTTON) restricts enumeration to buttons of any kind that can be used as effect triggers.

Applications should not rely on this method to determine whether certain keyboard keys or indicator lights are present, as these objects might be enumerated even though they are not present. Although the basic set of available objects can be determined from the device subtype, there is no reliable way of determining whether extra objects such as the menu key are available.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::Escape

Sends a hardware-specific command to the force-feedback driver.

HRESULT Escape(
  LPDIEFFESCAPE pesc
);

Parameters

pesc
DIEFFESCAPE structure that describes the command to be sent. On success, the cbOutBuffer member contains the number of bytes of the output buffer actually used.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICEFULL
DIERR_NOTINITIALIZED

Other device-specific error codes are also possible. Ask the hardware manufacturer for details.

Remarks

Because each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the DIDEVICEINSTANCE structure against the value the application is expecting.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::GetCapabilities

Obtains the capabilities of the DirectInputDevice object.

HRESULT GetCapabilities(
  LPDIDEVCAPS lpDIDevCaps
);

Parameters

lpDIDevCaps
Address of a DIDEVCAPS structure to be filled with the device capabilities. The dwSize member of this structure must be initialized before calling this method.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
E_POINTER

Remarks

For compatibility with Microsoft® DirectX® 3, it is also valid to pass a DIDEVCAPS_DX3 structure with the dwSize member initialized to sizeof(DIDEVCAPS_DX3).

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::GetDeviceData

Retrieves buffered data from the device.

HRESULT GetDeviceData(
  DWORD cbObjectData,
  LPDIDEVICEOBJECTDATA rgdod,
  LPDWORD pdwInOut,
  DWORD dwFlags
);

Parameters

cbObjectData
Size of the DIDEVICEOBJECTDATA structure, in bytes.
rgdod
Array of DIDEVICEOBJECTDATA structures to receive the buffered data. The number of elements in this array must be equal to the value of the pdwInOut parameter. If this parameter is NULL, the buffered data is not stored anywhere, but all other side-effects take place.
pdwInOut
On entry, the number of elements in the array pointed to by the rgdod parameter. On exit, the number of elements actually obtained.
dwFlags
Flags that control the manner in which data is obtained. This value can be 0 or the following flag:
DIGDD_PEEK
Do not remove the items from the buffer. A subsequent IDirectInputDevice8::GetDeviceData call will read the same data. Normally, data is removed from the buffer after it is read.

Return Values

If the method succeeds, the return value is DI_OK or DI_BUFFEROVERFLOW.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
DIERR_NOTBUFFERED
DIERR_NOTINITIALIZED

Remarks

Before device data can be obtained, you must set the data format and the buffer size by using the IDirectInputDevice8::SetDataFormat and IDirectInputDevice8::SetProperty methods, or by using the IDirectInputDevice8::SetActionMap method. You must also acquire the device by using the IDirectInputDevice8::Acquire method.

The following code example reads up to ten buffered data elements, removing them from the device buffer as they are read.

DIDEVICEOBJECTDATA rgdod[10];
DWORD dwItems = 10;
hres = IDirectInputDevice8_GetDeviceData(
    sizeof(DIDEVICEOBJECTDATA),
    rgdod,
    &dwItems,
    0);
if (SUCCEEDED(hres)) {
    // dwItems = number of elements read (could be zero)
    if (hres == DI_BUFFEROVERFLOW) {
    // Buffer had overflowed.
    }
}

Your application can flush the buffer and retrieve the number of flushed items by specifying NULL for the rgdod parameter and a pointer to a variable containing INFINITE for the pdwInOut parameter. The following code example illustrates how this can be done:

dwItems = INFINITE;
hres = IDirectInputDevice8_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            0);
if (SUCCEEDED(hres)) {
    // Buffer successfully flushed
    // dwItems = number of elements flushed
    if (hres == DI_BUFFEROVERFLOW) {
        // Buffer had overflowed.
    }
}

Your application can query for the number of elements in the device buffer by setting the rgdod parameter to NULL, setting pdwInOut to INFINITE and setting dwFlags to DIGDD_PEEK. The following code example illustrates how this can be done:

dwItems = INFINITE;
hres = IDirectInputDevice8_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            DIGDD_PEEK);
if (SUCCEEDED(hres)) {
    // dwItems = number of elements in buffer
    if (hres == DI_BUFFEROVERFLOW) {
        // Buffer overflow occurred; not all data
        // was successfully captured.
    }
}

To query about whether a buffer overflow has occurred, set the rgdod parameter to NULL and the pdwInOut parameter to 0. The following code example illustrates how this can be done:

dwItems = 0;
hres = IDirectInputDevice8_GetDeviceData(
            pdid,
            sizeof(DIDEVICEOBJECTDATA),
            NULL,
            &dwItems,
            0);
if (hres == DI_BUFFEROVERFLOW) {
    // Buffer overflow occurred
}

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::Poll, Polling and Event Notification


IDirectInputDevice8::GetDeviceInfo

Obtains information about the device's identity.

HRESULT GetDeviceInfo(
  LPDIDEVICEINSTANCE pdidi
);

Parameters

pdidi
Address of a DIDEVICEINSTANCE structure to be filled with information about the device's identity. An application must initialize the structure's dwSize member before calling this method.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
E_POINTER

Remarks

For compatibility with Microsoft® DirectX 3®, it is also valid to pass a DIDEVICEINSTANCE_DX3 structure with the dwSize member initialized to sizeof(DIDEVICEINSTANCE_DX3).

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::GetDeviceState

Retrieves immediate data from the device.

HRESULT GetDeviceState(
  DWORD cbData,
  LPVOID lpvData
);

Parameters

cbData
Size of the buffer in the lpvData parameter, in bytes.
lpvData
Address of a structure that receives the current state of the device. The format of the data is established by a prior call to the IDirectInputDevice8::SetDataFormat method.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTACQUIRED
DIERR_NOTINITIALIZED
E_PENDING

Remarks

Before device data can be obtained, set the cooperative level by using the IDirectInputDevice8::SetCooperativeLevel method, then set the data format by using IDirectInputDevice8::SetDataFormat, and acquire the device by using the IDirectInputDevice8::Acquire method.

The five predefined data formats require corresponding device state structures according to the following table:

Data format | State structure
c_dfDIMouse | DIMOUSESTATE
c_dfDIMouse2 | DIMOUSESTATE2
c_dfDIKeyboard | array of 256 bytes
c_dfDIJoystick | DIJOYSTATE
c_dfDIJoystick2 | DIJOYSTATE2

For example, if you passed the c_dfDIMouse format to the IDirectInputDevice8::SetDataFormat method, you must pass a DIMOUSESTATE structure to the IDirectInputDevice8::GetDeviceState method.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::Poll, Polling and Event Notification, Buffered and Immediate Data


IDirectInputDevice8::GetEffectInfo

Obtains information about an effect.

HRESULT GetEffectInfo(
  LPDIEFFECTINFO pdei,
  REFGUID rguid
);

Parameters

pdei
DIEFFECTINFO structure that receives information about the effect. The caller must initialize the dwSize member of the structure before calling this method.
rguid
Reference to (C++) or address of (C) the GUID identifying the effect for which information is being requested.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICENOTREG
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
E_POINTER

Note If this method is called on an non-Force Feedback device, E_POINTER will be returned.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::GetForceFeedbackState

Retrieves the state of the device's force-feedback system.

HRESULT GetForceFeedbackState(
  LPDWORD pdwOut
);

Parameters

pdwOut
Location for flags that describe the current state of the device's force-feedback system.

The value is a combination of the following constants:

DIGFFS_ACTUATORSOFF
The device's force-feedback actuators are disabled.
DIGFFS_ACTUATORSON
The device's force-feedback actuators are enabled.
DIGFFS_DEVICELOST
The device suffered an unexpected failure and is in an indeterminate state. It must be reset either by unacquiring and reacquiring the device, or by sending a DISFFC_RESET command.
DIGFFS_EMPTY
The device has no downloaded effects.
DIGFFS_PAUSED
Playback of all active effects has been paused.
DIGFFS_POWEROFF
The force-feedback system is not currently available. If the device cannot report the power state, neither DIGFFS_POWERON nor DIGFFS_POWEROFF is returned.
DIGFFS_POWERON
Power to the force-feedback system is currently available. If the device cannot report the power state, neither DIGFFS_POWERON nor DIGFFS_POWEROFF is returned.
DIGFFS_SAFETYSWITCHOFF
The safety switch is currently off; that is, the device cannot operate. If the device cannot report the state of the safety switch, neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF is returned.
DIGFFS_SAFETYSWITCHON
The safety switch is currently on; that is, the device can operate. If the device cannot report the state of the safety switch, neither DIGFFS_SAFETYSWITCHON nor DIGFFS_SAFETYSWITCHOFF is returned.
DIGFFS_STOPPED
No effects are playing, and the device is not paused.
DIGFFS_USERFFSWITCHOFF
The user force-feedback switch is currently off; that is, the device cannot operate. If the device cannot report the state of the user force-feedback switch, neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF is returned.
DIGFFS_USERFFSWITCHON
The user force-feedback switch is currently on; that is, the device can operate. If the device cannot report the state of the user force-feedback switch, neither DIGFFS_USERFFSWITCHON nor DIGFFS_USERFFSWITCHOFF is returned.

Future versions of Microsoft® DirectInput® can define additional flags. Applications should ignore any flags that are not currently defined.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED
DIERR_UNSUPPORTED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::GetImageInfo

Retrieves information about a device image for use in a configuration property sheet.

HRESULT GetImageInfo(
  LPDIDEVICEIMAGEINFOHEADER lpdiDevImageInfoHeader
);

Parameters

lpdiDevImageInfoHeader
Address of a DIDEVICEIMAGEINFOHEADER structure that receives information about the device image.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values.

DIERR_INVALIDPARAM
DIERR_MAPFILEFAIL
DIERR_MOREDATA
DIERR_NOTINITIALIZED
DIERR_OBJECTNOTFOUND

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::GetObjectInfo

Retrieves information about a device object, such as a button or axis.

HRESULT GetObjectInfo(
  LPDIDEVICEOBJECTINSTANCE pdidoi,
  DWORD dwObj,
  DWORD dwHow
);

Parameters

pdidoi
Address of a DIDEVICEOBJECTINSTANCE structure to be filled with information about the object. The structure's dwSize member must be initialized before this method is called.
dwObj
Value that identifies the object whose information is to be retrieved. The value set for this parameter depends on the value specified in the dwHow parameter.
dwHow
Value that specifies how the dwObj parameter should be interpreted. This value can be one of the following:
Value | Meaning
DIPH_BYOFFSET | The dwObj parameter is the offset into the current data format of the object whose information is being accessed.
DIPH_BYID | The dwObj parameter is the object type/instance identifier. This identifier is returned in the dwType member of the DIDEVICEOBJECTINSTANCE structure returned from a previous call to the IDirectInputDevice8::EnumObjects method.
DIPH_BYUSAGE | The dwObj parameter contains the HID Usage Page and Usage values of the object, combined by the DIMAKEUSAGEDWORD macro.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
DIERR_OBJECTNOTFOUND
E_POINTER

Remarks

For compatibility with Microsoft® DirectX® 3, it is also valid to pass a DIDEVICEOBJECTINSTANCE_DX3 structure with the dwSize member initialized to sizeof(DIDEVICEOBJECTINSTANCE_DX3).

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::GetProperty

Retrieves information about the input device.

HRESULT GetProperty(
  REFGUID rguidProp,
  LPDIPROPHEADER pdiph
);

Parameters

rguidProp
Reference to (C++) or address of (C) the GUID identifying the property to be retrieved. This can be one of the predefined values or a pointer to a GUID that identifies the property. The following properties are predefined for an input device:
DIPROP_APPDATA
Retrieves the application-defined value associated with an in-game action, as a DIPROPPOINTER.
DIPROP_AUTOCENTER
Determines whether device objects are self-centering. The value returned can be DIPROPAUTOCENTER_OFF or DIPROPAUTOCENTER_ON. See IDirectInputDevice8::SetProperty for more information.
DIPROP_AXISMODE
Retrieves the axis mode. The retrieved value can be DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL.
DIPROP_BUFFERSIZE
Retrieves the input buffer size.

The buffer size determines the amount of data that the buffer can hold between calls to the IDirectInputDevice8::GetDeviceData method before data is lost. This value can be set to 0 to indicate that the application will not be reading buffered data from the device. If the buffer size in the dwData member of the DIPROPDWORD structure is too large to be supported by the device, the largest possible buffer size is set. To determine whether the requested buffer size was set, retrieve the buffer-size property, and compare the result with the value that you previously attempted to set.

DIPROP_CALIBRATIONMODE
For use by device drivers; not used by applications.
DIPROP_CPOINTS
Retrieves calibration points used for the adjustment of incoming raw data as a DIPROPCPOINTS structure.
DIPROP_DEADZONE
Retrieves a value for the dead zone of a joystick, in the range from 0 through 10,000, where 0 indicates that there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range.
DIPROP_FFGAIN
Retrieves the gain of the device. See IDirectInputDevice8::SetProperty for more information.
DIPROP_FFLOAD
Retrieves the memory load for the device. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE. The retrieved value is in the range from 0 through 100, indicating the percentage of device memory in use. The device must be acquired in exclusive mode. If it is not, the method will fail with a return value of DIERR_NOTEXCLUSIVEACQUIRED.
DIPROP_GETPORTDISPLAYNAME
Retrieves the human-readable display name of the port to which this device is connected. Not generally used by applications. If no friendly name is returned, the method returns S_FALSE.
DIPROP_GRANULARITY
Retrieves the input granularity. Granularity represents the smallest distance over which the object reports movement. Most axis objects have a granularity of one; that is, all values are possible. Some axes have a larger granularity. For example, the wheel axis on a mouse can have a granularity of 20; that is, all reported changes in position are multiples of 20. In other words, when the user turns the wheel slowly, the device reports a position of 0, then 20, then 40, and so on. This is a read-only property.
DIPROP_GUIDANDPATH
Retrieves the class GUID and device interface (path) for the device. This property lets advanced applications perform operations on a HID that are not supported by Microsoft® DirectInput®. For more information, see the reference for the DIPROPGUIDANDPATH structure.
DIPROP_INSTANCENAME
Retrieves the friendly instance name of the device. For more information, see IDirectInputDevice8::SetProperty.
DIPROP_JOYSTICKID
Retrieves the instance number of a joystick. This property is not implemented for the mouse or keyboard.
DIPROP_KEYNAME
Retrieves the localized key name for a keyboard key, as a DIPROPSTRING.
DIPROP_LOGICALRANGE
Retrieves the range of the raw data returned for axes on a HID. Devices can return negative values.
DIPROP_PHYSICALRANGE
Retrieves the range of data for axes as suggested by the manufacturer of a HID. Values can be negative. Normally DirectInput® returns values from 0 through 0xFFFF, but the range can be made to conform to the manufacturer's suggested range by using DIPROP_RANGE.
DIPROP_PRODUCTNAME
Retrieves the friendly product name of the device. For more information, see IDirectInputDevice8::SetProperty.
DIPROP_RANGE
Retrieves the range of values an object can possibly report. For some devices, this is a read-only property.
DIPROP_SATURATION
Retrieves a value for the saturation zones of a joystick, in the range from 0 through 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone).
DIPROP_SCANCODE
Retrieves the scan code for a keyboard key, as a DIPROPDWORD.
DIPROP_USERNAME
Retrieves the user name for a user currently assigned to a device, as a DIPROPSTRING. User names are set by calling IDirectInputDevice8::SetActionMap. If no user name is set, the method returns S_FALSE.
pdiph
Address of the DIPROPHEADER portion of a larger property-dependent structure that contains the DIPROPHEADER structure as a member. The following structures are used for properties:
DIPROPDWORD
Used for properties represented by a single numerical value.
DIPROPGUIDANDPATH
Used for DIPROP_GUIDANDPATH.
DIPROPRANGE
Used for properties represented by a pair of numerical values. Currently, the only such property is DIPROP_RANGE.
DIPROPSTRING
Used for string properties.

Return Values

If the method succeeds, the return value is DI_OK or S_FALSE.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED
DIERR_OBJECTNOTFOUND
DIERR_UNSUPPORTED

Remarks

The following C example shows how to obtain the value of the DIPROP_BUFFERSIZE property:

DIPROPDWORD dipdw;  // DIPROPDWORD contains a DIPROPHEADER structure.
HRESULT hr;
dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
dipdw.diph.dwObj        = 0; // device property
dipdw.diph.dwHow        = DIPH_DEVICE;

hr = IDirectInputDevice8_GetProperty(pdid, DIPROP_BUFFERSIZE, &dipdw.diph);
if (SUCCEEDED(hr)) {
    // The dipdw.dwData member contains the buffer size.
}

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::SetProperty


IDirectInputDevice8::Initialize

Initializes a DirectInputDevice object. The IDirectInput8::CreateDevice method automatically initializes a device after creating it; applications normally do not need to call this method.

HRESULT Initialize(
  HINSTANCE hinst,
  DWORD dwVersion,
  REFGUID rguid
);

Parameters

hinst
Instance handle to the application or DLL that is creating the DirectInputDevice object. Microsoft® DirectInput® uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility.

It is an error for a DLL to pass the handle to the parent application. For example, a Microsoft ActiveX® control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle to the Web browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that may be necessary.

dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.
rguid
Reference to (C++) or address of (C) the GUID identifying the instance of the device with which the interface should be associated. The IDirectInput8::EnumDevices method can be used to determine which instance GUIDs are supported by the system.

Return Values

If the method succeeds, the return value is DI_OK or S_FALSE.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED
DIERR_DEVICENOTREG

If the method returns S_FALSE, the device had already been initialized with the instance GUID passed in though rGUID.

Remarks

If this method fails, the underlying object should be considered to be in an indeterminate state and must be reinitialized before use.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::Poll

Retrieves data from polled objects on a Microsoft® DirectInput® device. If the device does not require polling, calling this method has no effect. If a device that requires polling is not polled periodically, no new data is received from the device. Calling this method causes DirectInput to update the device state, generate input events (if buffered data is enabled), and set notification events (if notification is enabled).

HRESULT Poll()

Parameters

None.

Return Values

If the method succeeds, the return value is DI_OK, or DI_NOEFFECT if the device does not require polling.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_NOTACQUIRED
DIERR_NOTINITIALIZED

Remarks

Before a device data can be polled, the data format must be set by using the IDirectInputDevice8::SetDataFormat or IDirectInputDevice8::SetActionMap method, and the device must be acquired by using the IDirectInputDevice8::Acquire method.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

Polling and Event Notification


IDirectInputDevice8::RunControlPanel

Runs the Microsoft® DirectInput® control panel associated with this device. If the device does not have a control panel associated with it, the default device control panel is launched.

HRESULT RunControlPanel(
  HWND hwndOwner,
  DWORD dwFlags
);

Parameters

hwndOwner
Parent window handle. If this parameter is NULL, no parent window is used.
dwFlags
Not currently used. Zero is the only valid value.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::SendDeviceData

Sends data to a device that accepts output. The device must be in an acquired state.

HRESULT SendDeviceData(
  DWORD cbObjectData,
  LPCDIDEVICEOBJECTDATA rgdod,
  LPDWORD pdwInOut,
  DWORD fl
);

Parameters

cbObjectData
Size, in bytes, of a single DIDEVICEOBJECTDATA structure.
rgdod
Array of DIDEVICEOBJECTDATA structures containing the data to send to the device. It must consist of *pdwInOut elements.

The dwOfs field of each DIDEVICEOBJECTDATA structure must contain the device object identifier (as obtained from the dwType field of the DIDEVICEOBJECTINSTANCE structure) for the device object to which the data is directed. The dwTimeStamp and dwSequence members must be 0.

pdwInOut
On entry, the variable pointed to by this parameter contains the number of elements in the array pointed to by rgdod. On exit, it contains the number of elements sent to the device.
fl
Flags controlling the manner in which data is sent. This can be 0 or the following value:
DISDD_CONTINUE
The device data sent is overlaid on the previously sent device data. See Remarks.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_NOTACQUIRED
DIERR_REPORTFULL
DIERR_UNPLUGGED

Remarks

There is no guarantee that the individual data elements will be sent in a particular order. However, data sent by successive calls to IDirectInputDevice8::SendDeviceData is not interleaved. Furthermore, if multiple pieces of data are sent to the same object with a single call, it is unspecified which piece of data is sent.

Consider, for example, a device that can be sent data in packets, each packet describing two pieces of information; call them A and B. Suppose the application attempts to send three data elements: B = 2, A = 1, and B = 0.

The actual device is sent a single packet. The A field of the packet contains the value 1, and the B field of the packet is either 2 or 0.

If the data must to be sent to the device exactly as specified, three calls to IDirectInputDevice8::SendDeviceData should be performed, each call sending one data element.

In response to the first call, the device is sent a packet in which the A field is blank and the B field contains the value 2.

In response to the second call, the device is sent a packet in which the A field contains the value 1, and the B field is blank.

Finally, in response to the third call, the device is sent a packet in which the A field is blank and the B field contains the value 0.

If the DISDD_CONTINUE flag is set, the device data sent is overlaid on the previously sent device data. Otherwise, the device data sent does not include the previously sent device data.

For example, suppose a device supports two button outputs, Button0 and Button1. If an application first calls IDirectInputDevice8::SendDeviceData passing "Button0 pressed", a packet of the form "Button0 pressed, Button1 not pressed" is sent to the device. If the application then makes another call, passing "Button1 pressed" and the DISDD_CONTINUE flag, a packet of the form "Button0 pressed, Button1 pressed" is sent to the device. However, if the application had not passed the DISDD_CONTINUE flag, the packet sent to the device would have been "Button0 not pressed, Button1 pressed".

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::SendForceFeedbackCommand

Sends a command to the device's force-feedback system.

HRESULT SendForceFeedbackCommand(
  DWORD dwFlags
);

Parameters

dwFlags
Single value indicating the desired change in state. The value can be one of the following:
DISFFC_CONTINUE
Paused playback of all active effects is to be continued. It is an error to send this command when the device is not in a paused state.
DISFFC_PAUSE
Playback of all active effects is to be paused. This command also stops the clock-on effects so that they continue playing to their full duration when restarted.

While the device is paused, new effects cannot be started, and existing ones cannot be modified. Doing so can cause the subsequent DISFFC_CONTINUE command to fail to perform properly.

To abandon a pause and stop all effects, use the DISFFC_STOPALL or DISFCC_RESET commands.

DISFFC_RESET
The device's force-feedback system is to be put in its startup state. All effects are removed from the device, are no longer valid, and must be recreated if they are to be used again. The device's actuators are disabled.
DISFFC_SETACTUATORSOFF
The device's force-feedback actuators are to be disabled. While the actuators are off, effects continue to play but are ignored by the device. Using the analogy of a sound playback device, they are muted, rather than paused.
DISFFC_SETACTUATORSON
The device's force-feedback actuators are to be enabled.
DISFFC_STOPALL
Playback of any active effects is to be stopped. All active effects are reset, but are still being maintained by the device and are still valid. If the device is in a paused state, that state is lost.

This command is equivalent to calling the IDirectInputEffect::Stop method for each effect playing.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED
DIERR_UNSUPPORTED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::SetActionMap

Sets the data format for a device and maps application-defined actions to device objects. It also sets the buffer size for buffered data.

Note The device must be unacquired prior to calling this method.

HRESULT SetActionMap(
  LPCDIACTIONFORMAT lpdiActionFormat,
  LPCWSTR lptszUserName,
  DWORD dwFlags
);

Parameters

lpdiActionFormat
Address of a DIACTIONFORMAT structure containing information about the action map to be applied.
lptszUserName
Unicode string that specifies the name of the user for which the action map is being set. A value of NULL specifies the user currently logged into the system.
dwFlags
DWORD value that specifies how the action map is applied. This can be one of the following values.
DIDSAM_DEFAULT
Set the action map for this user. If the map differs from the current map, the new settings are saved to disk.
DIDSAM_FORCESAVE
Always save the configuration to disk.
DIDSAM_NOUSER
Reset user ownership for this device in the default configuration property sheet. Resetting user ownership does not remove the current action map.

Return Values

If the method succeeds, the return value can be one of the following error values:

DI_OK
DI_SETTINGSNOTSAVED
DI_WRITEPROTECT

If the method fails, the return value can be one of the following error values.

DIERR_ACQUIRED
DIERR_INVALIDPARAM

Remarks

This method provides the mechanism to change action-to-control mapping from the device defaults. An application must use this method to map its in-game actions to virtual controls.

The user name passed to this method binds a set of action mappings for a device to a specific user. Settings are automatically saved to disk when they differ from the currently applied map. Applications that accept input from multiple users should be very careful when applying action maps to the system mouse or keyboard, as the action maps for each user may conflict.

The method can be called only when the device is not acquired.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::BuildActionMap


IDirectInputDevice8::SetCooperativeLevel

Establishes the cooperative level for this instance of the device. The cooperative level determines how this instance of the device interacts with other instances of the device and the rest of the system.

HRESULT SetCooperativeLevel(
  HWND hwnd,
  DWORD dwFlags
);

Parameters

hwnd
Window handle to be associated with the device. This parameter must be a valid top-level window handle that belongs to the process. The window associated with the device must not be destroyed while it is still active in a Microsoft® DirectInput® device.
dwFlags
Flags that describe the cooperative level associated with the device. The following flags are defined:
DISCL_BACKGROUND
The application requires background access. If background access is granted, the device can be acquired at any time, even when the associated window is not the active window.
DISCL_EXCLUSIVE
The application requires exclusive access. If exclusive access is granted, no other instance of the device can obtain exclusive access to the device while it is acquired. However, nonexclusive access to the device is always permitted, even if another application has obtained exclusive access.

An application that acquires the mouse or keyboard device in exclusive mode should always unacquire the devices when it receives WM_ENTERSIZEMOVE and WM_ENTERMENULOOP messages. Otherwise, the user cannot manipulate the menu or move and resize the window.

DISCL_FOREGROUND
The application requires foreground access. If foreground access is granted, the device is automatically unacquired when the associated window moves to the background.
DISCL_NONEXCLUSIVE
The application requires nonexclusive access. Access to the device does not interfere with other applications that are accessing the same device.
DISCL_NOWINKEY
Disable the Windows logo key. Setting this flag ensures that the user cannot inadvertently break out of the application. Note, however, that DISCL_NOWINKEY has no effect when the default action mapping UI is displayed, and the Microsoft Windows® logo key will operate normally as long as that UI is present.

Applications must specify either DISCL_FOREGROUND or DISCL_BACKGROUND; it is an error to specify both or neither. Similarly, applications must specify either DISCL_EXCLUSIVE or DISCL_NONEXCLUSIVE.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
E_HANDLE

Remarks

If the system mouse is acquired in exclusive mode, the pointer is removed from the screen until the device is unacquired. This applies only to a mouse created by passing GUID_SysMouse to IDirectInput8::CreateDevice.

Applications must call this method before acquiring the device by using the IDirectInputDevice8::Acquire method.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

Cooperative Levels


IDirectInputDevice8::SetDataFormat

Sets the data format for the Microsoft® DirectInput® device.

HRESULT SetDataFormat(
  LPCDIDATAFORMAT lpdf
);

Parameters

lpdf
Address of a structure that describes the format of the data that the DirectInputDevice should return. An application can define its own DIDATAFORMAT structure or use one of the following predefined global variables:
  • c_dfDIKeyboard
  • c_dfDIMouse
  • c_dfDIMouse2
  • c_dfDIJoystick
  • c_dfDIJoystick2

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

The data format must be set before the device can be acquired by using the IDirectInputDevice8::Acquire method. It is necessary to set the data format only once. The data format cannot be changed while the device is acquired.

If the application is using action mapping, the data format is set instead by the call to IDirectInputDevice8::SetActionMap.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::GetDeviceState


IDirectInputDevice8::SetEventNotification

Specifies an event that is to be set when the device state changes. It is also used to turn off event notification.

HRESULT SetEventNotification(
  HANDLE hEvent
);

Parameters

hEvent
Handle to the event that is to be set when the device state changes. Microsoft® DirectInput® uses the Microsoft® Win32® SetEvent function on the handle when the state of the device changes. If the hEvent parameter is NULL, notification is disabled.

The application can create the handle as either a manual-reset or autoreset event by using the Microsoft® Win32® CreateEvent function. If the event is created as an autoreset event, the operating system automatically resets the event once a wait has been satisfied. If the event is created as a manual-reset event, it is the application's responsibility to call the Win32 ResetEvent function to reset it. DirectInput does not call the Win32 ResetEvent function for event notification handles. Most applications create the event as an automatic-reset event.

Return Values

If the method succeeds, the return value is DI_OK or DI_POLLEDDEVICE.

If the method fails, the return value can be one of the following error values:

DIERR_ACQUIRED
DIERR_HANDLEEXISTS
DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

A device state change is defined as any of the following:

  • A change in the position of an axis
  • A change in the state (pressed or released) of a button
  • A change in the direction of a POV control
  • Loss of acquisition

Do not call the Win32 CloseHandle function on the event while it has been selected into a DirectInputDevice object. You must call this method with the hEvent parameter set to NULL before closing the event handle.

The event notification handle cannot be changed while the device is acquired. If the function is successful, the application can use the event handle like any other Win32 event handle.

The following code example checks whether the handle is currently set without blocking:

dwResult = WaitForSingleObject(hEvent, 0);
if (dwResult == WAIT_OBJECT_0) {
    // Event is set. If the event was created as
    // autoreset, it has also been reset.
}

The following code example illustrates blocking indefinitely until the event is set. This behavior is strongly discouraged because the thread does not respond to the system until the wait is satisfied. In particular, the thread does not respond to Windows® messages.

dwResult = WaitForSingleObject(hEvent, INFINITE);
if (dwResult == WAIT_OBJECT_0) {
    // Event has been set. If the event was created
    // as autoreset, it has also been reset.
}

The following code example illustrates a typical message loop for a message-based application that uses two events:.

HANDLE ah[2] = { hEvent1, hEvent2 };

while (TRUE) {

    dwResult = MsgWaitForMultipleObjects(2, ah, FALSE,
                        INFINITE, QS_ALLINPUT);
    switch (dwResult) {
    case WAIT_OBJECT_0:
        // Event 1 has been set. If the event was created as
        // autoreset, it has also been reset.
        ProcessInputEvent1();
        break;

    case WAIT_OBJECT_0 + 1:
        // Event 2 has been set. If the event was created as
        // autoreset, it has also been reset.
        ProcessInputEvent2();
        break;

    case WAIT_OBJECT_0 + 2:
        // A Windows message has arrived. Process
        // messages until there aren't any more.
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
            if (msg.message == WM_QUIT) {
                goto exitapp;
            }
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        break;

    default:
        // Unexpected error.
        Panic();
        break;
    }
}

The following code example illustrates a typical application loop for a non-message-based application that uses two events:

HANDLE ah[2] = { hEvent1, hEvent2 };
DWORD dwWait = 0;

while (TRUE) {

    dwResult = MsgWaitForMultipleObjects(2, ah, FALSE,
                                         dwWait, QS_ALLINPUT);
    dwWait = 0;

    switch (dwResult) {
    case WAIT_OBJECT_0:
        // Event 1 has been set. If the event was
        // created as autoreset, it has also
        // been reset.
        ProcessInputEvent1();
        break;

    case WAIT_OBJECT_0 + 1:
        // Event 2 has been set. If the event was
        // created as autoreset, it has also
        // been reset.
        ProcessInputEvent2();
        break;

    case WAIT_OBJECT_0 + 2:
        // A Windows message has arrived. Process
        // messages until there aren't any more.
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)){
            if (msg.message == WM_QUIT) {
                goto exitapp;
            }
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        break;

    default:
        // No input or messages waiting.
        // Do a frame of the game.
        // If the game is idle, tell the next wait
        // to wait indefinitely for input or a message.
        if (!DoGame()) {
            dwWait = INFINITE;
        }
        break;
    }
}

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

Polling and Event Notification


IDirectInputDevice8::SetProperty

Sets properties that define the device behavior. These properties include input buffer size and axis mode.

HRESULT SetProperty(
  REFGUID rguidProp,
  LPCDIPROPHEADER pdiph
);

Parameters

rguidProp
Reference to (C++) or address of (C) the GUID identifying the property to be set. This can be one of the predefined values, or a pointer to a GUID that identifies the property. The following property values are predefined for an input device:
DIPROP_APPDATA
Sets the application-defined value associated with an in-game action, as a DIPROPPOINTER.
DIPROP_AUTOCENTER
Specifies whether device objects are self-centering. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE.

The dwData member can be one of the following values.

DIPROPAUTOCENTER_OFF: The device should not automatically center when the user releases the device. An application that uses force feedback should disable autocentering before playing effects.

DIPROPAUTOCENTER_ON: The device should automatically center when the user releases the device.

Not all devices support the autocenter property.

DIPROP_AXISMODE
Sets the axis mode. The value being set (DIPROPAXISMODE_ABS or DIPROPAXISMODE_REL) must be specified in the dwData member of the associated DIPROPDWORD structure. See the description of the pdiph parameter for more information.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

DIPROP_BUFFERSIZE
Sets the input buffer size. The value being set must be specified in the dwData member of the associated DIPROPDWORD structure. See Remarks.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

DIPROP_CALIBRATIONMODE
Enables the application to specify whether Microsoft® DirectInput® should retrieve calibrated or uncalibrated data from an axis. By default, DirectInput retrieves calibrated data.

Setting the calibration mode for the entire device is equivalent to setting it for each axis individually.

The dwData member of the DIPROPDWORD structure can be one of the following values:

DIPROPCALIBRATIONMODE_COOKED: DirectInput should return data after applying calibration information. This is the default mode.

DIPROPCALIBRATIONMODE_RAW: DirectInput should return raw, uncalibrated data. This mode is typically used only by Control Panel–type applications. Note that raw data might include negative values.

Setting a device into raw mode causes the dead zone, saturation, and range settings to be ignored.

DIPROP_CPOINTS
Sets calibration points used for the adjustment of incoming raw data. The values being set must be specified as CPOINT types in the cp array of the associated DIPROPCPOINTS structure.

This setting applies to individual device objects, so the dwHow member of the associated DIPROPHEADER structure must be set to either DIPH_BYID or DIPH_BYOFFSET.

DIPROP_DEADZONE
Sets the value for the dead zone of a joystick, in the range from 0 through 10,000, where 0 indicates that there is no dead zone, 5,000 indicates that the dead zone extends over 50 percent of the physical range of the axis on both sides of center, and 10,000 indicates that the entire physical range of the axis is dead. When the axis is within the dead zone, it is reported as being at the center of its range.

This setting can be applied to either the entire device or to a specific axis.

DIPROP_FFGAIN
Sets the gain for the device. This setting applies to the entire device, rather than to any particular object, so the dwHow member of the associated DIPROPDWORD structure must be DIPH_DEVICE.

The dwData member contains a gain value that is applied to all effects created on the device. The value is an integer in the range from 0 through 10,000, specifying the amount by which effect magnitudes should be scaled for the device. For example, a value of 10,000 indicates that all effect magnitudes are to be taken at face value. A value of 9,000 indicates that all effect magnitudes are to be reduced to 90% of their nominal magnitudes.

Setting a gain value is useful when an application wants to scale down the strength of all force-feedback effects uniformly, based on user preferences.

Unlike other properties, the gain can be set when the device is in an acquired state.

DIPROP_INSTANCENAME
This property exists for advanced applications that want to change the friendly instance name of a device (as returned in the tszInstanceName member of the DIDEVICEINSTANCE structure) to distinguish it from similar devices that are plugged in simultaneously. Most applications should have no need to change the friendly name.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

The pdiph parameter must be a pointer to the diph member of a DIPROPSTRING structure.

DIPROP_PRODUCTNAME
This property exists for advanced applications that want to change the friendly product name of a device (as returned in the tszProductName member of the DIDEVICEINSTANCE structure) to distinguish it from similar devices which are plugged in simultaneously. Most applications should have no need to change the friendly name.

This setting applies to the entire device, so the dwHow member of the associated DIPROPDWORD structure must be set to DIPH_DEVICE.

The pdiph parameter must be a pointer to the diph member of a DIPROPSTRING structure.

DIPROP_RANGE
Sets the range of values an object can possibly report. The minimum and maximum values are taken from the lMin and lMax members of the associated DIPROPRANGE structure.

For some devices, this is a read-only property.

You cannot set a reverse range; lMax must be greater than lMin.

DIPROP_SATURATION
Sets the value for the saturation zones of a joystick, in the range from 0 through 10,000. The saturation level is the point at which the axis is considered to be at its most extreme position. For example, if the saturation level is set to 9,500, the axis reaches the extreme of its range when it has moved 95 percent of the physical distance from its center position (or from the dead zone).

This setting can be applied to either the entire device or a specific axis.

pdiph
Address of the DIPROPHEADER structure contained within the type-specific property structure.

Return Values

If the method succeeds, the return value is DI_OK or DI_PROPNOEFFECT.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED
DIERR_OBJECTNOTFOUND
DIERR_UNSUPPORTED

Remarks

The buffer size determines the amount of data that the buffer can hold between calls to the IDirectInputDevice8::GetDeviceData method before data is lost. This value may be set to 0 to indicate that the application does not read buffered data from the device. If the buffer size in the dwData member of the DIPROPDWORD structure is too large to be supported by the device, the largest possible buffer size is set. To determine whether the requested buffer size was set, retrieve the buffer-size property and compare the result with the value that you previously attempted to set.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::GetProperty


IDirectInputDevice8::Unacquire

Releases access to the device.

HRESULT Unacquire();

Parameters

None.

Return Values

The return value is DI_OK is the device was unacquired, or DI_NOEFFECT if the device was not in an acquired state.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputDevice8::WriteEffectToFile

Saves information about one or more force-feedback effects to a file that can be read by using IDirectInputDevice8::EnumEffectsInFile. This method is chiefly of interest to those wanting to write their own force-authoring applications.

HRESULT WriteEffectToFile(
  LPCSTR lpszFileName,
  DWORD dwEntries,
  LPCDIFILEEFFECT rgDiFileEft,
  DWORD dwFlags
);

Parameters

lpszFileName
Name of the RIFF file.
dwEntries
Number of structures in the rgDiFileEft array.
rgDiFileEft
Array of DIFILEEFFECT structures.
dwFlags
Flags which control how the effect should be written. This can be DIFEF_DEFAULT (= 0) or the following value:
DIFEF_INCLUDENONSTANDARD
Includes effects that are not defined by Microsoft® DirectInput®. If this flag is not specified, only effects with GUIDs defined in Dinput.h, such as GUID_ConstantForce, are written.

Return Values

If the method succeeds, it returns DI_OK.

If it fails, the return value can be DIERR_INVALIDPARAM.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::EnumEffectsInFile


IDirectInputEffect

Applications use the methods of the IDirectInputEffect interface to manage effects of force-feedback devices.

The interface is obtained by using the IDirectInputDevice8::CreateEffect method.

The methods of the IDirectInputEffect interface can be organized into the following groups.

Effect information | GetEffectGuid
 | GetEffectStatus
 | GetParameters
Effect manipulation | Download
 | Initialize
 | SetParameters
 | Start
 | Stop
 | Unload
Miscellaneous | Escape

The IDirectInputEffect interface, like all COM interfaces, inherits the IUnknown interface methods. The IUnknown interface supports the following three methods:

IUnknown | AddRef
 | QueryInterface
 | Release

The LPDIRECTINPUTEFFECT type is defined as a pointer to the IDirectInputEffect interface:

typedef struct IDirectInputEffect    *LPDIRECTINPUTEFFECT;

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputEffect::Download

Places the effect on the device. If the effect is already on the device, the existing effect is updated to match the values set by the IDirectInputEffect::SetParameters method.

HRESULT Download(void);

Parameters

None.

Return Values

If the method succeeds, the return value is DI_OK or S_FALSE.

If the method fails, the return value can be one of the following error values:

DIERR_DEVICEFULL
DIERR_EFFECTPLAYING
DIERR_INCOMPLETEEFFECT
DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED

If the method returns S_FALSE, the effect has already been downloaded to the device.

Remarks

It is valid to update an effect while it is playing. The semantics of such an operation are explained in the reference for IDirectInputEffect::SetParameters.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputEffect::Escape

Sends a hardware-specific command to the driver.

HRESULT Escape(
  LPDIEFFESCAPE pesc
);

Parameters

pesc
DIEFFESCAPE structure that describes the command to be sent. On success, the cbOutBuffer member contains the number of bytes of the output buffer used.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_NOTINITIALIZED
DIERR_DEVICEFULL

Other device-specific error codes are also possible. Ask the hardware manufacturer for details.

Remarks

Because each driver implements different escapes, it is the application's responsibility to ensure that it is sending the escape to the correct driver by comparing the value of the guidFFDriver member of the DIDEVICEINSTANCE structure against the value the application is expecting.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputEffect::GetEffectGuid

Retrieves the GUID for the effect represented by the IDirectInputEffect object.

HRESULT GetEffectGuid(
  LPGUID pguid
);

Parameters

pguid
GUID structure that is filled by the method.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Remarks

Additional information about the effect can be obtained by passing the GUID to IDirectInputDevice8::GetEffectInfo.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputEffect::GetEffectStatus

Retrieves the status of an effect.

HRESULT GetEffectStatus(
  LPDWORD pdwFlags
);

Parameters

pdwFlags
Status flags for the effect. The value can be 0 or one or more of the following constants:
DIEGES_PLAYING
The effect is playing.
DIEGES_EMULATED
The effect is emulated.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_NOTINITIALIZED

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputEffect::GetParameters

Retrieves information about an effect.

HRESULT GetParameters(
  LPDIEFFECT peff,
  DWORD dwFlags
);

Parameters

peff
Address of a DIEFFECT structure that receives effect information. The dwSize member must be filled in by the application before calling this method.
dwFlags
Flags that specify which parts of the effect information are to be retrieved. The value can be 0 or one or more of the following constants:
DIEP_ALLPARAMS
The union of all other DIEP_* flags, indicating that all members of the DIEFFECT structure are being requested.
DIEP_ALLPARAMS_DX5
The union of all other DIEP_* flags except the DIEP_STARTDELAY flag.
DIEP_AXES
The cAxes and rgdwAxes members should receive data. The cAxes member on entry contains the size (in DWORDs) of the buffer pointed to by the rgdwAxes member. If the buffer is too small, the method returns DIERR_MOREDATA and sets cAxes to the necessary size of the buffer.
DIEP_DIRECTION
The cAxes and rglDirection members should receive data. The cAxes member on entry contains the size (in DWORDs) of the buffer pointed to by the rglDirection member. If the buffer is too small, the GetParameters method returns DIERR_MOREDATA and sets cAxes to the necessary size of the buffer.

The dwFlags member must include at least one of the coordinate system flags (DIEFF_CARTESIAN, DIEFF_POLAR, or DIEFF_SPHERICAL). Microsoft® DirectInput® returns the direction of the effect in one of the coordinate systems you specified, converting between coordinate systems as necessary. On exit, exactly one of the coordinate system flags is set in the dwFlags member, indicating which coordinate system DirectInput used. In particular, passing all three coordinate system flags retrieves the coordinates in exactly the same format in which they were set.

DIEP_DURATION
The dwDuration member should receive data.
DIEP_ENVELOPE
The lpEnvelope member points to a DIENVELOPE structure that should receive data. If the effect does not have an envelope associated with it, the lpEnvelope member is set to NULL.
DIEP_GAIN
The dwGain member should receive data.
DIEP_SAMPLEPERIOD
The dwSamplePeriod member should receive data.
DIEP_STARTDELAY
The dwStartDelay member should receive data.
DIEP_TRIGGERBUTTON
The dwTriggerButton member should receive data.
DIEP_TRIGGERREPEATINTERVAL
The dwTriggerRepeatInterval member should receive data.
DIEP_TYPESPECIFICPARAMS
The lpvTypeSpecificParams member points to a buffer whose size is specified by the cbTypeSpecificParams member. On return, the buffer is filled in with the type-specific data associated with the effect, and the cbTypeSpecificParams member contains the number of bytes copied. If the buffer supplied by the application is too small to contain all the type-specific data, the method returns DIERR_MOREDATA, and the cbTypeSpecificParams member contains the required size of the buffer in bytes.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INVALIDPARAM
DIERR_MOREDATA
DIERR_NOTINITIALIZED

Remarks

Common errors resulting in a DIERR_INVALIDPARAM error include not setting the dwSize member of the DIEFFECT structure, passing invalid flags, or not setting up the members in the DIEFFECT structure properly in preparation for receiving the effect information. For example, if information is to be retrieved in the dwTriggerButton member, the dwFlags member must be set to either DIEFF_OBJECTIDS or DIEFF_OBJECTOFFSETS so that DirectInput knows how to describe the button.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputEffect::Initialize

Initializes a DirectInputEffect object.

HRESULT Initialize(
  HINSTANCE hinst,
  DWORD dwVersion,
  REFGUID rguid
);

Parameters

hinst
Instance handle to the application or DLL that is creating the DirectInputEffect object. Microsoft® DirectInput® uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility. It is an error for a DLL to pass the handle to the parent application.
dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. Passing the version number of a previous version causes DirectInput to emulate that version.
rguid
Reference to (C++) or address of (C) the GUID identifying the effect with which the interface is associated. The IDirectInputDevice8::EnumEffects method can be used to determine which effect GUIDs are supported by the device.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be DIERR_DEVICENOTREG.

Remarks

If this method fails, the underlying object should be considered to be an indeterminate state and needs to be reinitialized before it can be subsequently used.

The IDirectInputDevice8::CreateEffect method automatically initializes the effect after creating it. Applications normally do not need to call the Initialize method.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputEffect::SetParameters

Sets the characteristics of an effect.

HRESULT SetParameters(
  LPCDIEFFECT peff,
  DWORD dwFlags
);

Parameters

peff
DIEFFECT structure that contains effect information. The dwSize member must be filled in by the application before calling this method, as well as any members specified by corresponding bits in the dwFlags parameter.
dwFlags
Flags that specify which portions of the effect information are to be set and how the downloading of the parameters should be handled. The value can be 0 or one or more of the following constants:
DIEP_AXES
The cAxes and rgdwAxes members contain data.
DIEP_DIRECTION
The cAxes and rglDirection members contain data. The dwFlags member specifies (with DIEFF_CARTESIAN or DIEFF_POLAR) the coordinate system in which the values should be interpreted.
DIEP_DURATION
The dwDuration member contains data.
DIEP_ENVELOPE
The lpEnvelope member points to a DIENVELOPE structure that contains data. To detach any existing envelope from the effect, pass this flag and set the lpEnvelope member to NULL.
DIEP_GAIN
The dwGain member contains data.
DIEP_NODOWNLOAD
Suppress the automatic IDirectInputEffect::Download that is normally performed after the parameters are updated. See Remarks.
DIEP_NORESTART
Suppress the stopping and restarting of the effect to change parameters. See Remarks.
DIEP_SAMPLEPERIOD
The dwSamplePeriod member contains data.
DIEP_START
The effect is to be started (or restarted if it is currently playing) after the parameters are updated. By default, the play state of the effect is not altered.
DIEP_STARTDELAY
The dwStartDelay member contains data.
DIEP_TRIGGERBUTTON
The dwTriggerButton member contains data.
DIEP_TRIGGERREPEATINTERVAL
The dwTriggerRepeatInterval member contains data.
DIEP_TYPESPECIFICPARAMS
The lpvTypeSpecificParams and cbTypeSpecificParams members of the DIEFFECT structure contain the address and size of type-specific data for the effect.

Return Values

If the method succeeds, the return value is one of the following:

DI_DOWNLOADSKIPPED
DI_EFFECTRESTARTED
DI_OK
DI_TRUNCATED
DI_TRUNCATEDANDRESTARTED

If the method fails, the return value can be one of the following error values:

DIERR_NOTINITIALIZED
DIERR_INCOMPLETEEFFECT
DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_EFFECTPLAYING

Remarks

The dwDynamicParams member of the DIEFFECTINFO structure for the effect specifies which parameters can be dynamically updated while the effect is playing.

The IDirectInputEffect::SetParameters method automatically downloads the effect, but this behavior can be suppressed by setting the DIEP_NODOWNLOAD flag. If automatic download has been suppressed, you can manually download the effect by invoking the IDirectInputEffect::Download method.

If the effect is playing while the parameters are changed, the new parameters take effect as if they were the parameters when the effect started.

For example, suppose a periodic effect with a duration of three seconds is started. After two seconds, the direction of the effect is changed. The effect then continues for one additional second in the new direction. The envelope, phase, amplitude, and other parameters of the effect continue smoothly, as if the direction had not changed.

In the same situation, if after two seconds the duration of the effect were changed to 1.5 seconds, the effect would stop.

Normally, if the driver cannot update the parameters of a playing effect, the driver is permitted to stop the effect, update the parameters, and then restart the effect. Passing the DIEP_NORESTART flag suppresses this behavior. If the driver cannot update the parameters of an effect while it is playing, the error code DIERR_EFFECTPLAYING is returned, and the parameters are not updated.

No more than one of the DIEP_NODOWNLOAD, DIEP_START, and DIEP_NORESTART flags should be set. (It is also valid to pass none of them.)

These three flags control download and playback behavior as follows:

If DIEP_NODOWNLOAD is set, the effect parameters are updated but not downloaded to the device.

If the DIEP_START flag is set, the effect parameters are updated and downloaded to the device, and the effect is started just as if the IDirectInputEffect::Start method had been called with the dwIterations parameter set to 1 and with no flags. (Combining the update with DIEP_START is slightly faster than calling Start separately, because it requires less information to be transmitted to the device.)

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is not playing, the parameters are updated and downloaded to the device.

If neither DIEP_NODOWNLOAD nor DIEP_START is set and the effect is playing, the parameters are updated if the device supports on-the-fly updating. Otherwise the behavior depends on the state of the DIEP_NORESTART flag. If it is set, the error code DIERR_EFFECTPLAYING is returned. If it is clear, the effect is stopped, the parameters are updated, and the effect is restarted.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputEffect::Start

Begins playing an effect. If the effect is already playing, it is restarted from the beginning. If the effect has not been downloaded or has been modified since its last download, it is downloaded before being started. This default behavior can be suppressed by passing the DIES_NODOWNLOAD flag.

HRESULT Start(
  DWORD dwIterations,
  DWORD dwFlags
);

Parameters

dwIterations
Number of times to play the effect in sequence. The envelope is re-articulated with each iteration.

To play the effect exactly once, pass 1. To play the effect repeatedly until explicitly stopped, pass INFINITE. To play the effect until explicitly stopped without re-articulating the envelope, modify the effect parameters with the IDirectInputEffect::SetParameters method, and change the dwDuration member to INFINITE.

dwFlags
Flags that describe how the effect should be played by the device. The value can be 0 or one or more of the following values:
DIES_SOLO
All other effects on the device should be stopped before the specified effect is played. If this flag is omitted, the effect is mixed with existing effects already started on the device.
DIES_NODOWNLOAD
Do not automatically download the effect.

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INCOMPLETEEFFECT
DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED
DIERR_UNSUPPORTED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Not all devices support multiple iterations.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputEffect::Stop

Stops playing an effect.

HRESULT Stop(void);

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED

Remarks

The device must be acquired at the exclusive cooperative level for this method to succeed.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


IDirectInputEffect::Unload

Removes the effect from the device. If the effect is playing, it is automatically stopped before it is unloaded.

HRESULT Unload(void);

Return Values

If the method succeeds, the return value is DI_OK.

If the method fails, the return value can be one of the following error values:

DIERR_INPUTLOST
DIERR_INVALIDPARAM
DIERR_NOTEXCLUSIVEACQUIRED
DIERR_NOTINITIALIZED

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


Callback Functions

The following seven functions are prototype callback functions for use with various enumeration methods. Applications can declare one of these callback functions under any name and define it in any way, but the parameter and return types must be the same as in the prototype.

  • DIConfigureDevicesCallback
  • DIEnumCreatedEffectObjectsCallback
  • DIEnumDeviceObjectsCallback
  • DIEnumDevicesBySemanticsCallback
  • DIEnumDevicesCallback
  • DIEnumEffectsCallback
  • DIEnumEffectsInFileCallback


DIConfigureDevicesCallback

Application-defined callback function that is called each time the property sheet image is refreshed. This function needs to be supplied only when the application is displaying the property sheet within its own window.

BOOL CALLBACK DIConfigureDevicesCallback(
  IUnknown FAR* lpDDSTarget,
  LPVOID pvRef
);

Parameters

lpDDSTarget
Pointer to the IUnknown interface of the surface in the lpUnkDDSTarget member of the DICONFIGUREDEVICESPARAMS structure that was passed to IDirectInput8::ConfigureDevices.
pvRef
Application-defined value passed to IDirectInput8::ConfigureDevices as the pvRef parameter.

Return Values

Can return TRUE or FALSE. DirectInput® does not use the return value.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.
Import Library: Use Dinput8.lib.


DIEnumCreatedEffectObjectsCallback

Application-defined callback function that receives DirectInputDevice effects as a result of a call to the IDirectInputDevice8::EnumCreatedEffectObjects method.

BOOL CALLBACK DIEnumCreatedEffectObjectsCallback(
  LPDIRECTINPUTEFFECT peff,
  LPVOID pvRef
);

Parameters

peff
Address of an effect object that has been created.
pvRef
The application-defined value passed to EnumCreatedEffectObjects as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.
Import Library: User-defined.


DIEnumDeviceObjectsCallback

Application-defined callback function that receives DirectInputDevice objects as a result of a call to the IDirectInputDevice8::EnumObjects method.

BOOL CALLBACK DIEnumDeviceObjectsCallback(
  LPCDIDEVICEOBJECTINSTANCE lpddoi,
  LPVOID pvRef
);

Parameters

lpddoi
DIDEVICEOBJECTINSTANCE structure that describes the object being enumerated.
pvRef
The application-defined value passed to EnumObjects as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.
Import Library: User-defined.


DIEnumDevicesBySemanticsCallback

Application-defined callback function that receives DirectInput® devices as a result of a call to the IDirectInput8::EnumDevicesBySemantics method.

BOOL CALLBACK DIEnumDevicesBySemanticsCallback(
  LPCDIDEVICEINSTANCE lpddi,
  LPDIRECTINPUTDEVICE8  lpdid,
  DWORD  dwFlags,
  DWORD  dwRemaining,
  LPVOID pvRef
);

Parameters

lpddi
Address of a DIDEVICEINSTANCE structure that describes the device instance.
lpdid
Pointer to the IDirectInputDevice8 interface for the device.
dwFlags
Flags that provide information about why the device is being enumerated. This can be a combination of action-mapping flags and one usage flag. At least one action-mapping flag is always present.

The following action-mapping flags are defined.

DIEDBS_MAPPEDPRI1
The device is being enumerated because priority 1 actions can be mapped to the device.
DIEDBS_MAPPEDPRI2
The device is being enumerated because priority 2 actions can be mapped to the device.

The following usage flags are defined.

DIEDBS_RECENTDEVICE
The device is being enumerated because the commands described by the action-mapping flags were recently used.
DIEDBS_NEWDEVICE
The device is being enumerated because the device was installed recently. Devices described by this flag have not been used with this game before.
dwRemaining
Number of devices, after this one, remaining to be enumerated.
pvRef
The application-defined value passed to IDirectInput8::EnumDevicesBySemantics as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Remarks

If a single hardware device can function as more than one DirectInput® device type, it is enumerated as each device type that it supports. For example, a keyboard with a built-in mouse is enumerated twice: once as a keyboard and once as a mouse. The product GUID is the same for each device, however.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.
Import Library: User-defined.

See Also

DIEnumDevicesCallback


DIEnumDevicesCallback

Application-defined callback function that receives DirectInput® devices as a result of a call to the IDirectInput8::EnumDevices method.

BOOL CALLBACK DIEnumDevicesCallback(
  LPCDIDEVICEINSTANCE lpddi,
  LPVOID pvRef
);

Parameters

lpddi
Address of a DIDEVICEINSTANCE structure that describes the device instance.
pvRef
The application-defined value passed to EnumDevices or EnumDevicesBySemantics as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration or DIENUM_STOP to stop the enumeration.

Remarks

If a single hardware device can function as more than one DirectInput device type, it is enumerated as each device type that it supports. For example, a keyboard with a built-in mouse is enumerated twice: once as a keyboard and once as a mouse. The product GUID is the same for each device, however.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.
Import Library: User-defined.

See Also

DIEnumDevicesBySemanticsCallback


DIEnumEffectsCallback

Application-defined callback function used with the IDirectInputDevice8::EnumEffects method.

BOOL CALLBACK DIEnumEffectsCallback(
  LPCDIEFFECTINFO pdei,
  LPVOID pvRef
);

Parameters

pdei
DIEFFECTINFO structure that describes the enumerated effect.
pvRef
The application-defined value passed to EnumEffects as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration, or DIENUM_STOP to stop it.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.
Import Library: User-defined.


DIEnumEffectsInFileCallback

Application-defined callback function used with the IDirectInputDevice8::EnumEffectsInFile method.

BOOL CALLBACK DIEnumEffectsInFileCallback(
  LPCDIFILEEFFECT lpDiFileEf,
  LPVOID pvRef
);

Parameters

lpDiFileEf
DIFILEEFFECT structure that describes the enumerated effect.
pvRef
The application-defined value passed to EnumEffectsInFile as the pvRef parameter.

Return Values

Returns DIENUM_CONTINUE to continue the enumeration, or DIENUM_STOP to stop it.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.
Import Library: User-defined.


Functions

This section is a reference for DirectInput® functions other than COM interface methods and callback functions.

The following function falls into this category:

  • DirectInput8Create


DirectInput8Create

Creates a DirectInput® object and returns an IDirectInput8 or later interface.

HRESULT WINAPI DirectInput8Create(
  HINSTANCE hinst,
  DWORD dwVersion,
  REFIID riidltf,
  LPVOID* ppvOut,
  LPUNKNOWN punkOuter
);

Parameters

hinst
Instance handle to the application or DLL that is creating the DirectInput object. DirectInput uses this value to determine whether the application or DLL has been certified and to establish any special behaviors that might be necessary for backward compatibility.

It is an error for a DLL to pass the handle to the parent application. For example, an ActiveX® control embedded in a Web page that uses DirectInput must pass its own instance handle, and not the handle to the Web browser. This ensures that DirectInput recognizes the control and can enable any special behaviors that might be necessary.

dwVersion
Version number of DirectInput for which the application is designed. This value is normally DIRECTINPUT_VERSION. If the application defines DIRECTINPUT_VERSION before including Dinput.h, the value must be greater than 0x0700. For earlier versions, use DirectInputCreateEx, which is in Dinput.lib.
riidltf
Unique identifier of the desired interface. For DirectX 8.0, this value is IID_IDirectInput8A or IID_IDirectInput8W. Passing the IID_IDirectInput8 define selects the ANSI or Unicode version of the interface, depending on whether UNICODE is defined during compilation.
ppvOut
Address of a pointer to a variable to receive the interface pointer if the call succeeds.
punkOuter
Pointer to the address of the controlling object's IUnknown interface for COM aggregation, or NULL if the interface is not aggregated. Most callers pass NULL. If aggregation is requested, the object returned in *ppvOut is a pointer to IUnknown, as required by COM aggregation.

Return Values

If the function succeeds, the return value is DI_OK.

If the function fails, the return value can be one of the following error values:

DIERR_BETADIRECTINPUTVERSION
DIERR_INVALIDPARAM
DIERR_OLDDIRECTINPUTVERSION
DIERR_OUTOFMEMORY

Remarks

The DirectInput object created by this function is implemented in Dinput8d.dll. Versions of interfaces earlier than DirectX 8.0 cannot be obtained in this implementation. To use earlier versions, create the DirectInput object by using DirectInputCreate or DirectInputCreateEx, which are in Dinput.lib.

Calling the function with punkOuter = NULL is equivalent to creating the object through CoCreateInstance(&CLSID_DirectInput8, punkOuter, CLSCTX_INPROC_SERVER, &IID_IDirectInput8W, lplpDirectInput), then initializing it with IDirectInput8::Initialize.

Calling the function with punkOuter != NULL is equivalent to creating the object through CoCreateInstance(&CLSID_DirectInput8, punkOuter, CLSCTX_INPROC_SERVER, &IID_IUnknown, lplpDirectInput). The aggregated object must be initialized manually.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.
Import Library: Use Dinput8.lib.


Macros

This section describes the following macros used in Microsoft® DirectInput®.

  • DIDFT_GETINSTANCE
  • DIDFT_GETTYPE
  • DIDFT_MAKEINSTANCE
  • DIEFT_GETTYPE
  • DIMAKEUSAGEDWORD
  • DISEQUENCE_COMPARE
  • GET_DIDEVICE_SUBTYPE
  • GET_DIDEVICE_TYPE

Dinput.h also defines macros for C calls to all the methods of the IDirectInput8 and IDirectInputDevice8 interfaces. These macros eliminate the need for pointers to method tables. For example, the following is a C call to the IDirectInputDevice8::Release method.

lpdid->lpVtbl->Release(lpdid));

The equivalent macro call looks like this.

IDirectInputDevice8_Release(lpdid);

All these macros take the same parameters as the method calls themselves.


DIDFT_GETINSTANCE

The DIDFT_GETINSTANCE macro extracts the object instance number code from a data format type.

DIDFT_GETINSTANCE(n) LOWORD((n) >> 8)

Parameters

n
Microsoft® DirectInput® data format type. The possible values for this parameter are identical to those found in the dwType member of the DIOBJECTDATAFORMAT structure.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

DIDFT_MAKEINSTANCE, DIDFT_GETTYPE


DIDFT_GETTYPE

The DIDFT_GETTYPE macro extracts the object type code from a data format type.

DIDFT_GETTYPE(n)  LOBYTE(n)

Parameters

n
Microsoft® DirectInput® data format type. The possible values for this parameter are identical to those found in the dwType member of the DIOBJECTDATAFORMAT structure.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

DIDFT_GETINSTANCE


DIDFT_MAKEINSTANCE

The DIDFT_MAKEINSTANCE macro creates an instance identifier of a device object for packing in the dwType member of the DIOBJECTDATAFORMAT structure.

DIDFT_MAKEINSTANCE(n) ((WORD)(n) << 8)

Parameters

n
Instance of the object; for example, 1 for button 1 of a mouse.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

DIDFT_GETINSTANCE


DIEFT_GETTYPE

The DIEFT_GETTYPE macro extracts the effect type code from an effect format type.

DIEFT_GETTYPE(n)  LOBYTE(n)

Parameters

n
Microsoft® DirectInput® effect format type. The possible values for this parameter are identical to those found in the dwEffType member of the DIEFFECTINFO structure.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIMAKEUSAGEDWORD

The DIMAKEUSAGEDWORD macro combines the usage page and usage codes for a device object representing a Human Interface Device, for passing to the IDirectInputDevice8::GetObjectInfo method.

DWORD DIMAKEUSAGEDWORD(
  WORD UsagePage,
  WORD Usage
);

Parameters

UsagePage
Usage page of the device object.
Usage
Usage of the device object.

Remarks

This macro is declared in Dinput.h as follows:

#define DIMAKEUSAGEDWORD(UsagePage, Usage) \
        ((DWORD)MAKELONG(Usage, UsagePage))

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in Dinput.h.


DISEQUENCE_COMPARE

The DISEQUENCE_COMPARE macro compares two Microsoft® DirectInput® sequence numbers, compensating for wraparound.

DISEQUENCE_COMPARE(dwSequence1, cmp, dwSequence2) \
                ((int)((dwSequence1) - (dwSequence2)) cmp 0)

Parameters

dwSequence1
First sequence number to compare.
cmp
One of the following comparison operators: ==, !=, <, >, <=, or >=.
dwSequence2
Second sequence number to compare.

Return Values

Returns a nonzero value if the result of the comparison specified by the cmp parameter is true, or zero otherwise.

Remarks

The following example checks whether the dwSequence1 parameter value precedes the dwSequence2 parameter value chronologically.

BOOL Sooner = (DISEQUENCE_COMPARE(dwSequence1, <, dwSequence2));

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


GET_DIDEVICE_SUBTYPE

The GET_DIDEVICE_SUBTYPE macro extracts the device subtype code from a device type description code.

GET_DIDEVICE_SUBTYPE(dwDevType)  HIBYTE(dwDevType)

Parameters

dwDevType
Microsoft® DirectInput® device type description code. The possible values for this parameter are identical to those found in the dwDevType member of the DIDEVICEINSTANCE structure.

Remarks

The interpretation of the subtype code depends on the primary type.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

GET_DIDEVICE_TYPE, DIDEVICEINSTANCE


GET_DIDEVICE_TYPE

The GET_DIDEVICE_TYPE macro extracts the device primary type code from a device type description code.

GET_DIDEVICE_TYPE(dwDevType)  LOBYTE(dwDevType)

Parameters

dwDevType
Microsoft® DirectInput® device type description code. Possible values for this parameter are identical to those found in the dwDevType member of the DIDEVICEINSTANCE structure.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

GET_DIDEVICE_SUBTYPE, DIDEVICEINSTANCE


Structures

This section contains information on the following structures used with Microsoft® DirectInput®.

  • DIACTION
  • DIACTIONFORMAT
  • DICOLORSET
  • DICONDITION
  • DICONFIGUREDEVICESPARAMS
  • DICONSTANTFORCE
  • DICUSTOMFORCE
  • DIDATAFORMAT
  • DIDEVCAPS
  • DIDEVICEIMAGEINFO
  • DIDEVICEIMAGEINFOHEADER
  • DIDEVICEINSTANCE
  • DIDEVICEOBJECTDATA
  • DIDEVICEOBJECTINSTANCE
  • DIEFFECT
  • DIEFFECTINFO
  • DIEFFESCAPE
  • DIENVELOPE
  • DIFILEEFFECT
  • DIJOYSTATE
  • DIJOYSTATE2
  • DIMOUSESTATE
  • DIMOUSESTATE2
  • DIOBJECTDATAFORMAT
  • DIPERIODIC
  • DIPROPCPOINTS
  • DIPROPDWORD
  • DIPROPGUIDANDPATH
  • DIPROPHEADER
  • DIPROPPOINTER
  • DIPROPRANGE
  • DIPROPSTRING
  • DIRAMPFORCE

Note The memory for all DirectX structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member should set the member to the size of the structure, in bytes, before use. The following example performs these tasks on a common structure, DIDEVCAPS:

DIDEVCAPS didevcaps; // Can't use this yet

ZeroMemory(&didevcaps, sizeof(didevcaps));
didevcaps.dwSize = sizeof(didevcaps);

// Now the structure Can be used.
.
.


CPOINT

Describes a calibration point. An array of CPOINT structures is contained by a DIPROPCPOINTS structure.

typedef struct _CPOINT
{
    LONG  lP;
    DWORD dwLog;
} CPOINT, *PCPOINT;

Members

lP
Raw data
dwLog
Scaling value to be associated with the lP number. The percentage of the maximum value multiplied by 10000.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

Using CPOINTs


DIACTION

Describes a mapping of one game action to one device semantic. An array of DIACTION structures is contained by a DIACTIONFORMAT structure.

typedef struct _DIACTION {
    UINT_PTR    uAppData;
    DWORD       dwSemantic;
    DWORD       dwFlags;
    union {
        LPCSTR  lptszActionName;
        UINT    uResIdString;
    };
    GUID        guidInstance;
    DWORD       dwObjID;
    DWORD       dwHow;
} DIACTION, *LPDIACTION;

typedef const DIACTION *LPCDIACTION;

Members

uAppData
Address of an application-defined UINT value to be returned to the application by IDirectInputDevice8::GetDeviceData when the state of the control associated with the action changes. This value is returned in the uAppData member of the DIDEVICEOBJECTDATA structure. It is typically an identifier for the application-specific action associated with the device object, but can also be a function pointer.
dwSemantic
For a joystick, a predefined action mapping constant for this application genre representing a virtual control or a constant for a control not defined in the genre. For a keyboard, mouse, or Microsoft® DirectPlay® voice device, a constant that represents a particular device object. See Action Mapping Constants.
dwFlags
Flags used to request specific attributes or processing. Can be zero or one or more of the following values.
DIA_APPFIXED
The action cannot be remapped by Microsoft DirectInput®.
DIA_APPMAPPED
The dwObjID member is valid, and IDirectInputDevice8::BuildActionMap will not override the application-defined mapping.
DIA_APPNOMAP
This action is not to be mapped.
DIA_FORCEFEEDBACK
The action must be mapped to an actuator or trigger.
DIA_NORANGE
The default range is not to be set for this action. This flag can be set only for absolute axis actions.
lptszActionName
Application-defined name of the action. This string is displayed by the device property sheet when IDirectInput8::ConfigureDevices is called.
uResIdString
Resource identifier for the string for this action. The module instance for this resource is specified in the hInstString member of the DIACTIONFORMAT structure that contains this structure.
guidInstance
Device instance GUID if a specific device is requested. Otherwise GUID_NULL.
dwObjID
Control identifier. Use the DIDFT_GETINSTANCE and DIDFT_GETTYPE macros to retrieve the instance and type from this value.
dwHow
When the structure is returned by IDirectInputDevice8::BuildActionMap, this member receives a value to indicate the mapping mechanism used by DirectInput to configure the action. The following values are defined.
DIAH_APPREQUESTED
The mapping was configured by the application, which specified the device (guidInstance) and device object (dwObjID) when calling BuildActionMap.
DIAH_DEFAULT
The mapping was determined by DirectInput in the absence of other mapping information.
DIAH_ERROR
An error occurred. The action cannot be matched to a control on the device. The action will be ignored when the action map is set.
DIAH_HWAPP
The mapping was specified by the hardware manufacturer for this game.
DIAH_HWDEFAULT
The mapping was specified by the hardware manufacturer for this genre.
DIAH_UNMAPPED
No suitable device object was found.
DIAH_USERCONFIG
The mapping was configured by the user.

This member is ignored when the action map is passed to IDirectInputDevice8::SetActionMap.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInput8::EnumDevicesBySemantics, IDirectInputDevice8::SetActionMap, IDirectInput8::ConfigureDevices, IDirectInputDevice8::BuildActionMap, Action Mapping


DIACTIONFORMAT

Contains information about the calling application and acts as a container for an array of DIACTION structures that define action-to-control mappings for a genre.

typedef struct {
    DWORD              dwSize;
    DWORD              dwActionSize;
    DWORD              dwDataSize;
    DWORD              dwNumActions;
    LPDIACTION         rgoAction;
    GUID               guidActionMap;
    DWORD              dwGenre;
    DWORD              dwBufferSize;
    OPTIONAL LONG      lAxisMin;
    OPTIONAL LONG      lAxisMax;
    OPTIONAL HINSTANCE hInstString;
    FILETIME           ftTimeStamp;
    DWORD              dwCRC;
    TCHAR              tszActionMap[MAX_PATH];
} DIACTIONFORMAT;

Members

dwSize
DWORD value that specifies the size of the DIACTIONFORMAT structure, in bytes.
dwActionSize
DWORD value that specifies the size of the DIACTION structure, in bytes.
dwDataSize
DWORD value that specifies the size of the device data to be returned by the device for immediate device data, in bytes. This member should be dwNumActions multiplied by four.
dwNumActions
DWORD value that specifies the number of elements in the rgoAction array.
rgoAction
Address of an array of DIACTION structures, each of which describes how an action maps to a virtual control or device object, and how the mapping information should be displayed to the user.
guidActionMap
GUID that identifies the action map. Device manufacturers can use this value to tune mappings for a specific title.
dwGenre
DWORD value that specifies the genre of the application. For possible values, see Action Mapping Constants.
dwBufferSize
DWORD value that specifies the number of input data packets in the buffer for each device to which this action map is to be applied. The buffer size must be set to a value greater than zero in order to retrieve data by using IDirectInputDevice8::GetDeviceData. Applications that set this member to the desired buffer size before calling IDirectInputDevice8::SetActionMap do not need to set the DIPROP_BUFFERSIZE property by using IDirectInputDevice8::SetProperty.
lAxisMin
Minimum value for the range of scaled data to be returned for all axes. This value is ignored for a specific action axis if the DIA_NORANGE flag is set in DIACTION.dwFlags.

This value is valid only for axis actions and should be set to zero for all other actions. It is used as the DIPROPRANGE.lMin value to set the range property on an absolute axis when the action map is applied using IDirectInputDevice8::SetActionMap.

lAxisMax
Maximum value for the range of scaled data to be returned for all axes. This value is ignored for a specific action axis if the DIA_NORANGE flag is set in DIACTION.dwFlags.

This value is valid only for axis actions and should be set to zero for all other actions. It is used as the DIPROPRANGE.lMax value to set the range property on an absolute axis when the action map is applied using IDirectInputDevice8::SetActionMap.

hInstString
Handle of the module containing string resources for action names, as specified in the uResIdString member of the DIACTION structure for each action. Can be zero if action names are specified in the lptszActionName member of the DIACTION structure for each action.
ftTimeStamp
FILETIME structure that receives the time at which this action map was last written to disk. See Remarks.
dwCRC
Cyclic redundancy check for this map. Used internally by Microsoft® DirectInput® to determine when a set of mappings should be saved to disk.
tszActionMap
Null-terminated string, of maximum length MAX_PATH, that specifies the friendly name for this action map. This string appears in the drop-down list box in the default property sheet.

Remarks

The ftTimeStamp member can contain special values that apply to new and unused devices. New devices have never been enumerated for this application and have never had an action map applied to them. Unused devices have been enumerated for the application before but have never had an action map applied. New devices always have DIAFTS_NEWDEVICELOW and DIAFTS_NEWDEVICEHIGH in the low and high DWORDs respectively of the FILETIME structure. Unused devices have DIAFTS_UNUSEDDEVICELOW and DIAFTS_UNUSEDDEVICEHIGH in these positions.

Applications should not use ftTimeStamp to check for new devices. Instead, they should look for the DIEDBS_RECENTDEVICE and DIEDBS_NEWDEVICE flags in the enumeration callback. For more information, see DIEnumDevicesBySemanticsCallback.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInput8::EnumDevicesBySemantics, IDirectInputDevice8::SetActionMap, IDirectInput8::ConfigureDevices, IDirectInputDevice8::BuildActionMap, Action Mapping


DICOLORSET

Describes a set of colors used to draw the device configuration user interface. It is part of the DICONFIGUREDEVICESPARAMS structure.

typedef struct _DICOLORSET {
    DWORD    dwSize
    D3DCOLOR cTextFore;
    D3DCOLOR cTextHighlight;
    D3DCOLOR cCalloutLine;
    D3DCOLOR cCalloutHighlight;
    D3DCOLOR cBorder;
    D3DCOLOR cControlFill;
    D3DCOLOR cHighlightFill;
    D3DCOLOR cAreaFill;
} DICOLORSET, *LPDICOLORSET;

typedef const DICOLORSET *LPCDICOLORSET;

Members

dwSize
Size of this structure, in bytes.
cTextFore
Foreground text color.
cTextHighlight
Foreground color for highlighted text.
cCalloutLine
Color used to display callout lines.
cCalloutHighlight
Color used to display callout lines.
cBorder
Border color, used to display lines around controls such as tabs and buttons.
cControlFill
Fill color for controls such as tabs and buttons.
cHighlightFill
Fill color for highlighted controls.
cAreaFill
Fill color for areas outside controls such as tabs and buttons.

Remarks

Text background color is always transparent.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

D3DCOLOR


DICONDITION

Contains type-specific information for effects that are marked as DIEFT_CONDITION.

A pointer to an array of DICONDITION structures for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure. The number of elements in the array must be either one, or equal to the number of axes associated with the effect.

typedef struct DICONDITION {
    LONG  lOffset;
    LONG  lPositiveCoefficient;
    LONG  lNegativeCoefficient;
    DWORD dwPositiveSaturation;
    DWORD dwNegativeSaturation;
    LONG  lDeadBand;
} DICONDITION, *LPDICONDITION;

typedef const DICONDITION *LPCDICONDITION;

Members

lOffset
Offset for the condition, in the range from –10,000 through 10,000.
lPositiveCoefficient
Coefficient constant on the positive side of the offset, in the range from –10,000 through 10,000.
lNegativeCoefficient
Coefficient constant on the negative side of the offset, in the range from –10,000 through 10,000.

If the device does not support separate positive and negative coefficients, the value of lNegativeCoefficient is ignored, and the value of lPositiveCoefficient is used as both the positive and negative coefficients.

dwPositiveSaturation
Maximum force output on the positive side of the offset, in the range from 0 through 10,000.

If the device does not support force saturations, the value of this member is ignored.

dwNegativeSaturation
Maximum force output on the negative side of the offset, in the range from 0 through 10,000.

If the device does not support force saturation, the value of this member is ignored.

If the device does not support separate positive and negative saturation, the value of dwNegativeSaturation is ignored, and the value of dwPositiveSaturation is used as both the positive and negative saturation.

lDeadBand
Region around lOffset in which the condition is not active, in the range from 0 through 10,000. In other words, the condition is not active between lOffset minus lDeadBand and lOffset plus lDeadBand.

Remarks

Different types of conditions interpret the parameters differently, but the basic idea is that force resulting from a condition is equal to A(q - q0) where A is a scaling coefficient, q is some metric, and q0 is the neutral value for that metric.

The preceding simplified formula must be adjusted if a nonzero deadband is provided. If the metric is less than lOffset - lDeadBand, the resulting force is given by the following formula:

force = lNegativeCoefficient * (q - (lOffset - lDeadBand))

Similarly, if the metric is greater than lOffset + lDeadBand, the resulting force is given by the following formula:

force = lPositiveCoefficient * (q - (lOffset + lDeadBand))

A spring condition uses axis position as the metric.

A damper condition uses axis velocity as the metric.

An inertia condition uses axis acceleration as the metric.

If the number of DICONDITION structures in the array is equal to the number of axes for the effect, the first structure applies to the first axis, the second applies to the second axis, and so on. For example, a two-axis spring condition with lOffset set to 0 in both DICONDITION structures would have the same effect as the joystick self-centering spring. When a condition is defined for each axis in this way, the effect must not be rotated.

If there is a single DICONDITION structure for an effect with more than one axis, the direction along which the parameters of the DICONDITION structure are in effect is determined by the direction parameters passed in the rglDirection field of the DIEFFECT structure. For example, a friction condition rotated 45 degrees (in polar coordinates) would resist joystick motion in the northeast-southwest direction but would have no effect on joystick motion in the northwest-southeast direction.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DICONFIGUREDEVICESPARAMS

Contains information for the device configuration property sheet. It is used by the IDirectInput8::ConfigureDevices method.

typedef struct _DICONFIGUREDEVICESPARAMS {
    DWORD            dwSize;
    DWORD            dwcUsers;
    LPSTR            lptszUserNames;
    DWORD            dwcFormats;
    LPDIACTIONFORMAT lprgFormats;
    HWND             hwnd;
    DICOLORSET       dics;
    IUnknown FAR *   lpUnkDDSTarget;
} DICONFIGUREDEVICESPARAMS, *LPDICONFIGUREDEVICESPARAMS;

Members

dwSize
Size of this structure, in bytes.
dwcUsers
Count of user names in the buffer at lptszUserNames. If lptszUserNames is NULL (to indicate that default user names should be used), the value in this member is ignored. If the dwcUsers value exceeds the number of entries actually in the buffer, the method fails, returning DIERR_INVALIDPARAM.
lptszUserNames
Pointer to a buffer containing a series of null-terminated name strings, the final element being designated by a double-null terminator. The lptszUserNames parameter can be set to NULL to instruct the use of default names. If the application passes more names than the dwcUsers count indicates, only the names within the count are used. If an application specifies names that are different from the names currently assigned to devices, ownership is revoked for all devices, a default name is created for the mismatched name, and the interface shows (No User) for all devices.
dwcFormats
Count of structures in the array at lprgFormats.
lprgFormats
Pointer to an array of DIACTIONFORMAT structures that contains action-mapping information for each genre used by the game. On input, this array contains action-to-control mappings and strings to display as callouts for each mapping. The configuration interface displays the genres in its drop-down list in the same order as in the array.
hwnd
Handle to the top-level window of the calling application. The member is needed only for applications that run in windowed mode, and is otherwise ignored.
dics
DICOLORSET structure that describes the color scheme to apply to the configuration user interface. Passing a zero-initialized DICOLORSET structure causes the default color scheme to be used.
lpUnkDDSTarget
Pointer to the IUnknown interface for a Microsoft® DirectDraw® or Microsoft Direct3D® target surface object that will be filled to contain an image of the configuration user interface. The image represents the current state of the user interface at the time that the DIEnumDevicesBySemanticsCallback function is invoked. The target surface will retain any alpha information passed as part of the DICOLORSET structure above, and also any alpha information encoded into the device image by the hardware manufacturer. The target surface object referred to by the IUnknown interface must support either IDirect3DSurface8 or IDirectDrawSurface7. Full-screen applications using DirectDraw must have target surfaces created using the DDSCAPS_SYSTEMEMORY flag.

Applications that are not using DirectDraw and applications that are using DirectDraw but are windowed rather than using the full screen may pass NULL in this parameter. This will cause Microsoft DirectInput® to use the Windows Graphics Device Interface (GDI) functions to draw the configuration user interface image.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DICONSTANTFORCE

Contains type-specific information for effects that are marked as DIEFT_CONSTANTFORCE.

The structure describes a constant force effect.

A pointer to a single DICONSTANTFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DICONSTANTFORCE {
    LONG lMagnitude;
} DICONSTANTFORCE, *LPDICONSTANTFORCE;

typedef const DICONSTANTFORCE *LPCDICONSTANTFORCE;

Members

lMagnitude
The magnitude of the effect, in the range from –10,000 through 10,000. If an envelope is applied to this effect, the value represents the magnitude of the sustain. If no envelope is applied, the value represents the amplitude of the entire effect.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DICUSTOMFORCE

Contains type-specific information for effects that are marked as DIEFT_CUSTOMFORCE.

The structure describes a custom or user-defined force.

A pointer to a DICUSTOMFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DICUSTOMFORCE {
    DWORD  cChannels;
    DWORD  dwSamplePeriod;
    DWORD  cSamples;
    LPLONG rglForceData;
} DICUSTOMFORCE, *LPDICUSTOMFORCE;

typedef const DICUSTOMFORCE *LPCDICUSTOMFORCE;

Members

cChannels
Number of channels (axes) affected by this force.

The first channel is applied to the first axis associated with the effect, the second to the second, and so on. If there are fewer channels than axes, nothing is associated with the extra axes.

If there is only a single channel, the effect is rotated in the direction specified by the rglDirection member of the DIEFFECT structure. If there is more than one channel, rotation is not allowed.

Not all devices support rotation of custom effects.

dwSamplePeriod
Sample period, in microseconds.
cSamples
Total number of samples in the rglForceData. It must be an integral multiple of the cChannels.
rglForceData
Pointer to an array of force values representing the custom force. If multiple channels are provided, the values are interleaved. For example, if cChannels is 3, the first element of the array belongs to the first channel, the second to the second, and the third to the third.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIDATAFORMAT

Describes a device's data format. This structure is used with the IDirectInputDevice8::SetDataFormat method.

typedef struct DIDATAFORMAT {
    DWORD dwSize;
    DWORD dwObjSize;
    DWORD dwFlags;
    DWORD dwDataSize;
    DWORD dwNumObjs;
    LPDIOBJECTDATAFORMAT rgodf;
} DIDATAFORMAT, *LPDIDATAFORMAT;

typedef const DIDATAFORMAT *LPCDIDATAFORMAT;

Members

dwSize
Size of this structure, in bytes.
dwObjSize
Size of the DIOBJECTDATAFORMAT structure, in bytes.
dwFlags
Flags describing other attributes of the data format. This value can be one of the following:
DIDF_ABSAXIS
The axes are in absolute mode. Setting this flag in the data format is equivalent to manually setting the axis mode property, using the IDirectInputDevice8::SetProperty method. This cannot be combined with DIDF_RELAXIS flag.
DIDF_RELAXIS
The axes are in relative mode. Setting this flag in the data format is equivalent to manually setting the axis mode property using the IDirectInputDevice8::SetProperty method. This cannot be combined with the DIDF_ABSAXIS flag.
dwDataSize
Size of a data packet returned by the device, in bytes. This value must be a multiple of 4 and must exceed the largest offset value for an object's data within the data packet.
dwNumObjs
Number of objects in the rgodf array.
rgodf
Address to an array of DIOBJECTDATAFORMAT structures. Each structure describes how one object's data should be reported in the device data. Typical errors include placing two pieces of information in the same location and placing one piece of information in more than one location.

Remarks

Applications do not typically need to create a DIDATAFORMAT structure. An application can use one of the predefined global data format variables, c_dfDIMouse, c_dfDIMouse2, c_dfDIKeyboard, c_dfDIJoystick, or c_dfDIJoystick2.

The following code example sets a data format that can be used by applications that need two axes (reported in absolute coordinates) and two buttons:

// Suppose an application uses the following
// structure to read device data.

typedef struct MYDATA {
    LONG  lX;                   // X-axis goes here.
    LONG  lY;                   // Y-axis goes here.
    BYTE  bButtonA;             // One button goes here.
    BYTE  bButtonB;             // Another button goes here.
    BYTE  bPadding[2];          // Must be DWORD multiple in size.
} MYDATA;

// Then, it can use the following data format.

DIOBJECTDATAFORMAT rgodf[ ] = {
  { &GUID_XAxis, FIELD_OFFSET(MYDATA, lX),
    DIDFT_AXIS | DIDFT_ANYINSTANCE, 0, },
  { &GUID_YAxis, FIELD_OFFSET(MYDATA, lY),
    DIDFT_AXIS | DIDFT_ANYINSTANCE, 0, },
  { &GUID_Button, FIELD_OFFSET(MYDATA, bButtonA),
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0, },
  { &GUID_Button, FIELD_OFFSET(MYDATA, bButtonB),
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, 0, },
};
#define numObjects (sizeof(rgodf) / sizeof(rgodf[0]))

DIDATAFORMAT df = {
    sizeof(DIDATAFORMAT),       // Size of this structure
    sizeof(DIOBJECTDATAFORMAT), // Size of object data format
    DIDF_ABSAXIS,               // Absolute axis coordinates
    sizeof(MYDATA),             // Size of device data
    numObjects,                 // Number of objects
    rgodf,                      // And here they are
};

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

DIACTIONFORMAT


DIDEVCAPS

Describes a Microsoft® DirectInput® device's capabilities. This structure is used with the IDirectInputDevice8::GetCapabilities method.

typedef struct DIDEVCAPS {
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwDevType;
    DWORD dwAxes;
    DWORD dwButtons;
    DWORD dwPOVs;
    DWORD dwFFSamplePeriod;
    DWORD dwFFMinTimeResolution;
    DWORD dwFirmwareRevision;
    DWORD dwHardwareRevision;
    DWORD dwFFDriverVersion;
} DIDEVCAPS, *LPDIDEVCAPS;

Members

dwSize
Size of this structure, in bytes. This member must be initialized by the application before a call to the IDirectInputDevice8::GetCapabilities method.
dwFlags
Flags associated with the device. This value can be a combination of the following:
DIDC_ALIAS
The device is a duplicate of another DirectInput device. Alias devices are by default not enumerated by IDirectInput8::EnumDevices.
DIDC_ATTACHED
The device is physically attached.
DIDC_DEADBAND
The device supports deadband for at least one force-feedback condition.
DIDC_EMULATED
If this flag is set, the data is coming from a user mode device interface, such as a Human Interface Device (HID), or by some other ring 3 means. If it is not set, the data is coming directly from a kernel mode driver.
DIDC_FORCEFEEDBACK
The device supports force feedback.
DIDC_FFFADE
The force-feedback system supports the fade parameter for at least one effect. If the device does not support fade, the fade level and fade time members of the DIENVELOPE structure are ignored by the device.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual effect sets the DIEFT_FFFADE flag if fade is supported for that effect.

DIDC_FFATTACK
The force-feedback system supports the attack parameter for at least one effect. If the device does not support attack, the attack level and attack time members of the DIENVELOPE structure are ignored by the device.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual effect sets the DIEFT_FFATTACK flag if attack is supported for that effect.

DIDC_HIDDEN
Fictitious device created by a device driver so that it can generate keyboard and mouse events. Such devices are not normally enumerated by IDirectInput8::EnumDevices or configured by IDirectInput8::ConfigureDevices.
DIDC_PHANTOM
Placeholder for a device that might exist in the future. Phantom devices are by default not enumerated by IDirectInput8::EnumDevices.
DIDC_POLLEDDATAFORMAT
At least one object in the current data format is polled, rather than interrupt-driven. For these objects, the application must explicitly call the IDirectInputDevice8::Poll method to obtain data.
DIDC_POLLEDDEVICE
At least one object on the device is polled, rather than interrupt-driven. For these objects, the application must explicitly call the IDirectInputDevice8::Poll method to obtain data. HID devices can contain a mixture of polled and nonpolled objects.
DIDC_POSNEGCOEFFICIENTS
The force-feedback system supports two coefficient values for conditions (one for the positive displacement of the axis and one for the negative displacement of the axis) for at least one condition. If the device does not support both coefficients, the negative coefficient in the DICONDITION structure is ignored.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_POSNEGCOEFFICIENTS flag if separate positive and negative coefficients are supported for that condition.

DIDC_POSNEGSATURATION
The force-feedback system supports a maximum saturation for both positive and negative force output for at least one condition. If the device does not support both saturation values, the negative saturation in the DICONDITION structure is ignored.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_POSNEGSATURATION flag if separate positive and negative saturation are supported for that condition.

DIDC_SATURATION
The force-feedback system supports the saturation of condition effects for at least one condition. If the device does not support saturation, the force generated by a condition is limited only by the maximum force that the device can generate.

After a call to the IDirectInputDevice8::GetEffectInfo method, an individual condition sets the DIEFT_SATURATION flag if saturation is supported for that condition.

DIDC_STARTDELAY
The force-feedback system supports the start delay parameter for at least one effect. If the device does not support start delays, the dwStartDelay member of the DIEFFECT structure is ignored.
dwDevType
Device type specifier. This member can contain values identical to those in the dwDevType member of the DIDEVICEINSTANCE structure.
dwAxes
Number of axes available on the device.
dwButtons
Number of buttons available on the device.
dwPOVs
Number of point-of-view controllers available on the device.
dwFFSamplePeriod
Minimum time between playback of consecutive raw force commands, in microseconds.
dwFFMinTimeResolution
Minimum time, in microseconds, that the device can resolve. The device rounds any times to the nearest supported increment. For example, if the value of dwFFMinTimeResolution is 1000, the device would round any times to the nearest millisecond.
dwFirmwareRevision
Firmware revision of the device.
dwHardwareRevision
Hardware revision of the device.
dwFFDriverVersion
Version number of the device driver.

Remarks

The semantics of version numbers are left to the manufacturer of the device. The only guarantee is that newer versions have larger numbers.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

DIDEVICEINSTANCE


DIDEVICEIMAGEINFO

Carries information required to display a device image or an overlay image with a callout. This structure is passed to the IDirectInputDevice8::GetImageInfo method as an array within a DIDEVICEIMAGEINFOHEADER structure.

typedef struct _DIDDEVICEIMAGEINFO {
    TCHAR  tszImagePath[MAX_PATH];
    DWORD  dwFlags;
    // The following are valid if DIDIFT_OVERLAY is present
    // in dwFlags
    DWORD  dwViewID;
    RECT   rcOverlay;
    DWORD  dwObjID;
    DWORD  dwcValidPts;
    POINT  rgptCalloutLine[5];
    RECT   rcCalloutRect;
    DWORD  dwTextAlign;
} DIDEVICEIMAGEINFO, * LPDIDEVICEIMAGEINFO;

Members

tszImagePath
Fully qualified path to the file that contains an image of the device. The file format is given in dwFlags. If no image is available for the device, this member will be set to NULL. If so, the application is responsible for enumerating controls on the device and displaying a default listing of actions to device controls (similar to the method used by most applications before Microsoft® DirectX® 8.0).
dwFlags
Flag that describes the intended use of the image.
DIDIFT_CONFIGURATION
The file is used to display the current configuration of actions on the device. Overlay image coordinates are relative to the upper-left corner of the configuration image.
DIDIFT_OVERLAY
The file (if provided) is an overlay for a configuration image. The dwViewID, rcOverlay, dwObjID, rgptCalloutLine, rcCalloutRect, and dwTextAlign members are valid and contain data used to display the overlay and callout information for a single control on the device. If no file is provided (null path string), all other pertinent members are relevant except rcOverlay.
dwViewID
For device view images (DIDIFT_CONFIGURATION), this is the ID of the device view. For device control overlays (DIDIFT_OVERLAY), this value refers to the device view (by ID) over which an image and callout information should be displayed.
rcOverlay
Rectangle, using coordinates relative to the top-left pixel of the device configuration image, in which the overlay image should be painted. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwObjID
Control identifier, as a combination of DIDFT_* flags and an instance value, to which an overlay image corresponds for this device. Applications use the DIDFT_GETINSTANCE and DIDFT_GETTYPE macros to decode this value to its constituent parts. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwcValidPts
Number of points in the array at rgptCalloutLine.
rgptCalloutLine
Array of POINT structures that specify coordinates of the points describing a callout line. A callout line connects a device control to a caption for the game action. Each line can have from one to four segments. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
rcCalloutRect
RECT structure that describes the rectangle in which the game action string is displayed. If the string cannot fit within the rectangle, the application is responsible for handling clipping. This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.
dwTextAlign
DWORD value that specifies the alignment of the text in the rectangle described by the rcCalloutRect member. Must be one horizontal alignment flag combined with one vertical alignment flag.

The following horizontal alignment flags are defined.

DIDAL_LEFTALIGNED
Text is aligned on the left border.
DIDAL_CENTERED
Text is horizontally centered.
DIDAL_RIGHTALIGNED
Text is aligned on the right border.

The following vertical alignment flags are defined.

DIDAL_MIDDLE
The text is vertically centered.
DIDAL_TOPALIGNED
The text is aligned on the top border.
DIDAL_BOTTOMALIGNED
The text is aligned on the bottom border.

This member is valid only if the DIDIFT_OVERLAY flag is present in dwFlags.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIDEVICEIMAGEINFOHEADER

Contains information about device images. Used in the IDirectInputDevice8::GetImageInfo method.

typedef struct _DIDEVICEIMAGEINFOHEADER{
    DWORD  dwSize;
    DWORD  dwSizeImageInfo;
    DWORD  dwcViews;
    DWORD  dwcButtons;
    DWORD  dwcAxes;
    DWORD  dwcPOVs;
    DWORD  dwBufferSize;
    DWORD  dwBufferUsed;
    DIDEVICEIMAGEINFO *lprgImageInfoArray;
} DIDEVICEIMAGEINFOHEADER, * LPDIDEVICEIMAGEINFOHEADER;

Members

dwSize
DWORD value that specifies the size of this structure, in bytes. Must be initialized before the structure can be used.
dwSizeImageInfo
DWORD value that specifies the size of the DIDEVICEIMAGEINFO structure, in bytes. Must be initialized before this structure can be used.
dwcViews
DWORD variable that receives the number of views of this device.
dwcButtons
DWORD variable that receives the number of buttons on the device.
dwcAxes
DWORD variable that receives the number of axes on the device.
dwcPOVs
DWORD variable that receives the number of point-of-view controllers on the device.
dwBufferSize
DWORD value that specifies the size, in bytes, of the buffer at lprgImageInfo. When set to zero, the IDirectInputDevice8::GetImageInfo method ignores all other members and returns the minimum buffer size required to hold information for all images.
dwBufferUsed
DWORD value that receives the size, in bytes, of the memory used in the buffer at lprgImageInfo. When dwBufferSize is set to zero, the IDirectInputDevice8::GetImageInfo method sets this member to the minimum size needed to hold information for all images.
lprgImageInfoArray
Pointer to a buffer that receives an array of DIDEVICEIMAGEINFO structures describing all the device images and views, overlay images, and callout-string coordinates.

Remarks

The buffer at lprgImageInfoArray must be large enough to hold all required image information structures. Applications can query for the required size by calling the IDirectInputDevice8::GetImageInfo method with the dwBufferSize member set to zero. After the call, dwBufferUsed contains the amount of memory, in bytes, that was modified.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIDEVICEINSTANCE

Describes an instance of a Microsoft® DirectInput® device. This structure is used with the IDirectInput8::EnumDevices, IDirectInput8::EnumDevicesBySemantics, and IDirectInputDevice8::GetDeviceInfo methods.

typedef struct DIDEVICEINSTANCE {
    DWORD dwSize;
    GUID  guidInstance;
    GUID  guidProduct;
    DWORD dwDevType;
    TCHAR tszInstanceName[MAX_PATH];
    TCHAR tszProductName[MAX_PATH];
    GUID  guidFFDriver;
    WORD  wUsagePage;
    WORD  wUsage;
} DIDEVICEINSTANCE, *LPDIDEVICEINSTANCE;

typedef const DIDEVICEINSTANCE  *LPCDIDEVICEINSTANCE;

Members

dwSize
Size of this structure, in bytes. This member must be initialized before the structure is used.
guidInstance
Unique identifier for the instance of the device. An application can save the instance GUID into a configuration file and use it at a later time. Instance GUIDs are specific to a particular computer. An instance GUID obtained from one computer is unrelated to instance GUIDs on another.
guidProduct
Unique identifier for the product. This identifier is established by the manufacturer of the device.
dwDevType
Device type specifier. The least-significant byte of the device type description code specifies the device type. The next-significant byte specifies the device subtype. This value can also be combined with DIDEVTYPE_HID, which specifies a Human Interface Device (HID).
tszInstanceName[MAX_PATH]
Friendly name for the instance. For example, "Joystick 1."
tszProductName[MAX_PATH]
Friendly name for the product.
guidFFDriver
Unique identifier for the driver being used for force feedback. The driver's manufacturer establishes this identifier.
wUsagePage
If the device is a Human Interface Device (HID), this member contains the HID usage page code.
wUsage
If the device is a Human Interface Device (HID), this member contains the HID usage code.

Remarks

The following device types and subtypes are defined for use in the dwDevType member.

DI8DEVTYPE_1STPERSON
First-person action game device. The following subtypes are defined.
DI8DEVTYPE1STPERSON_LIMITED
Device that does not provide the minimum number of device objects for action mapping.
DI8DEVTYPE1STPERSON_SHOOTER
Device designed for first-person shooter games.
DI8DEVTYPE1STPERSON_SIXDOF
Device with six degrees of freedom; that is, three lateral axes and three rotational axes.
DI8DEVTYPE1STPERSON_UNKNOWN
Unknown subtype.
DI8DEVTYPE_DEVICE
Device that does not fall into another category.
DI8DEVTYPE_DEVICECTRL
Input device used to control another type of device from within the context of the application. The following subtypes are defined.
DI8DEVTYPEDEVICECTRL_COMMSSELECTION
Control used to make communications selections.
DI8DEVTYPEDEVICECTRL_COMMSSELECTION_HARDWIRED
Device that must use its default configuration and cannot be remapped.
DI8DEVTYPEDEVICECTRL_UNKNOWN
Unknown subtype.
DI8DEVTYPE_DRIVING
Device for steering. The following subtypes are defined.
DI8DEVTYPEDRIVING_COMBINEDPEDALS
Steering device that reports acceleration and brake pedal values from a single axis.
DI8DEVTYPEDRIVING_DUALPEDALS
Steering device that reports acceleration and brake pedal values from separate axes.
DI8DEVTYPEDRIVING_HANDHELD
Hand-held steering device.
DI8DEVTYPEDRIVING_LIMITED
Steering device that does not provide the minimum number of device objects for action mapping.
DI8DEVTYPEDRIVING_THREEPEDALS
Steering device that reports acceleration, brake, and clutch pedal values from separate axes.
DI8DEVTYPE_FLIGHT
Controller for flight simulation. The following subtypes are defined.
DI8DEVTYPEFLIGHT_LIMITED
Flight controller that does not provide the minimum number of device objects for action mapping.
DI8DEVTYPEFLIGHT_RC
Flight device based on a remote control for model aircraft.
DI8DEVTYPEFLIGHT_STICK
Joystick.
DI8DEVTYPEFLIGHT_YOKE
Yoke.
DI8DEVTYPE_GAMEPAD
Gamepad. The following subtypes are defined.
DI8DEVTYPEGAMEPAD_LIMITED
Gamepad that does not provide the minimum number of device objects for action mapping.
DI8DEVTYPEGAMEPAD_STANDARD
Standard gamepad that provides the minimum number of device objects for action mapping.
DI8DEVTYPEGAMEPAD_TILT
Gamepad that can report x-axis and y-axis data based on the attitude of the controller.
DI8DEVTYPE_JOYSTICK
Joystick. The following subtypes are defined.
DI8DEVTYPEJOYSTICK_LIMITED
Joystick that does not provide the minimum number of device objects for action mapping.
DI8DEVTYPEJOYSTICK_STANDARD
Standard joystick that provides the minimum number of device objects for action mapping.
DI8DEVTYPE_KEYBOARD
Keyboard or keyboard-like device. The following subtypes are defined.
DI8DEVTYPEKEYBOARD_UNKNOWN
Subtype could not be determined.
DI8DEVTYPEKEYBOARD_PCXT
IBM PC/XT 83-key keyboard.
DI8DEVTYPEKEYBOARD_OLIVETTI
Olivetti 102-key keyboard.
DI8DEVTYPEKEYBOARD_PCAT
IBM PC/AT 84-key keyboard.
DI8DEVTYPEKEYBOARD_PCENH
IBM PC Enhanced 101/102-key or Microsoft Natural® keyboard.
DI8DEVTYPEKEYBOARD_NOKIA1050
Nokia 1050 keyboard.
DI8DEVTYPEKEYBOARD_NOKIA9140
Nokia 9140 keyboard.
DI8DEVTYPEKEYBOARD_NEC98
Japanese NEC PC98 keyboard.
DI8DEVTYPEKEYBOARD_NEC98LAPTOP
Japanese NEC PC98 laptop keyboard.
DI8DEVTYPEKEYBOARD_NEC98106
Japanese NEC PC98 106-key keyboard.
DI8DEVTYPEKEYBOARD_JAPAN106
Japanese 106-key keyboard.
DI8DEVTYPEKEYBOARD_JAPANAX
Japanese AX keyboard.
DI8DEVTYPEKEYBOARD_J3100
Japanese J3100 keyboard.
DI8DEVTYPE_MOUSE
A mouse or mouse-like device (such as a trackball). The following subtypes are defined.
DI8DEVTYPEMOUSE_ABSOLUTE
Mouse that returns absolute axis data.
DI8DEVTYPEMOUSE_FINGERSTICK
Fingerstick.
DI8DEVTYPEMOUSE_TOUCHPAD
Touchpad.
DI8DEVTYPEMOUSE_TRACKBALL
Trackball.
DI8DEVTYPEMOUSE_TRADITIONAL
Traditional mouse.
DI8DEVTYPEMOUSE_UNKNOWN
Subtype could not be determined.
DI8DEVTYPE_REMOTE
Remote-control device. The following subtype is defined.
DI8DEVTYPEREMOTE_UNKNOWN
Subtype could not be determined.
DI8DEVTYPE_SCREENPOINTER
Screen pointer. The following subtypes are defined.
DI8DEVTYPESCREENPTR_UNKNOWN
Unknown subtype.
DI8DEVTYPESCREENPTR_LIGHTGUN
Light gun.
DI8DEVTYPESCREENPTR_LIGHTPEN
Light pen.
DI8DEVTYPESCREENPTR_TOUCH
Touch screen.
DI8DEVTYPE_SUPPLEMENTAL
Specialized device with functionality unsuitable for the main control of an application, such as pedals used with a wheel. The following subtypes are defined.
DI8DEVTYPESUPPLEMENTAL_2NDHANDCONTROLLER
Secondary handheld controller.
DI8DEVTYPESUPPLEMENTAL_COMBINEDPEDALS
Device whose primary function is to report acceleration and brake pedal values from a single axis.
DI8DEVTYPESUPPLEMENTAL_DUALPEDALS
Device whose primary function is to report acceleration and brake pedal values from separate axes.
DI8DEVTYPESUPPLEMENTAL_HANDTRACKER
Device that tracks hand movement.
DI8DEVTYPESUPPLEMENTAL_HEADTRACKER
Device that tracks head movement.
DI8DEVTYPESUPPLEMENTAL_RUDDERPEDALS
Device with rudder pedals.
DI8DEVTYPESUPPLEMENTAL_SHIFTER
Device that reports gear selection from an axis.
DI8DEVTYPESUPPLEMENTAL_SHIFTSTICKGATE
Device that reports gear selection from button states.
DI8DEVTYPESUPPLEMENTAL_SPLITTHROTTLE
Device whose primary function is to report at least two throttle values. It may have other controls.
DI8DEVTYPESUPPLEMENTAL_THREEPEDALS
Device whose primary function is to report acceleration, brake, and clutch pedal values from separate axes.
DI8DEVTYPESUPPLEMENTAL_THROTTLE
Device whose primary function is to report a single throttle value. It may have other controls.
DI8DEVTYPESUPPLEMENTAL_UNKNOWN
Unknown subtype.

Versions of DirectInput earlier than Microsoft DirectX® 8.0 have a somewhat different scheme of device types and subtypes. See the DIDEVTYPExxx defines in Dinput.h.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIDEVICEOBJECTDATA

Contains buffered device information. This structure is used with the IDirectInputDevice8::GetDeviceData and the IDirectInputDevice8::SendDeviceData methods.

typedef struct DIDEVICEOBJECTDATA {
    DWORD    dwOfs;
    DWORD    dwData;
    DWORD    dwTimeStamp;
    DWORD    dwSequence;
    UINT_PTR uAppData;
} DIDEVICEOBJECTDATA, *LPDIDEVICEOBJECTDATA;

typedef const DIDEVICEOBJECTDATA *LPCDIDEVICEOBJECTDATA;

Members

dwOfs
For GetDeviceData, the offset into the current data format of the object whose data is being reported; that is, the location in which the dwData would have been stored if the data had been obtained by a call to the IDirectInputDevice8::GetDeviceState method. If the device is accessed as a mouse, keyboard, or joystick, the dwOfs member is one of the mouse device constants, keyboard device constants, or joystick device constants. If a custom data format has been set, it is an offset relative to the custom data format.

This member can be ignored if Action Mapping is being used. Instead, retrieve the action value from uAppData.

For SendDeviceData, the instance ID of the object to which the data is being sent, as obtained from the dwType member of a DIDEVICEOBJECTINSTANCE structure.

dwData
Data obtained from or sent to the device.

For axis input, if the device is in relative axis mode, the relative axis motion is reported. If the device is in absolute axis mode, the absolute axis coordinate is reported.

For button input, only the low byte of dwData is significant. The high bit of the low byte is set if the button was pressed; it is clear if the button was released.

dwTimeStamp
System time at which the input event was generated, in milliseconds. This value wraps around approximately every 50 days. See Remarks.

When the structure is used with the SendDeviceData method, this member must be 0.

dwSequence
Microsoft® DirectInput® sequence number for this event. All input events are assigned an increasing sequence number. This enables events from different devices to be sorted chronologically. Because this value can wrap around, care must be taken when comparing two sequence numbers. The DISEQUENCE_COMPARE macro can be used to perform this comparison safely.

When the structure is used with the SendDeviceData method, this member must be 0.

uAppData
Application-defined action value assigned to this object in the last call to IDirectInputDevice8::SetActionMap. This is the value in the uAppData member of the DIACTION structure associated with the object. Ignore this value if you are not using action mapping.

When the structure is used with the SendDeviceData method, this member must be zero.

Remarks

The system time returned in dwTimeStamp comes from the same clock used by the Microsoft® Win32® GetTickCount or timeGetTime functions, but it produces potentially more precise values. For example, on Microsoft® Windows® 95, the GetTickCount timer is updated only every 55 milliseconds, but the dwTimeStamp value is accurate to within 1 millisecond. Therefore, if you call GetTickCount and it returns n, and you then receive an event with a timestamp of n + n1, you cannot assume that the event took place exactly n1 milliseconds after the call to GetTickCount.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIDEVICEOBJECTINSTANCE

Describes a device object instance. This structure is used with the IDirectInputDevice8::EnumObjects method to provide the DIEnumDeviceObjectsCallback callback function with information about a particular object associated with a device, such as an axis or button. It is also used with the IDirectInputDevice8::GetObjectInfo method to retrieve information about a device object.

typedef struct DIDEVICEOBJECTINSTANCE {
    DWORD dwSize;
    GUID  guidType;
    DWORD dwOfs;
    DWORD dwType;
    DWORD dwFlags;
    TCHAR tszName[MAX_PATH];
    DWORD dwFFMaxForce;
    DWORD dwFFForceResolution;
    WORD  wCollectionNumber;
    WORD  wDesignatorIndex;
    WORD  wUsagePage;
    WORD  wUsage;
    DWORD dwDimension;
    WORD  wExponent;
    WORD  wReportId;
} DIDEVICEOBJECTINSTANCE, *LPDIDEVICEOBJECTINSTANCE;

typedef const DIDEVICEOBJECTINSTANCE *LPCDIDEVICEOBJECTINSTANCE;

Members

dwSize
Size of the structure, in bytes. During enumeration, the application can inspect this value to determine how many members of the structure are valid. When the structure is passed to the IDirectInputDevice8::GetObjectInfo method, this member must be initialized to sizeof(DIDEVICEOBJECTINSTANCE).
guidType
Unique identifier that indicates the object type. This member is optional. If present, it can be one of the following values:
GUID_XAxis
The horizontal axis. For example, it can represent the left-right motion of a mouse.
GUID_YAxis
The vertical axis. For example, it can represent the forward-backward motion of a mouse.
GUID_ZAxis
The z-axis. For example, it can represent the rotation of a mouse wheel or the movement of a joystick throttle control.
GUID_RxAxis
Rotation around the x-axis.
GUID_RyAxis
Rotation around the y-axis.
GUID_RzAxis
Rotation around the z-axis (often a rudder control).
GUID_Slider
A slider axis.
GUID_Button
A mouse button.
GUID_Key
A keyboard key.
GUID_POV
A point-of-view indicator.
GUID_Unknown
Unknown.

Other object types might be defined in the future.

dwOfs
Offset within the data format at which data is reported for this object. This value can be used to identify the object in method calls and structures that accept the DIPH_BYOFFSET flag. See Remarks.
dwType
Device type that describes the object. It is a combination of DIDFT_* flags that describe the object type (axis, button, and so on) and contains the object instance number in the middle 16 bits. Use the DIDFT_GETINSTANCE macro to extract the object instance number. For the DIDFT_* flags, see IDirectInputDevice8::EnumObjects.
dwFlags
Flags describing other attributes of the data format. This value can be one of the following:
DIDOI_ASPECTACCEL
The object reports acceleration information.
DIDOI_ASPECTFORCE
The object reports force information.
DIDOI_ASPECTMASK
The bits that are used to report aspect information. An object can represent at most one aspect.
DIDOI_ASPECTPOSITION
The object reports position information.
DIDOI_ASPECTVELOCITY
The object reports velocity information.
DIDOI_FFACTUATOR
The object can have force-feedback effects applied to it.
DIDOI_FFEFFECTTRIGGER
The object can trigger playback of force-feedback effects.
DIDOI_GUIDISUSAGE
The pguid member of the DIOBJECTDATAFORMAT structure contains the desired usage page and usage in a packed DWORD. See DIMAKEUSAGEDWORD.
DIDOI_POLLED
The object does not return data until the IDirectInputDevice8::Poll method is called.
tszName[MAX_PATH]
Name of the object; for example, "X-Axis" or "Right Shift."
dwFFMaxForce
The magnitude of the maximum force that can be created by the actuator associated with this object. Force is expressed in newtons and measured in relation to where the hand would be during normal operation of the device.
dwFFForceResolution
The force resolution of the actuator associated with this object. The returned value represents the number of gradations, or subdivisions, of the maximum force that can be expressed by the force-feedback system from 0 (no force) to maximum force.
wCollectionNumber
The Human Interface Device (HID) link collection to which the object belongs.
wDesignatorIndex
An index that refers to a designator in the HID physical descriptor. This number can be passed to functions in the HID parsing library (Hidpi.h) to obtain additional information about the device object.
wUsagePage
The Human Interface Device (HID) usage page associated with the object, if known. HIDs always report a usage page. Non-HID devices can optionally report a usage page; if they do not, the value of this member is 0.
wUsage
The HID usage associated with the object, if known. HIDs always report a usage. Non-HIDs can optionally report a usage; if they do not, the value of this member is 0.
dwDimension
A Human Interface Device (HID)code for the dimensional units in which the object's value is reported, if known, or 0 if not known.
wExponent
The exponent to associate with the dimension, if known. Dimensional units are always integral, so an exponent might be needed to convert them to nonintegral types.
wReportId
Reserved.

Remarks

If a data format has been set for the device, the value in dwOfs is the offset of the object's data within that format. If no format has been set, the value is the offset within the raw data returned by the device. Applications should not use this value unless a data format has been set.

Applications can use the wUsagePage and wUsage members to obtain additional information about how the object was designed to be used. For example, if wUsagePage has the value 0x02 (vehicle controls) and wUsage has the value 0xB9 (elevator trim), the object was designed to be the elevator trim control on a flight stick. A flight simulator application can use this information to provide more reasonable defaults for objects on the device. HID usage codes are determined by the USB standards committee.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIEFFECT

Used by the IDirectInputDevice8::CreateEffect method to initialize a new IDirectInputEffect object. It is also used by the IDirectInputEffect::SetParameters and IDirectInputEffect::GetParameters methods.

typedef struct DIEFFECT {
    DWORD   dwSize;
    DWORD   dwFlags;
    DWORD   dwDuration;
    DWORD   dwSamplePeriod;
    DWORD   dwGain;
    DWORD   dwTriggerButton;
    DWORD   dwTriggerRepeatInterval;
    DWORD   cAxes;
    LPDWORD rgdwAxes;
    LPLONG  rglDirection;
    LPDIENVELOPE lpEnvelope;
    DWORD   cbTypeSpecificParams;
    LPVOID  lpvTypeSpecificParams;
    DWORD   dwStartDelay;
} DIEFFECT, *LPDIEFFECT;

typedef const DIEFFECT *LPCDIEFFECT;

Members

dwSize
Specifies the size, in bytes, of the structure. This member must be initialized before the structure is used.
dwFlags
Flags associated with the effect. This value can be a combination of one or more of the following values:
DIEFF_CARTESIAN
The values of rglDirection are to be interpreted as Cartesian coordinates.
DIEFF_OBJECTIDS
The values of dwTriggerButton and rgdwAxes are object identifiers as obtained by IDirectInputDevice8::EnumObjects.
DIEFF_OBJECTOFFSETS
The values of dwTriggerButton and rgdwAxes are data format offsets.
DIEFF_POLAR
The values of rglDirection are to be interpreted as polar coordinates.
DIEFF_SPHERICAL
The values of rglDirection are to be interpreted as spherical coordinates.
dwDuration
The total duration of the effect, in microseconds. If this value is INFINITE, the effect has infinite duration. If an envelope has been applied to the effect, the attack is applied, followed by an infinite sustain.
dwSamplePeriod
The period at which the device should play back the effect, in microseconds. A value of 0 indicates that the default playback sample rate should be used.

If the device is not capable of playing back the effect at the specified rate, it chooses the supported rate that is closest to the requested value.

Setting a custom dwSamplePeriod can be used for special effects. For example, playing a sine wave at an artificially large sample period results in a rougher texture.

dwGain
The gain to be applied to the effect, in the range from 0 through 10,000. The gain is a scaling factor applied to all magnitudes of the effect and its envelope.
dwTriggerButton
The identifier or offset of the button to be used to trigger playback of the effect. The flags DIEFF_OBJECTIDS and DIEFF_OBJECTOFFSETS determine the semantics of the value. If this member is set to DIEB_NOTRIGGER, no trigger button is associated with the effect.
dwTriggerRepeatInterval
The interval, in microseconds, between the end of one playback and the start of the next when the effect is triggered by a button press and the button is held down. Setting this value to INFINITE suppresses repetition.

Support for trigger repeat for an effect is indicated by the presence of the DIEP_TRIGGERREPEATINTERVAL flag in the dwStaticParams member of the DIEFFECTINFO structure.

cAxes
Number of axes involved in the effect. This member must be filled in by the caller if changing or setting the axis list or the direction list.

The number of axes for an effect cannot be changed once it has been set.

rgdwAxes
Pointer to a DWORD array (of cAxes elements) containing identifiers or offsets identifying the axes to which the effect is to be applied. The flags DIEFF_OBJECTIDS and DIEFF_OBJECTOFFSETS determine the semantics of the values in the array.

The list of axes associated with an effect cannot be changed once it has been set.

No more than 32 axes can be associated with a single effect.

rglDirection
Pointer to a LONG array (of cAxes elements) containing either Cartesian coordinates, polar coordinates, or spherical coordinates. The flags DIEFF_CARTESIAN, DIEFF_POLAR, and DIEFF_SPHERICAL determine the semantics of the values in the array.

If Cartesian, each value in rglDirection is associated with the corresponding axis in rgdwAxes.

If polar, the angle is measured in hundredths of degrees from the (0, –1) direction, rotated in the direction of (1, 0). This usually means that north is away from the user, and east is to the user's right. The last element is not used.

If spherical, the first angle is measured in hundredths of a degree from the (1, 0) direction, rotated in the direction of (0, 1). The second angle (if the number of axes is three or more) is measured in hundredths of a degree toward (0, 0, 1). The third angle (if the number of axes is four or more) is measured in hundredths of a degree toward (0, 0, 0, 1), and so on. The last element is not used.

Note The rglDirection array must contain cAxes entries, even if polar or spherical coordinates are given. In these cases, the last element in the rglDirection array is reserved for future use and must be 0.

lpEnvelope
Optional pointer to a DIENVELOPE structure that describes the envelope to be used by this effect. Not all effect types use envelopes. If no envelope is to be applied, the member should be set to NULL.
cbTypeSpecificParams
Number of bytes of additional type-specific parameters for the corresponding effect type.
lpvTypeSpecificParams
Pointer to type-specific parameters, or NULL if there are no type-specific parameters.

If the effect is of type DIEFT_CONDITION, this member contains a pointer to an array of DICONDITION structures that define the parameters for the condition. A single structure may be used, in which case the condition is applied in the direction specified in the rglDirection array. Otherwise, there must be one structure for each axis, in the same order as the axes in rgdwAxes array. If a structure is supplied for each axis, the effect should not be rotated; you should use the following values in the rglDirection array:

  • DIEFF_SPHERICAL: 0, 0, ...
  • DIEFF_POLAR: 9000, 0, ...
  • DIEFF_CARTESIAN: 1, 0, ...

If the effect is of type DIEFT_CUSTOMFORCE, this member contains a pointer to a DICUSTOMFORCE structure that defines the parameters for the custom force.

If the effect is of type DIEFT_PERIODIC, this member contains a pointer to a DIPERIODIC structure that defines the parameters for the effect.

If the effect is of type DIEFT_CONSTANTFORCE, this member contains a pointer to a DICONSTANTFORCE structure that defines the parameters for the constant force.

If the effect is of type DIEFT_RAMPFORCE, this member contains a pointer to a DIRAMPFORCE structure that defines the parameters for the ramp force.

dwStartDelay
Time (in microseconds) that the device should wait after a IDirectInputEffect::Start call before playing the effect. If this value is 0, effect playback begins immediately. This member is not present in versions prior to Microsoft® DirectX® 7.0.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIEFFECTINFO

Used by the IDirectInputDevice8::EnumEffects and IDirectInputDevice8::GetEffectInfo methods to return information about a particular effect supported by a device.

typedef struct DIEFFECTINFO {
    DWORD dwSize;
    GUID  guid;
    DWORD dwEffType;
    DWORD dwStaticParams;
    DWORD dwDynamicParams;
    TCHAR tszName[MAX_PATH];
} DIEFFECTINFO, *LPDIEFFECTINFO;

typedef const DIEFFECTINFO  *LPCDIEFFECTINFO;

Members

dwSize
Size of the structure in bytes. During enumeration, the application can inspect this value to determine how many members of the structure are valid. This member must be initialized before the structure is passed to the IDirectInputDevice8::GetEffectInfo method.
guid
Identifier of the effect.
dwEffType
Zero or more of the following values:
DIEFT_ALL
Valid only for IDirectInputDevice8::EnumEffects . Enumerate all effects, regardless of type. This flag cannot be combined with any of the other flags.
DIEFT_CONDITION
The effect represents a condition. When creating or modifying a condition, the lpvTypeSpecificParams member of the DIEFFECT structure must point to an array of DICONDITION structures (one per axis), and the cbTypeSpecificParams member must be set to cAxis * sizeof(DICONDITION).

Not all devices support all the parameters of conditions. Check the effect capability flags to determine which capabilities are available.

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to conditions.

DIEFT_CONSTANTFORCE
The effect represents a constant-force effect. When creating or modifying a constant-force effect, the lpvTypeSpecificParams member of the DIEFFECT must point to a DICONSTANTFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DICONSTANTFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to constant-force effects.

DIEFT_CUSTOMFORCE
The effect represents a custom-force effect. When creating or modifying a custom-force effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DICUSTOMFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DICUSTOMFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to custom-force effects.

DIEFT_DEADBAND
The effect generator for this condition effect supports the lDeadBand parameter.
DIEFT_FFATTACK
The effect generator for this effect supports the attack envelope parameter. If the effect generator does not support attack, the attack level and attack time parameters of the DIENVELOPE structure are ignored by the effect.

If neither DIEFT_FFATTACK nor DIEFT_FFFADE is set, the effect does not support an envelope, and any provided envelope is ignored.

DIEFT_FFFADE
The effect generator for this effect supports the fade parameter. If the effect generator does not support fade, the fade level and fade time parameters of the DIENVELOPE structure are ignored by the effect.

If neither DIEFT_FFATTACK nor DIEFT_FFFADE is set, the effect does not support an envelope, and any provided envelope is ignored.

DIEFT_HARDWARE
The effect represents a hardware-specific effect. For additional information on using a hardware-specific effect, consult the hardware documentation.

The flag can be passed to the IDirectInputDevice8::EnumEffects method to restrict the enumeration to hardware-specific effects.

DIEFT_PERIODIC
The effect represents a periodic effect. When creating or modifying a periodic effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DIPERIODIC structure, and the cbTypeSpecificParams member must be set to sizeof(DIPERIODIC).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to periodic effects.

DIEFT_POSNEGCOEFFICIENTS
The effect generator for this effect supports two coefficient values for conditions, one for the positive displacement of the axis and one for the negative displacement of the axis. If the device does not support both coefficients, the negative coefficient in the DICONDITION structure is ignored, and the positive coefficient is used in both directions.
DIEFT_POSNEGSATURATION
The effect generator for this effect supports a maximum saturation for both positive and negative force output. If the device does not support both saturation values, the negative saturation in the DICONDITION structure is ignored, and the positive saturation is used in both directions.
DIEFT_RAMPFORCE
The effect represents a ramp-force effect. When creating or modifying a ramp-force effect, the lpvTypeSpecificParams member of the DIEFFECT structure must point to a DIRAMPFORCE structure, and the cbTypeSpecificParams member must be set to sizeof(DIRAMPFORCE).

The flag can be passed to IDirectInputDevice8::EnumEffects to restrict the enumeration to ramp-force effects.

DIEFT_SATURATION
The effect generator for this effect supports the saturation of condition effects. If the effect generator does not support saturation, the force generated by a condition is limited only by the maximum force that the device can generate.
DIEFT_STARTDELAY
The effect has a delay before it plays rather than beginning immediately. This can be used to offset effects so that they play in sequence.
dwStaticParams
Zero or more DIEP_* values describing the parameters supported by the effect. For example, if DIEP_ENVELOPE is set, the effect supports an envelope. For a list of possible values, see IDirectInputEffect::GetParameters.

It is not an error for an application to attempt to use effect parameters that are not supported by the device. The unsupported parameters are ignored.

This information is provided to enable the application to tailor its use of force feedback to the capabilities of the specific device.

dwDynamicParams
Zero or more DIEP_* values denoting parameters of the effect that can be modified while the effect is playing. For a list of possible values, see IDirectInputEffect::GetParameters.

If an application attempts to change a parameter while the effect is playing and the driver does not support modifying that effect dynamically, the driver is permitted to stop the effect, update the parameters, then restart it. For more information, see IDirectInputEffect::SetParameters.

tszName[MAX_PATH]
Name of the effect; for example, "Sawtooth up" or "Constant force".

Remarks

Use the DIEFT_GETTYPE macro to extract the effect type from the dwEffType flags.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIEFFESCAPE

Used by the IDirectInputDevice8::Escape and IDirectInputEffect::Escape methods to pass hardware-specific data directly to the device driver.

typedef struct DIEFFESCAPE {
    DWORD  dwSize;
    DWORD  dwCommand;
    LPVOID lpvInBuffer;
    DWORD  cbInBuffer;
    LPVOID lpvOutBuffer;
    DWORD  cbOutBuffer;
} DIEFFESCAPE, *LPDIEFFESCAPE;

Members

dwSize
Size of the structure in bytes. This member must be initialized before the structure is used.
dwCommand
Driver-specific command number. Consult the driver documentation for a list of valid commands.
lpvInBuffer
Buffer containing the data required to perform the operation.
cbInBuffer
Size, in bytes, of the lpvInBuffer buffer.
lpvOutBuffer
Buffer in which the operation's output data is returned.
cbOutBuffer
On entry, the size in bytes of the lpvOutBuffer buffer. On exit, the number of bytes actually produced by the command.

Remarks

Because each driver implements different escapes, it is the application's responsibility to ensure that it is talking to the correct driver by comparing the guidFFDriver member in the DIDEVICEINSTANCE structure against the value the application is expecting.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIENVELOPE

Used by the DIEFFECT structure to specify the optional envelope parameters for an effect. The sustain level for the envelope is represented by the dwMagnitude member of the DIPERIODIC structure and the lMagnitude member of the DICONSTANTFORCE structure. The sustain time is represented by dwDuration member of the DIEFFECT structure.

typedef struct DIENVELOPE {
    DWORD dwSize;
    DWORD dwAttackLevel;
    DWORD dwAttackTime;
    DWORD dwFadeLevel;
    DWORD dwFadeTime;
} DIENVELOPE, *LPDIENVELOPE;

typedef const DIENVELOPE *LPCDIENVELOPE;

Members

dwSize
Size, in bytes, of the structure. This member must be initialized before the structure is used.
dwAttackLevel
Amplitude for the start of the envelope, relative to the baseline, in the range from 0 through 10,000. If the effect's type-specific data does not specify a baseline, the amplitude is relative to 0.
dwAttackTime
The time, in microseconds, to reach the sustain level.
dwFadeLevel
Amplitude for the end of the envelope, relative to the baseline, in the range from 0 through 10,000. If the effect's type-specific data does not specify a baseline, the amplitude is relative to 0.
dwFadeTime
The time, in microseconds, to reach the fade level.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIFILEEFFECT

Describes data for a force-feedback effect stored in a file. It is used in conjunction with the IDirectInputDevice8::EnumEffectsInFile and IDirectInputDevice8::WriteEffectToFile methods.

typedef struct DIFILEEFFECT{
    DWORD       dwSize;
    GUID        GuidEffect;
    LPCDIEFFECT lpDiEffect;
    CHAR        szFriendlyName[MAX_PATH];
}DIFILEEFFECT, *LPDIFILEEFFECT;

Members

dwSize
Size, in bytes, of the structure. This member must be initialized before the structure is used.
GuidEffect
Unique identifier of the effect type. This can be one of the standard GUIDs defined in Dinput.h, such as GUID_ConstantForce, or one created by the designer.
lpDiEffect
Pointer to a DIEFFECT structure containing information about the effect.
szFriendlyName
Name of the effect.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIJOYSTATE

Describes the state of a joystick device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

typedef struct DIJOYSTATE {
    LONG    lX;
    LONG    lY;
    LONG    lZ;
    LONG    lRx;
    LONG    lRy;
    LONG    lRz;
    LONG    rglSlider[2];
    DWORD   rgdwPOV[4];
    BYTE    rgbButtons[32];
} DIJOYSTATE, *LPDIJOYSTATE;

Members

lX
X-axis, usually the left-right movement of a stick.
lY
Y-axis, usually the forward-backward movement of a stick.
lZ
Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0.
lRx
X-axis rotation. If the joystick does not have this axis, the value is 0.
lRy
Y-axis rotation. If the joystick does not have this axis, the value is 0.
lRz
Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0.
rglSlider[2]
Two additional axes, formerly called the u-axis and v-axis, whose semantics depend on the joystick. Use the IDirectInputDevice8::GetObjectInfo method to obtain semantic information about these values.
rgdwPOV[4]
Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as –1; but see Remarks. For indicators that have only five positions, the value for a controller is –1, 0, 9,000, 18,000, or 27,000.
rgbButtons[32]
Array of buttons. The high-order bit of the byte is set if the corresponding button is down, and clear if the button is up or does not exist.

Remarks

You must prepare the device for joystick-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIJoystick global data format variable.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

Note Under Microsoft® DirectX® 7, sliders on some joysticks could be assigned to the Z axis, with subsequent code retrieving data from that member. Using DirectX 8, those same sliders will be assigned to the rglSlider array. This should be taken into account when porting applications to DirectX 8. Make any necessary alterations to ensure that slider data is retrieved from the rglSlider array.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

DIJOYSTATE2


DIJOYSTATE2

Describes the state of a joystick device with extended capabilities. This structure is used with the IDirectInputDevice8::GetDeviceState method.

typedef struct DIJOYSTATE2 {
    LONG    lX;
    LONG    lY;
    LONG    lZ;
    LONG    lRx;
    LONG    lRy;
    LONG    lRz;
    LONG    rglSlider[2];
    DWORD   rgdwPOV[4];
    BYTE    rgbButtons[128];
    LONG    lVX;
    LONG    lVY;
    LONG    lVZ;
    LONG    lVRx;
    LONG    lVRy;
    LONG    lVRz;
    LONG    rglVSlider[2];
    LONG    lAX;
    LONG    lAY;
    LONG    lAZ;
    LONG    lARx;
    LONG    lARy;
    LONG    lARz;
    LONG    rglASlider[2];
    LONG    lFX;
    LONG    lFY;
    LONG    lFZ;
    LONG    lFRx;
    LONG    lFRy;
    LONG    lFRz;
    LONG    rglFSlider[2];
} DIJOYSTATE2, *LPDIJOYSTATE2;

Members

lX
X-axis, usually the left-right movement of a stick.
lY
Y-axis, usually the forward-backward movement of a stick.
lZ
Z-axis, often the throttle control. If the joystick does not have this axis, the value is 0.
lRx
X-axis rotation. If the joystick does not have this axis, the value is 0.
lRy
Y-axis rotation. If the joystick does not have this axis, the value is 0.
lRz
Z-axis rotation (often called the rudder). If the joystick does not have this axis, the value is 0.
rglSlider[2]
Two additional axis values (formerly called the u-axis and v-axis) whose semantics depend on the joystick. Use the IDirectInputDevice8::GetObjectInfo method to obtain semantic information about these values.
rgdwPOV[4]
Direction controllers, such as point-of-view hats. The position is indicated in hundredths of a degree clockwise from north (away from the user). The center position is normally reported as –1; but see Remarks. For indicators that have only five positions, the value for a controller is –1, 0, 9,000, 18,000, or 27,000.
rgbButtons[128]
Array of buttons. The high-order bit of the byte is set if the corresponding button is down, and clear if the button is up or does not exist.
lVX
X-axis velocity.
lVY
Y-axis velocity.
lVZ
Z-axis velocity.
lVRx
X-axis angular velocity.
lVRy
Y-axis angular velocity.
lVRz
Z-axis angular velocity.
rglVSlider[2]
Extra axis velocities.
lAX
X-axis acceleration.
lAY
Y-axis acceleration.
lAZ
Z-axis acceleration.
lARx
X-axis angular acceleration.
lARy
Y-axis angular acceleration.
lARz
Z-axis angular acceleration.
rglASlider[2]
Extra axis accelerations.
lFX
X-axis force.
lFY
Y-axis force.
lFZ
Z-axis force.
lFRx
X-axis torque.
lFRy
Y-axis torque.
lFRz
Z-axis torque.
rglFSlider[2]
Extra axis forces.

Remarks

You must prepare the device for access to a joystick with extended capabilities by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIJoystick2 global data format variable.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Some drivers report the centered position of the POV indicator as 65,535. Determine whether the indicator is centered as follows:

BOOL POVCentered = (LOWORD(dwPOV) == 0xFFFF);

Note Under Microsoft® DirectX® 7, sliders on some joysticks could be assigned to the Z axis, with subsequent code retrieving data from that member. Using DirectX 8, those same sliders will be assigned to the rglSlider array. This should be taken into account when porting applications to DirectX 8. Make any necessary alterations to ensure that slider data is retrieved from the rglSlider array.

Requirements

  Windows NT/2000: Requires Windows® 2000.

  Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.

  Header: Declared in Dinput.h.

See Also

DIJOYSTATE


DIMOUSESTATE

Describes the state of a mouse device that has up to four buttons, or another device that is being accessed as if it were a mouse device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

typedef struct DIMOUSESTATE {
    LONG lX;
    LONG lY;
    LONG lZ;
    BYTE rgbButtons[4];
} DIMOUSESTATE, *LPDIMOUSESTATE;

Members

lX
X-axis.
lY
Y-axis.
lZ
Z-axis, typically a wheel. If the mouse does not have a z-axis, the value is 0.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down.

Remarks

You must prepare the device for mouse-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIMouse global data format variable.

The mouse is a relative-axis device, so the absolute axis positions for mouse axes are simply accumulated relative motion. Therefore, the value of the absolute axis position is not meaningful except in comparison with other absolute axis positions.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

DIMOUSESTATE2


DIMOUSESTATE2

Describes the state of a mouse device that has up to eight buttons, or another device that is being accessed as if it were a mouse device. This structure is used with the IDirectInputDevice8::GetDeviceState method.

typedef struct DIMOUSESTATE {
    LONG lX;
    LONG lY;
    LONG lZ;
    BYTE rgbButtons[8];
} DIMOUSESTATE, *LPDIMOUSESTATE;

Members

lX
X-axis.
lY
Y-axis.
lZ
Z-axis, typically a wheel. If the mouse does not have a z-axis, the value is 0.
rgbButtons
Array of buttons. The high-order bit of the byte is set if the corresponding button is down.

Remarks

You must prepare the device for mouse-style access by calling the IDirectInputDevice8::SetDataFormat method, passing the c_dfDIMouse2 global data format variable.

The mouse is a relative-axis device, so the absolute axis positions for mouse axes are simply accumulated relative motion. Therefore, the value of the absolute axis position is not meaningful except in comparison with other absolute axis positions.

If an axis is in relative mode, the appropriate member contains the change in position. If it is in absolute mode, the member contains the absolute axis position.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

DIMOUSESTATE


DIOBJECTDATAFORMAT

Describes a device object's data format for use with the IDirectInputDevice8::SetDataFormat method.

typedef struct DIOBJECTDATAFORMAT {
    const GUID * pguid;
    DWORD        dwOfs;
    DWORD        dwType;
    DWORD        dwFlags;
} DIOBJECTDATAFORMAT, *LPDIOBJECTDATAFORMAT;

typedef const DIOBJECTDATAFORMAT *LPCDIOBJECTDATAFORMAT;

Members

pguid
Unique identifier for the axis, button, or other input source. When requesting a data format, making this member NULL indicates that any type of object is permissible.
dwOfs
Offset within the data packet where the data for the input source is stored. This value must be a multiple of 4 for DWORD size data, such as axes. It can be byte-aligned for buttons.
dwType
Device type that describes the object. It is a combination of the following flags describing the object type (axis, button, and so forth) and containing the object-instance number in the middle 16 bits. When requesting a data format, the instance portion must be set to DIDFT_ANYINSTANCE to indicate that any instance is permissible, or to DIDFT_MAKEINSTANCE(n) to restrict the request to instance n. See the examples under Remarks.
DIDFT_ABSAXIS
The object selected by the SetDataFormat method must be an absolute axis.
DIDFT_AXIS
The object selected by the SetDataFormat method must be an absolute or relative axis.
DIDFT_BUTTON
The object selected by the SetDataFormat method must be a push button or a toggle button.
DIDFT_FFACTUATOR
The object selected by the SetDataFormat method must contain a force-feedback actuator; in other words, it must be possible to apply forces to the object.
DIDFT_FFEFFECTTRIGGER
The object selected by the SetDataFormat method must be a valid force-feedback effect trigger.
DIDFT_POV
The object selected by the SetDataFormat method must be a point-of-view controller.
DIDFT_PSHBUTTON
The object selected by the SetDataFormat method must be a push button.
DIDFT_RELAXIS
The object selected by SetDataFormat must be a relative axis.
DIDFT_TGLBUTTON
The object selected by SetDataFormat must be a toggle button.
DIDFT_VENDORDEFINED
The object selected by SetDataFormat must be of a type defined by the manufacturer.
dwFlags
Zero or more of the following values:
DIDOI_ASPECTACCEL
The object selected by SetDataFormat must report acceleration information.
DIDOI_ASPECTFORCE
The object selected by SetDataFormat must report force information.
DIDOI_ASPECTPOSITION
The object selected by SetDataFormat must report position information.
DIDOI_ASPECTVELOCITY
The object selected by SetDataFormat must report velocity information.

Remarks

A data format is made up of several DIOBJECTDATAFORMAT structures, one for each object (axis, button, and so on). An array of these structures is contained in the DIDATAFORMAT structure that is passed to IDirectInputDevice8::SetDataFormat. An application typically does not need to create an array of DIOBJECTDATAFORMAT structures; rather, it can use one of the predefined data formats, c_dfDIMouse, c_dfDIMouse2, c_dfDIKeyboard, c_dfDIJoystick, or c_dfDIJoystick2, which have predefined settings for DIOBJECTDATAFORMAT.

The following object data format specifies that Microsoft® DirectInput® should choose the first available axis and report its value in the DWORD at offset 4 in the device data.

DIOBJECTDATAFORMAT dfAnyAxis = {
    0,                              // Wildcard
    4,                              // Offset
    DIDFT_AXIS | DIDFT_ANYINSTANCE, // Any axis is okay.
    0,                              // Ignore aspect
};

The following object data format specifies that the x-axis of the device should be stored in the DWORD at offset 12 in the device data. If the device has more than one x-axis, the first available one should be selected.

DIOBJECTDATAFORMAT dfAnyXAxis = {
    &GUID_XAxis,                    // Must be an X axis
    12,                             // Offset
    DIDFT_AXIS | DIDFT_ANYINSTANCE, // Any X axis is okay.
    0,                              // Ignore aspect
};

The following object data format specifies that DirectInput should choose the first available button and report its value in the high bit of the byte at offset 16 in the device data.

DIOBJECTDATAFORMAT dfAnyButton = {
    0,                                // Wildcard
    16,                               // Offset
    DIDFT_BUTTON | DIDFT_ANYINSTANCE, // Any button is okay.
    0,                                // Ignore aspect
};

The following object data format specifies that button 0 of the device should be reported as the high bit of the byte stored at offset 18 in the device data.

If the device does not have a button 0, the attempt to set this data format fails.

DIOBJECTDATAFORMAT dfButton0 = {
    0,                                    // Wildcard
    18,                                   // Offset
    DIDFT_BUTTON | DIDFT_MAKEINSTANCE(0), // Button zero
    0,                                    // Ignore aspect
};

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIPERIODIC

Contains type-specific information for effects that are marked as DIEFT_PERIODIC.

The structure describes a periodic effect.

A pointer to a single DIPERIODIC structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DIPERIODIC {
    DWORD dwMagnitude;
    LONG  lOffset;
    DWORD dwPhase;
    DWORD dwPeriod;
} DIPERIODIC, *LPDIPERIODIC;

typedef const DIPERIODIC *LPCDIPERIODIC;

Members

dwMagnitude
Magnitude of the effect, in the range from 0 through 10,000. If an envelope is applied to this effect, the value represents the magnitude of the sustain. If no envelope is applied, the value represents the amplitude of the entire effect.
lOffset
Offset of the effect. The range of forces generated by the effect is lOffset minus dwMagnitude to lOffset plus dwMagnitude. The value of the lOffset member is also the baseline for any envelope that is applied to the effect.
dwPhase
Position in the cycle of the periodic effect at which playback begins, in the range from 0 through 35,999. See Remarks.
dwPeriod
Period of the effect, in microseconds.

Remarks

A device driver cannot provide support for all values in the dwPhase member. In this case, the value is rounded off to the nearest supported value.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIPROPCPOINTS

Sets calibration points for the current instance.

typedef struct DIPROPCPOINTS {
    DIPROPHEADER diph;
    DWORD  dwCPointsNum;
    CPOINT cp[MAXCPOINTSNUM];
} DIPROPCPOINTS, *LPDIPROPCPOINTS;

typedef const DIPROPCPOINTS *LPCDIPROPCPOINTS;

Members

diph
DIPROPHEADER structure that must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPCPOINTS)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

This property can be applied only to individual device objects, so DIPH_DEVICE cannot be used.
dwHow | Specifies how the dwObj member should be interpreted. See the description of the dwObj member in this table for details.
dwCPointsNum
Number of stored calibration points. No more than 8 calibration points may be used.
cp[MAXCPOINTSNUM]
Array of calibration points.


DIPROPDWORD

Used to access DWORD properties.

typedef struct DIPROPDWORD {
    DIPROPHEADER diph;
    DWORD        dwData;
} DIPROPDWORD, *LPDIPROPDWORD;

typedef const DIPROPDWORD *LPCDIPROPDWORD;

Members

diph
DIPROPHEADER structure that must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPDWORD)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the description of the dwObj member in this table for details.

dwData
Property-specific value being set or retrieved.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::GetProperty, IDirectInputDevice8::SetProperty


DIPROPGUIDANDPATH

Used to access properties whose values represent a GUID and a path.

typedef struct DIPROPGUIDANDPATH {
    DIPROPHEADER diph;
    GUID         guidClass;
    WCHAR        wszPath[MAX_PATH];
} DIPROPGUIDANDPATH, *LPDIPROPGUIDANDPATH;

typedef const DIPROPGUIDANDPATH *LPCDIPROPGUIDANDPATH;

Members

diph
DIPROPHEADER structure that must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPGUIDANDPATH).
dwHeaderSize | sizeof(DIPROPHEADER).
dwObj | For this structure, this member must be set to 0.
dwHow | Specifies how the dwObj member should be interpreted. For this structure, dwHow should be DIPH_DEVICE.

guidClass
Class GUID for the object.
wszPath
Returned path for the object. This is a Unicode string.

Remarks

The DIPROP_GUIDANDPATH property associated with the DIPROPGUIDANDPATH structure enables advanced applications to perform operations on a Human Interface Device (HID) that are not supported by Microsoft® DirectInput®.

The application calls the IDirectInputDevice8::GetProperty method with DIPROP_GUIDANDPATH as the rguidProp parameter. The class GUID of the device is returned in the guidClass member of the DIPROPGUIDANDPATH structure, and the device interface path is returned in the wszPath member. The application can then call the CreateFile function on this path to access the device directly.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in Dinput.h.


DIPROPHEADER

Serves as a header for all property structures.

typedef struct DIPROPHEADER {
    DWORD    dwSize;
    DWORD    dwHeaderSize;
    DWORD    dwObj;
    DWORD    dwHow;
} DIPROPHEADER, *LPDIPROPHEADER;

typedef const DIPROPHEADER *LPCDIPROPHEADER;

Members

dwSize
Size of the enclosing structure. This member must be initialized before the structure is used.
dwHeaderSize
Size of the DIPROPHEADER structure.
dwObj
Object for which the property is to be accessed. The value set for this member depends on the value specified in the dwHow member.
dwHow
Value that specifies how the dwObj member should be interpreted. This value can be one of the following:
Value | Meaning
DIPH_DEVICE | The dwObj member must be 0.
DIPH_BYOFFSET | The dwObj member is the offset into the current data format of the object whose property is being accessed.
DIPH_BYUSAGE | The dwObj member is the HID usage page and usage values in packed form.
DIPH_BYID | The dwObj member is the object type/instance identifier. This identifier is returned in the dwType member of the DIDEVICEOBJECTINSTANCE structure returned from a previous call to the IDirectInputDevice8::EnumObjects member.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


DIPROPPOINTER

Used in setting and retrieving data values of type UINT_PTR. This is typically a value associated with an application-specific action associated with a device object in an action map, but can also be a function pointer.

typedef struct DIPROPPOINTER {
    DIPROPHEADER diph;
    UINT_PTR     uData;
} DIPROPPOINTER, *LPDIPROPPOINTER;

typedef const DIPROPPOINTER *LPCDIPROPPOINTER;

Members

diph
DIPROPHEADER structure that must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPPOINTER)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the description of the dwObj member in this table for details.
uData
Application-defined value of type UINT_PTR, which represents the uAppData value (from an action map) that is associated with a device control.


DIPROPRANGE

Contains information about the range of an object within a device. This structure is used with the DIPROP_RANGE flag set in the IDirectInputDevice8::GetProperty and IDirectInputDevice8::SetProperty methods.

typedef struct DIPROPRANGE {
    DIPROPHEADER diph;
    LONG         lMin;
    LONG         lMax;
} DIPROPRANGE, *LPDIPROPRANGE;

typedef const DIPROPRANGE *LPCDIPROPRANGE;

Members

diph
DIPROPHEADER structure that must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPRANGE)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.Identifier of the object whose property is being retrieved or set.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the description of the dwObj member in this table for details.

lMin
Lower limit of the range. If the range of the device is unrestricted, this value is DIPROPRANGE_NOMIN when the IDirectInputDevice8::GetProperty method returns.
lMax
Upper limit of the range. If the range of the device is unrestricted, this value is DIPROPRANGE_NOMAX when the IDirectInputDevice8::GetProperty method returns.

Remarks

The range values for devices whose ranges are unrestricted wraparound.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.

See Also

IDirectInputDevice8::GetProperty, IDirectInputDevice8::SetProperty


DIPROPSTRING

Gets and retrieves properties as strings.

typedef struct DIPROPSTRING {
    DIPROPHEADER diph;
    WCHAR        wsz[MAX_PATH];
} DIPROPSTRING, * LPDIPROPSTRING;;

typedef const DIPROPSTRING *LPCDIPROPSTRING;

Members

diph
DIPROPHEADER structure that must be initialized as follows:
Member | Value
dwSize | sizeof(DIPROPSTRING)
dwHeaderSize | sizeof(DIPROPHEADER)
dwObj If the dwHow member is DIPH_DEVICE, this member must be 0.

If the dwHow member is DIPH_BYID, this member must be the identifier for the object whose property setting is to be set or retrieved.

If the dwHow member is DIPH_BYOFFSET, this member must be a data format offset for the object whose property setting is to be set or retrieved. For example, if the c_dfDIMouse data format is selected, it must be one of the DIMOFS_* values.

If the dwHow member is DIPH_BYUSAGE, the device must be a Human Interface Device (HID). The device object will be identified by the HID usage page and usage values in packed form.

dwHow | Specifies how the dwObj member should be interpreted. See the description of the dwObj member in this table for details.

wsz
Unicode string that specifies or retrieves the property.

Remarks

The DIPROP_INSTANCENAME and DIPROP_PRODUCTNAME properties associated with the DIPROPSTRING structure enable advanced applications to perform operations on a Human Interface Device (HID) that are not supported by Microsoft® DirectInput®.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 98.
Header: Declared in Dinput.h.


DIRAMPFORCE

Contains type-specific information for effects that are marked as DIEFT_RAMPFORCE. The structure describes a ramp force effect.

A pointer to a single DIRAMPFORCE structure for an effect is passed in the lpvTypeSpecificParams member of the DIEFFECT structure.

typedef struct DIRAMPFORCE {
    LONG lStart;
    LONG lEnd;
} DIRAMPFORCE, *LPDIRAMPFORCE;

typedef const DIRAMPFORCE *LPCDIRAMPFORCE;

Members

lStart
Magnitude at the start of the effect, in the range from –10,000 through 10,000.
lEnd
Magnitude at the end of the effect, in the range from –10,000 through 10,000.

Remarks

The dwDuration for a ramp force effect cannot be INFINITE.

Requirements

Windows NT/2000: Requires Windows® 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dinput.h.


Device Constants

This section is a reference for constants used to interpret data for keys, buttons, and axes.

  • Keyboard Device Constants
  • DirectInput and Japanese Keyboards
  • Mouse Device Constants
  • Joystick Device Constants


Keyboard Device Constants

Keyboard device constants, defined in Dinput.h, represent offsets within a keyboard device's data packet, a 256-byte array. The data at a given offset is associated with a keyboard key. Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures, or as indices when accessing data within the array using array notation.

The standard keyboard device constants are listed in the following table.

Constant | Note
DIK_0 | On main keyboard
DIK_1 | On main keyboard
DIK_2 | On main keyboard
DIK_3 | On main keyboard
DIK_4 | On main keyboard
DIK_5 | On main keyboard
DIK_6 | On main keyboard
DIK_7 | On main keyboard
DIK_8 | On main keyboard
DIK_9 | On main keyboard
DIK_A |
DIK_ABNT_C1 | On numeric pad of Brazilian keyboards
DIK_ABNT_C2 | On numeric pad of Brazilian keyboards
DIK_ADD | PLUS SIGN (+) on numeric keypad
DIK_APOSTROPHE |
DIK_APPS | Application key
DIK_AT | On Japanese keyboard
DIK_AX | On Japanese keyboard
DIK_B |
DIK_BACK | BACKSPACE
DIK_BACKSLASH |
DIK_C |
DIK_CALCULATOR |
DIK_CAPITAL | CAPS LOCK
DIK_COLON | On Japanese keyboard
DIK_COMMA |
DIK_CONVERT | On Japanese keyboard
DIK_D |
DIK_DECIMAL | PERIOD (decimal point) on numeric keypad
DIK_DELETE |
DIK_DIVIDE | Forward slash (/) on numeric keypad
DIK_DOWN | DOWN ARROW
DIK_E |
DIK_END |
DIK_EQUALS | On main keyboard
DIK_ESCAPE |
DIK_F |
DIK_F1 |
DIK_F2 |
DIK_F3 |
DIK_F4 |
DIK_F5 |
DIK_F6 |
DIK_F7 |
DIK_F8 |
DIK_F9 |
DIK_F10 |
DIK_F11 |
DIK_F12 |
DIK_F13 | On NEC PC-98 Japanese keyboard
DIK_F14 | On NEC PC-98 Japanese keyboard
DIK_F15 | On NEC PC-98 Japanese keyboard
DIK_G |
DIK_GRAVE | Grave accent (`)
DIK_H |
DIK_HOME |
DIK_I |
DIK_INSERT |
DIK_J |
DIK_K |
DIK_KANA | On Japanese keyboard
DIK_KANJI | On Japanese keyboard
DIK_L |
DIK_LBRACKET | Left square bracket [
DIK_LCONTROL | Left CTRL
DIK_LEFT | LEFT ARROW
DIK_LMENU | Left ALT
DIK_LSHIFT | Left SHIFT
DIK_LWIN | Left Microsoft® Windows® logo key
DIK_M |
DIK_MAIL |
DIK_MEDIASELECT | Media Select key, which displays a selection of supported media players on the system
DIK_MEDIASTOP |
DIK_MINUS | On main keyboard
DIK_MULTIPLY | Asterisk (*) on numeric keypad
DIK_MUTE |
DIK_MYCOMPUTER |
DIK_N |
DIK_NEXT | PAGE DOWN
DIK_NEXTTRACK | Next track
DIK_NOCONVERT | On Japanese keyboard
DIK_NUMLOCK |
DIK_NUMPAD0 |
DIK_NUMPAD1 |
DIK_NUMPAD2 |
DIK_NUMPAD3 |
DIK_NUMPAD4 |
DIK_NUMPAD5 |
DIK_NUMPAD6 |
DIK_NUMPAD7 |
DIK_NUMPAD8 |
DIK_NUMPAD9 |
DIK_NUMPADCOMMA | On numeric keypad of NEC PC-98 Japanese keyboard
DIK_NUMPADENTER |
DIK_NUMPADEQUALS | On numeric keypad of NEC PC-98 Japanese keyboard
DIK_O |
DIK_OEM_102 | On British and German keyboards
DIK_P |
DIK_PAUSE |
DIK_PERIOD | On main keyboard
DIK_PLAYPAUSE |
DIK_POWER |
DIK_PREVTRACK | Previous track; circumflex on Japanese keyboard
DIK_PRIOR | PAGE UP
DIK_Q |
DIK_R |
DIK_RBRACKET | Right square bracket ]
DIK_RCONTROL | Right CTRL
DIK_RETURN | ENTER on main keyboard
DIK_RIGHT | RIGHT ARROW
DIK_RMENU | Right ALT
DIK_RSHIFT | Right SHIFT
DIK_RWIN | Right Windows logo key
DIK_S |
DIK_SCROLL | SCROLL LOCK
DIK_SEMICOLON |
DIK_SLASH | Forward slash (/) on main keyboard
DIK_SLEEP |
DIK_SPACE | SPACEBAR
DIK_STOP | On NEC PC-98 Japanese keyboard
DIK_SUBTRACT | MINUS SIGN (-) on numeric keypad
DIK_SYSRQ |
DIK_T |
DIK_TAB |
DIK_U |
DIK_UNDERLINE | On NEC PC-98 Japanese keyboard
DIK_UNLABELED | On Japanese keyboard
DIK_UP | UP ARROW
DIK_V |
DIK_VOLUMEDOWN |
DIK_VOLUMEUP |
DIK_W |
DIK_WAKE |
DIK_WEBBACK |
DIK_WEBFAVORITES | Displays the Microsoft Internet Explorer Favorites list, the Windows Favorites folder, or the Netscape Bookmarks list.
DIK_WEBFORWARD |
DIK_WEBHOME |
DIK_WEBREFRESH |
DIK_WEBSEARCH |
DIK_WEBSTOP |
DIK_X |
DIK_Y |
DIK_YEN | On Japanese keyboard
DIK_Z |

The following alternate names are available:

Alternate name | Regular name | Note
DIK_BACKSPACE | DIK_BACK | BACKSPACE
DIK_CAPSLOCK | DIK_CAPITAL | CAPS LOCK
DIK_CIRCUMFLEX | DIK_PREVTRACK | On Japanese keyboard
DIK_DOWNARROW | DIK_DOWN | On arrow keypad
DIK_LALT | DIK_LMENU | Left ALT
DIK_LEFTARROW | DIK_LEFT | On arrow keypad
DIK_NUMPADMINUS | DIK__SUBTRACT | MINUS SIGN (-) on numeric keypad
DIK_NUMPADPERIOD | DIK_DECIMAL | PERIOD (decimal point) on numeric keypad
DIK_NUMPADPLUS | DIK_ADD | PLUS SIGN (+) on numeric keypad
DIK_NUMPADSLASH | DIK__DIVIDE | Forward slash (/) on numeric keypad
DIK_NUMPADSTAR | DIK_MULTIPLY | Asterisk (*) on numeric keypad
DIK_PGDN | DIK_NEXT | On arrow keypad
DIK_PGUP | DIK_PRIOR | On arrow keypad
DIK_RALT | DIK_RMENU | Right ALT
DIK_RIGHTARROW | DIK_RIGHT | On arrow keypad
DIK_UPARROW | DIK_UP | On arrow keypad

For information on Japanese keyboards, see DirectInput and Japanese Keyboards.


DirectInput and Japanese Keyboards

The following chart lists keys that are available on Japanese keyboards but not on standard U.S. keyboards, as well as keys that are available on U.S. keyboards but not on the various Japanese keyboards.

On Microsoft® Windows® 2000 and with some keyboards (such as the NEC PC-98) using other operating systems, the DIK_CAPSLOCK, DIK_KANJI, and DIK_KANA keys are toggle buttons and not push buttons. These generate a down event when first pressed, then generate an up event when pressed a second time.

Japanese Keyboard | Additional keys | Missing keys
DOS/V 106, NEC PC-98 106 | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_CONVERT, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_APOSTROPHE, DIK_EQUALS, DIK_GRAVE
NEC PC-98 | DIK_AT, DIK_CIRCUMFLEX, DIK_COLON, DIK_F13, DIK_F14, DIK_F15, DIK_KANA, DIK_KANJI, DIK_NOCONVERT, DIK_NUMPADCOMMA, DIK_NUMPADEQUALS, DIK_STOP, DIK_UNDERLINE, DIK_YEN | DIK_APOSTROPHE, DIK_BACKSLASH, DIK_EQUALS, DIK_GRAVE, DIK_NUMLOCK, DIK_NUMPADENTER, DIK_RCONTROL, DIK_RMENU, DIK_RSHIFT, DIK_SCROLL
AX | DIK_AX, DIK_CONVERT, DIK_KANJI, DIK_NOCONVERT, DIK_YEN | DIK_RCONTROL, DIK_RMENU
J-3100 | DIK_KANA, DIK_KANJI, DIK_NOLABEL, DIK_YEN | DIK_RCONTROL, DIK_RMENU


Mouse Device Constants

Mouse device constants, defined in Dinput.h, represent offsets within a mouse device's data packet, the DIMOUSESTATE or DIMOUSESTATE2 structure. The data at a given offset is associated with a device object (button or axis). Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures.

The mouse device constants are the following:

Constant | Note
DIMOFS_BUTTON0 |
DIMOFS_BUTTON1 |
DIMOFS_BUTTON2 |
DIMOFS_BUTTON3 |
DIMOFS_BUTTON4 | DIMOUSESTATE2 only
DIMOFS_BUTTON5 | DIMOUSESTATE2 only
DIMOFS_BUTTON6 | DIMOUSESTATE2 only
DIMOFS_BUTTON7 | DIMOUSESTATE2 only
DIMOFS_X |
DIMOFS_Y |
DIMOFS_Z |


Joystick Device Constants

Joystick device constants represent offsets within a joystick device's data packet, the DIJOYSTATE structure. The data at a given offset is associated with a device object; that is, a button or axis. Typically, these values are used in the dwOfs member of the DIDEVICEOBJECTDATA, DIOBJECTDATAFORMAT or DIDEVICEOBJECTINSTANCE structures.

The following macros return a constant indicating the offset of the data for a particular button or axis relative to the beginning of the DIJOYSTATE structure.

Constant | Device object
DIJOFS_BUTTON0 to DIJOFS_BUTTON31 or DIJOFS_BUTTON(n) | Button
DIJOFS_POV(n) | Point-of-view indicator
DIJOFS_RX | X-axis rotation
DIJOFS_RY | Y-axis rotation
DIJOFS_RZ | Z-axis rotation (rudder)
DIJOFS_X | X-axis
DIJOFS_Y | Y-axis
DIJOFS_Z | Z-axis
DIJOFS_SLIDER(n) | Slider axis


Action Mapping Constants

This section is a reference to the constants defined in Dinput.h for application genres and controls mapped to actions within each genre.

The control constants, such as DIAXIS_FIGHTINGH_MOVE, are used in the dwSemantic member of the DIACTION structure to associate the control with an action in the application.

The constants for the genres, such as DIVIRTUAL_FIGHTING_HAND2HAND, are used in the dwGenre member of the DIACTIONFORMAT structure.

Action mapping constants are provided for application genres in the following categories.

  • Action Genres
  • Arcade Genres
  • CAD Genres
  • Control Genres
  • Driving Genres
  • Flight Genres
  • Sports Genres
  • Strategy Genres

The dwSemantic member of the DIACTION structure member can map the action to a particular device object rather than a virtual control. Device object constants are provided in the following categories.

  • Keyboard Mapping Constants
  • Mouse Mapping Constants
  • DirectPlay Voice Mapping Constants
  • Any-Control Constants


Action Genres

The following genres contain controls for fighting and action games.

  • Hand-to-Hand
  • Shooting
  • Third-Person Action


Hand-to-Hand

The DIVIRTUAL_FIGHTING_HAND2HAND genre contains controls for a first-person fighting game without guns.

Priority 1 Controls
DIAXIS_FIGHTINGH_LATERAL
DIAXIS_FIGHTINGH_MOVE
DIBUTTON_FIGHTINGH_BLOCK
DIBUTTON_FIGHTINGH_CROUCH
DIBUTTON_FIGHTINGH_JUMP
DIBUTTON_FIGHTINGH_KICK
DIBUTTON_FIGHTINGH_MENU
DIBUTTON_FIGHTINGH_PUNCH
DIBUTTON_FIGHTINGH_SPECIAL1
DIBUTTON_FIGHTINGH_SPECIAL2

Priority 2 Controls
DIAXIS_FIGHTINGH_ROTATE
DIBUTTON_FIGHTINGH_BACKWARD_LINK
DIBUTTON_FIGHTINGH_DEVICE
DIBUTTON_FIGHTINGH_DISPLAY
DIBUTTON_FIGHTINGH_DODGE
DIBUTTON_FIGHTINGH_FORWARD_LINK
DIBUTTON_FIGHTINGH_LEFT_LINK
DIBUTTON_FIGHTINGH_RIGHT_LINK
DIBUTTON_FIGHTINGH_PAUSE
DIBUTTON_FIGHTINGH_SELECT
DIHATSWITCH_FIGHTINGH_SLIDE


Shooting

The DIVIRTUAL_FIGHTING_FPS genre contains controls for a first-person fighting game with guns.

Priority 1 Controls
DIAXIS_FPS_LOOKUPDOWN
DIAXIS_FPS_MOVE
DIAXIS_FPS_ROTATE
DIBUTTON_FPS_APPLY
DIBUTTON_FPS_CROUCH
DIBUTTON_FPS_FIRE
DIBUTTON_FPS_JUMP
DIBUTTON_FPS_MENU
DIBUTTON_FPS_SELECT
DIBUTTON_FPS_STRAFE
DIBUTTON_FPS_WEAPONS

Priority 2 Controls
DIAXIS_FPS_SIDESTEP
DIBUTTON_FPS_BACKWARD_LINK
DIBUTTON_FPS_DEVICE
DIBUTTON_FPS_DISPLAY
DIBUTTON_FPS_DODGE
DIBUTTON_FPS_FIRESECONDARY
DIBUTTON_FPS_FORWARD_LINK
DIBUTTON_FPS_GLANCE_DOWN_LINK
DIBUTTON_FPS_GLANCE_UP_LINK
DIBUTTON_FPS_GLANCEL
DIBUTTON_FPS_GLANCER
DIBUTTON_FPS_PAUSE
DIBUTTON_FPS_ROTATE_LEFT_LINK
DIBUTTON_FPS_ROTATE_RIGHT_LINK
DIHATSWITCH_FPS_GLANCE


Third-Person Action

The DIVIRTUAL_FIGHTING_THIRDPERSON genre contains controls for a third-person action game.

Priority 1 Controls
DIAXIS_TPS_MOVE
DIAXIS_TPS_TURN
DIBUTTON_TPS_ACTION
DIBUTTON_TPS_JUMP
DIBUTTON_TPS_MENU
DIBUTTON_TPS_RUN
DIBUTTON_TPS_SELECT
DIBUTTON_TPS_USE

Priority 2 Controls
DIAXIS_TPS_STEP
DIBUTTON_TPS_BACKWARD_LINK
DIBUTTON_TPS_DEVICE
DIBUTTON_TPS_DODGE
DIBUTTON_TPS_FORWARD_LINK
DIBUTTON_TPS_GLANCE_DOWN_LINK
DIBUTTON_TPS_GLANCE_LEFT_LINK
DIBUTTON_TPS_GLANCE_RIGHT_LINK
DIBUTTON_TPS_GLANCE_UP_LINK
DIBUTTON_TPS_INVENTORY
DIBUTTON_TPS_PAUSE
DIBUTTON_TPS_STEPLEFT
DIBUTTON_TPS_STEPRIGHT
DIBUTTON_TPS_TURN_LEFT_LINK
DIBUTTON_TPS_TURN_RIGHT_LINK
DIBUTTON_TPS_VIEW
DIHATSWITCH_TPS_GLANCE


Arcade Genres

The following genres contain controls for arcade-type games in which the object is to move a figure through a dangerous environment.

  • Platform
  • Side-to-Side


Platform

The DIVIRTUAL_ARCADE_PLATFORM genre contains controls for an arcade-style game.

Priority 1 Controls
DIAXIS_ARCADEP_LATERAL
DIAXIS_ARCADEP_MOVE
DIBUTTON_ARCADEP_CROUCH
DIBUTTON_ARCADEP_FIRE
DIBUTTON_ARCADEP_JUMP
DIBUTTON_ARCADEP_MENU
DIBUTTON_ARCADEP_SELECT
DIBUTTON_ARCADEP_SPECIAL

Priority 2 Controls
DIBUTTON_ARCADEP_BACK_LINK
DIBUTTON_ARCADEP_DEVICE
DIBUTTON_ARCADEP_FIRESECONDARY
DIBUTTON_ARCADEP_FORWARD_LINK
DIBUTTON_ARCADEP_LEFT_LINK
DIBUTTON_ARCADEP_PAUSE
DIBUTTON_ARCADEP_RIGHT_LINK
DIBUTTON_ARCADEP_VIEW_DOWN_LINK
DIBUTTON_ARCADEP_VIEW_LEFT_LINK
DIBUTTON_ARCADEP_VIEW_RIGHT_LINK
DIBUTTON_ARCADEP_VIEW_UP_LINK
DIHATSWITCH_ARCADEP_VIEW


Side-to-Side

The DIVIRTUAL_ARCADE_SIDE2SIDE genre contains controls for a two-dimensional arcade-style game.

Priority 1 Controls
DIAXIS_ARCADES_LATERAL
DIAXIS_ARCADES_MOVE
DIBUTTON_ARCADES_ATTACK
DIBUTTON_ARCADES_CARRY
DIBUTTON_ARCADES_MENU
DIBUTTON_ARCADES_SELECT
DIBUTTON_ARCADES_SPECIAL
DIBUTTON_ARCADES_THROW

Priority 2 Controls
DIBUTTON_ARCADES_BACK_LINK
DIBUTTON_ARCADES_DEVICE
DIBUTTON_ARCADES_FORWARD_LINK
DIBUTTON_ARCADES_LEFT_LINK
DIBUTTON_ARCADES_PAUSE
DIBUTTON_ARCADES_RIGHT_LINK
DIBUTTON_ARCADES_VIEW_DOWN_LINK
DIBUTTON_ARCADES_VIEW_LEFT_LINK
DIBUTTON_ARCADES_VIEW_RIGHT_LINK
DIBUTTON_ARCADES_VIEW_UP_LINK
DIHATSWITCH_ARCADES_VIEW


CAD Genres

The following genres contain controls for computer-assisted drafting applications.

  • 2-D Object
  • 3-D Model
  • 3-D Navigation
  • 3-D Object


2-D Object

The DIVIRTUAL_CAD_2DCONTROL genre contains controls to select and move objects in a two-dimensional drafting environment.

Priority 1 Controls
DIAXIS_2DCONTROL_LATERAL
DIAXIS_2DCONTROL_MOVE
DIAXIS_2DCONTROL_INOUT
DIBUTTON_2DCONTROL_MENU
DIBUTTON_2DCONTROL_SELECT
DIBUTTON_2DCONTROL_SPECIAL
DIBUTTON_2DCONTROL_SPECIAL1
DIBUTTON_2DCONTROL_SPECIAL2

Priority 2 Controls
DIAXIS_2DCONTROL_ROTATEZ
DIBUTTON_2DCONTROL_DEVICE
DIBUTTON_2DCONTROL_DISPLAY
DIBUTTON_2DCONTROL_PAUSE
DIHATSWITCH_2DCONTROL_HATSWITCH


3-D Model

The DIVIRTUAL_CAD_MODEL genre contains controls for modeling three-dimensional objects.

Priority 1 Controls
DIAXIS_CADM_LATERAL
DIAXIS_CADM_MOVE
DIAXIS_CADM_INOUT
DIBUTTON_CADM_MENU
DIBUTTON_CADM_SELECT
DIBUTTON_CADM_SPECIAL
DIBUTTON_CADM_SPECIAL1
DIBUTTON_CADM_SPECIAL2

Priority 2 Controls
DIAXIS_CADM_ROTATEX
DIAXIS_CADM_ROTATEY
DIAXIS_CADM_ROTATEZ
DIBUTTON_CADM_DEVICE
DIBUTTON_CADM_DISPLAY
DIBUTTON_CADM_PAUSE
DIHATSWITCH_CADM_HATSWITCH


3-D Navigation

The DIVIRTUAL_CAD_FLYBY genre contains control for fly-through navigation of three-dimensional environments.

Priority 1 Controls
DIAXIS_CADF_LATERAL
DIAXIS_CADF_MOVE
DIAXIS_CADF_INOUT
DIBUTTON_CADF_MENU
DIBUTTON_CADF_SELECT
DIBUTTON_CADF_SPECIAL
DIBUTTON_CADF_SPECIAL1
DIBUTTON_CADF_SPECIAL2

Priority 2 Controls
DIAXIS_CADF_ROTATEX
DIAXIS_CADF_ROTATEY
DIAXIS_CADF_ROTATEZ
DIBUTTON_CADF_DEVICE
DIBUTTON_CADF_DISPLAY
DIBUTTON_CADF_PAUSE
DIHATSWITCH_CADF_HATSWITCH


3-D Object

The DIVIRTUAL_CAD_3DCONTROL genre contains controls to select and move objects in a three-dimensional drafting environment.

Priority 1 Controls
DIAXIS_3DCONTROL_LATERAL
DIAXIS_3DCONTROL_MOVE
DIAXIS_3DCONTROL_INOUT
DIBUTTON_3DCONTROL_MENU
DIBUTTON_3DCONTROL_SELECT
DIBUTTON_3DCONTROL_SPECIAL
DIBUTTON_3DCONTROL_SPECIAL1
DIBUTTON_3DCONTROL_SPECIAL2

Priority 2 Controls
DIAXIS_3DCONTROL_ROTATEX
DIAXIS_3DCONTROL_ROTATEY
DIAXIS_3DCONTROL_ROTATEZ
DIBUTTON_3DCONTROL_DEVICE
DIBUTTON_3DCONTROL_DISPLAY
DIBUTTON_3DCONTROL_PAUSE
DIHATSWITCH_3DCONTROL_HATSWITCH


Control Genres

The following genres contain controls for use with Web browsers and remote-control devices.

  • Browser
  • Remote Control


Browser

The DIVIRTUAL_BROWSER_CONTROL genre contains controls for a Web browser.

Priority 1 Controls
DIAXIS_BROWSER_LATERAL
DIAXIS_BROWSER_MOVE
DIAXIS_BROWSER_VIEW
DIBUTTON_BROWSER_MENU
DIBUTTON_BROWSER_REFRESH
DIBUTTON_BROWSER_SELECT

Priority 2 Controls
DIBUTTON_BROWSER_DEVICE
DIBUTTON_BROWSER_FAVORITES
DIBUTTON_BROWSER_HISTORY
DIBUTTON_BROWSER_HOME
DIBUTTON_BROWSER_NEXT
DIBUTTON_BROWSER_PAUSE
DIBUTTON_BROWSER_PREVIOUS
DIBUTTON_BROWSER_PRINT
DIBUTTON_BROWSER_SEARCH
DIBUTTON_BROWSER_STOP


Remote Control

The DIVIRTUAL_REMOTE_CONTROL genre contains controls for remote-control devices used with equipment such as media players.

Priority 1 Controls
DIAXIS_REMOTE_SLIDER
DIBUTTON_REMOTE_CHANGE
DIBUTTON_REMOTE_CUE
DIBUTTON_REMOTE_MENU
DIBUTTON_REMOTE_MUTE
DIBUTTON_REMOTE_PLAY
DIBUTTON_REMOTE_RECORD
DIBUTTON_REMOTE_REVIEW
DIBUTTON_REMOTE_SELECT

Priority 2 Controls
DIAXIS_REMOTE_SLIDER2
DIBUTTON_REMOTE_ADJUST
DIBUTTON_REMOTE_CABLE
DIBUTTON_REMOTE_CD
DIBUTTON_REMOTE_DEVICE
DIBUTTON_REMOTE_DIGIT0
DIBUTTON_REMOTE_DIGIT1
DIBUTTON_REMOTE_DIGIT2
DIBUTTON_REMOTE_DIGIT3
DIBUTTON_REMOTE_DIGIT4
DIBUTTON_REMOTE_DIGIT5
DIBUTTON_REMOTE_DIGIT6
DIBUTTON_REMOTE_DIGIT7
DIBUTTON_REMOTE_DIGIT8
DIBUTTON_REMOTE_DIGIT9
DIBUTTON_REMOTE_DVD
DIBUTTON_REMOTE_PAUSE
DIBUTTON_REMOTE_TUNER
DIBUTTON_REMOTE_TV
DIBUTTON_REMOTE_VCR


Driving Genres

The following genres are used in games where the players control vehicles in racing or combat.

  • Combat Racing
  • Mechanical Fighting
  • Racing
  • Tank


Combat Racing

The DIVIRTUAL_DRIVING_COMBAT genre contains controls for a vehicle race game with combat.

Priority 1 Controls
DIAXIS_DRIVINGC_ACCELERATE
DIAXIS_DRIVINGC_BRAKE
DIAXIS_DRIVINGC_STEER
DIBUTTON_DRIVINGC_FIRE
DIBUTTON_DRIVINGC_MENU
DIBUTTON_DRIVINGC_TARGET
DIBUTTON_DRIVINGC_WEAPONS

Priority 2 Controls
DIAXIS_DRIVINGC_ACCEL_AND_BRAKE
DIBUTTON_DRIVINGC_ACCELERATE_LINK
DIBUTTON_DRIVINGC_AIDS
DIBUTTON_DRIVINGC_BRAKE
DIBUTTON_DRIVINGC_DASHBOARD
DIBUTTON_DRIVINGC_DEVICE
DIBUTTON_DRIVINGC_FIRESECONDARY
DIBUTTON_DRIVINGC_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGC_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGC_PAUSE
DIBUTTON_DRIVINGC_SHIFTDOWN
DIBUTTON_DRIVINGC_SHIFTUP
DIBUTTON_DRIVINGC_STEER_LEFT_LINK
DIBUTTON_DRIVINGC_STEER_RIGHT_LINK
DIHATSWITCH_DRIVINGC_GLANCE


Mechanical Fighting

The DIVIRTUAL_DRIVING_MECHA genre contains controls for a walking vehicle in a mechanized-warfare game.

Priority 1 Controls
DIAXIS_MECHA_ROTATE
DIAXIS_MECHA_STEER
DIAXIS_MECHA_THROTTLE
DIAXIS_MECHA_TORSO
DIBUTTON_MECHA_FIRE
DIBUTTON_MECHA_JUMP
DIBUTTON_MECHA_MENU
DIBUTTON_MECHA_REVERSE
DIBUTTON_MECHA_TARGET
DIBUTTON_MECHA_WEAPONS
DIBUTTON_MECHA_ZOOM

Priority 2 Controls
DIBUTTON_MECHA_BACK_LINK
DIBUTTON_MECHA_CENTER
DIBUTTON_MECHA_DEVICE
DIBUTTON_MECHA_FASTER_LINK
DIBUTTON_MECHA_FIRESECONDARY
DIBUTTON_MECHA_FORWARD_LINK
DIBUTTON_MECHA_LEFT_LINK
DIBUTTON_MECHA_PAUSE
DIBUTTON_MECHA_RIGHT_LINK
DIBUTTON_MECHA_ROTATE_LEFT_LINK
DIBUTTON_MECHA_ROTATE_RIGHT_LINK
DIBUTTON_MECHA_SLOWER_LINK
DIBUTTON_MECHA_VIEW
DIHATSWITCH_MECHA_GLANCE


Racing

The DIVIRTUAL_DRIVING_RACE genre contains controls for an auto-racing game without combat.

Priority 1 Controls
DIAXIS_DRIVINGR_ACCELERATE
DIAXIS_DRIVINGR_BRAKE
DIAXIS_DRIVINGR_STEER
DIBUTTON_DRIVINGR_MENU
DIBUTTON_DRIVINGR_SHIFTDOWN
DIBUTTON_DRIVINGR_SHIFTUP
DIBUTTON_DRIVINGR_VIEW

Priority 2 Controls
DIAXIS_DRIVINGR_ACCEL_AND_BRAKE
DIBUTTON_DRIVINGR_ACCELERATE_LINK
DIBUTTON_DRIVINGR_AIDS
DIBUTTON_DRIVINGR_BOOST
DIBUTTON_DRIVINGR_BRAKE
DIBUTTON_DRIVINGR_DASHBOARD
DIBUTTON_DRIVINGR_DEVICE
DIBUTTON_DRIVINGR_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGR_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGR_MAP
DIBUTTON_DRIVINGR_PIT
DIBUTTON_DRIVINGR_PAUSE
DIBUTTON_DRIVINGR_STEER_LEFT_LINK
DIBUTTON_DRIVINGR_STEER_RIGHT_LINK
DIHATSWITCH_DRIVINGR_GLANCE


Tank

The DIVIRTUAL_DRIVING_TANK genre contains controls for a military tank simulation.

Priority 1 Controls
DIAXIS_DRIVINGT_ACCELERATE
DIAXIS_DRIVINGT_BARREL
DIAXIS_DRIVINGT_ROTATE
DIAXIS_DRIVINGT_STEER
DIBUTTON_DRIVINGT_FIRE
DIBUTTON_DRIVINGT_MENU
DIBUTTON_DRIVINGT_TARGET
DIBUTTON_DRIVINGT_WEAPONS

Priority 2 Controls
DIAXIS_DRIVINGT_ACCEL_AND_BRAKE
DIAXIS_DRIVINGT_BRAKE
DIBUTTON_DRIVINGT_ACCELERATE_LINK
DIBUTTON_DRIVINGT_BARREL_UP_LINK
DIBUTTON_DRIVINGT_BARREL_DOWN_LINK
DIBUTTON_DRIVINGT_BRAKE
DIBUTTON_DRIVINGT_DASHBOARD
DIBUTTON_DRIVINGT_DEVICE
DIBUTTON_DRIVINGT_FIRESECONDARY
DIBUTTON_DRIVINGT_GLANCE_LEFT_LINK
DIBUTTON_DRIVINGT_GLANCE_RIGHT_LINK
DIBUTTON_DRIVINGT_PAUSE
DIBUTTON_DRIVINGT_ROTATE_LEFT_LINK
DIBUTTON_DRIVINGT_ROTATE_RIGHT_LINK
DIBUTTON_DRIVINGT_STEER_LEFT_LINK
DIBUTTON_DRIVINGT_STEER_RIGHT_LINK
DIBUTTON_DRIVINGT_VIEW
DIHATSWITCH_DRIVINGT_GLANCE


Flight Genres

The following genres are used in games and simulations where the players control aircraft or spaceships.

  • Air Combat
  • Civilian Flight
  • Helicopter Combat
  • Space Combat


Air Combat

The DIVIRTUAL_FLYING_MILITARY genre contains controls for a fixed-wing aerial combat simulation.

Priority 1 Controls
DIAXIS_FLYINGM_BANK
DIAXIS_FLYINGM_PITCH
DIAXIS_FLYINGM_THROTTLE
DIBUTTON_FLYINGM_FIRE
DIBUTTON_FLYINGM_MENU
DIBUTTON_FLYINGM_TARGET
DIBUTTON_FLYINGM_WEAPONS

Priority 2 Controls
DIAXIS_FLYINGM_BRAKE
DIAXIS_FLYINGM_FLAPS
DIAXIS_FLYINGM_RUDDER
DIBUTTON_FLYINGM_BRAKE_LINK
DIBUTTON_FLYINGM_COUNTER
DIBUTTON_FLYINGM_DEVICE
DIBUTTON_FLYINGM_DISPLAY
DIBUTTON_FLYINGM_FASTER_LINK
DIBUTTON_FLYINGM_FIRESECONDARY
DIBUTTON_FLYINGM_FLAPSDOWN
DIBUTTON_FLYINGM_FLAPSUP
DIBUTTON_FLYINGM_GEAR
DIBUTTON_FLYINGM_GLANCE_DOWN_LINK
DIBUTTON_FLYINGM_GLANCE_LEFT_LINK
DIBUTTON_FLYINGM_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGM_GLANCE_UP_LINK
DIBUTTON_FLYINGM_PAUSE
DIBUTTON_FLYINGM_SLOWER_LINK
DIBUTTON_FLYINGM_VIEW
DIHATSWITCH_FLYINGM_GLANCE


Civilian Flight

The DIVIRTUAL_FLYING_CIVILIAN genre contains controls for noncombat flight simulations.

Priority 1 Controls
DIAXIS_FLYINGC_BANK
DIAXIS_FLYINGC_PITCH
DIAXIS_FLYINGC_THROTTLE
DIBUTTON_FLYINGC_DISPLAY
DIBUTTON_FLYINGC_GEAR
DIBUTTON_FLYINGC_MENU
DIBUTTON_FLYINGC_VIEW

Priority 2 Controls
DIAXIS_FLYINGC_BRAKE
DIAXIS_FLYINGC_FLAPS
DIAXIS_FLYINGC_RUDDER
DIBUTTON_FLYINGC_BRAKE_LINK
DIBUTTON_FLYINGC_DEVICE
DIBUTTON_FLYINGC_FASTER_LINK
DIBUTTON_FLYINGC_FLAPSDOWN
DIBUTTON_FLYINGC_FLAPSUP
DIBUTTON_FLYINGC_GLANCE_DOWN_LINK
DIBUTTON_FLYINGC_GLANCE_LEFT_LINK
DIBUTTON_FLYINGC_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGC_GLANCE_UP_LINK
DIBUTTON_FLYINGC_PAUSE
DIBUTTON_FLYINGC_SLOWER_LINK
DIHATSWITCH_FLYINGC_GLANCE


Helicopter Combat

The DIVIRTUAL_FLYING_HELICOPTER genre contains controls for a combat helicopter simulation.

Priority 1 Controls
DIAXIS_FLYINGH_BANK
DIAXIS_FLYINGH_COLLECTIVE
DIAXIS_FLYINGH_PITCH
DIBUTTON_FLYINGH_FIRE
DIBUTTON_FLYINGH_MENU
DIBUTTON_FLYINGH_TARGET
DIBUTTON_FLYINGH_WEAPONS

Priority 2 Controls
DIAXIS_FLYINGH_THROTTLE
DIAXIS_FLYINGH_TORQUE
DIBUTTON_FLYINGH_COUNTER
DIBUTTON_FLYINGH_DEVICE
DIBUTTON_FLYINGH_FASTER_LINK
DIBUTTON_FLYINGH_FIRESECONDARY
DIBUTTON_FLYINGH_GEAR
DIBUTTON_FLYINGH_GLANCE_DOWN_LINK
DIBUTTON_FLYINGH_GLANCE_LEFT_LINK
DIBUTTON_FLYINGH_GLANCE_RIGHT_LINK
DIBUTTON_FLYINGH_GLANCE_UP_LINK
DIBUTTON_FLYINGH_PAUSE
DIBUTTON_FLYINGH_SLOWER_LINK
DIBUTTON_FLYINGH_VIEW
DIHATSWITCH_FLYINGH_GLANCE


Space Combat

The DIVIRTUAL_SPACESIM genre contains controls for a spaceship combat simulation.

Priority 1 Controls
DIAXIS_SPACESIM_LATERAL
DIAXIS_SPACESIM_MOVE
DIAXIS_SPACESIM_THROTTLE
DIBUTTON_SPACESIM_FIRE
DIBUTTON_SPACESIM_MENU
DIBUTTON_SPACESIM_TARGET
DIBUTTON_SPACESIM_WEAPONS

Priority 2 Controls
DIAXIS_SPACESIM_CLIMB
DIAXIS_SPACESIM_ROTATE
DIBUTTON_SPACESIM_BACKWARD_LINK
DIBUTTON_SPACESIM_DEVICE
DIBUTTON_SPACESIM_DISPLAY
DIBUTTON_SPACESIM_FASTER_LINK
DIBUTTON_SPACESIM_FIRESECONDARY
DIBUTTON_SPACESIM_FORWARD_LINK
DIBUTTON_SPACESIM_GEAR
DIBUTTON_SPACESIM_GLANCE_DOWN_LINK
DIBUTTON_SPACESIM_GLANCE_LEFT_LINK
DIBUTTON_SPACESIM_GLANCE_RIGHT_LINK
DIBUTTON_SPACESIM_GLANCE_UP_LINK
DIBUTTON_SPACESIM_LEFT_LINK
DIBUTTON_SPACESIM_LOWER
DIBUTTON_SPACESIM_PAUSE
DIBUTTON_SPACESIM_RAISE
DIBUTTON_SPACESIM_RIGHT_LINK
DIBUTTON_SPACESIM_SLOWER_LINK
DIBUTTON_SPACESIM_TURN_LEFT_LINK
DIBUTTON_SPACESIM_TURN_RIGHT_LINK
DIBUTTON_SPACESIM_VIEW
DIHATSWITCH_SPACESIM_GLANCE


Sports Genres

The following genres contain controls for sports games and simulations.

  • Baseball Batting
  • Baseball Fielding
  • Baseball Pitching
  • Basketball Defense
  • Basketball Offense
  • Fishing
  • Football Defense
  • Football Offense
  • Football Play
  • Football Quarterback
  • Golf
  • Hockey Defense
  • Hockey Goalie
  • Hockey Offense
  • Hunting
  • Mountain Biking
  • Racquet
  • Skiing
  • Soccer Defense
  • Soccer Offense


Baseball Batting

The DIVIRTUAL_SPORTS_BASEBALL_BAT genre contains controls for a batter in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLB_LATERAL
DIAXIS_BASEBALLB_MOVE
DIBUTTON_BASEBALLB_BUNT
DIBUTTON_BASEBALLB_BURST
DIBUTTON_BASEBALLB_CONTACT
DIBUTTON_BASEBALLB_MENU
DIBUTTON_BASEBALLB_NORMAL
DIBUTTON_BASEBALLB_POWER
DIBUTTON_BASEBALLB_SELECT
DIBUTTON_BASEBALLB_SLIDE
DIBUTTON_BASEBALLB_STEAL

Priority 2 Controls
DIBUTTON_BASEBALLB_BOX
DIBUTTON_BASEBALLB_BACK_LINK
DIBUTTON_BASEBALLB_DEVICE
DIBUTTON_BASEBALLB_FORWARD_LINK
DIBUTTON_BASEBALLB_LEFT_LINK
DIBUTTON_BASEBALLB_NOSTEAL
DIBUTTON_BASEBALLB_PAUSE
DIBUTTON_BASEBALLB_RIGHT_LINK


Baseball Fielding

The DIVIRTUAL_SPORTS_BASEBALL_FIELD genre contains controls for fielders in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLF_LATERAL
DIAXIS_BASEBALLF_MOVE
DIBUTTON_BASEBALLF_BURST
DIBUTTON_BASEBALLF_DIVE
DIBUTTON_BASEBALLF_JUMP
DIBUTTON_BASEBALLF_MENU
DIBUTTON_BASEBALLF_NEAREST
DIBUTTON_BASEBALLF_THROW1
DIBUTTON_BASEBALLF_THROW2

Priority 2 Controls
DIBUTTON_BASEBALLF_AIM_LEFT_LINK
DIBUTTON_BASEBALLF_AIM_RIGHT_LINK
DIBUTTON_BASEBALLF_BACK_LINK
DIBUTTON_BASEBALLF_DEVICE
DIBUTTON_BASEBALLF_FORWARD_LINK
DIBUTTON_BASEBALLF_PAUSE
DIBUTTON_BASEBALLF_SHIFTIN
DIBUTTON_BASEBALLF_SHIFTOUT


Baseball Pitching

The DIVIRTUAL_SPORTS_BASEBALL_PITCH genre contains controls for a pitcher in a baseball game.

Priority 1 Controls
DIAXIS_BASEBALLP_LATERAL
DIAXIS_BASEBALLP_MOVE
DIBUTTON_BASEBALLP_BASE
DIBUTTON_BASEBALLP_FAKE
DIBUTTON_BASEBALLP_MENU
DIBUTTON_BASEBALLP_PITCH
DIBUTTON_BASEBALLP_SELECT
DIBUTTON_BASEBALLP_THROW

Priority 2 Controls
DIBUTTON_BASEBALLP_BACK_LINK
DIBUTTON_BASEBALLP_DEVICE
DIBUTTON_BASEBALLP_FORWARD_LINK
DIBUTTON_BASEBALLP_LEFT_LINK
DIBUTTON_BASEBALLP_LOOK
DIBUTTON_BASEBALLP_PAUSE
DIBUTTON_BASEBALLP_RIGHT_LINK
DIBUTTON_BASEBALLP_WALK


Basketball Defense

The DIVIRTUAL_SPORTS_BASKETBALL_DEFENSE genre contains controls for defensive moves in a basketball game.

Priority 1 Controls
DIAXIS_BBALLD_LATERAL
DIAXIS_BBALLD_MOVE
DIBUTTON_BBALLD_BURST
DIBUTTON_BBALLD_FAKE
DIBUTTON_BBALLD_JUMP
DIBUTTON_BBALLD_MENU
DIBUTTON_BBALLD_PLAY
DIBUTTON_BBALLD_PLAYER
DIBUTTON_BBALLD_SPECIAL
DIBUTTON_BBALLD_STEAL

Priority 2 Controls
DIBUTTON_BBALLD_BACK_LINK
DIBUTTON_BBALLD_DEVICE
DIBUTTON_BBALLD_FORWARD_LINK
DIBUTTON_BBALLD_LEFT_LINK
DIBUTTON_BBALLD_PAUSE
DIBUTTON_BBALLD_RIGHT_LINK
DIBUTTON_BBALLD_SUBSTITUTE
DIBUTTON_BBALLD_TIMEOUT
DIHATSWITCH_BBALLD_GLANCE


Basketball Offense

The DIVIRTUAL_SPORTS_BASKETBALL_OFFENSE genre contains controls for the player who has the ball in a basketball game.

Priority 1 Controls
DIAXIS_BBALLO_LATERAL
DIAXIS_BBALLO_MOVE
DIBUTTON_BBALLO_BURST
DIBUTTON_BBALLO_CALL
DIBUTTON_BBALLO_DUNK
DIBUTTON_BBALLO_FAKE
DIBUTTON_BBALLO_MENU
DIBUTTON_BBALLO_PASS
DIBUTTON_BBALLO_PLAYER
DIBUTTON_BBALLO_SHOOT
DIBUTTON_BBALLO_SPECIAL

Priority 2 Controls
DIBUTTON_BBALLO_BACK_LINK
DIBUTTON_BBALLO_DEVICE
DIBUTTON_BBALLO_FORWARD_LINK
DIBUTTON_BBALLO_JAB
DIBUTTON_BBALLO_LEFT_LINK
DIBUTTON_BBALLO_PAUSE
DIBUTTON_BBALLO_PLAY
DIBUTTON_BBALLO_POST
DIBUTTON_BBALLO_RIGHT_LINK
DIBUTTON_BBALLO_SCREEN
DIBUTTON_BBALLO_SUBSTITUTE
DIBUTTON_BBALLO_TIMEOUT
DIHATSWITCH_BBALLO_GLANCE


Fishing

The DIVIRTUAL_SPORTS_FISHING genre contains controls for a sport-fishing simulation.

Priority 1 Controls
DIAXIS_FISHING_LATERAL
DIAXIS_FISHING_MOVE
DIBUTTON_FISHING_BAIT
DIBUTTON_FISHING_BINOCULAR
DIBUTTON_FISHING_CAST
DIBUTTON_FISHING_MAP
DIBUTTON_FISHING_MENU
DIBUTTON_FISHING_TYPE

Priority 2 Controls
DIAXIS_FISHING_ROTATE
DIBUTTON_FISHING_BACK_LINK
DIBUTTON_FISHING_CROUCH
DIBUTTON_FISHING_DEVICE
DIBUTTON_FISHING_DISPLAY
DIBUTTON_FISHING_FORWARD_LINK
DIBUTTON_FISHING_JUMP
DIBUTTON_FISHING_LEFT_LINK
DIBUTTON_FISHING_PAUSE
DIBUTTON_FISHING_RIGHT_LINK
DIBUTTON_FISHING_ROTATE_LEFT_LINK
DIBUTTON_FISHING_ROTATE_RIGHT_LINK
DIHATSWITCH_FISHING_GLANCE


Football Defense

The DIVIRTUAL_SPORTS_FOOTBALL_DEFENSE genre contains controls for the defensive side in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLD_LATERAL
DIAXIS_FOOTBALLD_MOVE
DIBUTTON_FOOTBALLD_FAKE
DIBUTTON_FOOTBALLD_JUMP
DIBUTTON_FOOTBALLD_MENU
DIBUTTON_FOOTBALLD_PLAY
DIBUTTON_FOOTBALLD_SELECT
DIBUTTON_FOOTBALLD_SUPERTACKLE
DIBUTTON_FOOTBALLD_TACKLE

Priority 2 Controls
DIBUTTON_FOOTBALLD_AUDIBLE
DIBUTTON_FOOTBALLD_BACK_LINK
DIBUTTON_FOOTBALLD_BULLRUSH
DIBUTTON_FOOTBALLD_DEVICE
DIBUTTON_FOOTBALLD_FORWARD_LINK
DIBUTTON_FOOTBALLD_LEFT_LINK
DIBUTTON_FOOTBALLD_PAUSE
DIBUTTON_FOOTBALLD_RIGHT_LINK
DIBUTTON_FOOTBALLD_RIP
DIBUTTON_FOOTBALLD_SPIN
DIBUTTON_FOOTBALLD_SUBSTITUTE
DIBUTTON_FOOTBALLD_SWIM
DIBUTTON_FOOTBALLD_ZOOM


Football Offense

The DIVIRTUAL_SPORTS_FOOTBALL_OFFENSE genre contains controls for the ball carrier in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLO_LATERAL
DIAXIS_FOOTBALLO_MOVE
DIBUTTON_FOOTBALLO_JUMP
DIBUTTON_FOOTBALLO_LEFTARM
DIBUTTON_FOOTBALLO_MENU
DIBUTTON_FOOTBALLO_RIGHTARM
DIBUTTON_FOOTBALLO_SPIN
DIBUTTON_FOOTBALLO_THROW

Priority 2 Controls
DIBUTTON_FOOTBALLO_BACK_LINK
DIBUTTON_FOOTBALLO_DEVICE
DIBUTTON_FOOTBALLO_DIVE
DIBUTTON_FOOTBALLO_FORWARD_LINK
DIBUTTON_FOOTBALLO_JUKE
DIBUTTON_FOOTBALLO_LEFT_LINK
DIBUTTON_FOOTBALLO_PAUSE
DIBUTTON_FOOTBALLO_RIGHT_LINK
DIBUTTON_FOOTBALLO_SHOULDER
DIBUTTON_FOOTBALLO_SUBSTITUTE
DIBUTTON_FOOTBALLO_TURBO
DIBUTTON_FOOTBALLO_ZOOM


Football Play

The DIVIRTUAL_SPORTS_FOOTBALL_FIELD genre contains general controls for a North American football game.

Priority 1 Controls
DIBUTTON_FOOTBALLP_HELP
DIBUTTON_FOOTBALLP_MENU
DIBUTTON_FOOTBALLP_PLAY
DIBUTTON_FOOTBALLP_SELECT

Priority 2 Controls
DIBUTTON_FOOTBALLP_DEVICE
DIBUTTON_FOOTBALLP_PAUSE


Football Quarterback

The DIVIRTUAL_SPORTS_FOOTBALL_QBCK genre contains controls for the quarterback in a North American football game.

Priority 1 Controls
DIAXIS_FOOTBALLQ_LATERAL
DIAXIS_FOOTBALLQ_MOVE
DIBUTTON_FOOTBALLQ_FAKE
DIBUTTON_FOOTBALLQ_JUMP
DIBUTTON_FOOTBALLQ_MENU
DIBUTTON_FOOTBALLQ_PASS
DIBUTTON_FOOTBALLQ_SELECT
DIBUTTON_FOOTBALLQ_SLIDE
DIBUTTON_FOOTBALLQ_SNAP

Priority 2 Controls
DIBUTTON_FOOTBALLQ_AUDIBLE
DIBUTTON_FOOTBALLQ_BACK_LINK
DIBUTTON_FOOTBALLQ_DEVICE
DIBUTTON_FOOTBALLQ_FAKESNAP
DIBUTTON_FOOTBALLQ_FORWARD_LINK
DIBUTTON_FOOTBALLQ_LEFT_LINK
DIBUTTON_FOOTBALLQ_MOTION
DIBUTTON_FOOTBALLQ_PAUSE
DIBUTTON_FOOTBALLQ_RIGHT_LINK


Golf

The DIVIRTUAL_SPORTS_GOLF genre contains controls for a golf game.

Priority 1 Controls
DIAXIS_GOLF_LATERAL
DIAXIS_GOLF_MOVE
DIBUTTON_GOLF_DOWN
DIBUTTON_GOLF_FLYBY
DIBUTTON_GOLF_MENU
DIBUTTON_GOLF_SELECT
DIBUTTON_GOLF_SWING
DIBUTTON_GOLF_TERRAIN
DIBUTTON_GOLF_UP

Priority 2 Controls
DIBUTTON_GOLF_BACK_LINK
DIBUTTON_GOLF_DEVICE
DIBUTTON_GOLF_FORWARD_LINK
DIBUTTON_GOLF_LEFT_LINK
DIBUTTON_GOLF_PAUSE
DIBUTTON_GOLF_RIGHT_LINK
DIBUTTON_GOLF_SUBSTITUTE
DIBUTTON_GOLF_TIMEOUT
DIBUTTON_GOLF_ZOOM
DIHATSWITCH_GOLF_SCROLL


Hockey Defense

The DIVIRTUAL_SPORTS_HOCKEY_DEFENSE genre contains controls for defensive moves in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYD_LATERAL
DIAXIS_HOCKEYD_MOVE
DIBUTTON_HOCKEYD_BLOCK
DIBUTTON_HOCKEYD_BURST
DIBUTTON_HOCKEYD_FAKE
DIBUTTON_HOCKEYD_MENU
DIBUTTON_HOCKEYD_PLAYER
DIBUTTON_HOCKEYD_STEAL

Priority 2 Controls
DIBUTTON_HOCKEYD_BACK_LINK
DIBUTTON_HOCKEYD_DEVICE
DIBUTTON_HOCKEYO_FORWARD_LINK
DIBUTTON_HOCKEYO_LEFT_LINK
DIBUTTON_HOCKEYD_PAUSE
DIBUTTON_HOCKEYO_RIGHT_LINK
DIBUTTON_HOCKEYD_STRATEGY
DIBUTTON_HOCKEYD_SUBSTITUTE
DIBUTTON_HOCKEYD_TIMEOUT
DIBUTTON_HOCKEYD_ZOOM
DIHATSWITCH_HOCKEYD_SCROLL


Hockey Goalie

The DIVIRTUAL_SPORTS_HOCKEY_GOALIE genre contains controls for a goalkeeper in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYG_LATERAL
DIAXIS_HOCKEYG_MOVE
DIBUTTON_HOCKEYG_BLOCK
DIBUTTON_HOCKEYG_MENU
DIBUTTON_HOCKEYG_PASS
DIBUTTON_HOCKEYG_POKE
DIBUTTON_HOCKEYG_STEAL

Priority 2 Controls
DIBUTTON_HOCKEYG_BACK_LINK
DIBUTTON_HOCKEYG_DEVICE
DIBUTTON_HOCKEYG_FORWARD_LINK
DIBUTTON_HOCKEYG_LEFT_LINK
DIBUTTON_HOCKEYG_PAUSE
DIBUTTON_HOCKEYG_RIGHT_LINK
DIBUTTON_HOCKEYG_STRATEGY
DIBUTTON_HOCKEYG_SUBSTITUTE
DIBUTTON_HOCKEYG_TIMEOUT
DIBUTTON_HOCKEYG_ZOOM
DIHATSWITCH_HOCKEYG_SCROLL


Hockey Offense

The DIVIRTUAL_SPORTS_HOCKEY_OFFENSE genre contains controls for offensive moves in a hockey game.

Priority 1 Controls
DIAXIS_HOCKEYO_LATERAL
DIAXIS_HOCKEYO_MOVE
DIBUTTON_HOCKEYO_BURST
DIBUTTON_HOCKEYO_FAKE
DIBUTTON_HOCKEYO_MENU
DIBUTTON_HOCKEYO_PASS
DIBUTTON_HOCKEYO_SHOOT
DIBUTTON_HOCKEYO_SPECIAL

Priority 2 Controls
DIBUTTON_HOCKEYO_BACK_LINK
DIBUTTON_HOCKEYO_DEVICE
DIBUTTON_HOCKEYO_FORWARD_LINK
DIBUTTON_HOCKEYO_LEFT_LINK
DIBUTTON_HOCKEYO_PAUSE
DIBUTTON_HOCKEYO_RIGHT_LINK
DIBUTTON_HOCKEYO_STRATEGY
DIBUTTON_HOCKEYO_SUBSTITUTE
DIBUTTON_HOCKEYO_TIMEOUT
DIBUTTON_HOCKEYO_ZOOM
DIHATSWITCH_HOCKEYO_SCROLL


Hunting

The DIVIRTUAL_SPORTS_HUNTING genre contains controls for a hunting simulation.

Priority 1 Controls
DIAXIS_HUNTING_LATERAL
DIAXIS_HUNTING_MOVE
DIBUTTON_HUNTING_AIM
DIBUTTON_HUNTING_BINOCULAR
DIBUTTON_HUNTING_CALL
DIBUTTON_HUNTING_FIRE
DIBUTTON_HUNTING_MAP
DIBUTTON_HUNTING_MENU
DIBUTTON_HUNTING_SPECIAL
DIBUTTON_HUNTING_WEAPON

Priority 2 Controls
DIAXIS_HUNTING_ROTATE
DIBUTTON_HUNTING_BACK_LINK
DIBUTTON_HUNTING_CROUCH
DIBUTTON_HUNTING_DEVICE
DIBUTTON_HUNTING_DISPLAY
DIBUTTON_HUNTING_FIRESECONDARY
DIBUTTON_HUNTING_FORWARD_LINK
DIBUTTON_HUNTING_JUMP
DIBUTTON_HUNTING_LEFT_LINK
DIBUTTON_HUNTING_PAUSE
DIBUTTON_HUNTING_RIGHT_LINK
DIBUTTON_HUNTING_ROTATE_LEFT_LINK
DIBUTTON_HUNTING_ROTATE_RIGHT_LINK
DIHATSWITCH_HUNTING_GLANCE


Mountain Biking

The DIVIRTUAL_SPORTS_BIKING_MOUNTAIN contains controls for a mountain-bike game.

Priority 1 Controls
DIAXIS_BIKINGM_PEDAL
DIAXIS_BIKINGM_TURN
DIBUTTON_BIKINGM_CAMERA
DIBUTTON_BIKINGM_JUMP
DIBUTTON_BIKINGM_MENU
DIBUTTON_BIKINGM_SELECT
DIBUTTON_BIKINGM_SPECIAL1
DIBUTTON_BIKINGM_SPECIAL2

Priority 2 Controls
DIAXIS_BIKINGM_BRAKE
DIBUTTON_BIKINGM_BRAKE_BUTTON_LINK
DIBUTTON_BIKINGM_DEVICE
DIBUTTON_BIKINGM_FASTER_LINK
DIBUTTON_BIKINGM_LEFT_LINK
DIBUTTON_BIKINGM_PAUSE
DIBUTTON_BIKINGM_RIGHT_LINK
DIBUTTON_BIKINGM_SLOWER_LINK
DIBUTTON_BIKINGM_ZOOM
DIHATSWITCH_BIKINGM_SCROLL


Racquet

The DIVIRTUAL_SPORTS_RACQUET genre includes racquet games such as tennis, table tennis, and squash.

Priority 1 Controls
DIAXIS_RACQUET_LATERAL
DIAXIS_RACQUET_MOVE
DIBUTTON_RACQUET_BACKSWING
DIBUTTON_RACQUET_MENU
DIBUTTON_RACQUET_SELECT
DIBUTTON_RACQUET_SMASH
DIBUTTON_RACQUET_SPECIAL
DIBUTTON_RACQUET_SWING

Priority 2 Controls
DIBUTTON_RACQUET_BACK_LINK
DIBUTTON_RACQUET_DEVICE
DIBUTTON_RACQUET_FORWARD_LINK
DIBUTTON_RACQUET_LEFT_LINK
DIBUTTON_RACQUET_PAUSE
DIBUTTON_RACQUET_RIGHT_LINK
DIBUTTON_RACQUET_SUBSTITUTE
DIBUTTON_RACQUET_TIMEOUT
DIHATSWITCH_RACQUET_GLANCE


Skiing

The DIVIRTUAL_SPORTS_SKIING contains controls for skiing games as well as for similar sports simulations such as snowboarding and skateboarding.

Priority 1 Controls
DIAXIS_SKIING_SPEED
DIAXIS_SKIING_TURN
DIBUTTON_SKIING_CAMERA
DIBUTTON_SKIING_CROUCH
DIBUTTON_SKIING_JUMP
DIBUTTON_SKIING_MENU
DIBUTTON_SKIING_SELECT
DIBUTTON_SKIING_SPECIAL1
DIBUTTON_SKIING_SPECIAL2

Priority 2 Controls
DIBUTTON_SKIING_DEVICE
DIBUTTON_SKIING_FASTER_LINK
DIBUTTON_SKIING_LEFT_LINK
DIBUTTON_SKIING_PAUSE
DIBUTTON_SKIING_RIGHT_LINK
DIBUTTON_SKIING_SLOWER_LINK
DIBUTTON_SKIING_ZOOM
DIHATSWITCH_SKIING_GLANCE


Soccer Defense

The DIVIRTUAL_SPORTS_SOCCER_DEFENSE contains controls for defensive moves in a soccer (international football) game.

Priority 1 Controls
DIAXIS_SOCCERD_LATERAL
DIAXIS_SOCCERD_MOVE
DIBUTTON_SOCCERD_BLOCK
DIBUTTON_SOCCERD_FAKE
DIBUTTON_SOCCERD_MENU
DIBUTTON_SOCCERD_PLAYER
DIBUTTON_SOCCERD_SELECT
DIBUTTON_SOCCERD_SLIDE
DIBUTTON_SOCCERD_SPECIAL
DIBUTTON_SOCCERD_STEAL

Priority 2 Controls
DIBUTTON_SOCCERD_BACK_LINK
DIBUTTON_SOCCERD_CLEAR
DIBUTTON_SOCCERD_DEVICE
DIBUTTON_SOCCERD_FORWARD_LINK
DIBUTTON_SOCCERD_FOUL
DIBUTTON_SOCCERD_GOALIECHARGE
DIBUTTON_SOCCERD_HEAD
DIBUTTON_SOCCERD_LEFT_LINK
DIBUTTON_SOCCERD_PAUSE
DIBUTTON_SOCCERD_RIGHT_LINK
DIBUTTON_SOCCERD_SUBSTITUTE
DIHATSWITCH_SOCCERD_GLANCE


Soccer Offense

The DIVIRTUAL_SPORTS_SOCCER_OFFENSE contains controls for offensive moves in a soccer (international football) game.

Priority 1 Controls
DIAXIS_SOCCERO_BEND
DIAXIS_SOCCERO_LATERAL
DIAXIS_SOCCERO_MOVE
DIBUTTON_SOCCERO_FAKE
DIBUTTON_SOCCERO_MENU
DIBUTTON_SOCCERO_PASS
DIBUTTON_SOCCERO_PLAYER
DIBUTTON_SOCCERO_SELECT
DIBUTTON_SOCCERO_SHOOT
DIBUTTON_SOCCERO_SPECIAL1

Priority 2 Controls
DIBUTTON_SOCCERO_BACK_LINK
DIBUTTON_SOCCERO_CONTROL
DIBUTTON_SOCCERO_DEVICE
DIBUTTON_SOCCERO_FORWARD_LINK
DIBUTTON_SOCCERO_HEAD
DIBUTTON_SOCCERO_LEFT_LINK
DIBUTTON_SOCCERO_PASSTHRU
DIBUTTON_SOCCERO_PAUSE
DIBUTTON_SOCCERO_RIGHT_LINK
DIBUTTON_SOCCERO_SHOOTHIGH
DIBUTTON_SOCCERO_SHOOTLOW
DIBUTTON_SOCCERO_SPRINT
DIBUTTON_SOCCERO_SUBSTITUTE
DIHATSWITCH_SOCCERO_GLANCE


Strategy Genres

The following genres contain controls for strategy, role-playing, and adventure games.

  • Role-Playing
  • Turn-Based


Role-Playing

The DIVIRTUAL_STRATEGY_ROLEPLAYING genre contains controls for a role-playing or adventure game in which navigation, problem-solving, and fighting with weapons and magic are common activities.

Priority 1 Controls
DIAXIS_STRATEGYR_LATERAL
DIAXIS_STRATEGYR_MOVE
DIBUTTON_STRATEGYR_APPLY
DIBUTTON_STRATEGYR_ATTACK
DIBUTTON_STRATEGYR_CAST
DIBUTTON_STRATEGYR_CROUCH
DIBUTTON_STRATEGYR_GET
DIBUTTON_STRATEGYR_JUMP
DIBUTTON_STRATEGYR_MENU
DIBUTTON_STRATEGYR_SELECT

Priority 2 Controls
DIAXIS_STRATEGYR_ROTATE
DIBUTTON_STRATEGYR_BACK_LINK
DIBUTTON_STRATEGYR_DEVICE
DIBUTTON_STRATEGYR_DISPLAY
DIBUTTON_STRATEGYR_FORWARD_LINK
DIBUTTON_STRATEGYR_LEFT_LINK
DIBUTTON_STRATEGYR_MAP
DIBUTTON_STRATEGYR_PAUSE
DIBUTTON_STRATEGYR_RIGHT_LINK
DIBUTTON_STRATEGYR_ROTATE_LEFT_LINK
DIBUTTON_STRATEGYR_ROTATE_RIGHT_LINK
DIHATSWITCH_STRATEGYR_GLANCE


Turn-Based

The DIVIRTUAL_STRATEGY_TURN genre contains controls for a turn-based strategy game.

Priority 1 Controls
DIAXIS_STRATEGYT_LATERAL
DIAXIS_STRATEGYT_MOVE
DIBUTTON_STRATEGYT_APPLY
DIBUTTON_STRATEGYT_INSTRUCT
DIBUTTON_STRATEGYT_MENU
DIBUTTON_STRATEGYT_SELECT
DIBUTTON_STRATEGYT_TEAM
DIBUTTON_STRATEGYT_TURN

Priority 2 Controls
DIBUTTON_STRATEGYT_BACK_LINK
DIBUTTON_STRATEGYT_DEVICE
DIBUTTON_STRATEGYT_DISPLAY
DIBUTTON_STRATEGYT_FORWARD_LINK
DIBUTTON_STRATEGYT_LEFT_LINK
DIBUTTON_STRATEGYT_MAP
DIBUTTON_STRATEGYT_PAUSE
DIBUTTON_STRATEGYT_RIGHT_LINK
DIBUTTON_STRATEGYT_ZOOM


Keyboard Mapping Constants

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to a physical key.

Constant | Note
DIKEYBOARD_0 | On main keyboard
DIKEYBOARD_1 | On main keyboard
DIKEYBOARD_2 | On main keyboard
DIKEYBOARD_3 | On main keyboard
DIKEYBOARD_4 | On main keyboard
DIKEYBOARD_5 | On main keyboard
DIKEYBOARD_6 | On main keyboard
DIKEYBOARD_7 | On main keyboard
DIKEYBOARD_8 | On main keyboard
DIKEYBOARD_9 | On main keyboard
DIKEYBOARD_A |
DIKEYBOARD_ABNT_C1 | On numeric pad of Brazilian keyboards
DIKEYBOARD_ABNT_C2 | On numeric pad of Brazilian keyboards
DIKEYBOARD_ADD | PLUS SIGN (+) on numeric keypad
DIKEYBOARD_APOSTROPHE |
DIKEYBOARD_APPS | Application key
DIKEYBOARD_AT | On Japanese keyboard
DIKEYBOARD_AX | On Japanese keyboard
DIKEYBOARD_B |
DIKEYBOARD_BACK | BACKSPACE
DIKEYBOARD_BACKSLASH |
DIKEYBOARD_C |
DIKEYBOARD_CALCULATOR |
DIKEYBOARD_CAPITAL | CAPS LOCK
DIKEYBOARD_COLON | On Japanese keyboard
DIKEYBOARD_COMMA |
DIKEYBOARD_CONVERT | On Japanese keyboard
DIKEYBOARD_D |
DIKEYBOARD_DECIMAL | PERIOD (decimal point) on numeric keypad
DIKEYBOARD_DELETE |
DIKEYBOARD_DIVIDE | Forward slash (/) on numeric keypad
DIKEYBOARD_DOWN | DOWN ARROW
DIKEYBOARD_E |
DIKEYBOARD_END |
DIKEYBOARD_EQUALS | On main keyboard
DIKEYBOARD_ESCAPE |
DIKEYBOARD_F |
DIKEYBOARD_F1 |
DIKEYBOARD_F2 |
DIKEYBOARD_F3 |
DIKEYBOARD_F4 |
DIKEYBOARD_F5 |
DIKEYBOARD_F6 |
DIKEYBOARD_F7 |
DIKEYBOARD_F8 |
DIKEYBOARD_F9 |
DIKEYBOARD_F10 |
DIKEYBOARD_F11 |
DIKEYBOARD_F12 |
DIKEYBOARD_F13 | On NEC PC-98 Japanese keyboard
DIKEYBOARD_F14 | On NEC PC-98 Japanese keyboard
DIKEYBOARD_F15 | On NEC PC-98 Japanese keyboard
DIKEYBOARD_G |
DIKEYBOARD_GRAVE | Grave accent (`)
DIKEYBOARD_H |
DIKEYBOARD_HOME |
DIKEYBOARD_I |
DIKEYBOARD_INSERT |
DIKEYBOARD_J |
DIKEYBOARD_K |
DIKEYBOARD_KANA | On Japanese keyboard
DIKEYBOARD_KANJI | On Japanese keyboard
DIKEYBOARD_L |
DIKEYBOARD_LBRACKET | Left square bracket [
DIKEYBOARD_LCONTROL | Left CTRL
DIKEYBOARD_LEFT | LEFT ARROW
DIKEYBOARD_LMENU | Left ALT
DIKEYBOARD_LSHIFT | Left SHIFT
DIKEYBOARD_LWIN | Left Microsoft® Windows® logo key
DIKEYBOARD_M |
DIKEYBOARD_MAIL |
DIKEYBOARD_MEDIASELECT | Media Select key, which displays a selection of supported media players on the system
DIKEYBOARD_MEDIASTOP |
DIKEYBOARD_MINUS | On main keyboard
DIKEYBOARD_MULTIPLY | Asterisk (*) on numeric keypad
DIKEYBOARD_MUTE |
DIKEYBOARD_MYCOMPUTER |
DIKEYBOARD_N |
DIKEYBOARD_NEXT | PAGE DOWN
DIKEYBOARD_NEXTTRACK | Next track
DIKEYBOARD_NOCONVERT | On Japanese keyboard
DIKEYBOARD_NUMLOCK |
DIKEYBOARD_NUMPAD0 |
DIKEYBOARD_NUMPAD1 |
DIKEYBOARD_NUMPAD2 |
DIKEYBOARD_NUMPAD3 |
DIKEYBOARD_NUMPAD4 |
DIKEYBOARD_NUMPAD5 |
DIKEYBOARD_NUMPAD6 |
DIKEYBOARD_NUMPAD7 |
DIKEYBOARD_NUMPAD8 |
DIKEYBOARD_NUMPAD9 |
DIKEYBOARD_NUMPADCOMMA | On numeric keypad of NEC PC-98 Japanese keyboard
DIKEYBOARD_NUMPADENTER |
DIKEYBOARD_NUMPADEQUALS | On numeric keypad of NEC PC-98 Japanese keyboard
DIKEYBOARD_O |
DIKEYBOARD_OEM_102 | On British and German keyboards
DIKEYBOARD_P |
DIKEYBOARD_PAUSE |
DIKEYBOARD_PERIOD | On main keyboard
DIKEYBOARD_PLAYPAUSE |
DIKEYBOARD_POWER |
DIKEYBOARD_PREVTRACK | Previous track; circumflex on Japanese keyboard
DIKEYBOARD_PRIOR | PAGE UP
DIKEYBOARD_Q |
DIKEYBOARD_R |
DIKEYBOARD_RBRACKET | Right square bracket ]
DIKEYBOARD_RCONTROL | Right CTRL
DIKEYBOARD_RETURN | ENTER on main keyboard
DIKEYBOARD_RIGHT | RIGHT ARROW
DIKEYBOARD_RMENU | Right ALT
DIKEYBOARD_RSHIFT | Right SHIFT
DIKEYBOARD_RWIN | Right Windows logo key
DIKEYBOARD_S |
DIKEYBOARD_SCROLL | SCROLL LOCK
DIKEYBOARD_SEMICOLON |
DIKEYBOARD_SLASH | Forward slash (/) on main keyboard
DIKEYBOARD_SLEEP |
DIKEYBOARD_SPACE | SPACEBAR
DIKEYBOARD_STOP | On NEC PC-98 Japanese keyboard
DIKEYBOARD_SUBTRACT | MINUS SIGN (-) on numeric keypad
DIKEYBOARD_SYSRQ |
DIKEYBOARD_T |
DIKEYBOARD_TAB |
DIKEYBOARD_U |
DIKEYBOARD_UNDERLINE | On NEC PC-98 Japanese keyboard
DIKEYBOARD_UNLABELED | On Japanese keyboard
DIKEYBOARD_UP | UP ARROW
DIKEYBOARD_V |
DIKEYBOARD_VOLUMEDOWN |
DIKEYBOARD_VOLUMEUP |
DIKEYBOARD_W |
DIKEYBOARD_WAKE |
DIKEYBOARD_WEBBACK |
DIKEYBOARD_WEBFAVORITES | Displays the Microsoft Internet Explorer Favorites list, the Windows Favorites folder, or the Netscape Bookmarks list.
DIKEYBOARD_WEBFORWARD |
DIKEYBOARD_WEBHOME |
DIKEYBOARD_WEBREFRESH |
DIKEYBOARD_WEBSEARCH |
DIKEYBOARD_WEBSTOP |
DIKEYBOARD_X |
DIKEYBOARD_Y |
DIKEYBOARD_YEN | On Japanese keyboard
DIKEYBOARD_Z |


Mouse Mapping Constants

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to a physical axis or button on a mouse.

DIMOUSE_BUTTON0
DIMOUSE_BUTTON1
DIMOUSE_BUTTON2
DIMOUSE_BUTTON3
DIMOUSE_BUTTON4
DIMOUSE_BUTTON5
DIMOUSE_BUTTON6
DIMOUSE_BUTTON7
DIMOUSE_WHEEL
DIMOUSE_XAXIS
DIMOUSE_YAXIS
DIMOUSE_XAXISAB
DIMOUSE_YAXISAB

Note DIMOUSE_XAXISAB and DIMOUSE_YAXISAB represent the x-axis and y-axis on a mouse that returns absolute rather than relative axis data.


DirectPlay Voice Mapping Constants

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to a channel on Microsoft® a DirectPlay® voice device.

DIVOICE_CHANNEL1
DIVOICE_CHANNEL2
DIVOICE_CHANNEL3
DIVOICE_CHANNEL4
DIVOICE_CHANNEL5
DIVOICE_CHANNEL6
DIVOICE_CHANNEL7
DIVOICE_CHANNEL8
DIVOICE_ALL
DIVOICE_TEAM
DIVOICE_PLAYBACKMUTE
DIVOICE_RECORDMUTE
DIVOICE_TRANSMIT
DIVOICE_VOICECOMMAND


Any-Control Constants

The following constants are used in the dwSemantic member of the DIACTION structure to map an action to any matching control on the device.

Constant | Device object
DIAXIS_ANY_1 | Any axis
DIAXIS_ANY_2 | Any axis
DIAXIS_ANY_3 | Any axis
DIAXIS_ANY_4 | Any axis
DIAXIS_ANY_A_1 | Any accelerator
DIAXIS_ANY_A_2 | Any accelerator
DIAXIS_ANY_B_1 | Any brake
DIAXIS_ANY_B_2 | Any brake
DIAXIS_ANY_C_1 | Any clutch
DIAXIS_ANY_C_2 | Any clutch
DIAXIS_ANY_R_1 | Any r-axis
DIAXIS_ANY_R_2 | Any r-axis
DIAXIS_ANY_S_1 | Any s-axis
DIAXIS_ANY_S_2 | Any s-axis
DIAXIS_ANY_U_1 | Any u-axis
DIAXIS_ANY_U_2 | Any u-axis
DIAXIS_ANY_V_1 | Any v-axis
DIAXIS_ANY_V_2 | Any v-axis
DIAXIS_ANY_X_1 | Any x-axis
DIAXIS_ANY_X_2 | Any x-axis
DIAXIS_ANY_Y_1 | Any y-axis
DIAXIS_ANY_Y_2 | Any y-axis
DIAXIS_ANY_Z_1 | Any z-axis
DIAXIS_ANY_Z_2 | Any z-axis
DIBUTTON_ANY(x) | Any button
DIPOV_ANY_1 | Any point-of-view controller
DIPOV_ANY_2 | Any point-of-view controller
DIPOV_ANY_3 | Any point-of-view controller
DIPOV_ANY_4 | Any point-of-view controller

These constants can be used to map an application action to a virtual control that is not defined in a genre. Such actions are mapped after genre-specific actions. If the mapper has already mapped all matching controls to genre-specific actions, the any-control action is left unmapped.

Any-control actions are treated with equal priority. If a device has one x-axis and the action array specifies DIAXIS_ANY_1 and DIAXIS_ANY_X_1, the action mapped to the x-axis is the one that appears first in the action array.

DIBUTTON_ANY(x) can accept any value from 0 through 255. Do not use any given index more than once. For instance, the following set of DIACTION structures would be invalid.

{eB_MUTE,    DIBUTTON_ANY(0), 0, "Toggle Sound",},
{eB_VOLUP,   DIBUTTON_ANY(0), 0, "Volume Up",   },
{eB_VOLDOWN, DIBUTTON_ANY(0), 0, "Volume Down", },

The correct method would use different indexes as shown below.

{eB_MUTE,    DIBUTTON_ANY(0), 0, "Toggle Sound",}
{eB_VOLUP,   DIBUTTON_ANY(1), 0, "Volume Up",   }
{eB_VOLDOWN, DIBUTTON_ANY(2), 0, "Volume Down", }


Return Values

The list below contains the HRESULT values that can be returned by Microsoft® DirectInput® methods and functions. Errors are represented by negative values and cannot be combined.

For a list of the error values each method or function can return, see the individual descriptions. Lists of error codes in the documentation are necessarily incomplete. For example, any DirectInput method can return DIERR_OUTOFMEMORY even though the error code is not explicitly listed as a possible return value in the documentation for that method.

DI_BUFFEROVERFLOW
The device buffer overflowed and some input was lost. This value is equal to the S_FALSE standard COM return value.
DI_DOWNLOADSKIPPED
The parameters of the effect were successfully updated, but the effect could not be downloaded because the associated device was not acquired in exclusive mode.
DI_EFFECTRESTARTED
The effect was stopped, the parameters were updated, and the effect was restarted.
DI_NOEFFECT
The operation had no effect. This value is equal to the S_FALSE standard COM return value.
DI_NOTATTACHED
The device exists but is not currently attached. This value is equal to the S_FALSE standard COM return value.
DI_OK
The operation completed successfully. This value is equal to the S_OK standard COM return value.
DI_POLLEDDEVICE
The device is a polled device. As a result, device buffering does not collect any data and event notifications is not signaled until the IDirectInputDevice8::Poll method is called.
DI_PROPNOEFFECT
The change in device properties had no effect. This value is equal to the S_FALSE standard COM return value.
DI_SETTINGSNOTSAVED
The action map was applied to the device, but the settings could not be saved.
DI_TRUNCATED
The parameters of the effect were successfully updated, but some of them were beyond the capabilities of the device and were truncated to the nearest supported value.
DI_TRUNCATEDANDRESTARTED
Equal to DI_EFFECTRESTARTED | DI_TRUNCATED.
DI_WRITEPROTECT
A SUCCESS code indicating that settings cannot be modified.
DIERR_ACQUIRED
The operation cannot be performed while the device is acquired.
DIERR_ALREADYINITIALIZED
This object is already initialized
DIERR_BADDRIVERVER
The object could not be created due to an incompatible driver version or mismatched or incomplete driver components.
DIERR_BETADIRECTINPUTVERSION
The application was written for an unsupported prerelease version of DirectInput.
DIERR_DEVICEFULL
The device is full.
DIERR_DEVICENOTREG
The device or device instance is not registered with DirectInput. This value is equal to the REGDB_E_CLASSNOTREG standard COM return value.
DIERR_EFFECTPLAYING
The parameters were updated in memory but were not downloaded to the device because the device does not support updating an effect while it is still playing.
DIERR_GENERIC
An undetermined error occurred inside the DirectInput subsystem. This value is equal to the E_FAIL standard COM return value.
DIERR_HANDLEEXISTS
The device already has an event notification associated with it. This value is equal to the E_ACCESSDENIED standard COM return value.
DIERR_HASEFFECTS
The device cannot be reinitialized because effects are attached to it.
DIERR_INCOMPLETEEFFECT
The effect could not be downloaded because essential information is missing. For example, no axes have been associated with the effect, or no type-specific information has been supplied.
DIERR_INPUTLOST
Access to the input device has been lost. It must be reacquired.
DIERR_INVALIDPARAM
An invalid parameter was passed to the returning function, or the object was not in a state that permitted the function to be called. This value is equal to the E_INVALIDARG standard COM return value.
DIERR_MAPFILEFAIL
An error has occured either reading the vendor-supplied action-mapping file for the device or reading or writing the user configuration mapping file for the device.
DIERR_MOREDATA
Not all the requested information fit into the buffer.
DIERR_NOAGGREGATION
This object does not support aggregation.
DIERR_NOINTERFACE
The object does not support the specified interface. This value is equal to the E_NOINTERFACE standard COM return value.
DIERR_NOTACQUIRED
The operation cannot be performed unless the device is acquired.
DIERR_NOTBUFFERED
The device is not buffered. Set the DIPROP_BUFFERSIZE property to enable buffering.
DIERR_NOTDOWNLOADED
The effect is not downloaded.
DIERR_NOTEXCLUSIVEACQUIRED
The operation cannot be performed unless the device is acquired in DISCL_EXCLUSIVE mode.
DIERR_NOTFOUND
The requested object does not exist.
DIERR_NOTINITIALIZED
This object has not been initialized.
DIERR_OBJECTNOTFOUND
The requested object does not exist.
DIERR_OLDDIRECTINPUTVERSION
The application requires a newer version of DirectInput.
DIERR_OTHERAPPHASPRIO
Another application has a higher priority level, preventing this call from succeeding. This value is equal to the E_ACCESSDENIED standard COM return value. This error can be returned when an application has only foreground access to a device but is attempting to acquire the device while in the background.
DIERR_OUTOFMEMORY
The DirectInput subsystem could not allocate sufficient memory to complete the call. This value is equal to the E_OUTOFMEMORY standard COM return value.
DIERR_READONLY
The specified property cannot be changed. This value is equal to the E_ACCESSDENIED standard COM return value.
DIERR_REPORTFULL
More information was requested to be sent than can be sent to the device.
DIERR_UNPLUGGED
The operation could not be completed because the device is not plugged in.
DIERR_UNSUPPORTED
The function called is not supported at this time. This value is equal to the E_NOTIMPL standard COM return value.
E_HANDLE
The HWND parameter is not a valid top-level window that belongs to the process.
E_PENDING
Data is not yet available.
E_POINTER
An invalid pointer, usually NULL, was passed as a parameter.


DirectPlay

The Microsoft® DirectPlay® application programming interface (API) is the component of Microsoft DirectX® that enables you to write network applications such as multiplayer games.

Like other components of DirectX, DirectPlay can be used with C, C++, and Microsoft Visual Basic®.

For an overview of the organization of the DirectPlay Help, see Roadmap.


Roadmap

Information on Microsoft® DirectPlay® is presented in the following sections.

What's New in DirectPlay. New features and functionality of this component in Microsoft DirectX® 8. If you've used DirectPlay before, read this section first because this technology has been completely redesigned since DirectX 7.

Introduction to DirectPlay. An overview of what DirectPlay is and what it can do for your application, together with a first look at some key objects and the steps involved in creating a network application.

Understanding DirectPlay. A deeper look at the underlying mechanisms. This section won't teach you how to implement a DirectPlay session, but it will help you understand the application programming interface (API) when you get into the details.

Using DirectPlay. A guide to using the API. You'll probably want to familiarize yourself with the table of contents for this section and then refer to parts of it as you need specific information. Use it in conjunction with the reference section.

DirectPlay C++ Samples. A guide to the C/C++ sample applications in the SDK.

DirectPlay C/C++ Reference. Detailed information for the DirectPlay C++ API.


What's New in DirectPlay

The networking component of Microsoft® DirectX® has undergone a major revision. Microsoft DirectPlay® introduces a new set of interfaces that enable games to have more direct access to the hardware, providing better performance.

The following list describes some of the new DirectPlay features.

Interfaces have been completely rewritten.
The complexity of creating a networked application has been dramatically simplified by separating the interfaces for creating peer-to-peer and client/server sessions. The interfaces for creating DirectPlay transport sessions, which are defined in the Dplay8.h header file, are now:
IDirectPlay8Peer
Provides methods for creating peer-to-peer sessions.
IDirectPlay8Client
Provides methods for creating the client-side portion of a client/server application.
IDirectPlay8Server
Provides methods for creating the server-side portion of a client/server application.
Lobbying is now independent from the rest of DirectPlay.
DirectPlay has removed the requirement that a lobby client work only with a DirectPlay application. This will allow for either the lobby service provider or the application to implement DirectPlay without concern for the other. Lobby implementation is now separated into two simplified interfaces that are defined in the Dplobby8.h header file.
IDirectPlay8LobbyClient
This interface is used to manage a lobby client and for enumerating and launching lobby-aware applications.
IDirectPlay8LobbiedApplication
This interface is used to register a lobby launchable application with the system so it can be lobby launched. It also is used to get the connection information from the lobby to enable game launching without querying the user.
Voice transmission has been added.
DirectPlay Voice provides a set of interfaces to add real-time voice communication to an application. The following interfaces are defined in the Dvoice.h header file.
IDirectPlayVoiceClient
Provides methods to create and manage clients in a DirectPlay Voice session.
IDirectPlayVoiceServer
Provides methods to host and manage a DirectPlay Voice session.
IDirectPlayVoiceTest
Used to test DirectPlay Voice audio configurations.
Addressing information has moved from GUID-based data to URL-based data format.
Previous versions of DirectPlay used binary chunks of data with GUID addresses that were difficult to implement and that humans could not read. In DirectX 8.0, DirectPlay introduces the representation of addresses in URL format. A set of interfaces, defined in Dpaddr.h, is used to create and manipulate the new addressing format.
IDirectPlay8Address
Provides generic addressing methods used to create and manipulate DirectPlay addresses.
IDirectPlay8AddressIP
Provides IP provider-specific addressing services.
Higher scalability and better memory management have been added.
Increases in consumer bandwidth have dramatically affected network game design and implementation. Improved DirectPlay thread-pool management makes it easier to for the developer to design scalable, more robust applications that can support massive multiplayer online applications.
Better support for Firewalls and Network Address Translators has been added.
Writing network games that traverse Network Address Translators (NATs), Firewalls, and other Internet Connection Sharing (ICS) methods can be difficult, particularly for non-guaranteed (UDP) traffic. Because DirectPlay 8.0 has been developed with these issues in mind, it will support NAT solutions where possible. The DirectPlay 8 TCP/IP service provider uses a single, developer-selectable UDP port for game data, making it possible to configure firewalls and NATs appropriately. Additionally, DirectPlay makes use of UDP so that, for client/server games, clients behind some NATs will be able to connect to games without additional configuration.


Introduction To DirectPlay

The Microsoft® DirectPlay® API provides developers with the tools to develop multiplayer applications such as games or chat clients. For simplicity, this documentation will refer to all such applications as "games". A multiplayer application has two basic characteristics:

  • Two or more individual users, each with a game client on their computer.
  • Network links that enable the users' computers to communicate with each other, perhaps through a centralized server.

DirectPlay provides a layer that largely isolates your application from the underlying network. For most purposes, your application can simply use the DirectPlay API, and enable DirectPlay to handle the details of network communication. DirectPlay provides many features that simplify the process of implementing many aspects of a multiplayer application, including:

  • Creating and managing both peer-to-peer and client/server sessions
  • Managing users and groups within a session
  • Managing messaging between the members of a session over different network links and varying network conditions
  • Enabling applications to interact with lobbies
  • Enabling users to communicate with each other by voice

This documentation provides a high-level overview of the capabilities of DirectPlay. Subsequent sections will take you into the details of how to use DirectPlay in your multiplayer game.

  • Creating and Managing Sessions
  • DirectPlay Network Communication
  • Communicating with DirectPlay Objects
  • DirectPlay Lobby Support
  • DirectPlay Voice Communication


Creating and Managing Sessions

A game session is an instance of a particular multiplayer game. A session has two or more users playing simultaneously, each with the same game client on his or her computer. A player is an entity in the game itself, and is defined by the particular game. Each user may have more than one player in a game. However, the game application must manage these players itself, using separate Microsoft® DirectPlay® interfaces or objects for each player.

The first step in creating a session is to collect a group of users. There are two basic approaches:

  • Many game sessions are arranged by a lobby application running on a remote computer. This approach is used by most Internet-based games.
  • It is also possible to arrange games by having the individual users' computers communicate with each other. This approach is typically limited such situations as a group of potential users that are all on the same LAN.

Once the session has been arranged, the game is launched and gameplay begins. As the session proceeds, players may be eliminated from the session, or new players added. The details are up to the individual game.

With a multiplayer game, each user's UI can be synchronized with that of all the other users in the session. Managing a multiplayer session thus requires a continual stream of messages to and from each user. For example, every time a player moves, a message must be sent to update that player's position on all the other game clients in the session. The core of DirectPlay is that part of the API that supports efficient and flexible messaging between all the computers in a session.

There are two basic ways to structure the messaging topology of a session: peer-to-peer and client/server. Both topologies have their advantages and limitations, so you will need to evaluate which is most appropriate for your game.

This section discusses

  • Peer-to-Peer Topology
  • Client/Server Topology


Peer-to-Peer Topology

A peer-to-peer game consists of the individual players' computers, connected by network links. Schematically, the topology of a four-player peer-to-peer game looks like:

Gameplay is handled by having each user's game client communicate directly with the other users' clients. For instance, when one user moves, the game client must send three update messages, one to each of the other users' computers.

A peer-to-peer game is normally arranged and launched through a lobby client application that resides on the user's computer. There are two basic ways the lobby client can arrange a session:

  • The lobby client communicates directly with other potential users' lobby clients. This approach can be used, for instance, to arrange a game among users on the same LAN subnet.
  • The lobby client acts as a link to lobby server application running on a remote computer. This is the way Internet-based games are normally arranged.

Once a session has been arranged and launched, most or all of the messaging will be user to user. If a lobby server is involved, it will only be handling such tasks as updating its list of session members when a player leaves the game, or enabling a new user to request entry to the session. Otherwise, the server stays in the background, and is typically not even aware of most of the messages that are being sent.

Because the server is either non-existent or at least not directly involved with the game play, one user is designated as the game host. They are responsible for handling logistical details such as bringing new players into an ongoing session.

Peer-to-peer games have the advantage of simplicity. All that is needed is a collection of players with game clients, and a way to organize a session. The primary drawback of the peer-to-peer topology is scalability. As the number of users increase, the number of messages needed to facilitate game play increases geometrically. The maximum number of users that can be accommodated depends on the game and the network bandwidth, but is typically no more than 20-30.


Client/Server Topology

A client/server game consists of the individual players' computers, connected to a central server computer. Schematically, the topology of a four-player peer-to-peer game looks like:

Gameplay is handled by having each user's game client communicate with the server. The server is responsible for passing information on to the other users. For instance, when one user moves, they send a message to the server. The server then sends messages to the other players to inform them of a change in game state. The server can have a number of responsibilities:

  • Act as the session's messaging hub. Each computer only needs to send messages to the server. The server handles the logistics of synchronizing all the other users. This arrangement can substantially reduce message traffic, especially for large games.
  • Host the game. The server normally takes care of the tasks that must be handled by the session host in a peer-to-peer game.
  • Support many aspects of the game. The server often does much more than support game logistics. With many games, especially large ones, much of the processing that maintains the "game universe" takes place on the server. The game clients are primarily responsible for handling the user's UI.

A client/server game is normally arranged and launched through a lobby client application that resides on the user's computer. The lobby client acts as a link to a lobby server application that is normally running on a the same remote computer that is hosting the game. Once the game has been launched, the game server application becomes the host, and handles tasks such as admitting new users to the game.

There are a number of advantages to client/server games:

  • They are more efficient, especially for large-scale games. In particular, the scale much better than peer-to-peer games, because additional players only cause a linear increase in the messaging traffic. The client/server topology is necessary for massively-multiplayer games.
  • You not limited by the processing power of your users' computers. You can locate much of the processing required to maintain a large complex "game universe" on a single powerful computer, and let the users' computers handle the UI.
  • You can control key aspects of your game at a central site. For instance, you can often update the game or fix bugs by simply modifying the server application, avoiding the need to update large numbers of game clients.

However, once you have developed and shipped a peer-to-peer game, you are essentially finished. The game clients are largely self-sufficient. With a client/server game, you have an ongoing commitment to your users that goes beyond providing normal support services. You must also provide and maintain a game server computer and the associated software, along with the network links to handle all the messaging, for the lifetime of the application. In the case of massively multiplayer games, you may need to operate your servers for extended periods with few or no breaks in service, or risk angering users by disrupting their gameplay.


DirectPlay Network Communication

The primary function of Microsoft® DirectPlay® is to provide you with efficient and flexible messaging support that largely isolates your application from the underlying network hardware and software. If you need to send a status update, you can simply call the relevant DirectPlay API, regardless of what kind of network link is involved. DirectPlay network service providers support communication over TCP/IP, IPX, modem, and serial links.

This section discusses.

  • DirectPlay Transport Protocol
  • DirectPlay Addresses

Notes

DirectPlay does not support secure communications.

To use modems on Microsoft Windows® 95 systems, you must install version 2.0 of the Telephony API (TAPI). You can download TAPI 2.0 from http://www.microsoft.com.


DirectPlay Transport Protocol

The core of the Microsoft® DirectPlay® networking capabilities is the DirectPlay protocol. This transport-layer protocol has been completely overhauled for DirectPlay 8, and is now used for all messaging. The DirectPlay protocol is focused on making it simple for you to send data from the sending application to the target application, without needing to worry about what happens in between. The protocol offers a number of features that are tailored to the needs of multiplayer games, including:

  • Reliable and unreliable delivery of messages. Reliable messages will be resent until the target application receives them. You can assign the delivery type on a message-by-message basis.
  • Sequential and non-sequential delivery of messages. Sequential messages will be passed to the target application in the order they were sent.
  • Message fragmentation and reassembly. If message size exceeds the capacity of a particular network, DirectPlay automatically fragments and reassembles the message.
  • Congestion control. DirectPlay automatically throttles your outgoing messages to a level that can be handled by the target. This feature prevents you from flooding the target with more messages than it can process.
  • Send prioritization. To ensure that the most important messages get sent first, DirectPlay enables you to designate messages as low, medium, or high priority. The high priority messages are sent to the front of the output queue, followed by medium and low priority messages.
  • Message timeouts. To prevent the outgoing message queue from being clogged with messages that have been superseded by more recent messages, DirectPlay enables you to assign a timeout value to all messages. When a message times out, it is removed from the outgoing message queue, regardless of whether it has been sent or not.


DirectPlay Addresses

In order to deliver messages, each participant in a multiplayer game must have a unique address. Addresses can refer either to the computer that your application is running on (device address), or a computer that your application needs to communicate with (host address).

Microsoft® DirectPlay® addresses are in the form of URL strings. These strings consist of a scheme, scheme separator, and data string in the following general format.

x-directplay:/[data string]

The data string contains several elements that specify everything that is needed to enable communication to take place between sender and target, over a variety of different types of network link.

In use, the URL strings are embedded in a DirectPlay address object which is passed to or from DirectPlay API methods. You have the option of either manipulating the URL string directly, or using the methods exposed by the address object to handle each element of the data string separately.


Communicating with DirectPlay Objects

Microsoft® DirectPlay® essentially consists of a collection of COM objects. Each object exposes one or more interfaces that enable you to control various aspects of DirectPlay. For instance, the DirectPlay peer object (CLSID_DirectPlay8Peer) is used to manage peer-to-peer games.

You communicate with a DirectPlay object by calling the methods exposed by its interfaces. For instance, to send some data to another user in a peer-to-peer game, you would send a message by calling the IDirectPlay8Peer::SendTo method. DirectPlay then takes care of getting the message to its target.

DirectPlay communicates with your application through one or more callback functions. These functions are similar in principle to the familiar Window procedure. Your application implements the callback function and passes a pointer to the function to DirectPlay during initialization. When DirectPlay needs to communicate with your application, it calls the callback function and passes in two key items of information:

  • A message ID that identifies the message type
  • A pointer to a block of data, typically a structure, that provides any needed details.

For instance, when the message sent in the above example arrives at its target, the target application's callback function will receive a message with a DPNMSGID_RECEIVE message id, indicating that a message has arrived from another user. The accompanying structure contains the data.

Because much of DirectPlay messaging is multithreaded, it is critical that callback functions be properly implemented.


DirectPlay Lobby Support

A lobby is an application whose primary purpose is to enable players to meet and arrange games. It is typically located on a remote computer, and accessed over the Internet. Lobby servers often also perform a variety of other functions, such as hosting chat rooms, posting news and information, and selling merchandise. While lobby servers are convenient and commonly used to arrange multiplayer games, they aren't required. Multiplayer games can also be arranged by direct communication between lobby clients.

There are normally three components that are needed to enable a game to interact with a lobby:

  • A lobby server
  • A lobby client
  • A lobbyable game.

Microsoft® DirectPlay® does not specify how you should implement a lobby server application. Instead, DirectPlay provides support for a lobby client. A lobby client is an application that is implemented by a lobby server vendor, and installed on each user's system. It serves as a link between the user and the lobby. While you could handle such communication directly, you would have to know the specific implementation details of every lobby that might launch your game.

The lobby client application handles the details of communicating with its associated lobby server, using whatever protocols are appropriate. The lobby client communicates with the user and their game applications through a DirectPlay interface. DirectPlay then passes messages to the application. The application can also use a DirectPlay interface to pass messages to the lobby client.

A lobby can launch virtually any application. However, the application must have some specific lobby-aware components to take full advantage of lobby-launching. In particular, a lobbyable application can communicate with the lobby client throughout the course of the session. If an application is registered as lobbyable, the lobby client also automatically receives updates for various changes in game status, such as host migration.


DirectPlay Voice Communication

The current trend toward team-based multiplayer games makes player-to-player communication an essential part of gameplay. Historically this has been confined to text-based communication, where players type out the messages to their teammates. Although suitable for slower, turn-based games, text-based communication is at best an inconvenience for real-time games. Not only does it put slow typists at a disadvantage during gameplay but also it is a significant break in the reality that games attempt to create for the player. An obvious solution to the problem is the use of speech as a means for communication. It requires no training and increases the immersion of the game itself.

The windows platform provides all the tools required to provide real-time voice conferencing to video game developers, but it requires a significant amount of effort on the part of the game developer. This, combined with the cost and difficulty of obtaining the rights to compression technology capable of handling extremely low bandwidth situations, has prevented the wide-spread use of voice in games.

Microsoft® DirectPlay® 8.0 provides the game developer with a robust real-time voice conferencing system that requires a minimal amount of effort to use.


Understanding DirectPlay

This section of the Microsoft® DirectPlay® documentation provides the basic background you need to understand how to use the DirectPlay API in your application.

  • Peer-to-Peer Sessions
  • Client/Server Sessions
  • DirectPlay Lobbies
  • Basic Networking
  • DirectPlay Callback Functions and Multithreading Issues
  • Understanding DirectPlay Voice


Peer-to-Peer Sessions

A peer-to-peer session consists of a collection of users connected by a network. While a lobby server may be used to arrange and launch the game, the messaging needed to run the game is sent directly from one user's to another. Any communication with the lobby server is for such limited purposes as updating the list of participants.

With a peer-to-peer game, everything that is needed to run the game is part of the client software. With no server involved, all the processing needed to create and maintain the game universe must be handled by the client applications. This document discusses the basic principles of a lobbyable Microsoft® DirectPlay® peer-to-peer game. For a simple working example of a peer-to-peer application, see the SimplePeer application included with the SDK.

  • Initiating a Peer-to-Peer Session
  • Selecting a Service Provider for a Peer-to-Peer Session
  • Selecting a Host for a Peer-to-Peer Session
  • Connecting to a Peer-to-Peer Session
  • Managing a Peer-to-Peer Session
  • Host Migration
  • Normal Peer-to-Peer Game Play
  • Leaving a Peer-to-Peer Session
  • Terminating a Peer-to-Peer Session


Initiating a Peer-to-Peer Session

A peer-to-peer game can be launched directly by the user, or lobby-launched by a lobby client application that resides on the user's computer. This documentation will assume that the game is lobbyable, and can communicate with the lobby client.

One of the first steps you should take is to determine whether your game was lobby-launched. To do so, create and initialize a lobbied application object (CLSID_DirectPlay8LobbiedApplication). When you do so, you pass the object a pointer to your lobbied application message handler. This message handler receives messages directly from the lobbied application object, and indirectly from the lobby client and the lobby.

  • If the application was lobby-launched, the IDirectPlay8LobbiedApplication::Initialize method returns a connection handle for the lobby client and a DPL_MSGID_CONNECT message is sent to your lobbied application message handler. The pdplConnectionSettings member of the associated structure points to a DPL_CONNECTION_SETTINGS structure that contains connection information such as address objects for the members of the session.
  • If the application was not lobby launched, you will receive neither the connection handle, nor the message. However, if you call IDirectPlay8LobbiedApplication::SetAppAvailable, a lobby client can later connect your running application to a session by sending your lobbied application message handler a DPL_MSGID_CONNECT message.

You should also create and initialize a peer object (CLSID_DirectPlay8Peer). This object will be your primary means of communicating with Microsoft® DirectPlay®, and the other users in the session. If you want to have multiple players in the session, you must create a separate instance of this object for each player.


Selecting a Service Provider for a Peer-to-Peer Session

The service provider is your network connection. Most games use either the TCP/IP or modem service provider, but Microsoft® DirectPlay® also provides support for serial and IPX connections.

If your user was connected to the session by a lobby client, you can determine the appropriate service provider by examining the DPL_CONNECTION_SETTINGS structure that accompanies the DPL_MSGID_CONNECT message. Otherwise, you may need to determine which service provider to use, perhaps by querying the user. You can use the peer object's IDirectPlay8Peer::EnumServiceProviders method to enumerate the available service providers. See Using DirectPlay Enumerations for further discussion.

Once you have selected a service provider, you can then create a DirectPlay address object for your user (a device address). You will use this address to identify your device with a number of DirectPlay methods. See DirectPlay Addressing for a detailed discussion of DirectPlay addresses and address objects.


Selecting a Host for a Peer-to-Peer Session

Although most aspects of peer-to-peer games can be handled by the various users' communicating directly with each other, there are some tasks that must have a single owner. These tasks are handled by the game host. To join a session, you must know the address of the session's host. A common way to select a host is through a lobby server. In that case, when a user's application is connected to the session, the connection settings that you receive with the DPL_MSGID_CONNECT message include the host's address object. To find out who the session host is:

  • Check the dwFlags member of the DPL_CONNECTION_SETTINGS structure that is returned. If that member is set to DPLCONNECTSETTINGS_HOST, your system is the host.
  • If the DPLCONNECTSETTINGS_HOST flag is not set, then you can get the address of the host from the pdp8HostAddress member.

You can also create a broadcast session, perhaps on a LAN subnet, by advertising yourself as a session host. To do so call IDirectPlay8Peer::SetPeerInfo to set the player's name and then call IDirectPlay8Peer::Host to advertise yourself as a potential host. You specify the configuration of the game by assigning values the DPN_APPLICATION_DESC structure that is passed through the pdnAppDesc parameter of IDirectPlay8Peer::Host.

To allow your user to examine the available sessions and hosts, you can enumerate the available hosts by calling IDirectPlay8Peer::EnumHosts. Once the user has selected a session, you can request a connection.


Connecting to a Peer-to-Peer Session

Unless you are the session host, you will need to connect your player to the session. To do so, you must have the address of the session host. If your application was connected by a lobby client, you can obtain the host's address by calling IDirectPlay8LobbiedApplication::GetConnectionSettings. You can also obtain the address by enumerating the available hosts. The information returned by the enumeration includes each host's addresses, and a DPN_APPLICATION_DESC structure that describes the associated session.

To ask to join a session, call IDirectPlay8Peer::SetPeerInfo to set your player's name, and then call IDirectPlay8Peer::Connect with the selected host's address to connect to the session.

When a player attempts to join a session, the host receives a DPN_MSGID_INDICATE_CONNECT message. To accept the player into the session, return S_OK. Returning any other value rejects the request. In either case, the player will receive a DPN_MSGID_CONNECT_COMPLETE message that contains your response. If the host accepted the connection, the hResultCode member of the associated structure will be set to S_OK. If not, hResultCode will be set to DPNERR_HOSTREJECTEDCONNECTION.

The host can define a player context value when they receive the DPN_MSGID_INDICATE_CONNECT message, however the player ID will not yet be defined. The host can also wait to define a player context value until they receive a DPN_MSGID_CREATE_PLAYER message, which includes the player ID. Ordinary players to not receive a DPN_MSGID_INDICATE_CONNECT message.

Once the new player is connected, each member of the session, including the host, receives a DPN_MSGID_CREATE_PLAYER message announcing the new player. The structure associated with the message contains the player ID that you will use to send messages to that player. Peers that are not hosts must define the player context value when they handle this message. Once a peer or host has returned from handling this message, that player context value is set for the session, and cannot be changed. See Using Player Context Values for more discussion of player context values.


Managing a Peer-to-Peer Session

The session host is responsible for managing the session, including:

  • Managing the list of session members and their network addresses
  • Deciding whether a new user is allowed to join the session.
  • Notifying all members when a new user joins the session, and passing them the new user's address.
  • Providing new users with the current game state
  • Notifying all users when a user leaves the session

When players attempt to join a session, the host will receive a DPN_MSGID_INDICATE_CONNECT message. To accept the player into the session return S_OK. Returning any other value rejects the request. In either case, the player will receive a DPN_MSGID_CONNECT_COMPLETE message that contains your response.

The host can remove a player from the session by calling IDirectPlay8Peer::DestroyPeer. Other members of the session cannot call this method successfully. If you want to allow players to request that another player be removed from the session, you must send the request to the host with normal Microsoft® DirectPlay® messaging, and have the host handle the request.


Host Migration

While the host must be one of the initial members of the session, they may choose to leave before session is finished. When the host leaves the session, there are two possible outcomes :

  • The session terminates.
  • The host migrates, and another user becomes host.

Sessions may or may not permit host migration. To enable host migration, the session organizer must set the DPNSESSION_MIGRATE_HOST flag in the dwFlags member of the DPN_APPLICATION_DESC structure when they set up the game. If this flag is not set, the session terminates when the host leaves.

If the DPNSESSION_MIGRATE_HOST flag is set, the host can still force the session to terminate by calling IDirectPlay8Peer::TerminateSession.

If DPNSESSION_MIGRATE_HOST flag is set and the host leaves the session, Microsoft® DirectPlay® will select a new session host. All remaining session members will receive a DPN_MSGID_HOST_MIGRATE message that includes the ID of the new host.


Normal Peer-to-Peer Game Play

In Microsoft® DirectPlay®, a message is essentially a block of game-related data that you send to one or more members of the session. DirectPlay does not specify the contents or format of the data block, it just provides a mechanism to transmit the data from one user to another. Once the game is underway, each session member will normally send a constant stream of messages to all other members of the session for the duration of the game. The primary purpose of these messages is to keep the game state synchronized, so that each user's application displays the same UI. However, messages can also be used for a variety of other game-specific purposes.

For many games, especially rapidly changing ones, you may have to manage your messaging carefully. DirectPlay throttles outgoing messages to a level that can be handled by the target. You will have be careful that you do not send messages too rapidly, and ensure that the most important messages get through. See Basic Networking for a discussion of how to effectively handle DirectPlay messaging.

To send a message to another session member, call IDirectPlay8Peer::SendTo. That member will receive a DPN_MSGID_RECEIVE message with the data. To send a message to a specific player, set the dpnid parameter to the player ID that you received with the associated DPN_MSGID_CREATE_PLAYER message. You can also send a message to every player in the session by setting dpnid to DPNID_ALL_PLAYERS_GROUP. You can also define groups of players, and use a single SendTo call to send a message to all members of a group.

Note You can also use the IDirectPlay8Peer::SetPeerInfo method to send information to other users. They will receive the information with a DPN_MSGID_PEER_INFO message. However, this way of transmitting information is not very efficient, and should not be used for normal messaging.

Using Groups

Many games allow players to be organized into groups. For instance, strategy games typically allow individual players to be organized into groups that can then be directed as a single entity. Microsoft® DirectPlay® also allows the formation of groups of players. DirectPlay groups are essentially a way to simplify your messaging. Once you have defined a group, you can send a message to every group member with a single call to IDirectPlay8Peer::SendTo. While DirectPlay groups normally correspond to the groups that are defined by the game, you are free to create a group for any reason.

To create a DirectPlay group, call IDirectPlay8Peer::CreateGroup All session members will then receive a DPN_MSGID_CREATE_GROUP message with the details. The message will include a group ID that is used to send messages to the group.

Once the group is created, you then add players by calling IDirectPlay8Peer::AddPlayerToGroup. Session members will then receive a DPN_MSGID_ADD_PLAYER_TO_GROUP message with the IDs of the group and the player that was just added.

Once the group is established, you can send data to the group by calling IDirectPlay8Peer::SendTo, with the dpnid parameter set to the group ID. All group members will then receive a DPN_MSGID_RECEIVE message with the data.

To remove a player from a group, call IDirectPlay8Peer::RemovePlayerFromGroup. The session members will receive a DPN_MSGID_DESTROY_PLAYER message with the player's ID.

Finally, when you no longer need the group, you can destroy it by calling IDirectPlay8Peer::DestroyGroup All session members will then receive a DPN_MSGID_DESTROY_GROUP message with the group ID.


Leaving a Peer-to-Peer Session

To leave a session, terminate the connection by calling IDirectPlay8Peer::Close. The session members will be notified with a DPN_MSGID_DESTROY_PLAYER message.

If you are the session host, leaving also terminates the session unless you configured the session to allow host migration. See Host Migration for details.


Terminating a Peer-to-Peer Session

When the session is over, the host should terminate the session by calling IDirectPlay8Peer::TerminateSession. This method terminates the session even if host-migration is enabled. All session members will be notified by a DPN_MSGID_TERMINATE_SESSION message. You should then perform any necessary cleanup. To start another session, you must first call IDirectPlay8Peer::Close, and then IDirectPlay8Peer::Initialize.

If you registered your application as available for connection by calling IDirectPlay8LobbiedApplication::SetAppAvailable, a lobby client can offer to connect you to a new session by sending your lobbied application message handler a DPL_MSGID_CONNECT message. You must have first called IDirectPlay8Peer::Close and IDirectPlay8Peer::Initialize.


Client/Server Sessions

A client/server session consists of a collection of players, or clients, connected to a central server. As far as Microsoft® DirectPlay® is concerned, a client has no knowledge of any other clients, only the server. The messaging needed to run the game is between the individual clients and the server. DirectPlay does not provide direct client-to-client messaging, as it does for peer-to-peer sessions.

A client/server session requires two distinctly different applications:.

  • The server application runs on a remote server. At a minimum, it serves as a central messaging hub and game host. The server must receive and handle all incoming messages from the clients, and send appropriate messages back out. Any transfer of data from one client to another must be handled by the server application.
  • A client application runs on each players' computer. The primary function of this application is to handle the UI, and keep the player's game state synchronized with the server.

There are certain aspects of the session that can be handled by only one of these applications. For instance, updating a player's video display can only be done by the client application. However, many aspects of the processing needed to maintain the game universe can, at least in principle, be done by either application. Writing an effective client/server game requires some careful consideration of how to divide the processing chores between the two applications.

This document describes the basic principles of client server games, and outlines how to implement client and server applications.

  • Initiating a Client/Server Session
  • Selecting a Service Provider for a Client
  • Selecting a Client/Server Host
  • Connecting to a Client/Server Session
  • Managing a Client/Server Session
  • Normal Client/Server Game Play
  • Leaving a Client/Server Session
  • Terminating a Client/Server Session


Initiating a Client/Server Session

A client/server game can be launched through a lobby, or directly by the server application.

The Server Application

Client/server games are often arranged through lobbies. The most straightforward way to launch the server is to implement it as a lobbyable application. This approach provides a way to launch the server, and supports communication between server and lobby during the course of the session. See DirectPlay Lobbies for further discussion.

A server can also be directly launched, and then advertise itself as available and wait for clients to connect. See Selecting a Client/Server Host for details.

Once the server application has been launched, it should initialize itself by calling IDirectPlay8Server::Initialize. As with other similar Microsoft® DirectPlay® methods, the primary purpose of initialization is to provide DirectPlay with a pointer to your callback message handler. You should also call IDirectPlay8Server::SetServerInfo to describe the current game. Clients cannot connect to a server until this method has been called.

The Client Application

One of the first steps you should take is to determine whether your game was lobby-launched. To do so, create and initialize a lobbied application object (CLSID_DirectPlay8LobbiedApplication). When you do so, you pass the object a pointer to your lobbied application message handler. This message handler receives messages directly from the lobbied application object, and indirectly from the lobby client and the lobby.

  • If the application was lobby-launched, the IDirectPlay8LobbiedApplication::Initialize method returns a connection handle for the lobby client and a DPL_MSGID_CONNECT message is sent to your lobbied application message handler. The pdplConnectionSettings member of the associated structure points to a DPL_CONNECTION_SETTINGS structure that contains connection information such as an address object for the server.
  • If the application was not lobby launched, you will receive neither the connection handle, nor the message. However, if you call IDirectPlay8LobbiedApplication::SetAppAvailable, a lobby client can later connect your running application to a session by sending your lobbied application message handler a DPL_MSGID_CONNECT message.

You should also create and initialize a client object (CLSID_DirectPlay8Client). This object will be your primary means of communicating with Microsoft® DirectPlay® and the server. If you want to have multiple players in the session, you must create a separate instance of this object for each player.


Selecting a Service Provider for a Client

The service provider is your network connection. Most games use either the TCP/IP or modem service provider, but Microsoft® DirectPlay® also provides support for serial and IPX connections.

If your user was connected to the session by a lobby client, you can determine the appropriate service provider by examining the DPL_CONNECTION_SETTINGS structure that accompanies the DPL_MSGID_CONNECT message. Otherwise, you may need to determine which service provider to use, perhaps by querying the user. You can use the client object's IDirectPlay8Client::EnumServiceProviders method to enumerate the available service providers. See Using DirectPlay Enumerations for further discussion.

Once you have selected a service provider, you can then create a DirectPlay address object for your user (a device address). You will use this address to identify your device with a number of DirectPlay methods. See DirectPlay Addressing for a detailed discussion of DirectPlay addresses and address objects.


Selecting a Client/Server Host

By definition, the server application hosts the session. To join a session, a client application must determine the host server's address. A common way to select a host is through a lobby server. In that case, when a user's application is connected to the session, the connection settings that you receive with the DPL_MSGID_CONNECT message include the host's address object. The pdp8HostAddress member of the associate structure points to an address object with the host's address.

Servers using an IP or IPX service provider can also create a broadcast session, perhaps on a LAN subnet, by advertising themselves as session hosts. To create a broadcast session, specify call IDirectPlay8Server::SetServerInfo specify the server settings. Then call IDirectPlay8Server::Host to advertise the server as a session host. You specify the configuration of the game by assigning values the DPN_APPLICATION_DESC structure that is passed through pdnAppDesc parameter of IDirectPlay8Server::Host.

To allow your user to look at the available sessions and hosts, a client application can query for available hosts by calling IDirectPlay8Client::EnumHosts. Once the user has selected a host, you can request a connection.


Connecting to a Client/Server Session

All clients must explicitly join the session by connecting to the host, even if the session has been arranged through a lobby. A connection establishes the client as a member of the session, and provides the host with the information it needs to communicate with the client. The host has the option of accepting or rejecting a connection request.

The Server Application

When a client attempts to join a session, the host receives a DPN_MSGID_INDICATE_CONNECT message. To accept the player into the session, return S_OK. Returning any other value rejects the request. In either case, the client will receive a DPN_MSGID_CONNECT_COMPLETE message that contains your response. You can define a player context value at this time, or wait until you receive a DPN_MSGID_CREATE_PLAYER message. See Using Player Context Values for more discussion of player context values.

If the player is successfully added to the session, all clients and the server will receive a DPN_MSGID_CREATE_PLAYER message with the new player's ID (DPNID). If you want to define a player context value, and have not yet done so, you must define it before your message handler returns from handling this message. Once it has done so, you cannot change the player context value.

The Client Application

To connect to a session, you must have the address of the session host. If your application was connected by a lobby client, you can obtain the host's address by calling IDirectPlay8LobbiedApplication::GetConnectionSettings.

If you not have the address of a session host and you are using either an IP or IPX service provider, you can look for broadcast sessions by calling IDirectPlay8Client::EnumHosts and enumerating the available hosts. You can also obtain the address by enumerating the available hosts. The information returned by the enumeration includes each host's address, the device use to reach the host, and a DPN_APPLICATION_DESC structure that describes the associated session.

To ask to join a session, call IDirectPlay8Client::SetClientInfo to set your player's name, and then call IDirectPlay8Client::Connect with the selected host's address to connect to the session.

Your message handler will receive a DPN_MSGID_CONNECT_COMPLETE message with the host's response. If the host accepted the connection, the hResultCode member of the associated structure will be set to S_OK. If not, hResultCode will be set to DPNERR_HOSTREJECTEDCONNECTION.


Managing a Client/Server Session

As host, the server is responsible for managing the course of the session. The details will depend on how the application is designed, but a session host's duties include, at a minimum,:

  • Managing the list of session members and their network addresses. Microsoft® DirectPlay® handles some of this task, but server applications typically need to manage more player data than is provided by DirectPlay.
  • Deciding whether a new user is allowed to join the session.
  • Providing new users with the current game state.

When a player attempts to join a session, the host receives a DPN_MSGID_INDICATE_CONNECT message. To accept the player into the session return S_OK. Returning any other value rejects the connection request. In either case, the player will receive a DPN_MSGID_CONNECT_COMPLETE message that contains your response.

The host can remove a player from the session by calling IDirectPlay8Server::DestroyClient.


Normal Client/Server Game Play

In Microsoft® DirectPlay®, a message is essentially a block of game-related data that is sent from client to server or vice versa. DirectPlay does not specify the contents or format of the data block, it just provides a mechanism to transmit the data. Once the game is underway, each client will normally send a constant stream of messages to the server, and vice versa, for the duration of the game. The primary purpose of these messages is to keep the game state synchronized, so that each user's application displays the same UI. However, messages can also be used for a variety of other game-specific purposes.

For many games, especially rapidly changing ones, you may have to manage your messaging carefully. DirectPlay throttles outgoing messages to a level that can be handled by the target. You will have be careful that you do not send messages too rapidly, and ensure that the most important messages get through. See Basic Networking for a discussion of how to effectively handle DirectPlay messaging.

The Server Application

To send a message to a client, call IDirectPlay8Server::SendTo. The client will receive a DPN_MSGID_RECEIVE message with the data.

The Client Application

To send a message to the server, call IDirectPlay8Client::Send. The server will receive a DPN_MSGID_RECEIVE message with the data.

Note DirectPlay does not provide a mechanism for clients to communicate with other clients, only with the server. Any client-client communication must be implemented by the server application.

Using Groups

Many games allow players to be organized into groups. For example, in a squad-based game, every player in the squad could be a member of a group. DirectPlay allows servers in a client/server game to create groups of players. While DirectPlay groups typically correspond to the groups that defined by the game, you are free to create a group for any reason. DirectPlay groups are essentially a way to simplify your messaging. Once you have defined a group, you can send a message to every group member with a single IDirectPlay8Server::SendTo call.

To create a DirectPlay group, call IDirectPlay8Server::CreateGroup. Your message handler will then receive a DPN_MSGID_CREATE_GROUP message with the details. The message will include a group ID that is used to send messages to the group. Once the group is created, you then add players by calling IDirectPlay8Server::AddPlayerToGroup.

Once the group is established, you can send data to the group by calling IDirectPlay8Server::SendTo, with the dpnid parameter set to the group ID. All group members will then receive a DPN_MSGID_RECEIVE message with the data.

To remove a player from a group, call IDirectPlay8Server::RemovePlayerFromGroup. Finally, when you no longer need the group, you can destroy it by calling IDirectPlay8Server::DestroyGroup


Leaving a Client/Server Session

A client can leave a session by calling IDirectPlay8Client::Close. The server is notified with a DPN_MSGID_DESTROY_PLAYER message.


Terminating a Client/Server Session

To terminate a client/server session, the server calls IDirectPlay8Server::Close. There is no host migration in a client/server session, so this method terminates all connections and closes the session. The clients are notified of the session end by a DPN_MSGID_TERMINATE_SESSION message.

The server will then receive a DPN_MSGID_DESTROY_PLAYER message for each player, including itself. IDirectPlay8Server::Close is synchronous, and will not return until all the DPN_MSGID_DESTROY_PLAYER messages have been processed. Once IDirectPlay8Server::Close has returned, you can safely shut down the server application.


DirectPlay Lobbies

A lobby is an application whose primary purpose is to help users arrange multiplayer games. The lobby is usually an application that is hosted on a remote server. The user visits the lobby, typically through the Internet, and either sets up a game session or joins a session started by someone else. The lobby application then launches the group's individual game applications, and the game is underway.

Because many multiplayer games are arranged through lobbies, most games based on Microsoft® DirectPlay® must be able to interact with lobby applications. Conversely, because most lobbies will want to support DirectPlay-based games, the lobby application must be able to interact with the game application. This document discusses how to enable a Microsoft DirectX® game to interact with a lobby, and vice versa.

  • DirectPlay Lobby Architecture
  • Lobby Servers
  • Lobby Clients
  • Lobbyable Applications


DirectPlay Lobby Architecture

The process of arranging and managing a session of a multiplayer game based on Microsoft® DirectPlay® involves five separate components. The lobby server application is a third-party application that typically resides on a remote server and is accessed through the Internet. The remaining four components are installed on each player's computer.

  • Lobby client. The lobby client is a third-party application that communicates with the lobby server. It also communicates with the user's game application through the DirectPlay lobby client object.
  • Lobbyable game application. The lobbyable game application is a third-party application that uses the DirectPlay lobbied application object to communicate with the lobby client, and through the lobby client with the lobby server.
  • DirectPlay lobby client object.
  • DirectPlay lobbied application object.

The two DirectPlay objects act as links between the game application and the lobby client. They communicate with each other through private interfaces. The following graphic shows how these pieces are linked, and how they communicate.:


Lobby Servers

The lobby server is an application whose primary purpose is to enable players to meet and arrange games. It is typically located on a remote computer, and accessed over the Internet. Lobby servers often perform a variety of other functions such as hosting chat rooms, posting news and information, and selling merchandise.

To manage multiplayer games, a lobby server typically handles a variety of tasks, including:

  • Managing the network addresses of the various game sessions and players.
  • Launching a session by launching the associated game applications on the players' computers.
  • Adding players to an ongoing session.
  • Connecting the various computers in a session to the correct network addresses.
  • Keeping track of changes in the session, such as players leaving the game or changes in the game's host.

The details of the lobby server application depend on what kind of services the vendor wants to offer. Microsoft® DirectPlay® does not specify how a lobby server should be implemented nor how it should communicate with its users' computers. However, lobby vendors must implement and distribute to their users a lobby client that is compatible with DirectPlay.


Lobby Clients

A lobby client is an application that is implemented by the lobby server vendor and installed on each player's computer. It handles communication between the players and their game applications, and the lobby server. A common way to install a lobby client is to have the user download it from the lobby server's Web site as part of the sign-up procedure.

The following is a typical scenario.

  1. A new player goes to the Web site and signs up.
  2. As part of the sign-up procedure, the lobby client is downloaded to the client's computer.
  3. The player determines which to play and asks to join a session.
  4. The Web site launches the lobby client on the player's computer. A typical launch mechanism is a URL that points to the lobby client's executable file.
  5. The lobby client handles the mechanics of arranging the session, and then launches the user's game application.
  6. If the game is a lobbyable application, the lobby client enables the game application to communicate with the lobby server. This connection enables the lobby server to keep track of events such as players entering and leaving the game and host migration.

Lobby clients do not necessarily have to be linked to a remote server. In another scenario the user launches the lobby client directly. The lobby client then lists the available games and sessions, perhaps among the people connected to the user's LAN subnet. Once the user chooses a game and session, the lobby client launches the game.

This section discusses some the general features of a lobby client. For more information on communicating between a lobby client and its associated lobby server, see Communicating with a Lobbyable Game.

For more information on implementation details, see Implementing a Lobby Client or the LobbyClient sample application included in the SDK.


Communicating with a Lobbyable Game

Communication between a lobby client and its associated lobby server can be handled in any way that is convenient. Microsoft® DirectPlay® specifies only how the lobby client must communicate with a lobbyable game application.

Lobby clients do not communicate directly with game applications. Instead, they communicate with the DirectPlay lobby client object (CLSID_DirectPlay8LobbyClient) through its IDirectPlay8LobbyClient interface. If the game application is lobbyable, the lobbied application object then passes messages to the game. The IDirectPlay8LobbyClient interface enables the lobby client to do the following.

  • Enumerate the lobbyable applications on the user's system.
  • Launch the application, if it is not already running, and connect it to the session.
  • Release the application from a session, and close the link with the lobby client
  • Send a message to a lobbied application that was launched or connected by the lobby client.

Note A DirectPlay lobby client can launch any application, whether or not it is lobbyable. However, only lobbyable applications can use DirectPlay to communicate back to the lobby client during the course of the game.

The lobby client object communicates with the lobby client through a callback function that is implemented by the lobby client. A function pointer is passed to the lobby client object during initialization. This callback function enables the lobby client object to send the lobby client information such as:

  • Connection information.
  • Connection status.
  • Session status, including connection, disconnection, and host migration.
  • Messages from the application to the lobby client.

Launching an Application

When you launch an application, you can attempt to pass a block of game-specific information to the application. When a lobbyable application is launched by a lobby client, the application creates and initializes a lobbied application object. The information is passed to the game through the initialization method.

When the lobbied application object is initialized, the lobby client receives a message indicating that the user has been connected. One primary purpose of this message is to notify the lobby client that the application is lobbyable. If the lobby client has not received a connect message after a reasonable period of time following the launch, the game is not lobbyable and you can stop attempting to make this connection.

After Launching an Application

The lobby client has relatively little to do once a lobbyable game is in progress. Depending on the game topology, most of the user's messages are sent directly to the other players or to the game server,. However, DirectPlay sends the lobby client messages in response to events such as disconnection and host migration. These messages enable the lobby client to pass such status changes to the lobby server. For instance, if the host migrates, the lobby server can update its UI to indicate the new host.

The application can also pass messages to the lobby client. This message can contain virtually anything, and it can be used for any purpose. The lobby client typically passes the data to the lobby server for processing. For example, at the end of the game, the application might send a message that enables the lobby server to update its high-score list.


Lobbyable Applications

Lobbyable applications are designed to work with a lobby client based on Microsoft® DirectPlay®. While a lobby client can use DirectPlay to launch any application, lobbyable applications have a number of advantages.

  • The lobby client receives automatic updates when game status changes.
  • The lobby client can use a standard API to communicate with the application.
  • The application can use a standard API to communicate with the lobby client.

In short, DirectPlay virtually eliminates the need for game-specific or lobby client-specific communication code. You can use a standard API for everything with little or no modification for the particular game or lobby client.

This section discusses some of the general features of a lobbyable application. For more information, see Launching a Lobbyable Application.

For a discussion of implementation details, see Implementing a Lobbyable Application or SDK samples such as SimplePeer, or StagedPeer.


Launching a Lobbyable Application

One of the first things a lobbyable application should do after it is launched is create a lobbied application object. Among other things, this object enables your application to determine whether it was lobby-launched. A lobbied application must also implement a message-handler callback function to receive messages from the lobby client. The basic procedure is:

  • Create a lobbied application object.
  • Initialize the object.
  • If the initialization method returns a valid connection handle, your application was lobby launched.
  • Examine the user context value that is returned by the initialization method. This value might contain game-specific information from the lobby client.
  • Examine the connection message received through the lobbied application message handler. This message carries with it a variety of information, including the ID that you will use to send messages to the lobby client.

Once an application has been successfully lobby launched, Microsoft® DirectPlay® can automatically send status updates to the lobby client when events such as host migration occur. To enable automatic status updates, call the RegisterLobby method of the IDirectPlay8Peer, IDirectPlay8Client, or IDirectPlay8Server interface. You can also use the lobbied application interface to send messages to the lobby client.

Be aware that your message handler function might receive messages from the lobby client before the initialization method returns. In addition to the connection message, the callback function receives messages when the lobby client changes connection settings, or it breaks the connection. The lobby client can also send messages directly to your message handler that contain game-specific information.

Note It is possible to receive messages from more than one thread. To handle messaging properly, your lobbied application callback function should be re-entrant.


Basic Networking

This section covers some basic networking technology topics that you need to understand to write Microsoft® DirectPlay® applications. For a general discussion of networking technology, see one of the standard texts on the subject, such as Computer Networks by Andrew Tannenbaum.

  • DirectPlay Service Providers
  • DirectPlay Addressing
  • DirectPlay Protocol
  • Optimizing Network Usage
  • Using the DirectX Protocol in an Application


DirectPlay Service Providers

Microsoft® DirectPlay® provides your application with a virtual network connection that enables you to communicate with other computers in the same way, regardless of type of network involved. To provide this level of abstraction, network connections are made through a service provider. Once you have selected a service provider, your application uses the appropriate DirectPlay methods to communicate with other computers in a session. The service provider handles the details of communicating over the selected network hardware.

DirectPlay includes service providers for four types of network connections: TCP/IP, IPX, modem, and serial. See DirectPlay Addressing for a discussion of how to select a service provider.

Note DirectPlay uses the telephony API (TAPI) to handle modem communication. The use of this API means that the code that is used to answer the phone must be in the message loop's thread. To use modems on Microsoft Windows® 95 systems, you must install version 2.0 of the Telephony API (TAPI). You can download TAPI 2.0 from http://www.microsoft.com.


DirectPlay Addressing

To deliver messages, each participant in a multiplayer game must have a unique address. Addresses can refer either to the computer that your application is running on (device address), or a computer that your application needs to communicate with (host address).

Microsoft® DirectPlay® 8.0 represents addresses in the form of a URL string. That address string is then encapsulated in a DirectPlay address object that is passed as a parameter in or out of methods such as IDirectPlay8Peer::Connect.

This section describes two ways to handle DirectPlay addresses.

  • DirectPlay URLs discusses how to construct the address string directly.
  • DirectPlay Address Objects discusses how to manipulate the address string using the methods exposed by the address object's IDirectPlay8Address interface.


DirectPlay URLs

Microsoft® DirectPlay® represents addresses as URLs. In general, URLs are strings that consist of three basic components in the following order: scheme, scheme separator, and data string.

All DirectPlay addresses use "x-directplay" as the scheme, and ":/" (a colon followed by a forward slash) as the scheme separator. Using ":/" as a separator implies that the data that follows is opaque. In other words, the data string does not conform to any Internet standard and should be passed to the receiving application without modification. All DirectPlay URLs thus have the following general form.

x-directplay:/[data string]

Note Do not use "://" (a colon followed by two forward slashes) as a scheme separator. That separator implies that the data that follows conforms to an Internet standard and can be interpreted as such. To prevent confusion, DirectPlay flags any URL containing"://" as invalid.

This section discusses

  • Data Strings
  • Data Values
  • Data Value Summary
  • Sample URLs


Data Strings

The data string holds address information. The first part of a data string consists of a series of keyname=value elements separated by semicolons (;). You can include optional user data by putting a number sign (#) after the last value, followed by an application-defined string.

The key name is a lowercase string that identifies the data and implicitly indicates what type of data is contained in the value. For instance, the "provider" key name indicates that the value contains a Microsoft® DirectPlay® service provider GUID, in the form of a GUID string. The following characters are reserved and should not be used in value strings.

Ampersand (&) | Forward slash (/)
At sign (@) | Number sign (#)
Colon (:) | Question mark (?)
Equal sign (=) | Semicolon (;)

The first element in the data string must be the provider. Other elements can follow in any order. A generic URL looks something like this.

x-directplay:/provider=%provider GUID%;[keyname1=value1];[keyname2=value2][...]#[user defined string]


Data Values

The values that need to be included in the data string depend on the particular service provider. Modem providers, for instance, need a telephone number in their address, whereas LAN providers might need a port number. This section provides a detailed description of the standard data values. It also includes a key name that can be used in place of the literal string. These names are defined in Dpaddr.h.

  • Application Instance
  • Baud
  • Device
  • Flow Control
  • Host Name
  • Parity
  • Phone Number
  • Port
  • Program
  • Provider
  • Stop Bits

Application Instance

An optional GUID that identifies an application instance. This value is used when specifying the game that is to be connected to.

Key Name: DPNA_KEY_APPLICATION_INSTANCE

Key String: "applicationinstance"

Data Type: GUID

Providers: All

Valid Values: Any valid application instance GUID

Baud

The baud rate

Key Name: DPNA_KEY_BAUD

Key String: "baud"

Data Type: DWORD

Providers: Modem and serial

Valid Values: Any valid baud rate. You can set this value to the appropriate integer, or you can use one of the following predefined values from Dpaddr.h.

DPNA_BAUD_RATE_9600
DPNA_BAUD_RATE_14400
DPNA_BAUD_RATE_19200
DPNA_BAUD_RATE_38400
DPNA_BAUD_RATE_56000

Device

A GUID that identifies the device on the local computer that will be used. If the service provider supports all adapters, you do not need to specify a device.

Key Name: DPNA_KEY_DEVICE

Key String: "device"

Data Type: GUID

Providers: All, but for device addresses only, not host addresses

Valid Values: Any valid device GUID.

Flow Control

The type of flow control to be used

Key Name: DPNA_KEY_FLOWCONTROL

Key String: "flowcontrol"

Data Type: String

Providers: Serial and modem

Valid Values: Any of the following predefined values from Dpaddr.h.

DPNA_FLOW_CONTROL_NONE | DPNA_FLOW_CONTROL_DTR
DPNA_FLOW_CONTROL_XONXOFF | DPNA_FLOW_CONTROL_RTSDTR
DPNA_FLOW_CONTROL_RTS |

Host Name

The name of a remote host computer

Key Name: DPNA_KEY_HOSTNAME

Key String: "hostname"

Data Type: String

Providers: All, but for host addresses only, not device addresses

Valid Values: A fully-qualified host name, or a dotted address.

Parity

The parity of the connection

Key Name: DPNA_KEY_PARITY

Key String: "parity"

Data Type: String

Providers: Serial and modem

Valid Values: Any of the following predefined values from Dpaddr.h.

DPNA_PARITY_NONE | DPNA_PARITY_MARK
DPNA_PARITY_EVEN | DPNA_PARITY_SPACE
DPNA_PARITY_ODD |

Phone Number

A phone number

Key Name: DPNA_KEY_PHONENUMBER

Key String: "phonenumber"

Data Type: String

Providers: Modem

Valid Values: Any valid phone number

Port

An optional port number

Key Name: DPNA_KEY_PORT

Key String: "port"

Data Type: DWORD

Providers: IP and IPX

Valid Values: Any 16-bit integer. Only the lower 16 bits of the value are valid. If you do not specify a port, DirectPlay will choose one for you.

Program

An optional application GUID

Key Name: DPNA_KEY_PROGRAM

Key String: "program"

Data Type: GUID

Providers: All

Valid Values: Any valid application GUID

Provider

A GUID that identifies the Microsoft® DirectPlay® service provider that will be used

Key Name: DPNA_KEY_PROVIDER

Key String: "provider"

Data Type: GUID

Providers: All.

Valid Values: Any valid service provider GUID

Stop Bits

The number of stop bits

Key Name: DPNA_KEY_STOPBITS

Key String: "stopbits"

Data Type: String

Providers: Serial and modem

Valid Values: Any of the following predefined values from Dpaddr.h.

DPNA_STOP_BITS_ONE | DPNA_STOP_BITS_TWO
DPNA_STOP_BITS_ONE_FIVE |


Data Value Summary

The following two tables outline the standard data values, and they indicate which values are used by each type service provider for both host and device addresses.

Host Addresses

 | IP | IPX | Serial | Modem
Application Instance | Optional | Optional | Optional | Optional
Baud | Not used | Not used | Required |
Device | Not used | Optional | Required | Required
Flow Control | Not used | Not used | Required |
Host Name | Required | Required | Optional | Optional
Parity | Not used | Not used | Required |
Phone Number | Not used | Not used | Not used | Required
Port | Required | Required | Not used | Not used
Program | Optional | Optional | Optional | Optional
Provider | Required | Required | Required | Required
Stop Bits | Not used | Not used | Required |

Device Addresses

 | IP | IPX | Serial | Modem
Application Instance | Optional | Optional | Optional | Optional
Baud | Not used | Not used | Required | Not used
Flow Control | Not used | Not used | Required | Not used
Host Name | Optional | Optional | Optional | Optional
Device | Optional | Required | Required | Required
Parity | Not used | Not used | Required | Not used
Phone Number | Not used | Not used | Not used | Not used
Port | Optional | Required | Not used | Not used
Program | Optional | Optional | Optional | Optional
Provider | Required | Required | Required | Required
Stop Bits | Not used | Not used | Required | Not used


Sample URLs

The following sample URLs illustrate what a Microsoft® DirectPlay® URL might look like for the four standard service providers.

Local IP Address

x-directplay:/provider=%7BEBFE7BA0-628D-11D2-AE0F-006097B01411%7D;device=%7BIP ADAPTER GUID%7D;port=0000230034#IPUserData

Local IPX Address

x-directplay:/provider=%7B53934290-628D-11D2-AE0F-006097B01411%7D;device=%7BIPX ADAPTER GUID%7D;port=00230#IPXUserData

Local Serial Address

x-directplay:/provider=%7B743B5D60-628D-11D2-AE0F-006097B01411%7D;device=%7BCOM PORT GUID%7D;baud=57600;stopbits=1;parity=NONE;flowcontrol=RTSDTR#SerialUserData

Remote Modem Address

x-directplay:/provider=%7B6D4A3650-628D-11D2-AE0F-006097B01411%7D;device=%7BMODEM DEVICE GUID%7D;phonenumber=555-1212#ModemUserData


Handling Addresses

If you call the Host, EnumHosts, or Connect methods exposed by the IDirectPlay8Peer, IDirectPlay8Client, or IDirectPlay8Server you must pass address objects as parameters. If Microsoft® DirectPlay® does not have sufficient address information, the method that you called will fail, and it will return DPNERR_ADDRESSING. However, it is not necessary to have all the information in the address object at the time you call the method.

All address objects must have the service provider GUID set. However, it is possible to omit other data values.

  • You can omit the device if the service provider supports all adapters.
  • You can omit the port number for IP and IPX service providers for the Host, EnumHosts, and Connect methods. DirectPlay will assign a port number. This number may vary.
  • If you set the OKTOQUERYFORADDRESSING flag, the service provider can display a dialog box asking the user for the information needed to complete the address. If the user does not supply sufficient information, the method will fail. If the OKTOQUERYFORADDRESSING flag is not set, no dialog box will be displayed. If the address you pass to the method is insufficient, the method will fail. In the last two cases, the error value that is returned will be DPNERR_ADDRESSING.

There are two important issues for IP and IPX service providers that you need to be aware of. Failing to handle them properly may cause your application to fail.

  • If you set the NOBROADCASTFALLBACK flag when you call an enumeration method, you must supply a hostname. If you do not do so, the method will fail and return DPNERR_ADDRESSING.
  • If you do not specify a port, do not assume that DirectPlay will always choose the same port number. The only way to be certain of the port number is to specify it in your address. If you do not specify a port number, you must retrieve the actual value later, after the command is in progress.


DirectPlay Address Objects

Microsoft® DirectPlay® does not handle URL strings directly. Instead, the string must be encapsulated in a DirectPlay address object (CLSID_DirectPlayAddress). This object exposes the IDirectPlay8Address interface that enables you to insert URL information into, or extract it from, the address object.

To create DirectPlay address, you must call CoCreateInstance to create a DirectPlay address object. You can then define the address in one of two ways:

  • Create the URL string directly. Then use either IDirectPlay8Address::BuildFromURLA or IDirectPlay8Address::BuildFromURLW to insert the complete string.
  • Use IDirectPlay8Address methods to insert the various pieces of data that make up the string directly into the object.

When you receive an address object, you have a similar pair of options.

  • Extract the entire URL string with either IDirectPlay8Address::GetURLA or IDirectPlay8Address::GetURLW. Then parse the string and extract the needed information
  • Use other IDirectPlay8Address methods to extract the particular data you are interested in from the address object.


DirectPlay Protocol

Multiplayer games require efficient and flexible network messaging services for optimal performance. The Microsoft® DirectPlay® protocol is a transport-layer messaging protocol that is used for all DirectPlay messaging. The protocol has been substantially reworked for DirectPlay 8.0. It provides your application with the messaging support it needs to make everything run smoothly. The DirectPlay protocol includes the following messaging support.

  • Reliable and unreliable delivery of messages
  • Sequential and non-sequential delivery of messages
  • Message fragmentation and reassembly
  • Congestion control
  • Send prioritization
  • Message timeouts

Note With previous versions of DirectPlay, the DirectPlay protocol was optional, and had to be specified explicitly. With DirectPlay 8.0, this protocol is used for all DirectPlay messaging.

This document provides a general description of how the DirectX protocol works, and how you can use it in your application.

  • Basic Message Handling
  • Message Categories
  • Congestion Control
  • Send Prioritization
  • Monitoring Messaging Statistics
  • Monitoring the Pending Message Queues


Basic Message Handling

A message, as the term is used in this document, is a block of data that needs to be sent to another computer. A network protocol creates a packet by adding some bits to the data block that hold information such as the target's network address. This packet is the basic unit of network data. When the target receives the packet, the target's network protocol removes the extra bits and passes the data block to the receiving application.

Although similar in usage, the terms message and packet are not strictly interchangeable. This document uses the term message to refer to the unit of information that is passed to and received from the Microsoft® DirectPlay® API. Packet refers to the unit of information handled by the network. DirectPlay handles packets internally. With rare exceptions, DirectPlay applications need to deal only with messages.

The primary reason for the distinction between message and packet is that networks generally limit the maximum size of the packets they handle. This size is referred to as a Maximum Transmission Unit (MTR). If a message is small, it is sent in a single packet and the two terms are effectively synonymous. However, large messages might need to be fragmented into two or more packets and then be reassembled by the receiver. The DirectPlay protocol automatically handles fragmentation and reassembly of messages as needed. As far as your application is concerned, you send a message, and the target receives it.

Note DirectPlay delivers messages of any size. However, the more packets that are required for a single message, the greater the odds that one or more packets will be lost and have to be retransmitted. Messages that are large enough to require fragmentation and reassembly thus typically have more network latency than single-packet messages. If you need to keep network latency to a minimum, avoid sending large messages, especially on lossy networks. You can determine the maximum size that your connection can accommodate in a single packet by calling the GetSPCaps method exposed by the IDirectPlay8Peer, IDirectPlay8Client, and IDirectPlay8Server interfaces.


Message Categories

The Microsoft® DirectPlay® protocol is designed to handle the following two basic types of network messaging.

  • Reliable versus unreliable messaging determines whether messages are guaranteed to be delivered to the target application.
  • Non-sequential versus sequential messaging determines whether messages are received by the target application in the same order they are sent.

Games use messaging for a variety of purposes, each with different demands. To support this range of messaging needs, the DirectPlay protocol enables you to designate a message as belonging to one of four categories:

  • Reliable and sequential
  • Unreliable and sequential
  • Reliable and non-sequential
  • Unreliable and non-sequential

The DirectPlay protocol enables you to optimize your messaging strategy by assigning categories on a message-by-message basis.

Reliable and Unreliable Messaging

Messages are sometimes lost in transit. Reliable messaging provides a guarantee that the target will receive every message. This type of messaging is required when data loss cannot be tolerated. Most reliable messaging schemes require the target to acknowledge receipt of each message. If the sender does not receive an acknowledgment within a specified timeout period, it resends the message. This process typically continues until the sender receives an acknowledgment, confirming that the message has arrived.

The DirectPlay protocol imposes a limit on the number of resend attempts. If no acknowledgment is received after a reasonable number of attempts, DirectPlay assumes that the connection has been lost, and closes it.

Unreliable messaging is the simplest form of network communication. It might be faster than reliable messaging because there is no guarantee that the message will be delivered to the target. The sender transmits the message. If the target does not receive the message, the sender will not transmit the message again, and the packet is lost.

Unreliable messaging is used primarily when speed or bandwidth is more important than an occasional lost message. For example, high-bandwidth streaming media applications often use unreliable messaging. They cannot afford to take up bandwidth with acknowledgments and retransmissions, nor can they wait for a lost message to be retransmitted. An occasional lost message normally has only a minor impact on quality, so it can be ignored.

Sequential and Non-Sequential Messaging

Messages leave the sender in a particular sequence. However, there is no guarantee that messages will arrive at the target's computer in the same order that they are sent. For example, if a message is lost and must be retransmitted, that message will typically arrive later than messages that followed it in the original sequence.

Sequential messaging uses sequencing information embedded in the message to ensure that the messages are presented to the target application in the correct order. This type of messaging is required when the target application must receive messages in the correct order. Out-of-order messages are buffered until the missing messages arrive.

Non-sequential messaging presents the received messages to the target as soon as they arrive at the target computer, regardless of the order in which they were sent. Because there is no need to wait for a missing packet, applications often use non-sequential messaging when speed is more important than an occasional out-of-order message. The out-of-order message is ignored.

Choosing the Best Message Category

Choosing the best category for messages is a core issue for multiplayer game developers. While DirectPlay provides the tools to manage your messaging, the choice of a message category ultimately depends on the semantic content of the message and the nature of the game.

The following are general guidelines for choosing the best message category.

  • Use non-guaranteed messaging whenever the content permits. For example, your game might send frequent player-location updates. Each update is independent, and it supersedes any previous updates. If an update is lost, the next update is sufficient to maintain the player's game state. A lost and retransmitted message might arrive later than the subsequent update message.
  • Use guaranteed messaging when data loss cannot be tolerated. For example, a text-based chat feature depends on every character being delivered to its target.
  • Use sequential messaging when the order of the messages is important. For example, streaming media typically uses sequential-unreliable messaging. An occasional dropped message can be tolerated, but an out-of-order message would cause problems.


Congestion Control

In an ideal world, your game can send messages as often as it needs to. They arrive at the target immediately and are processed instantaneously. If all of the computers in your game have ample processing power and are connected by a lightly used high-bandwidth network link, you might approach this ideal situation. You can then send messages as often as you like. However, a number of factors can create congestion and cause messaging to work more slowly than this ideal:

  • Network latency. Even under ideal conditions, messages take a finite time to traverse the network from sender to target, especially over the Internet. There might be further delays for acknowledgments, retransmission of lost packets, or reassembly of out-of-order packets.
  • Network bandwidth. The network bandwidth controls the rate at which a message can be sent or received by a computer. Network links have a wide range of bandwidths, and even high-bandwidth networks might be slowed by high traffic levels. If one or more of your players has a low-bandwidth connection, they will be able to send and receive messages only at a limited rate.
  • Processing speed. Even if network bandwidth is high and latency low, the target application still needs some time to process a received message. If one or more of the players in a session is using a relatively slow computer, the rate at which they can process received messages might be below the rate at which messages can be sent.

Message Throttling

If there is no control over the rate at which messages are sent, a target can be flooded by more messages than it can handle. To prevent this situation, the Microsoft® DirectPlay® protocol throttles the rate at which messages are sent. The net effect of throttling is that the rate at which messages are sent is controlled by the rate at which the target can handle them.

Throttling is implemented with a sliding window mechanism. The sliding window is basically a queue with a limited number of slots that holds messages that have been sent but not yet received. All outgoing messages are placed in this queue, regardless of their category. Once the sent-message queue is full, it accepts no more outgoing messages until one of the messages in the queue has been received.

For optimal performance, the size of the sliding window must be matched to current network conditions. The DirectPlay protocol automatically monitors such factors as the number of messages and the total number of bytes in the sent-message queue. This information is then used to dynamically adjust the size of the sliding window to optimize messaging for the current network conditions.

Connection Checking

If there is no activity on a link, the DirectPlay protocol periodically tests the connection by sending an empty reliable packet. If no acknowledgment is received from the target after a reasonable number of attempts, DirectPlay concludes that the link has been disconnected.


Send Prioritization

Messages often vary widely in importance. Some are time-critical, and must be delivered as quickly as possible. Others can be delayed if necessary, or possibly not sent at all. One issue with congestion control algorithms is that an application might create messages faster than they can be sent. Unsent messages must then be held in a queue until an outgoing slot opens up. If all unsent messages are held in a single pending-message queue, high priority messages might be blocked while waiting for lower priority messages to be sent first.

The Microsoft® DirectPlay® protocol solves this problem by having three pending message queues: low, medium, and high priority. When a slot opens up in the sent-message queue, the protocol selects the next message to be sent as follows:

  1. Send the oldest message in the high-priority queue.
  2. If there are no messages in the high-priority queue, send the oldest message in the medium-priority queue.
  3. If there are no messages in the medium-priority queue, send the oldest message in the low-priority queue.

This priority mechanism enables you to get your time-critical messages out as quickly as possible, even though other less important messages have already been submitted.

Send Timeouts

One of the consequences of throttling is that messages might spend a relatively long amount of time in a pending-message queue, especially if they are low priority. Some messages might stay long enough to have been superseded by subsequent messages. These messages are no longer relevant. For example, your application might periodically send player-location update messages. Each update is independent of the others, and supersedes any previous updates. If you have two player-location updates in the pending message queue, only the most recent one needs to be sent.

The DirectPlay protocol enables you to handle the problem of outdated messages by adding an optional timeout value to the message. If the message is still in a pending-message queue when the timeout expires, the message will be canceled.

Disconnection

When an application sends a disconnect message, the message is placed at the end of the low-priority pending-message queue, and the protocol stops accepting outgoing messages. This practice guarantees that all pending messages are sent before the link is disconnected. The disconnect message is sent as a reliable sequential message to guarantee that it arrives, but not before all other messages in the queue have been delivered.


Monitoring Messaging Statistics

While the Microsoft® DirectPlay® protocol handles many aspects of messaging automatically, your application should still monitor messaging behavior. For example, if you are consistently sending messages faster than they can be delivered, you might need to modify your messaging scheme.

Because network conditions change continuously, your application should periodically check the behavior of the network and adjust its messaging scheme accordingly. To do so, call the GetConnectionInfo method that is exposed by every DirectPlay 8.0 interface that supports messaging. GetConnectionInfo returns a structure that contains a wide variety of statistical information that you can use to refine your messaging scheme, including the following:

  • Round trip latency
  • Throughput
  • Packets sent
  • Packets received
  • Packets resent
  • Packets dropped
  • Messages transmitted at different priority levels

Note The messaging statistics are obtained by monitoring the actual network traffic. If you call GetConnectionInfo immediately after you initialize the connection, there will have been little time to collect data and the statistics might be misleading.


Monitoring the Pending Message Queues

You should monitor your pending message queues to ensure that they do not become too large. The IDirectPlay8Peer, IDirectPlay8Client, and IDirectPlay8Server interfaces all expose a GetSendQueueInfo method that can be used to check the number of messages and the number of bytes currently in the queue. By default, the method returns the total for all three queues, but you can also obtain values for each of the three priority levels.


Optimizing Network Usage

Providing the best gaming experience normally means sending updates and other information as rapidly as possible without flooding the target with more messages than it can handle. The Microsoft® DirectPlay® protocol combined with asynchronous messaging enables you to dynamically optimize your messaging strategy to provide your users with the best possible game experience.

The bulk of your messaging will use the IDirectPlay8Peer::SendTo, IDirectPlay8Client::Send, or IDirectPlay8Server::SendTo methods. These methods normally work asynchronously for all message categories. They return immediately, and your message handler receives a DPNMSG_SEND_COMPLETE message when the message is actually sent. You can choose to send messages synchronously by setting the DPNSEND_SYNC flag. If you do so, the method will block until the message is actually sent.

The DirectPlay protocol's throttling mechanism guarantees that the client will not receive messages faster than they can be handled. However, the throttling protocol does not control how frequently you submit messages to the outgoing queue. You can easily end up with a large backlog of messages in your unsent message queues. You can avoid this situation by sending messages as infrequently as possible, but then you might unnecessarily degrade the user's experience. An optimal messaging strategy sends messages as fast as possible without exceeding the target's ability to handle them.

The following are tips for optimizing your messaging strategy.

  • Send most if not all of your messages asynchronously. If you send a message synchronously, the method will block until the throttling mechanism allows the message to be sent.
  • Monitor the pending message queues and the network statistics. If there are few or no messages in the queue, you can increase your transmission rate. If the queues are large or growing rapidly, decrease your transmission rate and perhaps cancel some messages. See the discussion of send timeouts in Send Prioritization for further discussion.
  • Analyze the pending message queues on a player-by-player basis. Some players might be able to receive messages at a much higher rate than others. The bulk statistics might be misleading. Consider using directed sends rather than group sends.
  • Choose the appropriate category for each message. Reserve the categories with the highest overhead for the most important messages.
  • Prioritize your messages, so that the most important are assured of being sent promptly and not delayed by relatively unimportant messages.
  • Do not let the pending message queues grow too large. In addition to delaying the transmission of your messages, a large number of pending messages might consume significant memory resources.
  • Use the timeout feature of the Send and SendTo methods to automatically clear outdated messages from the pending message queue.
  • Minimize the amount of data per message. It is usually better to send frequent small messages than a smaller number of large messages.
  • Do not loop tightly when checking the pending message queue. Doing so wastes CPU cycles. Instead, use a sleep period based on how long it typically takes the queue to get down to the level that it will be ready for another send.


Using the DirectX Protocol in an Application

This section covers how you can use the features of the Microsoft® DirectPlay® protocol in your application.

You can use five DirectPlay interfaces to send messages.

  • IDirectPlay8Peer
  • IDirectPlay8Client
  • IDirectPlay8Server
  • IDirectPlay8LobbyClient
  • IDirectPlay8LobbiedApplication

Depending on which interface your application is using to send messages, you send a message by calling a method named either Send, or SendTo. While the usage of these five methods is similar, they vary in detail. Refer to the appropriate reference pages for further discussion.

The Send/Sendto method's parameters might allow you to control many of the DirectPlay protocol's features. For example, the dwFlags field of IDirectPlay8Peer::SendTo allows you to specify:

  • The message's priority level.
  • Whether the message is reliable or unreliable.
  • Whether the message is sequential or non-sequential.

Refer to the appropriate method reference for further details.

When your application receives a message, your callback function will receive a DPN_RECEIVE message. The associated structure contains a pointer to the data block, along with information such as the source of the message.


DirectPlay Callback Functions and Multithreading Issues

Microsoft® DirectPlay® and DirectPlay Voice both require you to implement and register several callback functions to handle the events fired by DirectPlay. DirectPlay is multithreaded and will fire multiple events concurrently. It is possible that your application will receive multiple overlapping callbacks.

DirectPlay maintains a thread pool to service callback indications, and your callback is invoked on a thread from the pool of threads maintained by DirectPlay. The size of this thread pool is configurable on a per process basis in Microsoft Windows 2000. Also, DirectPlay will use I/O completion ports when running on Windows 2000. I/O completion ports is an advanced topic beyond the scope of this document, and it is recommended that you look in the Microsoft Developer Network documents or in one of the Win32 multithreading references currently available.

In order to correctly and reliably access data in DirectPlay callbacks, you are required to implement a method of multithreading synchronization. This is known as making your callback re-entrant or threadsafe.

The Microsoft Windows family of operating systems currently offers three methods of synchronizing data in multithreaded environments:

  • Mutex Objects
  • Semaphore Objects
  • Critical Section Objects

The DirectPlay voice samples that ship with the DirectX 8.0 SDK demonstrate synchronization using Critical Section Objects. If you wish to implement a Mutex or Semaphore Object, these topics are discussed in the Microsoft Platform SDK as well as in many reference books. Implementing any of these synchronization methods requires an expert knowledge level in these areas due of the level of complexity and difficulty in debugging should any issues arise.

The DirectPlay threading model is optimized for maximum efficiency and there are no thread context switches during "send" operations and during "indication" messages, including receive messages.

This section discusses DirectPlay Networking Callbacks.

See Implementing a Callback Function in DirectPlay and DirectPlay Voice for more information.


DirectPlay Networking Callbacks

Microsoft® DirectPlay® networking callback functions are of type PFNDPNMESSAGEHANDLER. Depending on the type of networking session, you register the address of your callback function with IDirectPlay8Peer::Initialize, IDirectPlay8Client::Initialize, or IDirectPlay8Server::Initialize.

Synchronization Issues

You must employ one of the three thread synchronization objects in order to maintain the integrity of your game data during processing in a DirectPlay callback.

In order to understand how your game data could be corrupted, consider that your callback inserts a packet of game data into a structure. If another thread enters the callback reentrantly before the first callback has completed, it is possible that this thread could also attempt to access the structure at the same location in memory and change the data. Therefore, the data placed in the structure by the first thread is overwritten by the data placed in the structure by the second thread. Please note that this is an oversimplified example of multithreading and there are many other implications to not properly synchronizing multiple threads. Again, it is advisable to achieve an expert level of knowledge in implementing multithreaded callbacks before you attempt to create your own.

See Implementing a DirectPlay Networking Callback Using Critical Section Objects for an example of how to synchronize data in a DirectPlay networking session.

Worker Threads

You have the option of creating your own "worker threads". A worker thread is another multithreaded application defined callback that is created to process game data independently of the DirectPlay callbacks. The most common way of accomplishing this is to buffer data received during a DirectPlay networking callback thread. Then, a new thread is created and a message is sent to your worker thread callback to notify it to process the buffered data.

Multithreading Performance Issues and Asynchronous Operations

It is important to carefully consider how much time is spent processing messages in DirectPlay callbacks. If you process a lot of data within the DirectPlay callbacks and you employ a data locking mechanism to synchronize threads, you will run into blocking problems as other threads wait to enter the callback.

If you choose to implement a worker thread and offset the processing of game data to another callback, you run the risk of adding a lot of overhead processing time as the CPU switches context between the threads you create and the threads created by DirectPlay. This should be done only if the game data requires a large amount of processing time, and the data is not critical to the real time operation of the game. For example, it is not recommended to process player location data in a worker thread because this data is critical to positioning players in real time within the game.

You can also return DPNSUCCESS_PENDING from the callback, create a pointer to the data buffer, and make that pointer available the worker thread. When the worker thread is finished processing the game data, it calls the ReturnBuffer method of either IDirectPlay8Peer or IDirectPlay8Client, depending on the topology used.


Understanding DirectPlay Voice

Microsoft® DirectPlay® Voice is a full-voice communications API that is integrated with DirectPlay for network session management and network transport.

DirectPlay Voice is also integrated with DirectPlay Sound for voice recording and playback, and all DirectPlay Sound audio features are inherited including the ability to target voice data to different playback buffers and the use of special audio effects such as three-dimensional sound positioning.

DirectPlay Voice Networking

DirectPlay Voice Topologies

Voice Host Migration

Audio Device Testing

Voice Codecs

Automatic Gain Control

Transmission Control

Capture Focus

Jitter Buffers

Working Set Guidelines


DirectPlay Voice Networking

Microsoft® DirectPlay® Voice uses a DirectPlay session for media-independent network transport and player management. The DirectPlay Voice API does not duplicate session control features from DirectPlay. A DirectPlay network transport session must also be created before DirectPlay Voice can transmit and receive voice communications. DirectPlay Voice can use either the IDirectPlay4 object or IDirectPlay8 object for network transport.

Note that if DirectPlay Voice is being used in-process with a multiplayer game, the game will most likely also use the transport session to exchange its game-specific data. This makes it possible to optimize the use of network resources between the game and voice data.

It is also acceptable to create and use a transport session specifically for the voice session, as would be the case for a standalone voice conferencing application.


DirectPlay Voice Topologies

Microsoft® DirectPlay® Voice sessions require a DirectPlay network session to transport voice communication. Once the network session has been created, a DirectPlay Voice object can be created to use one of three topologies.

  • Peer-to-Peer Voice Topology
  • Forwarding Server Voice Topology
  • Mixing Server Sessions

The choice of topology is dependent on several factors, and these factors are discussed in the individual DirectPlay Voice topology topics. Note that not all voice topologies can be transported over all types of DirectPlay networking sessions.


Peer-to-Peer Voice Topology

In a Microsoft® DirectPlay® Voice session using a peer-to-peer topology, each voice-session client streams its voice audio data directly to every other voice-session client. Each client receives all individual incoming voice audio streams, mixes the received streams, and plays the resulting mixed signal on the client's computer.

The advantage of using a peer-to-peer topology is that no computer in the voice session requires high bandwidth or processor power. However, the bandwidth and processor usage on each client's computer varies according to the number of incoming and outgoing audio streams. The number of outgoing voice audio streams is equal to the number of targets participating in the voice session, unless the network provider is capable of true multicasting, as noted below. The number of incoming voice audio streams depends on how many other voice-session clients are targeting the client in question and also on how many of the other clients are speaking.

As a game design consideration, it is not useful for a voice-session client to be the target of more than about six to eight other clients. If all six to eight clients are speaking at once, the conversation can become confusing, and communication between clients can be difficult.

If the DirectPlay network session supports true multicasting, the number of outgoing voice audio streams can be reduced considerably. If all clients are part of a multicast network and the target of the voice stream is a DirectPlay group, there is only one outgoing stream.

A DirectPlay voice session using a peer-to-peer voice topology supports 3-D spatialization of the voice data using the IDirectPlayVoiceClient::Create3DSoundBuffer method.

It is important to note that a voice session using a peer-to-peer voice topology cannot be used if the network transport is a client/server session.


Forwarding Server Voice Topology

In a Microsoft® DirectPlay® voice session using a forwarding server topology, one computer in the session acts as a forwarding server. Each client in the voice session streams voice data to the forwarding server, which then forwards the voice data to all other clients in the session. Each client receives all incoming audio streams forwarded from the forwarding server. Each client's computer then mixes the incoming streams and plays them back.

The outgoing bandwidth requirement on each client in a voice session using a forwarding server topology is constant because there is only one outgoing voice audio stream. The incoming bandwidth and processor requirements are identical to the requirements of a voice session using a peer-to-peer topology, but they vary depending on the number of incoming voice audio streams.

The server has much higher bandwidth requirements than the individual clients in a forwarding server DirectPlay voice session. However, the processor requirements are not high because no compression or decompression of voice data occurs on the server. This reduced load on the computer's processor also means that an individual client's computer with a high bandwidth connection can host the forwarding server without adversely affecting the performance of the individual client's computer or the performance of a game server and/or client program running on the same computer.

Note that in a voice session using a peer-to-peer topology, the outgoing bandwidth requirements on the individual clients are usually much higher than the incoming bandwidth requirements. Therefore, reducing the outgoing bandwidth requirement to a single stream of audio can result in a significant reduction in total bandwidth usage. For example, if a client is taking part in an eight-person voice session in which all clients can hear one another, the client has seven outgoing voice streams each time voice data is captured and transmitted on his or her computer. However, it is rare that all clients talk at once, so there are most likely fewer than two or three incoming voice streams at any one time.


Mixing Server Sessions

In mixing server sessions, one computer in the session acts as a mixing server. Each client streams its voice data to the mixing server. The mixing server examines the targets of each voice stream, performs decompression, mixing, and recompression as appropriate to generate a mixed stream of audio data for each client. Each client receives this single stream of pre-mixed audio data and plays it back.

The outgoing bandwidth, incoming bandwidth, and CPU requirement on the client in a mixing server session is easily predictable because each client has only one outgoing stream of audio to compress and send, and one incoming stream of audio to decompress and play back.

The mixing server has much higher bandwidth and CPU requirements than do the clients. Typically, the mixing server is either a completely dedicated computer, or it shares a computer with a dedicated game server.

Mixing server voice sessions do not support 3-D spatialization of the voice data through the IDirectPlayVoiceClient::Create3DSoundBuffer method.

You can run mixing server voice sessions using either a peer-to-peer or a client/server transport session.


Voice Host Migration

In a peer-to-peer Microsoft® DirectPlay® network session, one client of the networking session acts as host. If that host should exit the session or stop responding for any reason, another client in the session is elected as host.

In a DirectPlay voice session, a similar process of host migration occurs in peer-to-peer voice sessions, except that the voice host migrates independently of the DirectPlay network session. The voice host migrates when the server calls IDirectPlayVoiceServer::StopSession or if the voice host stops responding. When the voice host migrates, each client in the voice session receives a DVMSG_HOSTMIGRATED callback. The structure passed to the new host has a valid pdvServerInterface pointer and can begin making IDirectPlayVoiceServer calls.


Audio Device Testing

Microphone setup is supported by the IDirectPlayVoiceTest interface. This interface has one method, IDirectPlayVoiceTest::CheckAudioSetup, that can be used to run the test wizard. This wizard confirms that your system properly supports full duplex operation and ensures your microphone and playback settings are correct. You need to run the wizard only once for each combination of playback and capture device you select. Each time your application starts, you should test the configuration by calling IDirectPlayVoiceTest::CheckAudioSetup with the dwFlags parameter set to DVFLAGS_QUERYONLY. This enables you to quickly test whether the device configuration has changed since you last tested them. If your devices have not been tested, you should run IDirectPlayVoiceTest::CheckAudioSetup again to invoke the wizard. If you do not do so, then IDirectPlayVoiceClient::Connect will return DVERR_RUNSETUP, and you will not be able to initialize DirectPlay Voice.

If the user's sound card does not have full duplex capability, it can only listen to voice communications. It cannot send voice communications because the game typically holds the audio card in playback mode. To prevent problems, DirectX 8.0 does not enable switching dynamically between playback and capturing. The DirectX audio setup wizard provides feedback to the user on the duplexing capabilities of the system.

Note that there are still many computer systems in active use that do not include a full duplex sound card. Full duplex sound cards came into popular use in 1998, although at the time few of the audio card drivers had full duplex operation enabled. Customers who purchased new systems in 1999 or upgraded drivers in 1999 are more likely to have full duplex capability.


Voice Codecs

The compression/decompression (codec) algorithms provided specifically with Microsoft® DirectPlay® are voice-quality codecs. They are all 8 kHz, 16-bit mono-format–based algorithms. Third-party codecs are not supported, and you cannot write proprietary codecs for use with DirectPlay Voice.

It is important to note that as the bandwidth requirements drop, the audio quality of the voice data also drops. The following table describes the sound quality of each codec.

Codecs cannot be dynamically switched during a game voice session, and all users must use the same codec in a voice session. However, a game could possibly create an appropriate user interface to force codec switching by dropping a current session and creating a new session using a different codec. This would be appropriate if the game application's users were jumping from a lobby chat to a game.

As with all other game setup parameters, the host should control the codec used. The voice-session host does not necessarily have to be the same as the game-data host.

As with any form of network communication, it is important to analyze the cost of the voice communication to ensure that adequate bandwidth is available to support communication of the game data and voice data. Analyzing the voice bandwidth consumption is straightforward. Estimate the number of simultaneous voice streams that you anticipate and multiply that number by the sum of the bandwidth required by the codec and the protocol overhead.

CPU consumption is another factor to consider when choosing a codec. Even low bandwidth codecs typically require about 8 percent of a 200 megahertz (MHz) Pentium processor's resources to encode a voice stream and an additional 4 percent to decode. As with network bandwidth, CPU resource consumption is additive per stream.


Automatic Gain Control

Microsoft® DirectPlay® Voice offers functionality to adjust the hardware input volume on the sound card automatically to provide the best recording input level possible. To enable Automatic Gain Control, set the DVCLIENTCONFIG_AUTORECORDVOLUME flag in the dwFlags member of the DVCLIENTCONFIG structure when you set the client configuration. Automatic Gain Control can be activated or deactivated at any time during the voice session.

Most game applications should use automatic gain control because it requires a negligible amount of game resources and prevents the need for an in-game volume recording control. Users are not required to set the level themselves, yet they experience the highest quality of voice transmission and reception possible.


Transmission Control

To keep the performance requirements of Microsoft® DirectPlay® Voice low, voice data should be transmitted only when the user is speaking. There are two methods to control voice data transmission. The choice of which method to use depends on your game's design considerations.

  • Voice Activation
  • Push to Talk


Voice Activation

With voice activated transmission control, the microphone input is constantly analyzed to determine if the user is speaking. Voice activation has two benefits. It does not require the user to do anything more than speak into the microphone. Also, it is easily coded because it requires only setting the dwFlags parameter of the DVCLIENTCONFIG structure to DVCLIENTCONFIG_AUTOVOICEACTIVATED when the voice session is connected.


Push to Talk

Push-to-talk transmission control requires users to actively select when they want to transmit voice data. With this transmission control method, there is no danger that anything besides voice data will be transmitted. This method is analogous to pushing the Talk button on a two-way radio, and this functionality adds reality to certain game genres such as first-person shooters. Another benefit of using this method is that requiring users to actively select when they want to speak reduces the number of users speaking at once. This transmission control requires more design and development than voice activation because user-control functionality is required.


Capture Focus

The concept of capturing focus is integral to creating lobbyable game applications and lobby applications with Microsoft® DirectPlay® Voice support. If your game application does not properly implement focus capture, it is possible that voice communication will not function if your game was launched from a lobby application.

To illustrate this point, consider two players who meet in a lobby application that has DirectPlay Voice support. The two players agree to launch the game. After the game is launched, the lobby application loses focus on each player's computer, and each copy of the game application gains focus. If the game application does not properly gain focus from the lobby application, it is possible that the lobby application can still have focus while the game application is running.

For example, this will occur if the first player's lobby application retains focus while the game session is running while the second player's game session gains focus from the lobby application. From the second player's perspective, the first player's voice session has fallen back to half-duplex. The second player can hear the first player, but the first player cannot hear the second player. From the first player's perspective, the voice session has ended because the second player does not seem to be speaking. Also, the first player does not know that the second player can hear him or her.

Note that this behavior is by design. Consider the same scenario as above, but when the first player attempts to start the game session from the lobby application, there is a problem and the session fails to start. If the second player's session starts successfully, that player can hear the voice of the first player and the first player can inform the second player that their game session failed. Both players might then drop back to the lobby and attempt to start the session once again.

To handle capture focus properly, your game application must set the hwndAppWindow parameter in the DVSOUNDDEVICECONFIG structure to the window handle that will have focus when the game is running. The DirectPlay Voice session can then be created through a call to Connect. The game application must then handle the DVMSGID_LOSTFOCUS and DVMSGID_GAINFOCUS messages.

See Implementing Capture Focus for more information.


Jitter Buffers

Microsoft® DirectPlay® Voice features a jitter buffer, an adaptive buffering algorithm that provides optimal voice quality with the least amount of latency.

On busy networks, individual packets of voice data information might arrive in a different sequence from that in which they were encoded on the host computer. Because voice data is sequential in nature, these incoming packets must be queued for a period of time so that delayed packets have an opportunity to arrive and be played back in order.

If the jitter buffer is set to maximize the quality voice communication, it takes longer for the required number of voice packets to arrive and be queued for play. The result is voice latency, and the effect is that voice communication is not heard in real time. Instead, the voice data might be heard anywhere from a fraction of a second to several seconds after it was recorded. This can introduce problems during cooperative gameplay because events can occur in the game but players will not be able to communicate information based on those events in real time. For example, if a player in a first-person shooter is about to be attacked from behind and a teammate attempts to warn the player, the voice communication might not be heard until after the player has been attacked.

If the jitter buffer is set to a reduce latency, the number of packets required to fill the queue is reduced. However, it is possible that not all sequential packets will arrive in time and, as a result, voice data will be missing from the buffer when it is played. The voice communication will be heard much closer to the actual time it was recorded. However, it will have a "broken-up" quality.

The DirectPlay jitter buffer uses two methods to determine how to provide the best quality of voice communication with the least amount of latency. First, network conditions are monitored to determine the amount of lag or network congestion. The size of the jitter buffer, or queue, is then dynamically sized to keep latency as low as possible while providing the least amount of voice break up.

The default behavior of DirectPlay Voice jitter buffer is to automatically adjust to network conditions. You can manually adjust how closely the algorithm tracks network conditions using the dwBufferAggressiveness and dwBufferQuality members of the DVCLIENTCONFIG structure. The higher the level of "aggressiveness", the more closely the algorithm monitors network conditions. In general, the higher the quality value, the higher the quality of the voice but the higher the latency. The lower the quality value, the lower the latency but the lower the quality of the voice.

It is important to choose an appropriate level of aggressiveness for network conditions when your game application is running because selecting a high level of aggressiveness during times of steady network performance can cause the algorithm to misinterpret a transitory problem and overcompensate for a problem that might not exist.


Working Set Guidelines

Determining the best configuration of transport topology, voice topology, transmission control, and codec depends on the type or genre of game you are creating, the number of players that will participate in a single game session, and the type of connection that will be targeted.

It's important to note that the number of players participating in the voice session is not necessarily the number of players actually participating in the game session. For example, if your game is a first-person shooter, voice communication can be represented in the game as a radio or communicator that is offered as a time-limited powerup. Also, the radio metaphor can be used to limit communication to radios in either vehicles or stationary command stations.

A second example to consider is an online bridge game, which involves four players at one time. Because this is a small working set, it is appropriate to choose a peer-to-peer voice topology transported over a peer-to-peer network topology. This small working set also allows for the use of voice activation as the mode of transmission control. The peer-to-peer voice topology is easily implemented and does not require any player to act as a server. If all four players use the Voxware SC6 codec, the maximum resulting bandwidth is 4.2 Kbps per speech stream, including the codec protocol overhead. Further assuming that game data requires negligible bandwidth, the outgoing maximum bandwidth requirement for an individual speaker is three independent streams to the other three players, or 12.6 Kbps. The incoming stream to any client ranges from 0 if no other players are talking, to 12.6 Kbps if all three other players speak simultaneously. The CPU requirement is 8 percent for encoding and 0 to 12 percent for decoding. This results in a worst-case requirement of 25.2 Kbps. Therefore each player must have a minimum of a 14,400-baud modem.

Another example is a squad combat game that can involve up to 32 players split between 2 teams. Assume that the game data requires a 28,800 baud modem. In this example, there is a larger number of players and it is appropriate to choose a forwarding server voice topology. Again, if all players use the Voxware SC6 codec, the bandwidth requirements are the same as the bridge game above: 4.2 Kbps. In this example we see that there is 4.2 Kbps outgoing when speaking, and a maximum of 12.6 Kbps incoming from the squad. The maximum CPU requirement is 8 percent of a Pentium 200 for encode and 12 percent receiving. Therefore, each player requires 28.8 Kbps for game data, and the greater incoming bandwidth of 12.6 Kbps requires a minimum 41,400 baud rate from each player's modem.

The worst-case scenario for the forwarding server itself is if all 32 players talk at once, requiring 134.4 Kbps. The server CPU use is minimal because the server is not encoding or decoding the streams. It is merely redirecting them. More typically, there might be 16 players talking simultaneously for 67.2 Kbps.

To illustrate the difference between choosing a mixing server voice topology and a forwarding server voice topology, consider the same 32-player squad combat game discussed above. If a mixing server voice topology is used, each client requires 4.2 Kbps to send and 4.2 Kbps to receive. The worst-case bandwidth requirements drop to 8.4 Kbps and 12 percent of the Pentium processor running at 200 MHz. This reduces the modem requirement to a 33,600 Kbps baud rate for the client.

For the server, the CPU burden changes. The server is now decoding and re-encoding all incoming streams and is also mixing the streams as required. The CPU burden mix the stream is relatively low and is considered negligible. The worst case is the decoding and encoding of 32 simultaneous streams. This results in a requirement of at least a Pentium II processor running at 400 MHz for the voice service alone.


Using DirectPlay

This section of the Microsoft® DirectPlay® documentation is designed to show you how to use the DirectPlay API to implement a number of important aspects of multiplayer applications.

  • Using DirectPlay Enumerations
  • Using Player Context Values
  • Implementing a Lobby Client
  • Implementing a Lobbyable Application
  • Monitoring DirectPlay Network Traffic with Netmon
  • Implementing a Callback Function in DirectPlay and DirectPlay Voice
  • Implementing a DirectPlay Networking Callback Using Critical Section Objects
  • Using the DirectPlay DPNSVR Application


Using DirectPlay Enumerations

Enumeration is one of the ways that Microsoft® DirectPlay® provides information to applications. Enumerations are used to collect data associated with a number of similar elements. For instance, you can use an enumeration to obtain information about each player in a session. To perform an enumeration, an application queries DirectPlay for a particular type of information, and DirectPlay returns a data structure for each related element, typically as an array of structures.

Most applications will need to perform at least one and often several enumeration operations. Each DirectPlay interface supports a different set of enumerations. Thus the details will vary from application to application. The following is a list of available enumerations, along with the interfaces that support each type of enumeration.

  • Session hosts (IDirectPlay8Peer, IDirectPlay8Client)
  • Service providers (IDirectPlay8Peer, IDirectPlay8Client, IDirectPlay8Server)
  • Players (IDirectPlay8Peer, IDirectPlay8Server)
  • Groups (IDirectPlay8Peer, IDirectPlay8Server)
  • Group members (IDirectPlay8Peer, IDirectPlay8Server)
  • Local programs (IDirectPlay8LobbyClient)

For more information, see Implementing a DirectPlay Enumeration.


Implementing a DirectPlay Enumeration

Most Microsoft® DirectPlay® enumerations follow a standard pattern: call the appropriate enumeration method, and examine the returned data array. The exception to this pattern is host enumerations, which are discussed separately.

Before you can call the method to obtain the data, you must allocate enough memory to contain the returned data block. However, you typically do not know, in advance, how large that array will be. Allocating a large enough block of memory to hold any conceivable array will work, but is inefficient. Instead DirectPlay is allows you query for the required array size, and then repeat the query to obtain the structure itself.

The following procedure outlines how to enumerate the members of a group in a peer-to-peer game. The same general procedure is followed by all other types of enumeration, except for host enumerations. Because enumerations are often used to obtain a snapshot of information that might be changing, you should perform enumerations in a loop until you are successful.

  1. Call IDirectPlay8Peer::EnumGroupMembers. This method returns an integer array in the prgdpnid parameter that contains the ID of each player in the group. The pcdpnid parameter is used to indicate the number of elements in the array. Set the pcdpnid parameter to 0 to request the appropriate value. Set prgdpnid to NULL.
  2. When the method returns, pcdpnid will point to the number of elements that will be in the array.
  3. Allocate your array using the returned pcdpnid value, and assign the array to the prgdpnid parameter.
  4. Set pcdpnid to the value that was returned in the first method call.
  5. Call IDirectPlay8Peer::EnumGroupMembers again.
  6. When the method returns the second time, check the return value. If successful, the method will return S_OK, and the array will contain the player's IDs.
  7. If the method returns DPNERR_BUFFERTOOSMALL again, the number of players has increased since the previous method call. Return to step three and use the new pcdpnid value to increase the array size. Be careful not to leak memory.

In some cases, the method returns an array of structures. In that case, you follow the same procedure, but the value returned from the first method call gives you the size of the array in bytes, instead of the number of elements in the array. Refer to the individual method references for details.

For more information, see Enumerating Hosts.


Enumerating Hosts

One way to arrange a session is to have session hosts advertise themselves as available. This type of session is referred to as a broadcast session. Peers or clients can look for a game to join by enumerating the available hosts, selecting one, and then join the game by sending a connection request. See Peer-to-Peer Sessions or Client/Server Sessions for a detailed discussion.

Unlike other enumerations, the information needed to respond to a request for available hosts is not stored on the local computer. Instead, a client or peer must broadcast a request, for instance on their local subnet, and wait for available hosts to respond. Hosts, on the other hand, must wait for these requests, and then respond appropriately. There are thus two slightly different procedures, depending on whether you are a potential session member, or a session host.

The following procedure illustrates how enumerate the available hosts for a peer-to-peer session. The procedure for a client/server session is essentially the same. IDirectPlay8Peer::EnumHosts is the method that starts the enumeration. The key parameters to set are pApplicationDesc, pdpaddrDeviceinfo, and pdpaddrHost.

  1. Assign the GUID of the game you are interested in playing to the guidApplication member of the DPN_APPLICATION_DESC structure and assign the structure pointer to the pApplicationDesc parameter.
  2. Create an address object for your device and assign its pointer to pdpaddrDeviceinfo. This object contains the information needed to make a network connection.
  3. To query a specific computer for available hosts, create a host address object for that computer and assign its pointer to pdpaddrHost. If you set this parameter to NULL, Microsoft® DirectPlay® will create an address object from the information contained in pdpaddrDeviceinfo. See DirectPlay Addressing for further discussion of address objects. If you are using an IP or IPX service provider, the query will then normally be broadcast to your local subnet. If you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag, the service provider may display a dialog box to the user to request address information.
  4. Call IDirectPlay8Peer::EnumHosts.
  5. Your callback message handler will then receive a series of DPN_MSGID_ENUM_HOSTS_RESPONSE messages, one for each host that responds.
    1. Examine the information returned to your message handler, select a session, and ask to join it by calling IDirectPlay8Peer::Connect.

If you want to be the host of a broadcast session, advertise yourself as available, and wait for queries or connection requests. The following procedure applies to peer-to-peer hosts, but is essentially similar to the procedure for client/server hosts.

  1. Call IDirectPlay8Peer::SetPeerInfo to specify the static settings for your player.
  2. Specify the configuration of the game by assigning values the DPN_APPLICATION_DESC structure.
  3. Call IDirectPlay8Peer::Host to advertise yourself as a potential host. Set the pdnAppDesc parameter to the DPN_APPLICATION_DESC structure defined in the previous step.
  4. Wait for enumeration requests. They will take the form of a DPN_MSGID_ENUM_HOSTS_QUERY message sent to your callback message handler. If you wish to respond to the enumeration request, fill in the DPN_APPLICATION_DESC and return S_OK. The peer will receive a DPN_MSGID_ENUM_HOSTS_RESPONSE message with the information.
  5. If the peer decides that they would like to join your session, you will receive a DPN_MSGID_INDICATE_CONNECT message.

See the Peer-to-Peer Sessions and Client/Server Sessions sections for further discussion of how to arrange and launch a game.


Using Player Context Values

Most applications will want to associate some data with each player. However, when you receive a message that is associated to a player, you need some way to access that data quickly. Player context values are designed to provide you with an efficient way to access your player data.

Note Only the IDirectPlay8Peer and IDirectPlay8Server interfaces use player context values. They are not needed for the IDirectPlay8Client interface because clients use this interface to communicate only with the server, not other clients.

  • Defining a Player Context Value
  • Managing Player Context Data


Defining a Player Context Value

To user player context values, you need to have a block of data on your system for each player, typically in the form of a structure. A player context value is normally an index into an array of pointers to the various players' data blocks. When you receive a message from a player, there is no need for time-consuming operations such as searching for the player's ID in a table. The index contained in the player context value allows you to quickly obtain the necessary pointer.

You define a player context value when you handle the DPN_MSGID_CREATE_PLAYER message that notifies you that a player has been added to the game. Host's can also define a player context value when they handle the DPN_MSGID_INDICATE_CONNECT message. That player context value will be set in the subsequent DPN_MSGID_CREATE_PLAYER message. When the host processes that message, it has the option of changing the player context value. To create a player context value:

  • Allocate a structure to hold the player's data.
  • Add the structure pointer to your player data array.
  • Assign the index of that pointer to the pvPlayerContext member of the message's DPNMSG_CREATE_PLAYER structure.

Microsoft® DirectPlay® does not specify how you should obtain the data to populate the structure. Each game is responsible for handling that issue in its own way.

Note The only place you can define a player context value is in a DPN_MSGID_CREATE_PLAYER or DPN_MSGID_INDICATE_CONNECT message handler. Once the DPN_MSGID_CREATE_PLAYER message handler returns, the player context value is set. For each subsequent message associated with that player, the player context value will be the same value that was set by the DPN_MSGID_CREATE_PLAYER message handler. You can modify the contents of the associated data structure, but you cannot change the player context value itself.


Managing Player Context Data

While player context values are fairly straightforward to handle, there are a couple of issues that you need to be careful with.

The player context value provides you with a quick way to obtain a valid memory address that will presumably be accessed each time a message arrives. However, you must be careful that different parts of your application do not access the data at the same time. Microsoft® DirectPlay® serializes messages associated with a particular player, which guarantees that you will never be handling two messages from the same player at the same time. As long as you only access the data structure from your callback message handler, you can safely access the structure. However, most applications will need to access player data outside the message handler.

If your application accesses the data outside the callback message handler, you must prevent concurrent access by providing some sort of global mechanism to lock the structure. Even if your application does not require such locking in the early stages of development, you should assume that locking will eventually be required, and build it in from the beginning. If your player context values that are indexes into an array, you should also make sure that you read and update that array safely.

Don't deallocate a player's data structure prematurely. When a player leaves the game, you will normally want to deallocate their data structure and free the associated memory. However, be careful about deallocating the structure as soon as you receive a DPN_MSGID_DESTROY_PLAYER message. If your application accesses that structure outside the callback message handler, that data may still be in use when the message arrives. If you simply deallocate the structure as soon as the message arrives, you may cause other parts of your application to fail.

To avoid prematurely deallocating the structure, you should not only provide an application-level locking mechanism, you should also implement some sort of reference counting. Increment this reference count when you create the structure, and every time you use it. Decrement the reference count every time you have finished with the structure, including in your DPN_MSGID_DESTROY_PLAYER message handler. As long as the reference count is non-zero, some part of your application is accessing the structure. Do not deallocate the structure until the reference count drops to zero.


Implementing a Lobby Client

A lobby client is an application that resides on a user's computer. It typically serves as a link between a game application on the user's computer and a lobby server on a remote computer. However, lobby clients can also function as stand-alone applications. For instance, they can be used to arrange a game session among the users of a particular LAN subnet.

Lobby clients typically consist of three primary components that handle the following tasks:

  • Communicating with the outside world, either a lobby server or other lobby clients.
  • Communicating with the user, typically through a graphical user interface (GUI).
  • Communicating with Microsoft® DirectPlay®.

DirectPlay does not specify how the first two items should be implemented. Lobby client vendors should use whatever approach is suitable to their product. What DirectPlay provides is a standard API that a lobby client can use to communicate with DirectPlay, and through DirectPlay with the user's lobbyable game applications.

This section discusses the following essential details of lobby client implementation.

  • Initializing a Lobby Client
  • Launching a Lobbied Application
  • Implementing a Lobby Client Message Handler
  • Communicating with a Lobbied Application
  • Closing Down a Lobby Client

See the LobbyClient sample application for a fully implemented example of a simple lobby client.


Initializing a Lobby Client

Lobby clients are either launched by a lobby server or directly by a user. Once a lobby client is launched, it must be initialized before it can launch an application. Initialization involves the following tasks.

  • Call CoCreateInstance to create a lobby client object (CLSID_DirectPlay8LobbyClient). Use the riid parameter to request a IDirectPlay8LobbyClient interface (IID_IDirectPlay8LobbyClient).
  • Call the lobby client's IDirectPlay8LobbyClient::Initialize method. Pass the method a pointer to your lobby client's callback message handler.
  • Use the IDirectPlay8LobbyClient::EnumLocalPrograms method to enumerate the lobbyable applications on the user's system.

The first two steps create the lobby client object, and set up a communication link between that object and your lobby client. The final step determines what lobbyable applications are available on the user's system. You need this information in order to launch the selected application.

The following code sample illustrates how to enumerate local applications. It is a simplified version of the EnumRegisteredApplications function in the SDK's LobbyClient sample. Error handling and dialog-box-related code has been deleted for clarity. See the LobbyClient sample in the SDK for the complete code.

HRESULT EnumRegisteredApplications()
{
    HRESULT hr;
    DWORD   dwSize     = 0;
    DWORD   dwPrograms = 0;
    DWORD   iProgram;
    BYTE*   pData   = NULL;

//g_pLobbyClient is a pointer to an IDirectPlay8LobbyClient interface
//Start with a NULL data buffer. The required buffer size is
//returned through dwSize.
  hr = g_pLobbyClient->EnumLocalPrograms( NULL, pData, &dwSize, &dwPrograms, 0 );

  if( dwSize == 0 )
  {
//No registered applications.
  }
//Set the data buffer to the appropriate size
  pData = new BYTE[dwSize];
  hr = g_pLobbyClient->EnumLocalPrograms( NULL, pData, &dwSize, &dwPrograms, 0 )

//Cast the returned data to the appropriate structure type
  DPL_APPLICATION_INFO* pAppInfo = (DPL_APPLICATION_INFO*) pData;

//Enumerate the names of the registered applications
  for( iProgram=0; iProgram<dwPrograms; iProgram++ )
  {
    TCHAR strAppName[MAX_PATH];
    DXUtil_ConvertWideStringToGeneric( strAppName, pAppInfo->pwszApplicationName );

  }
  SAFE_DELETE_ARRAY( pData );
  return S_OK;
}

You should store the application GUIDs of the registered applications because you need them to launch the application.

Depending on the design of your lobby client, you may also want to do one or more of the following tasks.

  • Perform any initialization that is not related to Microsoft® DirectPlay®, such as establishing a link with the lobby server.
  • Create a DirectPlay peer or DirectPlay client object (CLSID_DirectPlay8Peer or CLSID_DirectPlay8Client, respectively).
  • Use the peer or client object's enumeration methods to enumerate available service providers, adapters, and so on.


Launching a Lobbied Application

Once the user has selected an application, and your lobby client has verified that it has been registered on the user's system, you can launch the application. To do so, call IDirectPlay8LobbyClient::ConnectApplication. The first parameter is a DPL_CONNECT_INFO structure that contains a variety of information needed to launch the application including the following:

  • The GUID that identifies the application.
  • The connection settings, including the user's Microsoft® DirectPlay® address. See DirectPlay Addressing for a discussion of DirectPlay addresses.
  • Whether the application will be a host.

The IDirectPlay8LobbyClient::ConnectApplication method returns an application handle that is used to identify the application in all further communication. Once the application has launched and the connection successfully established, your message handler receives a DPL_MESSAGE_CONNECT message.

Note Your message handler may receive the DPL_MESSAGE_CONNECT before the IDirectPlay8LobbyClient::ConnectApplication method has confirmed the connection by returning a success code. Your message handler should be prepared to handle the message even if the method has not yet returned.


Implementing a Lobby Client Message Handler

The message handler is a callback function that is used by the lobby client object to communicate with the lobby client. The lobby client message handler has three parameters that pass in the following information.

  • A message ID that indicates the message type.
  • A pointer to a message data block. You must cast this parameter to the structure that is used by the particular message.
  • A pointer to an optional application-defined user-context data block.

The user context value is defined by the lobby client when it calls IDirectPlay8LobbyClient::Initialize. It can be used for such purposes as differentiating between messages that are sent from different objects. See PFNDPNMESSAGEHANDLER for a complete description the message handler function.

Your message handler must be able to handle the following five lobby client-specific messages.

  • DPL_MESSAGE_CONNECT
  • DPL_MESSAGE_CONNECTION_SETTINGS
  • DPL_MESSAGE_DISCONNECT
  • DPL_MESSAGE_RECEIVE
  • DPL_MESSAGE_SESSION_STATUS

Most of these messages are generated by the lobby client object in response to changes in the game status, or when the lobby client requests information. The exception is DPL_MESSAGE_RECEIVE. This message is used to pass data directly from the game application to the lobby client.

Note Microsoft® DirectPlay® message handlers must be written to work properly in a multithreaded environment, or your application may not function well.

DPL_MSGID_CONNECT

This message is sent by the lobby client following the launch of a lobbyable application. The message indicates that the application has been successfully connected. The associated DPL_MESSAGE_CONNECT structure holds a variety of information, including:

  • A connection ID. Use this ID when your lobby client needs to send data to the application with IDirectPlay8LobbyClient::Send, or release the connection with IDirectPlay8LobbyClient::ReleaseApplication.
  • Lobby connection data.
  • An optional connection context value.

DPL_MSGID_CONNECTION_SETTINGS

This message is sent by DirectPlay whenever an associated lobbyable application calls its IDirectPlay8LobbiedApplication::SetConnectionSettings method to modify the session connections. The associated DPL_MESSAGE_CONNECTION_SETTINGS structure contains the updated connection information.

DPL_MSGID_DISCONNECT

This message is sent when the lobbyable application disconnects from the session by calling IDirectPlay8LobbiedApplication::Close. Your lobby client application should delete the connection from its list and free any data that is associated with the application.

DPL_MSGID_RECEIVE

This message enables an application to pass data to the lobby client. DirectPlay passes the data block from the application to the lobby client in a DPL_MESSAGE_RECEIVE structure. It is up to the lobby client to process the data.

DPL_MSGID_SESSION_STATUS

This message is sent by DirectPlay whenever one of the following six changes in the session's status occurs.

  • The session is connected.
  • The session could not connect.
  • The session has been disconnected.
  • The session has been terminated.
  • The session host has migrated.
  • This computer has become the session host.

The type of status change is indicated by the value of the dwStatus field in the associated DPL_MESSAGE_SESSION_STATUS structure.

For more information, see A Sample Lobby Client Message Handler.


A Sample Lobby Client Message Handler

The following code is a simplified version of the message handler from the SDK's LobbyClient sample. Error handling code has been removed for clarity. See the sample for a complete version.

HRESULT WINAPI DirectPlayLobbyMessageHandler( PVOID pvUserContext,
                                              DWORD dwMessageId,
                                              PVOID pMsgBuffer )
{
  switch( dwMessageId )
  {
    case DPL_MSGID_DISCONNECT:
    {
      PDPL_MESSAGE_DISCONNECT pDisconnectMsg;
      pDisconnectMsg = (PDPL_MESSAGE_DISCONNECT)pMsgBuffer;

      // Free any data associated with the application and
      // Remove the connection from the list
      break;
    }
    case DPL_MSGID_RECEIVE:
    {
      PDPL_MESSAGE_RECEIVE pReceiveMsg;
      pReceiveMsg = (PDPL_MESSAGE_RECEIVE)pMsgBuffer;

      // The lobby application sent data. Process the data and
      // Respond appropriately
      break;
    }
    case DPL_MSGID_SESSION_STATUS:
    {
      PDPL_MESSAGE_SESSION_STATUS pStatusMsg;
      pStatusMsg = (PDPL_MESSAGE_SESSION_STATUS)pMsgBuffer;

      switch( pStatusMsg->dwStatus )
      {
        case DPLSESSION_CONNECTED: //Session connected
          break;
        case DPLSESSION_COULDNOTCONNECT: //Session could not connect
          break;
        case DPLSESSION_DISCONNECTED: //Session disconnected
          break;
        case DPLSESSION_TERMINATED: //Session terminated
          break;
        case DPLSESSION_HOSTMIGRATED: //Host migrated
          break;
        case DPLSESSION_HOSTMIGRATEDHERE: //Host migrated here
          break;
      }
      case DPL_MSGID_CONNECTION_SETTINGS:
      {
        PDPL_MESSAGE_CONNECTION_SETTINGS pConnectionStatusMsg;
        pConnectionStatusMsg = (PDPL_MESSAGE_CONNECTION_SETTINGS)pMsgBuffer;
        // The application has changed the connection settings.
        break;
      }
  }
  return S_OK;
}


Communicating with a Lobbied Application

Much of the lobby client's interaction with an associated application is indirect. The lobby client does something that affects the application, and Microsoft® DirectPlay® sends an appropriate message, and vice versa. For instance, if the lobby client changes the connection settings, DirectPlay notifies the application and provides the new settings. However, the IDirectPlay8LobbyClient::Send method enables the lobby client to send a message directly to the application. DirectPlay passes the data to the application without modification. It is the responsibility of the application to process that data.

The lobbied application can also send data directly to the lobby client. The data is passed to the lobby client's message handler with a DPL_MSGID_RECEIVE message. DirectPlay passes the data to the lobby client without modification. It is up to the lobby client to process the data.


Closing Down a Lobby Client

When you are ready to close the session, disconnect the application by calling IDirectPlay8LobbyClient::ReleaseApplication. The application receives a DPL_MSGID_DISCONNECT message.

After releasing the application, perform any cleanup that is necessary, and close the session by calling IDirectPlay8LobbyClient::Close. You should then free the lobby client object by calling IDirectPlay8LobbyClient::Release.


Implementing a Lobbyable Application

A lobbyable application must be designed to work properly with a lobby client. While a lobby client can launch any application, only lobby-launched applications can receive messages from Microsoft® DirectPlay® and from the lobby client. To be lobby launched, an application must be appropriately registered, and it must be able to use a DirectPlay lobbied application object to communicate with DirectPlay and the lobby client.

This section discusses how to implement lobbyable applications.

  • Registering a Lobbyable Application
  • Handling Lobby Launching
  • Implementing a Lobbied Application Callback Message Handler
  • Communicating with a Lobby Client
  • Closing Down a Lobbied Application


Registering a Lobbyable Application

A lobbyable application must be registered before it can be lobby launched. This registration needs to be done only once and is typically handled by the application's setup procedure. Do not attempt to modify the registry directly to register an application as lobbyable. Instead, do the following:

  • Call CoCreateInstance to create a lobbied application object (CLSID_DirectPlay8LobbiedApplication). Set the riid parameter to IID_IDirectPlay8LobbiedApplication to request an IDirectPlay8LobbiedApplication interface.
  • Call IDirectPlay8LobbiedApplication::RegisterProgram.This method takes the information and creates appropriate registry keys and values.

You must provide IDirectPlay8LobbiedApplication::RegisterProgram with a variety of information, including the following:

  • A GUID that is used to identify the application.
  • A friendly name for the application.
  • The location and name of the application's executable file.
  • The location and name of an optional launcher application.
  • Any command-line arguments that need to be passed to the executable file when it is launched.

Instead of launching the game application, Microsoft® DirectPlay® launches a launcher application. The launcher application then launches the game. Launcher applications can be used, for example, as an anti-piracy measure.

To unregister a registered program, call IDirectPlay8LobbiedApplication::UnregisterProgram. This method removes the registry entries created by IDirectPlay8LobbiedApplication::RegisterProgram.


Handling Lobby Launching

The first thing your lobbyable application should do when it is launched is to create and initialize a Microsoft® DirectPlay® lobbied application object. To do this, perform the following tasks.

  • Call CoCreateInstance to create a lobbied application object (CLSID_DirectPlay8LobbiedApplication). Set the riid parameter to IID_IDirectPlay8LobbiedApplication to request an IDirectPlay8LobbiedApplication interface.
  • Call IDirectPlay8LobbiedApplication::Initialize to initialize the lobbied application object. Pass the object a pointer to your lobbied application callback message handler.

Next, determine whether your application was lobby launched. If so, your application needs to set up a communication channel with DirectPlay so that you can effectively manage the session. Do the following to detect whether your application was lobby launched.

  • When the IDirectPlay8LobbiedApplication::Initialize method returns, examine the pdpnhConnection parameter. If this parameter is set to a valid connection handle, the game was lobby launched.
  • Examine the DPL_MSGID_CONNECT message you receive through your message handler. This message carries with it a variety of information, including the ID that you use to send messages to the lobby client.

Note Your message handler may receive the DPL_MSGID_CONNECT message before the IDirectPlay8LobbiedApplication::Initialize method returns. Your message handler should be prepared to handle the message appropriately.

If your application was not lobby launched, you can indicate that your application is available to lobby clients for connection by calling IDirectPlay8LobbiedApplication::SetAppAvailable. This method is typically called when the application has been launched by the user. However, it can also be used if the user has closed one session but the application is still running and available for another session. In either case, your message handler receives a DPL_MSGID_CONNECT message when the lobby client connects your application to a session.

The following sample code illustrates how to initialize a lobbied application, and how to detect whether an application was lobby launched. It is a simplified version of the InitDirectPlay function used by the SDK's SimplePeer application. Refer to that sample application for the complete code. In particular, error-handling code has been deleted for clarity. The g_bWasLobbyLaunched variable is a global variable that is set to TRUE if the application was lobby launched.

HRESULT InitDirectPlay()
{
  DPNHANDLE hLobbyLaunchedConnection = NULL;
  HRESULT hr;

  // Create IDirectPlay8LobbiedApplication
  hr = CoCreateInstance( CLSID_DirectPlay8LobbiedApplication, NULL,
                         CLSCTX_INPROC_SERVER,
                         IID_IDirectPlay8LobbiedApplication,
                         (LPVOID*) &g_pLobbiedApp );

  // Initialize IDirectPlay8LobbiedApplication
  hr = g_pLobbiedApp->Initialize( NULL,
                                  DirectPlayLobbyMessageHandler,
                                  &hLobbyLaunchedConnection,
                                  0 );
  //Check for a valid connection handle. If it is non-NULL
  //the application was lobby launched.
  g_bWasLobbyLaunched = ( hLobbyLaunchedConnection != NULL );

  return S_OK;
}


Implementing a Lobbied Application Callback Message Handler

The message handler is a callback function that is used by the lobbied application object to communicate with a lobbied application. The lobbied application message handler has three parameters that pass in the following information.

  • A message ID that indicates the message type.
  • A pointer to a message data block. You must cast this parameter to the structure that is used by the particular message.
  • A pointer to an optional application-defined user-context data block.

The user context value is defined by the lobby client when it calls IDirectPlay8LobbyClient::Initialize. It can be used for such purposes as differentiating between messages that are sent from different objects. See PFNDPNMESSAGEHANDLER for a complete description the message handler function.

Your message handler must to be able to handle the following four lobbied application-specific messages.

  • DPL_MESSAGE_CONNECT
  • DPL_MESSAGE_CONNECTION_SETTINGS
  • DPL_MESSAGE_DISCONNECT
  • DPL_MESSAGE_RECEIVE

Most of these messages are generated by the lobbied application object in response to changes in the connection, or when the lobbied application requests connection information. The exception is DPL_MESSAGE_RECEIVE. This message is used to pass data directly from the lobby client to the game application.

Note Microsoft® DirectPlay® message handlers must be written to work properly in a multithreaded environment, or your application may not function well.

DPL_MSGID_CONNECT

This message is sent by the lobbied application object when the lobby client calls IDirectPlay8LobbyClient::ConnectApplication to connect an application to a session. The associated DPL_MESSAGE_CONNECT structure includes the following information.

  • A connection ID. Use this ID when your application needs to send data to the lobby client with IDirectPlay8LobbiedApplication::Send, or update the session status with IDirectPlay8LobbiedApplication::UpdateStatus.
  • Lobby connection data.
  • An optional connection context value.

DPL_MSGID_CONNECTION_SETTINGS

DirectPlay sends this message whenever an associated lobby client calls its IDirectPlay8LobbyClient::SetConnectionSettings method to modify the session connections. The associated DPL_MESSAGE_CONNECTION_SETTINGS structure contains the updated connection information.

DPL_MSGID_DISCONNECT

This message is sent when the lobby client disconnects the application from the session by calling IDirectPlay8LobbyClient::ReleaseApplication. Your application should delete the connection from its list, and free any data that is associated with the session.

DPL_MSGID_RECEIVE

This message enables a lobby client to pass data to an application. DirectPlay passes the data block from the lobby client to the application in a DPL_MESSAGE_RECEIVE structure. It is up to the application to process the data.

For more information, see A Sample Lobbied Application Message Handler.


A Sample Lobbied Application Message Handler

The following code is a simplified version of the message handler from the SDK's SimplePeer sample. Error handling code has been removed for clarity. See the sample for a complete version.

HRESULT WINAPI DirectPlayLobbyMessageHandler( PVOID pvUserContext,
                                              DWORD dwMessageId,
                                              PVOID pMsgBuffer )
{
  switch( dwMessageId )
  {
    case DPL_MSGID_CONNECT:
    {
      PDPL_MESSAGE_CONNECT pConnectMsg;
      pConnectMsg = (PDPL_MESSAGE_CONNECT)pMsgBuffer;

      // Connected. Start the session.
      break;
    }
    case DPL_MSGID_DISCONNECT:
    {
      PDPL_MESSAGE_DISCONNECT pDisconnectMsg;
      pDisconnectMsg = (PDPL_MESSAGE_DISCONNECT)pMsgBuffer;

      // Disconnected. Free any data associated with
      // the lobby client.
      break;
    }
    case DPL_MSGID_RECEIVE:
    {
      PDPL_MESSAGE_RECEIVE pReceiveMsg;
      pReceiveMsg = (PDPL_MESSAGE_RECEIVE)pMsgBuffer;

      // The lobby client sent data. Process the data and
      // respond appropriately.
      break;
    }

    case DPL_MSGID_CONNECTION_SETTINGS:
    {
      PDPL_MESSAGE_CONNECTION_SETTINGS pConnectionStatusMsg;
      pConnectionStatusMsg = (PDPL_MESSAGE_CONNECTION_SETTINGS)pMsgBuffer;

      // The lobby client has changed the connection settings.
      break;
    }
  }
  return S_OK;
}


Communicating with a Lobby Client

Much of the lobbied application's interaction with an associated lobby client is indirect. The application does something that affects the lobby client, Microsoft® DirectPlay® sends an appropriate message, and vice versa. For instance, if the application changes the connection settings, DirectPlay notifies the lobby client, and provides the new settings. However, there are two methods that provide information directly to the lobby client: IDirectPlay8LobbiedApplication::UpdateStatus and IDirectPlay8LobbiedApplication::Send.

You must notify the lobby client when any of the following changes in the game status take place.

  • The session is connected.
  • The session could not connect.
  • The session has been disconnected.
  • The session has been terminated.
  • The session host has migrated.
  • This computer has become the session host.

To notify the lobby client of one of these status changes, call IDirectPlayLobbiedApplication::UpdateStatus, and set the dwStatus parameter to the appropriate value. The lobby client receives a DPL_MSGID_SESSION_STATUS message to notify it of the status change.

The IDirectPlay8LobbiedApplication::Send method enables the application to send a message directly to the lobby client. DirectPlay passes the data to the lobby client without modification. It is the responsibility of the lobby client to process that data.

The lobby client can also send data directly to the application. The data is passed to the lobby client's message handler with a DPL_MSGID_RECEIVE message. DirectPlay passes the data to the application without modification. The lobby client must process the data.


Closing Down a Lobbied Application

To close a session, call IDirectPlay8LobbiedApplication::Close. The lobby client receives a DPL_MSGID_DISCONNECT message to notify it of the disconnection. If you want to keep the application running and connect to another session, indicate that your application is available by calling IDirectPlay8LobbiedApplication::SetAppAvailable. Otherwise, call IDirectPlay8LobbiedApplication::Release to free the lobbied application object, and shut the application down.


Monitoring DirectPlay Network Traffic with Netmon

During game development, you may find it useful to monitor Microsoft® DirectPlay® network traffic, especially when trying understand bugs. The network monitor (netmon) is a standard utility for analyzing network traffic. DirectPlay includes a set of parsers, that allow you to use netmon to analyze four components of DirectPlay messaging: the service provider layer, the transport layer, the session layer, and the voice layer.

  • How Netmon Works With DirectPlay
  • Configuring Netmon for DirectPlay
  • Capturing DirectPlay Network Traffic
  • Tips for Using Netmon with DirectPlay


How Netmon Works With DirectPlay

The Microsoft® DirectPlay® protocol stack has three basic layers.

  • The voice and session layers share the top level of the stack. Normal messaging passes through the session layer, and voice-related messaging passes through the voice layer.
  • The transport layer is the middle of the stack. Both voice and session traffic passes through this layer, which is responsible for such tasks as fragmentation and reassembly of messages and retransmission of lost packets.
  • The service provider layer is at the bottom of the stack. All messaging is handled by this layer, which is responsible for communicating with the network. For example, for TCP/IP networking, the service provider uses the Winsock API to communicate with the network stack. Netmon can only parse network traffic that is carried on an IP or IPX service provider.

By installing the DirectPlay parsers, you can use Netmon to analyze the network traffic as it passes through any of these four layers. You can see all DirectPlay traffic by selecting the service provider parser. However, by selecting one of the higher level parsers, you can filter out traffic that may not be of interest.

With the transport layer parser, you see all voice and session traffic, but not low-level traffic such as connection handshaking. Be aware that the transport layer breaks messages that are longer than the network's Maximum Transfer Unit (MTU) into one or more fragments.

The session and voice layer parsers allow you to analyze session and voice-related traffic separately. Both of these parsers are aware of fragmentation, and notify the user, but cannot parse fragmented packets.


Configuring Netmon for DirectPlay

If you have a Windows 2000 Server system, Netmon is already installed. For Windows 2000 Professional, you must purchase a copy of Systems Management Server (SMS). See the Netmon documentation for a general discussion of how to use Netmon. To configure Netmon to handle Microsoft® DirectPlay® traffic:

  1. Copy Dp8parser.dll to the appropriate folder. The Netmon root folder is normally installed in the \Winnt\System32 folder. If you have installed SMS, the root folder will be called NetMonFull. For Windows 2000 Server, the root folder will be called NetMon. Depending on which version of Netmon you are using, copy the parser DLL to either the ...\NetMonFull\Parsers, or ...\NetMon\parsers folder.
  2. Start Netmon
  3. Set the adapter to capture from (Capture|Networks...|Local Computer). Be sure to choose the adapter with the "Dial-up Connection" property set to FALSE.

You are now ready to start capturing traffic.


Capturing DirectPlay Network Traffic

To start the capture process, click the Start Capture button on the Netmon toolbar to open the capture view. Initially, you will see all the traffic that is passing through your adapter. You can filter that raw traffic stream to focus on only those packets that are of interest. By installing the Microsoft® DirectPlay® parsers, you essentially add four DirectPlay-oriented filters to Netmon that allow you to filter everything but DirectPlay traffic from your capture view.

To select a filter:

  1. Click the Edit Display Filter button on the Netmon toolbar.
  2. Double-click "Protocol == Any".
  3. Click "Disable All".
  4. Under "Disabled Protocols", double-click DPLAYSESSION, DPLAYSP, DPLAYTRANSPORT, and DPLAYVOICE.

Click OK twice to return to the capture view, and you are ready to start viewing DirectPlay traffic.

You can also apply a filter to the capture process itself, rather than to the capture view. This allows you, for instance, to capture only IP packets with specified source and destination ports. See the Netmon documentation for details.


Tips for Using Netmon with DirectPlay

Here are a few tips to using Netmon with Microsoft® DirectPlay®:

  • By default, Netmon only captures 1MB of the most recent traffic. You will probably want to increase this value to at least 10-20 MB.
  • Netmon doesn't stream to the hard drive, so all you can see is what is in the capture buffer. To stream captured traffic to a hard drive, you will need to implement your own capturer. See MSDN for details.
  • By default, DirectPlay parsing uses the [2302,2400]U{6073} port/socket range to filter IP and IPX packets. If you are using non-standard port/socket ranges, you can have the parsers recognize user-defined port/socket values. To do so, add two DWORD values, MinUserPort and MaxUserPort, to the \HKEY_CURRENT_USER\Software\Microsoft\DirectX\DirectPlay\Parsers registry key. This allows you to extend the port/socket range to [2302,2400]U{6073}U[MinUserPort,MaxUserPort].
  • Because the DirectPlay and RTP protocols are both layered on top of the UDP protocol, their parsers may conflict. You should disable the RTP parser when analyzing DirectPlay traffic, and vice versa.


Implementing a Callback Function in DirectPlay and DirectPlay Voice

Microsoft® DirectPlay® and DirectPlay Voice both require you to implement and register several callback functions to handle the events fired by DirectPlay. DirectPlay is multithreaded and will fire multiple events concurrently. Therefore, in order to correctly and reliably access data in DirectPlay callbacks, you are required to implement a method of multithreading synchronization. This is known as making your callback re-entrant or threadsafe.

Callback Function Structure

The structure of the callback follows standard Microsoft Windows Win32 API programming guidelines.

HRESULT WINAPI Callback(
  PVOID pvUserContext,
  DWORD dwMessageType,
  PVOID pMessage );

pvUserContext is the a context value you supply when you register the callback function with DirectPlay. If you pass this value to DirectPlay when you register your callback, the context value will be returned when DirectPlay invokes your callback.

dwMessageType is one of the ID values passed to your callback by DirectPlay.

pMessage will contain the message passed by DirectPlay.

Registering Your Callback

Microsoft DirectPlay networking callback functions are of type PFNDPNMESSAGEHANDLER. Depending on the type of networking session, you register the address of your callback function with IDirectPlay8Peer::Initialize, IDirectPlay8Client::Initialize, or IDirectPlay8Server::Initialize. If you are registering a DirectPlay voice callback function, register the address of your callback with IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize, depending on the type of DirectPlay voice session you wish to create.

The following code snippet demonstrates how to register a callback function with the IDirectPlay8Peer interface.

HRESULT WINAPI Callback(PVOID, DWORD, PVOID);
IDirectPlay8Peer* pdp8Peer;

// Get the server interface
hr = CoCreateInstance( CLSID_DirectPlay8Peer, ...)
...

// Register the callback
hr = pdp8Peer->Initialize(NULL, Callback, 0);


Implementing a DirectPlay Networking Callback Using Critical Section Objects

Microsoft® DirectPlay® networking and voice callback are multithreaded. Therefore, in order to correctly and reliably access data in DirectPlay callbacks, you are required to implement a method of multithreading synchronization.

Currently, there are three methods of synchronizing mulithreaded callback data.

  • Mutex Objects
  • Semaphore Objects
  • Critical Section Objects

The DirectPlay voice samples that ship with the DirectX 8.0 SDK demonstrate synchronization using Critical Section Objects, and the following topics will also demonstrate how Critical Section Objects are used. If you wish to implement a Mutex or Semaphore Object, these topics are discussed in the Microsoft Platform Software Development Kit (SDK) as well as in many reference books. Implementing any of these synchronization methods requires an expert knowledge level in these areas due of the level of complexity and difficulty in debugging should any issues arise.

CRITICAL_SECTION g_csPlayerContext;
InitializeCriticalSection(&g_csPlayerContext);

Next, implement the DirectPlay message callback handler.

HRESULT WINAPI DirectPlayMessageHandler( PVOID pvUserContext,
                                         DWORD dwMessageId,
                                         PVOID pMsgBuffer )
{
    switch( dwMessageId )
    {
        case DPN_MSGID_CREATE_PLAYER:
        {
             EnterCriticalSection( &g_csPlayerContext );
             //callback is now locked
             //perform operation on player data
             LeaveCriticalSection( &g_csPlayerContext );
        }
    }
}

Finally, during application exit, ensure that you call the DeleteCriticalSection function to free the memory associated with your critical section object.

DeleteCriticalSection( &g_csPlayerContext );


Using the DirectPlay DPNSVR Application

Microsoft Windows does not allow multiple processes to share a single IP or IPX port. Each application that wants to act as a communication host must use a separate port. This restriction creates several issues, especially when doing such tasks as enumerating running games:

  • Avoiding port conflicts. You must choose a port that does not conflict with other applications.
  • Managing multiple communications hosts on a single system. Each instance of a host must use a different port. Client applications then have to determine which port a particular host is using.
  • Avoiding ports that are already in use. If your preferred port is in use, your application must be able to use another port.

The DPNSVR application addresses these issues by acting as a forwarding service for enumeration requests. When an application begins hosting, it informs DPNSVR which port it is running on. DPNSVR listens on a well-known port, and forwards any enumeration requests to all Microsoft® DirectPlay® hosts on the system. Responses to enumeration requests contain the actual port that the host is connected to. DPNSVR offers developers the following advantages:

  • You can write generic enumeration routines that enumerate all the games running on a particular system.
  • You can use DirectPlay to select the host's port. Client applications can use the services of DPNSVR to enumerate the running games on a well-known port, and the responses will contain the actual port that the host is connected to.
  • You do not have to allow for the situation where your application does not get the port it requests.
  • You do not need to be concerned about conflicts with other applications on the system

While most applications will want to use the services of DPNSVR, there are some circumstances where you may want to disable it. Two examples are:

  • You know what port you want to use, and only one instance of your application will be running on the computer.
  • You want to restrict the ability of players to enumerate your session. If you disable DPNSVR, only those players that know the port that your host is connected to will be able to enumerate your host.

For more information, see How to Use DPNSVR.


How to Use DPNSVR

To determine whether DPNSVR is supported by your service provider, call the GetSPCaps methods supported by the IDirectPlay8Peer, IDirectPlay8Client, or IDirectPlay8Server. If the service provider supports DPNSVR, the DPNSPCAPS_SUPPORTSDPNSRV flag will be set in the dwFlags member or the returned DPN_SP_CAPS structure. Only IP and IPX service providers currently support DPNSVR.

Using DPNSVR requires no special effort, because it is selected by default. If you do not want enumeration requests forwarded to your host, you must explicitly disable DPNSVR by setting the DPNSESSION_NODPNSVR flag in the dwFlags member of the DPN_APPLICATION_DESC structure.

Note Applications can always enumerate your host if they know the port that it is running on, even if the DPNSESSION_NODPNSVR flag is set.


Implementing Capture Focus

The concept of capturing focus is integral to creating lobbyable game applications and lobby applications with Microsoft® DirectPlay® Voice support. If your game application does not properly implement focus capture, it is possible that voice communication will not function if your game was launched from a lobby application.

Before the DirectPlay voice session is created, there are several initialization steps to be completed:

// Create a DirectPlay voice client interface
hr = CoCreateInstance( CLSID_DirectPlayVoiceClient,
                       NULL,
                       CLSCTX_INPROC_SERVER,
                       IID_IDirectPlayVoiceClient,
                       (LPVOID*) &m_pVoiceClient )

// Set the hwndAppWindow member to the window that will have
// focus when your game application is running
DVSOUNDDEVICECONFIG dvSoundDeviceConfig;

dvSoundDeviceConfig.hwndAppWindow = hWnd;
// Set dwFlags to DVSOUNDCONFIG_STRICTFOCUS so that only application
// windows that are in the foreground will gain focus
dvSoundDeviceConfig.dwFlags = DVSOUNDCONFIG_STRICTFOCUS;

// Connect to the voice session
hr = m_pVoiceClient->Connect( &dvSoundDeviceConfig,
                              pdvClientConfig,
                              DVFLAGS_SYNC )

Once the application is connected to the session, message will be received by your DirectPlay voice callback. The two messages which you must handle to properly implement capture focus are DVMSGID_GAINFOCUS and DVMSGID_LOSTFOCUS.

HRESULT CALLBACK DirectPlayVoiceClientMessageHandler(
                     LPVOID lpvUserContext,
                     DWORD dwMessageType,
                     LPVOID lpMessage )
{
    switch( dwMessageType )
    {
     case DVMSGID_GAINFOCUS:
        // the game application has gained focus in the system
            break;
        case DVMSGID_LOSTFOCUS:
        // the game application has lost focus in the system
            break;
    }
  ...
}

If recording is muted, focus will be lost. DirectPlay voice will send a DVMSGID_LOSTFOCUS message to your callback. When recording is unmuted, focus will be regained, with the exception that applications using DVSOUNDCONFIG_STRICTFOCUS will only gain focus is the application window is in the foreground.

DVCLIENTCONFIG dvClientConfig;
dvClientConfig.dwFlags = DVCLIENTCONFIG_RECORDMUTE;

// Mute recording, DVMSGID_LOSTFOCUS is sent to DirectPlay
// voice callback function
m_pVoiceClient->SetClientConfig(dvClientConfig);


DirectPlay C++ Samples

The following sample applications demonstrate the use and capabilities of the Microsoft® DirectPlay® application programming interface for the C++ programming language. Refer to the Readme.txt file in each sample folder for details. All sample folders can be found under the SDK root directory, typically C:\mssdk.

  • AddressOverride
  • ChatPeer
  • DataRelay
  • LobbyClient
  • Maze
  • SimpleClientServer
  • SimplePeer
  • StagedPeer
  • VoiceClientServer
  • VoiceConnect
  • VoiceGroup
  • VoicePosition


AddressOverride

AddressOverride demonstrates how to override the Microsoft® DirectPlay® addressing in order to host or connect to another session on the network.

Path
(SDK Root)\Samples\Multimedia\DirectPlay\AddressOverride


ChatPeer

The ChatPeer sample is similar in form to SimplePeer. Once a player hosts or connects to a session, the players can chat with each other by passing text strings.

Path

(SDK Root)\Samples\Multimedia\DirectPlay\ChatPeer


DataRelay

The DataRelay sample is similar to SimplePeer but differs by sending a single target (or everyone) a packet of data with options specified in the dialog box's UI.

Path

(SDK Root)\Samples\Multimedia\DirectPlay\DataRelay


LobbyClient

LobbyClient is a simple lobby client application. It displays all registered Microsoft® DirectPlay® applications on the local system. It enables the user to launch one or more of these applications using a chosen service provider. A launched lobbied application may be told to either join or host a game.

Path

(SDK Root)\Samples\Multimedia\DirectPlay\LobbyClient


Maze

The maze sample is a Microsoft® DirectPlay® client/server application. The client comes in two flavors: a console-based version and a D3D client. The D3D client can optionally be run as screen saver by copying Mazeclient.exe to your \winnt\system32\ folder and renaming it Mazeclient.scr. Doing so will make it a screen saver that can be detected by the display control panel application.

Path

(SDK Root)\Samples\Multimedia\DirectPlay\Maze


SimpleClientServer

The SimpleClientServer sample is a simple client/server application.

Path

(SDK Root)\Samples\Multimedia\DirectPlay\SimpleClientServer


SimplePeer

The SimplePeer sample illustrates how to implement a simple peer-to-peer application. After joining or creating a session, the game begins immediately. Other players may join the session in progress at any time.

Path

(SDK Root)\Samples\Multimedia\DirectPlay\SimplePeer


StagedPeer

The StagedPeer sample connects players together with two dialog boxes that prompt users on the connection settings needed to join or create a session. After the user connects to a session, the sample displays a multiplayer stage that enables all players connected to the same session to chat. Players can start a new game when everyone is ready and the host decides to begin. The host may reject players or close player slots.

Path

(SDK Root)\Samples\Multimedia\DirectPlay\StagedPeer


VoiceClientServer

The VoiceClientServer sample is a simple Microsoft® DirectPlay® voice-based client/server application.

Path

(SDK Root)\Samples\Multimedia\DirectPlay\VoiceClientServer


VoiceConnect

The VoiceConnect sample shows how to network other players to start a Microsoft® DirectPlay® Voice chat session. After joining or creating a session, the players may use a microphone to talk to one other. Other players may join the session in progress at any time.

Path

(SDK Root)\Samples\Multimedia\DirectPlay\VoiceConnect


VoiceGroup

The VoiceGroup sample shows how use Microsoft® DirectPlay® voice to enable users to talk to a specific group of players.

Path

(SDK Root)\Samples\Multimedia\DirectPlay\VoiceGroup


VoicePosition

The VoicePosition sample shows how use Microsoft® DirectPlay® Voice with 3-D positioning. The sample uses a simple 2-D grid to represent a playing field. Players can move around the playing field to hear the effects of 3-D spatialization.

Path

(SDK Root)\Samples\Multimedia\DirectPlay\VoicePosition


DirectPlay C/C++ Reference

Reference material for the Microsoft® DirectPlay® C/C++ application programming interface is divided into the following categories.

  • Interfaces
  • Functions
  • Callback Functions
  • System Messages
  • Structures
  • Return Values


Interfaces

This section contains references for methods of the following Microsoft® DirectPlay® interfaces.

  • IDirectPlay8Peer
  • IDirectPlay8Client
  • IDirectPlay8Server
  • IDirectPlayVoiceClient
  • IDirectPlayVoiceServer
  • IDirectPlayVoiceTest
  • IDirectPlay8LobbyClient
  • IDirectPlay8LobbiedApplication
  • IDirectPlay8Address
  • IDirectPlay8AddressIP


IDirectPlay8Peer

Applications use the methods of the IDirectPlay8Peer interface to create a peer-to-peer Microsoft® DirectPlay® session.

The methods of the IDirectPlay8Peer interface can be organized into the following groups.

Session Management | Close
 | Connect
 | EnumHosts
 | EnumServiceProviders
 | GetApplicationDesc
 | GetCaps
 | GetConnectionInfo
 | GetSPCaps
 | Host
 | SetApplicationDesc
 | SetCaps
 | SetSPCaps
 | TerminateSession
Message Management | GetSendQueueInfo
 | Initialize
 | ReturnBuffer
 | SendTo
Player Management | DestroyPeer
 | GetPeerInfo
 | SetPeerInfo
 | GetPlayerContext
Group Management | AddPlayerToGroup
 | CreateGroup
 | DestroyGroup
 | EnumPlayersAndGroups
 | EnumGroupMembers
 | GetGroupContext
 | GetGroupInfo
 | RemovePlayerFromGroup
 | SetGroupInfo
Miscellaneous | CancelAsyncOperation
 | GetLocalHostAddresses
 | GetPeerAddress
 | RegisterLobby

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::AddPlayerToGroup

Adds a peer to a group.

When this method is called, all peers connected to the application receive a DPN_MSGID_ADD_PLAYER_TO_GROUP message.

HRESULT AddPlayerToGroup(
const DPNID idGroup,
const DPNID idClient,
PVOID const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

idGroup
Variable of type DPNID that specifies the identifier of the group to add the peer to.
idClient
Variable of type DPNID that specifies the identifier of the peer that is added to the group.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message. This parameter is optional and may be set to NULL.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNADDPLAYERTOGROUP_SYNC
Causes the method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method runs asynchronously and usually returns DPNSUCCESS_PENDING. It may also return one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP

Remarks

Any peer can add itself or another peer to an existing group. Once the peer is successfully added to the group, all messages sent to the group are also sent to the peer.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::CancelAsyncOperation

Cancels asynchronous requests. For instance, several methods of the IDirectPlay8Peer interface run asynchronously by default. Depending on the situation, you might want to cancel requests before they are processed. All the methods of this interface that can run asynchronously return an hAsyncHandle parameter.

Specific requests are canceled by passing the hAsyncHandle of the request in this method's hAsyncHandle parameter. You can cancel all pending asynchronous operations by calling this method, specifying NULL in the hAsyncHandle parameter, and specifying DPNCANCEL_ALL_OPERATIONS in the dwFlags parameter. If a specific handle is provided to this method, no flags should be set.

HRESULT CancelAsyncOperation(
const DPNHANDLE hAsyncHandle,
const DWORD dwFlags
);

Parameters

hAsyncHandle
Handle of the asynchronous operation to stop. You receive this handle when you call one of several methods that support asynchronous operations. This value can be set to NULL to stop all operations or a particular type of asynchronous request. If you specify a particular handle for the request, the dwFlags parameter must be 0.
dwFlags
Flag that specifies which asynchronous request is to be canceled. One of the following flags can be set.
DPNCANCEL_ENUM
Cancel all asynchronous IDirectPlay8Peer::EnumHosts requests. A single EnumHosts request can be canceled by specifying the handle returned from the EnumHosts method.
DPNCANCEL_CONNECT
Cancel an asynchronous IDirectPlay8Peer::Connect request.
DPNCANCEL_SEND
Cancel an asynchronous IDirectPlay8Peer::SendTo request.
DPNCANCEL_ALL_OPERATIONS
Cancel all asynchronous Connect, Send, and SentTo operations.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_CANNOTCANCEL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDHANDLE

Remarks

You can use this method to cancel an asynchronous operation for the IDirectPlay8Peer::Connect, IDirectPlay8Peer::SendTo, and IDirectPlay8Peer::EnumHosts methods. Microsoft® DirectPlay® 8.0 does not support cancellation of other asynchronous operations.

You can cancel a send request by providing the handle returned from the IDirectPlay8Peer::SendTo method. A DPN_MSGID_SEND_COMPLETE, or DPN_CONNECT_COMPLETE system message is still posted to the application's message handler for each asynchronous send request that is sent without the DPNSEND_NOCOMPLETE flag set. Send requests that are canceled by this method return DPNERR_USERCANCEL in the hResultCode member of the DPN_MSGID_SEND_COMPLETE message.

If you set the DPNCANCEL_ALL_OPERATIONS, DPN_CANCELCONNECT, DPN_CANCELSEND, or DPNCANCEL_ENUM flags in dwFlags, DirectPlay will attempt to cancel all matching operations. This method will return an error if any attempted cancellation fails, even though some cancellations may have been successful.

Note The completion message might not arrive until after this method returns. Do not assume that the operation has been terminated until you have received a DPN_MSGID_SEND_COMPLETE, DPN_MSGID_CONNECT_COMPLETE, or DPN_MSGID_ASYNC_OP_COMPLETE message.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::Close

Closes the open connection with a session. This method must be called on any object successfully initialized with IDirectPlay8Peer::Initialize.

HRESULT Close(
const DWORD dwFlags
);

Parameters

dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_UNINITIALIZED

Remarks

This method will cancel any operations still outstanding. It will block until all callback indications on other threads have returned.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::Connect

Establishes the connection to all the peers in a peer-to-peer session. Once a connection is established, the communication channel on the interface is open and the application should expect messages to arrive immediately. No messages can be sent by way of the IDirectPlay8Peer::SendTo method until the connection has completed.

Before this method is called, you can obtain application descriptions and the addresses of the associated hosts by calling IDirectPlay8Peer::EnumHosts. The EnumHosts method returns a DPN_APPLICATION_DESC structure for each currently hosted application. The structure describes the application, including the instance GUID of the application.

If this method is called asynchronously (which is the default choice) and returns DPNSUCCESS_PENDING, when the connection completes a DPN_MSGID_CONNECT_COMPLETE message is sent to the application's message handler.

HRESULT Connect(
const DPN_APPLICATION_DESC *const pdnAppDesc,
IDirectPlay8Address *const pHostAddr,
IDirectPlay8Address *const pDeviceInfo,
const DPN_SECURITY_DESC *const pdnSecurity,
const DPN_SECURITY_CREDENTIALS *const pdnCredentials,
const void *const pvUserConnectData,
const DWORD dwUserConnectDataSize,
void *const pvPlayerContext,
void *const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

pdnAppDesc
Pointer to a DPN_APPLICATION_DESC structure that describes the application. Only some of the members of this structure are used by this method. The only members that you must set are dwSize and guidApplication. You can also set guidInstance, pwszPassword, and dwFlags.
pHostAddr
Pointer to an IDirectPlay8Address interface that specifies the addressing information to use to connect to the computer that is hosting.
pDeviceInfo
Pointer to an IDirectPlay8Address interface that specifies the network adapter (for example, NIC, modem, and so on) to use to connect to the server.
pdnSecurity
Reserved. Must be NULL.
pdnCredentials
Reserved. Must be NULL.
pvUserConnectData
Pointer to application-specific data provided to the host or server to further validate the connection. This data is sent to the DPN_MSGID_INDICATE_CONNECT message in the pvUserConnectData member. This parameter is optional and may be set to NULL if no additional connection validation is provided by the user code.
dwUserConnectDataSize
Variable of type DWORD that specifies the size of the data contained in the pvUserConnectData parameter.
pvPlayerContext
Pointer to the context value of the local player. This value is preset when the local computer handles the DPN_MSGID_CREATE_PLAYER message. This parameter is optional and may be set to NULL.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_CONNECT_COMPLETE system message. This parameter is optional and may be set to NULL.
phAsyncHandle
A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Peer::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNCONNECT_SYNC flag in dwFlags.
dwFlags
Flag that describes the connection mode. You can set the following flags.
DPNCONNECT_OKTOQUERYFORADDRESSING
Setting this flag will display a standard Microsoft® DirectPlay® dialog box, which queries the user for more information if not enough information is passed in this method.
DPNCONNECT_SYNC
Process the connection request synchronously. Your message handler still receives a DPN_MSGID_CONNECT_COMPLETE message, so that you can process any connection reply data from the host. You will receive this message before IDirectPlay8Peer::Connect returns.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method runs asynchronously and normally returns DPNSUCCESS_PENDING. It may also return one of the following error values.

DPNERR_HOSTREJECTEDCONNECTION
DPNERR_INVALIDAPPLICATION
DPNERR_INVALIDDEVICEADDRESS
DPNERR_INVALIDFLAGS
DPNERR_INVALIDHOSTADDRESS
DPNERR_INVALIDINSTANCE
DPNERR_INVALIDINTERFACE
DPNERR_INVALIDPASSWORD
DPNERR_NOCONNECTION
DPNERR_NOTHOST
DPNERR_SESSIONFULL

Remarks

Although multiple enumerations can be run concurrently and can be run across the duration of a connection, only one connection is allowed per interface. To establish a connection to more than one application, you must create another interface.

If this method is called asynchronously (which is the default choice), when the connection completes a DPN_MSGID_CONNECT_COMPLETE message is posted to the application's message handler. If this method returns an error, no completion message is posted.

When this method is called, a DPN_MSGID_INDICATE_CONNECT message is posted to the host's message handler. When the host handles this message, it can specify connection reply data that the player will receive with the DPN_MSGID_CONNECT_COMPLETE message. If the host accepts the connection, the connection reply data might contain custom startup information. If the connection was rejected, the connection reply data might contain an explanation of the rejection.

You must call IDirectPlay8Peer::Close to end the connection to the host.

Note If you set the DPNCONNECT_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider may attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box, or your application will lock.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::CreateGroup

Creates a group in the current session. A group is a logical collection of players.

Note Multicasting is not supported for this release.

When this method is called, all peers connected to the application receive a DPN_MSGID_CREATE_GROUP system message.

HRESULT CreateGroup(
const DPN_GROUP_INFO *const pdpnGroupInfo,
VOID *const pvGroupContext,
VOID *const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

pdpnGroupInfo
Pointer to a DPN_GROUP_INFO structure that contains the group description.
pvGroupContext
Pointer to the group's context value. This value is preset when the local application's message handler receives the associated DPN_MSGID_CREATE_GROUP message. This parameter is optional and may be set to NULL.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message. This parameter is optional and may be set to NULL.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNCREATEGROUP_SYNC
Causes the method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return the following error value.

DPNERR_INVALIDFLAGS

Remarks

Microsoft® DirectPlay® does not maintain hierarchical groups because these can easily be implemented with flat groups and expeditious use of the group data.

All peers receive a DPN_MSGID_CREATE_GROUP message when this method is called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::DestroyPeer

Deletes a peer from the session.

HRESULT DestroyPeer(
const DPNID dpnidClient,
void *const pDestroyInfo,
const DWORD dwDestroyInfoSize,
const DWORD dwFlags
);

Parameters

dpnidClient
Variable of type DPNID that specifies the identifier of the peer to delete.
pDestroyInfo
Pointer to a value that describes additional delete data information.
dwDestroyInfoSize
Variable of type DWORD that specifies the size of the data contained in the pDestroyInfo parameter.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDPLAYER
DPNERR_NOTHOST

Remarks

A player can only be deleted by the session host. The deleted player will be notified through a DPN_MSGID_TERMINATE_SESSION message. The structure associated with the message will contain the data passed through the pDestroyInfo parameter. If any other session member calls this method, it will fail, and return DPNERR_NOTHOST.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::DestroyGroup

Deletes a group created by the IDirectPlay8Peer::CreateGroup method. This method can be called by any peer in the session.

HRESULT DestroyGroup(
const DPNID idGroup,
PVOID const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

idGroup
Variable of type DPNID that should be set to the identifier of the group to be deleted.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message. This parameter is optional and may be set to NULL.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNDESTROYGROUP_SYNC
Causes the method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::EnumPlayersAndGroups

Retrieves a list of all the player and/or group identifiers for the session.

HRESULT EnumPlayersAndGroups(
DPNID *const prgdpnid,
DWORD *const pcdpnid,
const DWORD dwFlags
);

Parameters

prgdpnid
Pointer to an array that will be filled with the session's group and/or player identifiers.
pcdpnid
Pointer to a variable of type DWORD that specifies the number of identifiers that can be contained in the buffer pointed to by prgdpnid. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the number of entries that are required.
dwFlags
Flag that describes enumeration behavior. You can set one or both of the following flags.
DPNENUM_PLAYERS
Return a list of player identifiers.
DPNENUM_GROUPS
Return a list of group identifiers.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDFLAGS

Remarks

Because group and player information changes frequently, the required buffer size returned may change between subsequent calls. Check and reallocate the buffer until the method succeeds.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::EnumGroupMembers

Retrieves a list of all players in a group.

HRESULT EnumGroupMembers(
const DPNID dpnid,
DPNID *const prgdpnid,
DWORD *const pcdpnid,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the group that contains the players to enumerate.
prgdpnid
Pointer to an array that will contain the identifiers of the group's players.
pcdpnid
Pointer to a variable of type DWORD that specifies the number of identifiers that can be contained in the buffer pointed to by dpnid. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the number of entries that are required.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP

Remarks

Because player information changes frequently, the required buffer size returned may change between subsequent calls. Check and reallocate the buffer until the method succeeds.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::EnumHosts

Enumerates applications that host Microsoft® DirectPlay® games. When an application is found that meets the enumeration criteria, the application's message handler is called with a DPN_MSGID_ENUM_HOSTS_RESPONSE system message. The message contains a DPN_APPLICATION_DESC structure describing the applications found.

Any number of enumerations can be run concurrently. The pvUserContext value is provided in the message handler to help differentiate replies to different enumerations.

Because of the variation in the number of ways enumeration can happen, an application should not attempt to specify dwEnumPeriod, dwRetryInterval, or dwTimeOut unless the application has some specific media knowledge.

The default enumeration count and timeout values will cause EnumHosts to complete within a reasonable amount of time. These values are set by the service provider, and can be obtained by calling IDirectPlay8Peer::GetSPCaps. Asynchronous enumerations can be stopped at any time by calling IDirectPlay8Peer::CancelAsyncOperation and either passing the handle returned in the pAsyncHandle parameter or setting the DPENUM_CANCEL flag in the dwFlags parameter. An enumeration can also be stopped by returning anything other than S_OK from the message handler.

HRESULT EnumHosts(
PDPN_APPLICATION_DESC const pApplicationDesc,
IDirectPlay8Address *const pdpaddrHost,
IDirectPlay8Address *const pdpaddrDeviceInfo,
PVOID const pvUserEnumData,
const DWORD dwUserEnumDataSize,
const DWORD dwEnumCount,
const DWORD dwRetryInterval,
const DWORD dwTimeOut,
PVOID const pvUserContext,
HANDLE *const pAsyncHandle
const DWORD dwFlags,
);

Parameters

pApplicationDesc
Pointer to a DPN_APPLICATION_DESC structure that specifies which application hosts to enumerate. You must set the pApplicationDesc.dwSize member to the appropriate value. To reduce the number of responses, set pApplicationDesc.guidApplication to the GUID of the application to be found. If this member is not set, the search will include all applications.
pdpaddrHost
Pointer to an IDirectPlay8Address object that specifies the address of the computer that is hosting the application. If you specify NULL, DirectPlay will create an address. By default, DirectPlay will create the address from the pdpaddrDeviceInfo parameter. If you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in dwFlags, the user can be queried for address information.
pdpaddrDeviceInfo
Pointer to an IDirectPlay8Address object that specifies the service provider and local device settings to use when enumerating.
pvUserEnumData
Pointer to a block of data that is sent in the enumeration request to the host. The size of the data is limited depending on the network type. Call IDirectPlay8Peer::GetSPCaps to obtain the exact value.
dwUserEnumDataSize
Variable of type DWORD that specifies the size of the data pointed at in the pvUserEnumData parameter.
dwEnumCount
Value specifying how many times that the enumeration data will be sent. Set this parameter to zero to use the default value. You can obtain the default value for dwEnumCount by calling IDirectPlay8Peer::GetSPCaps. If dwEnumCount is set to INFINITE, the enumeration will continue until canceled.
dwRetryInterval
Value specifying how many milliseconds between enumeration retries. Set this parameter to zero to use the default value. You can obtain the default value for dwRetryInterval by calling IDirectPlay8Peer::GetSPCaps.
dwTimeOut
Variable of type DWORD that specifies the number of milliseconds that DirectPlay will wait for replies after the last enumeration is sent. Set this parameter to zero to use the default value. You can obtain the default value for dwTimeOut by calling IDirectPlay8Peer::GetSPCaps. If INFINITE is specified, the enumeration continues until it is canceled.
pvUserContext
Context that is provided in the peer's message handler when it is called with responses to the enumeration. This can be useful to differentiate replies from concurrent enumerations.
pAsyncHandle
A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Peer::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNENUMHOSTS_SYNC flag in dwFlags.
dwFlags
The following flags can be set.
DPNENUMHOSTS_SYNC
Causes the method to process synchronously.
DPNENUMHOSTS_OKTOQUERYFORADDRESSING
Setting this flag will display a standard DirectPlay® dialog box, which queries the user for more information if not enough information is passed in this method.
DPNENUMHOSTS_NOBROADCASTFALLBACK
If the service provider supports broadcasting, setting this flag will disable the broadcast capabilities. Check to see if broadcasting is supported by examining the DPN_SP_CAPS structure before setting this flag.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_INVALIDDEVICEADDRESS
DPNERR_INVALIDFLAGS
DPNERR_INVALIDHOSTADDRESS
DPNERR_INVALIDPARAM
DPNERR_ENUMQUERYTOOLARGE

Remarks

If you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider may attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box, or your application will lock.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::EnumServiceProviders

Enumerates all the registered service providers available to the application.

HRESULT EnumServiceProviders(
const GUID *const pguidServiceProvider,
const GUID *const pguidApplication,
const DPN_SERVICE_PROVIDER_INFO *const pSPInfoBuffer,
DWORD *const pcbEnumData,
DWORD *const pcReturned
constDWORD dwFlags,
);

Parameters

pguidServiceProvider
Pointer to a variable of type GUID that specifies a service provider. This optional parameter forces the enumeration of subdevices for the specified service provider. You should normally set this value to NULL, to enumerate all available service providers.
pguidApplication
Pointer to a variable of type GUID that specifies an application. If a pointer is passed in this parameter, only service providers who can be connected by the application are enumerated. You can also pass NULL to enumerate all the registered service providers for the system.
pSPInfoBuffer
Pointer to an array of DPN_SERVICE_PROVIDER_INFO structures that will be filled with service provider information.
pcbEnumData
Pointer to DWORD that is filled with the size of the pEnumData buffer if the buffer is too small.
pcReturned
Pointer to a variable of type DWORD that specifies the number of DPN_SERVICE_PROVIDER_INFO structures returned in the pcbEnumData array.
dwFlags
The following flag can be specified.
DPNENUMSERVICEPROVIDERS_ALL
Enumerates all the registered service providers for the system, including those that are not available to the application or do not have devices installed.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDPARAM

Remarks

Call this method initially by specifying NULL in the pguidServiceProvider parameter to determine the base service providers available to the system. Specific devices for a service provider can then be obtained by passing a pointer to a service provider GUID in the pguidServiceProvider. This is useful, for example, when using the Modem Connection for Microsoft® DirectPlay® service provider. You can choose different modems for dialing out and specific modems for hosting.

If the pcbEnumData buffer is not big enough to hold the requested service provider information, the method returns DPNERR_BUFFERTOOSMALL and the pcbEnumData parameter contains the required buffer size. Typically, the best strategy is to call the method once with a zero-length buffer to determine the required size. Then call it again with the appropriate-sized buffer.

Normally, this method will return only those service providers that can be used by the application. For example, if the IPX networking protocol is not installed, DirectPlay will not return the IPX service provider. To have DirectPlay return all service providers, even those that cannot be used by the application, set the DPNENUMSERVICEPROVIDERS_ALL flag in dwFlags.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::GetApplicationDesc

Retrieves the full application description for the connected application.

HRESULT GetApplicationDesc(
DPN_APPLICATION_DESC *const pAppDescBuffer,
DWORD *const pcbDataSize,
const DWORD dwFlags
);

Parameters

pAppDescBuffer
Pointer to a DPN_APPLICATION_DESC structure where the application description data is to be written. Set this parameter to NULL to request only the size of data. If pAppDescBuffer is not set to NULL, you must set the pAppDescBuffer.dwSize member to an appropriate value. The pcbDataSize parameter is set to the size required to hold the data.
pcbDataSize
Pointer to a variable of type DWORD that is initialized to the size of the buffer before calling this method. After the method returns, this parameter is set to the size, in bytes, of the session data. If the buffer is too small, this method returns the DPNERR_BUFFERTOOSMALL error value, and this parameter is set to the buffer size required. If this parameter is NULL, the method returns DPNERR_INVALIDPARAM.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_NOCONNECTION

Remarks

Call this method initially by passing NULL in the pAppDescBuffer parameter to obtain the size of the required buffer. When you call the method a second time to fill the buffer, be sure to set the structures dwSize member to the appropriate value.

The returned DPN_APPLICATION_DESC structure will have the guidInstance, guidApplication, and pwszSessionName members set. It will not contain information about other clients that are connected to the session. That information, if available, can be obtained only from the server application. In particular, the dwCurrentPlayers member will always be set to 0.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::GetCaps

Retrieves the DPN_CAPS structure for the current interface.

HRESULT GetCaps(
DPN_CAPS *const pdpnCaps,
const DWORD dwFlags
);

Parameters

pdpnCaps
Pointer to a DPN_CAPS structure to receive caps information. You must set the dwSize member of this structure to an appropriate value.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

A successful call to Initialize must be made before this method can be called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::GetConnectionInfo

Retrieves statistical information about the connection between the local application and the specified remote player.

HRESULT GetConnectionInfo(
const DPNID dpnidEndPoint,
DPN_CONNECTION_INFO *const pdnConnectInfo,
const DWORD dwFlags
);

Parameters

dpnidEndPoint
The DPNID of the remote player whose connection information will be retrieved.
pdnConnectInfo
Pointer to a DPN_CONNECTION_INFO structure to retrieve information about the specified connection. The dwSize member of this structure must be set to the size of a DPN_CONNECTION_INFO structure.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED
DPNERR_INVALIDPLAYER

Remarks

This method can be called only after a successful Host or Connect call has completed.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::GetGroupContext

Retrieves the group context value for the specified group.

HRESULT GetGroupContext(
const DPNID dpnid,
PVOID *const ppvGroupContext,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the identifier of the group to retrieve context data for.
ppvGroupContext
Pointer to the context value of the group.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDPARAM

Remarks

Group context values are set by pointing the pvGroupContext member of the DPN_MSGID_CREATE_GROUP system message to the context value data.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::GetGroupInfo

Retrieves a block of data associated with a group, including the group name.

This method is typically called after a DPN_MSGID_GROUP_INFO system message is received indicating that the group data has been modified.

HRESULT GetGroupInfo(
const DPNID dpnid,
DPN_GROUP_INFO *const pdpnGroupInfo,
DWORD *const pdwSize,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the identifier of the group whose data block will be retrieved.
pdpnGroupInfo
Pointer to a DPN_GROUP_INFO structure that describes the group data. If pdwSize is not set to NULL, you must set pdpnGroupInfo.dwSize to the size of a DPN_GROUP_INFO structure.
pdwSize
Pointer to a variable of type DWORD that returns the size of the data in the pdpnGroupInfo parameter. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the required size.
dwFlags
Reserved. Set to 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP

Remarks

Microsoft® DirectPlay® returns the DPN_GROUP_INFO structure, and the pointers assigned to the structure's pwszName and pvData members in a contiguous buffer. If the two pointers were set, you must have allocated enough memory for the structure, plus the two pointers. The most robust way to use this method is to first call it with pdwSize set to NULL. When the method returns, pdwSize will point to the correct value. Use that value to allocate memory for your structure and call the method a second time to retrieve the information.

When the method returns, the dwInfoFlags member of the DPN_GROUP_INFO structure will always have the DPNINFO_DATA and DPNINFO_NAME flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Peer::SetGroupInfo, to notify DirectPlay which values have changed.

Transmission of nonstatic information should be handled with the IDirectPlay8Peer::SendTo method because of the high cost of using the IDirectPlay8Peer::SetGroupInfo method.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::GetLocalHostAddresses

Retrieves the local addresses being used to host the session.

HRESULT GetLocalHostAddresses(
IDirectPlay8Address **const prgpAddress,
DWORD *const pcAddress,
const DWORD dwFlags
);

Parameters

prgpAddress
A pointer to an array of IDirectPlay8Address objects that specify the local host addresses. You must release these objects when you no longer need them, or you will create memory leaks.
pcAddress
The maximum number of address objects that can be returned in the array pointed to by prgpAddress. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the required size.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED
DPNERR_NOTHOST

Remarks

The most robust way to use this method is to call it first with pcAddress set to 0. When the method returns, pcAddress will point to the correct value, and you can use that value to call the method a second time to retrieve the information.

If the caller is not the session host, the method returns DPNERR_NOTHOST. Use IDirectPlay8Peer::GetPeerAddress to retrieve the address of a remote player.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::GetPeerAddress

Retrieves the address for the specified player in the session.

HRESULT GetPeerAddress(
const DPNID dpnid,
IDirectPlay8Address **const pAddress,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID specifying the identification of the player.
pAddress
Address of a pointer to an IDirectPlay8Address object that specifies the address of the peer. You must release this object when you no longer need it.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPLAYER
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

Use IDirectPlay8Peer::GetLocalHostAddresses to retrieve addresses that can be used to connect to the session.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::GetPeerInfo

Retrieves peer information set for the specified peer.

HRESULT GetPeerInfo(
const DPNID dpnid,
DPN_PLAYER_INFO *const pdpnPlayerInfo,
DWORD *const pdwSize,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the identifier of the peer whose information will be retrieved.
pdpnPlayerInfo
Pointer to a DPN_PLAYER_INFO structure to fill with peer information. If pdwSize is not set to NULL, you must set pdpnPlayerInfo.dwSize to the size of a DPN_PLAYER_INFO structure.
pdwSize
Pointer to a variable of type DWORD that contains the size of the peer data returned in the pdpnPlayerInfo parameter. If the buffer is too small this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the size of the required buffer.
dwFlags
Reserved. Set to 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_INVALIDPLAYER

Remarks

Call this method after the peer receives a DPN_MSGID_PEER_INFO message from the application, which indicates a peer has updated their information.

Microsoft® DirectPlay® returns the DPN_PLAYER_INFO structure, and the pointers assigned to the structure's pwszName and pvData members in a contiguous buffer. If the two pointers were set, you must have allocated enough memory for the structure, plus the two pointers. The most robust way to use this method is to first call it with pdwSize set to NULL. When the method returns, pdwSize will point to the correct value. Use that value to allocate memory for the structure and call the method a second time to retrieve the information.

When the method returns, the dwInfoFlags member of the DPN_PLAYER_INFO structure will always have the DPNINFO_DATA and DPNINFO_NAME flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Peer::SetPeerInfo, to notify DirectPlay of which values have changed.

Transmission of nonstatic information should be handled with the IDirectPlay8Peer::SendTo method because of the high cost of using the IDirectPlay8Peer::SetPeerInfo method.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::GetPlayerContext

Retrieves the player context value for the specified peer.

HRESULT GetPlayerContext(
const DPNID dpnid,
PVOID *const ppvPlayerContext,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the identifier of the player to get context data for.
ppvPlayerContext
Pointer to the context data of the peer.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDPLAYER

Remarks

Player context values are set by pointing the pvPlayerContext member of the DPN_MSGID_CREATE_PLAYER system message to the context value data.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::GetSendQueueInfo

Used by the application to monitor the size of the send queue. Microsoft® DirectPlay® will not send messages faster than the receiving computer can process them. As a result, if the sending computer is sending faster than the receiver can receive, messages accumulate in the sender's queue. If the application registers that the send queue is growing too large, it should slow the rate that messages are sent.

HRESULT GetSendQueueInfo(
DWORD *const pdwNumMsgs,
DWORD *const pdwNumBytes,
const DWORD dwFlags
);

Parameters

dpnid
DPNID of the player to get send queue information for.
pdwNumMsgs
Pointer to a variable of type DWORD that contains the number of messages currently queued. This value is optional, and may be set to NULL.
pdwNumBytes
Pointer to a variable of type DWORD that specifies the total number of bytes of data of the messages currently queued. This value is optional, and may be set to NULL.
dwFlags
You may specify the DPNGETSENDQUEUEINFO_PRIORITY_NORMAL, DPNGETSENDQUEUEINFO_PRIORITY_HIGH, or DPNGETSENDQUEUEINFO_PRIORITY_LOW flag to inquire about specific messages of that priority.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM

Remarks

You cannot set both pdwNumMsgs and pdwNumBytes to NULL. At least one of them must be set to a valid pointer.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::GetSPCaps

Retrieves the DPN_SP_CAPS structure for the specified service provider.

HRESULT GetSPCaps(
const GUID *const pguidSP,
DPN_SP_CAPS *const pdpnSPCaps,
const DWORD dwFlags
);

Parameters

pguidSP
Pointer to a GUID specifying the service provider you want to get information about.
pdpnSPCaps
Pointer to a DPN_SP_CAPS structure to receive the information about the specified service provider. You must set the pdpnSPCaps.dwSize member of the structure.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

This method retrieves information about the specified service provider. A successful call to IDirectPlay8Peer::Initialize must be made before this method can be called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::Host

Creates a new peer-to-peer session, hosted by the local computer.

HRESULT Host(
const DPN_APPLICATION_DESC *const pdnAppDesc,
IDirectPlay8Address **const prgpDeviceInfo,
const DWORD cDeviceInfo,
const DPN_SECURITY_DESC *const pdpSecurity,
const DPN_SECURITY_CREDENTIALS *const pdpCredentials,
VOID *const pvPlayerContext,
const DWORD dwFlags
);

Parameters

pdnAppDesc
Pointer to a DPN_APPLICATION_DESC structure that describes the application.
prgpDeviceInfo
A pointer to an array of IDirectPlay8Address objects containing the device addresses that should be used to host the application. You must release these objects when you no longer need them.
cDeviceInfo
Variable of type DWORD that specifies the number of device address objects in the array pointed to by prgpDeviceInfo.
pdpSecurity
Reserved. Must be NULL.
pdpCredentials
Reserved. Must be NULL.
pvPlayerContext
Pointer to the context value of the local player. This value is preset when the local computer handles the DPN_MSGID_CREATE_PLAYER message. This parameter is optional and may be set to NULL.
dwFlags
The following flag can be specified.
DPNHOST_OKTOQUERYFORADDRESSING
Setting this flag will display a standard Microsoft® DirectPlay® dialog box, which queries the user for more information if not enough information is passed in this method.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_DATATOOLARGE
DPNERR_INVALIDPARAM
DPNERR_INVALIDDEVICEADDRESS

Remarks

If you set the DPNHOST_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider may attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box, or your application will lock.

The maximum size of the application data that you assign to the pvApplicationReservedData member of the DPN_APPLICATION_DESC structure is limited by the service provider's Maximum Transmission Unit. If your application data is too large, the method will fail and return DPNERR_DATATOOLARGE.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::Initialize

Registers an entry point in the peer's code that receives all the messages from the IDirectPlay8Peer interface and from remote peers. This method must be called before calling any other methods of this interface.

HRESULT Initialize(
PVOID const pvUserContext,
const PFNDPNMESSAGEHANDLER pfn,
const DWORD dwFlags
);

Parameters

pvUserContext
Pointer to the user-provided context value in calls to the message handler. A user-provided context value can be used to differentiate messages coming from multiple interfaces to a common message handler.
pfn
Pointer to a PFNDPNMESSAGEHANDLER callback function that is used to receive all messages from remote peers and indications of session changes from the IDirectPlay8Peer interface.
dwFlags
You may specify the following flag.
DPNINITIALIZE_DISABLEPARAMVAL
Passing this flag will disable parameter validation for the current object.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

Call this method first after using CoCreateInstance to obtain the IDirectPlay8Peer interface.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::RegisterLobby

Allows launched applications to automatically propagate game status to the lobby.

HRESULT RegisterLobby(
const DPNHANDLE dpnHandle,
IDirectPlay8LobbiedApplication *const pIDP8LobbiedApplication,
const DWORD dwFlags
);

Parameters

dpnHandle
The connection handle used when making the calls to IDirectPlay8LobbiedApplication::UpdateStatus.
pIDP8LobbiedApplication
Pointer to the IDirectPlay8LobbiedApplication object that specifies the application.
dwFlags
One of the following flags:
DPNLOBBY_REGISTER
Registers the lobby with the application.
DPNLOBBY_UNREGISTER
Unregisters the lobby with the application.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::RemovePlayerFromGroup

Removes a peer from a group.

When this method is called all peers connected to the application receive a DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message.

HRESULT RemovePlayerFromGroup(
const DPNID idGroup,
const DPNID idClient,
PVOID const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

idGroup
Variable of type DPNID that specifies the identifier of the group that the peer will be removed from.
idClient
Variable of type DPNID that specifies the identifier of the peer that will be removed from the group.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNREMOVEPLAYERFROMGROUP_SYNC
Causes the method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP
DPNERR_INVALIDPLAYER

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::ReturnBuffer

Retrieves message buffers provided to the application through the pReceiveData member of the DPN_MSGID_RECEIVE system message. If the user's message handler returns DPNSUCCESS_PENDING to the RECEIVE callback, Microsoft® DirectPlay® assumes that ownership of the buffer is transferred to the application, and neither frees nor modifies it until ownership is returned to DirectPlay through this call.

HRESULT ReturnBuffer(
const DPNHANDLE hBufferHandle,
const DWORD dwFlags
);

Parameters

hBufferHandle
Variable of type DPNHANDLE that specifies the buffer handle for the message. This is obtained in the hBufferHandle member of the DPN_MSGID_RECEIVE system message.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDHANDLE
DPNERR_INVALIDPARAM

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::SendTo

Transmits data to another peer or group within the session by sending a message to the appropriate message handlers. The message can be sent synchronously or asynchronously.

HRESULT SendTo(
const DPNID dpnid,
const DPN_BUFFER_DESC *const pBufferDesc,
const DWORD cBufferDesc,
const DWORD dwTimeOut,
void *const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

dpnid
Identifier of the peer or group that receives data. Set this parameter to DPNID_ALL_PLAYERS_GROUP to send a message to all players in the session.
pBufferDesc
Pointer to a DPN_BUFFER_DESC structure that contains the data to be sent.
cBufferDesc
The number of DPN_BUFFER_DESC structures pointed to by pBufferDesc. There can only be one buffer in this version of Microsoft® DirectPlay®.
dwTimeOut
Number of milliseconds to wait for the message to send. If the message has not been sent by the dwTimeOut value, the message is not sent. If you do not want a time out for message sends, set this parameter to 0.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_SEND_COMPLETE system message. This parameter is optional and may be set to NULL.
phAsyncHandle
A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Peer::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNSEND_SYNC flag in dwFlags.
dwFlags
Flags that describe send behavior. You can set one or more of the following flags.
DPNSEND_SYNC
Process the SendTo request synchronously.
DPNSEND_NOCOPY
Use the data in the DPN_BUFFER_DESC structure and do not make an internal copy. This may be a more efficient method of sending data. However, it is less robust because the sender might be able to modify message before the receiver has processed it. This flag cannot be combined with DPNSEND_NOCOMPLETE.
DPNSEND_NOCOMPLETE
Does not send the DPN_MSGID_SEND_COMPLETE to the message handler. This flag may not be used with DPNSEND_NOCOPY or DPNSEND_GUARANTEED. Additionally, when using this flag the pvAsyncContext must be NULL.
DPNSEND_COMPLETEONPROCESS
Sends the DPN_MSGID_SEND_COMPLETE to the message handler when this message has been delivered to the target and the target's message handler returns from indicating its reception. There is additional internal message overhead when this flag is set, and the message transmission process may become significantly slower. If you set this flag, DPNSEND_GUARANTEED must also be set.
DPNSEND_GUARANTEED
Sends the message by a guaranteed method of delivery.
DPNSEND_PRIORITY_HIGH
Sets the priority of the message to high. This flag cannot be used with DPNSEND_PRIORITY_LOW.
DPNSEND_PRIORITY_LOW
Sets the priority of the message to low. This flag cannot be used with DPNSEND_PRIORITY_HIGH.
DPNSEND_NONSEQUENTIAL
If this flag is set, the target application will receive the messages in the order that they arrive at the user's computer. If this flag is not set, messages are delivered sequentially, and will be received by the target application in the order that they were sent. Doing so may require buffering incoming messages until missing messages arrive.
DPNSEND_NOLOOPBACK
Suppresses the DPN_MSGID_RECEIVE system message to your message handler when you are sending to a group that includes the local player. For example, this flag is useful if you are broadcasting to the entire session.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_CONNECTIONLOST
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_INVALIDPLAYER
DPNERR_TIMEDOUT

Remarks

This method generates a DPN_MSGID_RECEIVE system message in the receiver's message handler. The data buffer is contained in the pReceiveData member of the associated structure.

Messages can have one of three priorities: low, normal, and high. To specify a low or high priority for the message, set the appropriate flag in dwFlags. If neither of the priority flags is set, the message will have normal priority. See Basic Networking for a discussion of send priorities.

When the SendTo request is completed, a DPN_MSGID_SEND_COMPLETE system message is normally posted to the sender's message handler. The success or failure of the request is contained in the hResultCode member of the associated structure. You can suppress send completions by setting the DPNSEND_NOCOMPLETE flag in dwFlags.

Send completions are typically posted on the source computer as soon as the message is sent. In other words, a send completion does not necessarily mean that the message has been processed on the target. It may still be in a queue. If you want to be certain that the message has been processed by the target, set the DPNSEND_COMPLETEONPROCESS flag in dwFlags. This flag ensures that the send completion will not be sent until the target's message handler has processed the message, and returned.

Note Do not assume that resources such as the data buffer will remain valid until the method has returned. If you call this method asynchronously, the DPN_MSGID_SEND_COMPLETE message may be received and processed by your message handler before the call has returned. If your message handler deallocates or otherwise invalidates a resource such as the data buffer, that resource may become invalid at any time after the method has been called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::SetApplicationDesc

Changes the settings for the application that is being hosted. Only some settings can be changed.

HRESULT SetApplicationDesc(
const DPN_APPLICATION_DESC *const pad,
const DWORD dwFlags
);

Parameters

pad
Pointer to a DPN_APPLICATION_DESC structure that describes the application settings to modify.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_DATATOOLARGE
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_NOTHOST

Remarks

You can use this method to modify only the following members of the DPN_APPLICATION_DESC structure:

  • dwMaxPlayers
  • pwszSessionName
  • pwszPassword
  • pvApplicationReservedData
  • dwApplicationReservedDataSize

The maximum size of the application data that you assign to the pvApplicationReservedData member of the DPN_APPLICATION_DESC structure is limited by the service provider's Maximum Transmission Unit. If your application data is too large, the method will fail and return DPNERR_DATATOOLARGE.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::SetCaps

Sets the DPN_CAPS structure for the current interface.

HRESULT SetCaps(
const DPN_CAPS *const pdpCaps,
const DWORD dwFlags
);

Parameters

pdpCaps
Pointer to a DPN_CAPS structure used to set the information about the current interface.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

This method sets parameters for the specified service provider. A successful call to Initialize must be made before this method can be called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::SetGroupInfo

Sets a block of data associated with a group, including the name of the group.

Calling this method generates a DPN_MSGID_GROUP_INFO message, which is sent to all the peers connected to the application.

HRESULT SetGroupInfo(
const DPNID dpnid,
DPN_GROUP_INFO *const pdpnGroupInfo,
PVOID const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the identifier of the group whose data block will be modified.
pdpnGroupInfo
Pointer to a DPN_GROUP_INFO structure that describes the group data to set. To change the values of the pwszName or pvData members, you must set the corresponding DPNINFO_NAME or DPNINFO_DATA flags in the dwInfoFlags member.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method:
DPNSETGROUPINFO_SYNC
Causes the method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP

Remarks

Transmission of nonstatic information should be handled with the IDirectPlay8Peer::SendTo method because of the high cost of using the IDirectPlay8Peer::SetGroupInfo method.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::SetPeerInfo

Sets the static settings of the local peer. Call this method before connecting to relay basic player information with the application. Once the peer successfully connects with the application, information set through this method can be retrieved by other players by calling the IDirectPlay8Peer::GetPeerInfo method.

HRESULT SetPeerInfo(
const DPN_PLAYER_INFO *const pdpnPlayerInfo,
PVOID const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

pdpnPlayerInfo
Pointer to a DPN_PLAYER_INFO structure that contains the peer information to set.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNSETPEERINFO_SYNC
Causes the method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and normally returns DPNSUCCESS_PENDING. It can also return one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_NOCONNECTION

Remarks

This method can be called at any time during the session.

Transmission of nonstatic information should be handled with the IDirectPlay8Peer::SendTo method because of the high cost of using the IDirectPlay8Peer::SetPeerInfo method.

You can modify the peer information with this method after connecting to the application. Calling this method after connection generates a DPN_MSGID_PEER_INFO system message to all players, informing them that data has been updated.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::SetSPCaps

Sets the DPN_SP_CAPS structure for the specified service provider.

HRESULT SetSPCaps(
const GUID *const pguidSP,
const DPN_SP_CAPS *const pdpSPCaps
);

Parameters

pguidSP
Pointer to a GUID specifying the service provider you want to set information about.
pdpSPCaps
Pointer to a DPN_SP_CAPS structure to set the information about the specified service provider.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

This method sets parameters for the specified service provider. A successful call to Initialize must be made before this method can be called. Currently only the dwNumThreads field can be set by this call, the dwFlags field must be 0.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Peer::TerminateSession

Terminates the current Microsoft® DirectPlay® session.

HRESULT TerminateSession(
void *const pvTerminateData,
const DWORD dwTerminateDataSize,
const DWORD dwFlags
);

Parameters

pvTerminateData
Pointer to termination data. This data is also sent in the pvTerminateData member of the DPN_MSGID_TERMINATE_SESSION system message.
dwTerminateDataSize
Size of data contained in the pvTerminateData parameter.
dwFlags
Reserved. Must be 0.

Remarks

This method may be called only by the host player.

When this method is called, the DPN_MSGID_TERMINATE_SESSION will be sent to the message handler of each player in the session.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client

Applications use the methods of the IDirectPlay8Client interface to create and manage client applications for client/server sessions.

The methods of the IDirectPlay8Client interface can be organized into the following groups.

Session Management | Close
 | Connect
 | EnumHosts
 | EnumServiceProviders
 | GetApplicationDesc
 | GetCaps
 | GetSPCaps
 | SetCaps
 | SetSPCaps
Message Management | GetSendQueueInfo
 | Initialize
 | ReturnBuffer
 | Send
Client Information | SetClientInfo
Server Information | GetServerInfo
Miscellaneous | CancelAsyncOperation
 | RegisterLobby
 | GetConnectionInfo
 | GetServerAddress


IDirectPlay8Client::CancelAsyncOperation

Cancels asynchronous requests. Many methods of the IDirectPlay8Client interface run asynchronously by default. Depending on the situation, you might want to cancel requests before they are processed. All the methods of this interface that can be run asynchronously return a hAsyncHandle parameter.

Specific requests are canceled by passing the hAsyncHandle of the request in this method's hAsyncHandle parameter. You can cancel all pending asynchronous operations by calling this method, specifying NULL in the hAsyncHandle parameter, and specifying DPNCANCEL_ALL_OPERATIONS in the dwFlags parameter. If a specific handle is provided to this method, no flags should be set.

HRESULT CancelAsyncOperation(
const DPNHANDLE hAsyncHandle,
const DWORD dwFlags
);

Parameters

hAsyncHandle
Handle of the asynchronous operation to stop. You receive this handle when you call one of several methods that support asynchronous operations. This value can be set to NULL to stop all requests or a particular type of asynchronous request. If a particular handle is specified, the dwFlags parameter must be 0.
dwFlags
Flag that specifies which asynchronous request to canceled. You can set one of the following flags.
DPNCANCEL_ENUM
Cancel all asynchronous IDirectPlay8Client::EnumHosts requests. A single EnumHosts request can be canceled by specifying the handle returned from the EnumHosts method.
DPNCANCEL_CONNECT
Cancel an asynchronous IDirectPlay8Client::Connect request.
DPNCANCEL_SEND
Cancel an asynchronous IDirectPlay8Client::Send request.
DPNCANCEL_ALL_OPERATIONS
Cancel all asynchronous requests.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_CANNOTCANCEL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDHANDLE
DPNSUCCESS_PENDING

Remarks

You can use this method to cancel an asynchronous operation for the IDirectPlay8Client::Connect, IDirectPlay8Client::Send, and IDirectPlay8Client::EnumHosts methods. Microsoft® DirectPlay® 8.0 does not support cancellation of other asynchronous operations.

You can cancel a send by providing the handle returned from IDirectPlay8Client::Send method. A DPN_MSGID_SEND_COMPLETE system message is still posted to the applications message handler for each asynchronous send that is sent without the DPNSEND_NOCOMPLETE flag set. Sends that are canceled by this method return DPNERR_USERCANCEL in their hResultCode member of the DPN_MSGID_SEND_COMPLETE message.

If you set the DPNCANCEL_ALL_OPERATIONS, DPN_CANCELCONNECT, DPN_CANCELSEND, or DPNCANCEL_ENUM flags in dwFlags, DirectPlay will attempt to cancel all matching operations. This method will return an error if any attempted cancellation fails, even though some cancellations may have been successful.

Note The completion message might not arrive until after this method returns. Do not assume that the operation has been terminated until you have received a DPN_MSGID_SEND_COMPLETE, DPN_MSGID_CONNECT_COMPLETE, or DPN_MSGID_ASYNC_OP_COMPLETE message.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::Close

Closes the open connection with a session. This method must be called on any object that is successfully initialized with a call to the IDirectPlay8Client::Initialize method.

HRESULT Close(
const DWORD dwFlags
);

Parameters

dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_UNINITIALIZED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::Connect

Establishes the connection to the server. After a connection is established, the communication channel on the interface is open and the application should expect messages to arrive immediately. No messages can be sent by means of the IDirectPlay8Client::Send method until the connection has completed.

Before this method is called, you can obtain an application description by calling IDirectPlay8Client::EnumHosts. The EnumHosts method returns a DPN_APPLICATION_DESC structure for each hosted application. The structure describes the application, including the GUID of the application.

If this method is called asynchronously (by default), when the connection completes a DPN_MSGID_CONNECT_COMPLETE message is sent to the application's message handler.

HRESULT Connect(
const DPN_APPLICATION_DESC *const pdnAppDesc,
IDirectPlay8Address *const pHostAddr,
IDirectPlay8Address *const pDeviceInfo,
const DPN_SECURITY_DESC *const pdnSecurity,
const DPN_SECURITY_CREDENTIALS *const pdnCredentials,
const void *const pvUserConnectData,
const DWORD dwUserConnectDataSize,
void *const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

pdnAppDesc
Pointer to a DPN_APPLICATION_DESC structure that describes the application. The only member of this structure that you must set is the guidApplication member. Only some of the members of this structure are used by this method. The only member that you must set is guidApplication. You can also set guidInstance, pwszPassword, dwFlags, and dwSize.
pHostAddr
Pointer to an IDirectPlay8Address interface that specifies the addressing information to use to connect to the computer that is hosting.
pDeviceInfo
Pointer to an IDirectPlay8Address object that specifies what network adapter (for example, NIC, modem, and so on) to use to connect to the server.
pdnSecurity
Reserved. Must be NULL.
pdnCredentials
Reserved. Must be NULL.
pvUserConnectData
Pointer to application-specific data provided to the host or server to further validate the connection. This data is sent to the DPN_MSGID_INDICATE_CONNECT message in the pvUserConnectData member. This parameter is optional and you may pass NULL to bypass the connection validation provided by the user code.
dwUserConnectDataSize
Variable of type DWORD that specifies the size of the data contained in pvUserConnectData.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_CONNECT_COMPLETE system message. This parameter is optional and may be set to NULL.
phAsyncHandle
A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Client::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNCONNECT_SYNC flag in dwFlags.
dwFlags
Flag that describes the connection mode. You can set the following flag.
DPNCONNECT_OKTOQUERYFORADDRESSING
Setting this flag will display a standard Microsoft® DirectPlay® dialog box, which queries the user for more information if not enough information is passed in this method.
DPNCONNECT_SYNC
Process the connection request synchronously. Setting this flag does not generate a DPN_MSGID_CONNECT_COMPLETE system message.

Return Values

Returns S_OK if this method is processed synchronously and is successful. If the request is processed asynchronously, S_OK will be returned if the method is instantly processed. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_HOSTREJECTEDCONNECTION
DPNERR_INVALIDAPPLICATION
DPNERR_INVALIDDEVICEADDRESS
DPNERR_INVALIDFLAGS
DPNERR_INVALIDHOSTADDRESS
DPNERR_INVALIDINSTANCE
DPNERR_INVALIDINTERFACE
DPNERR_INVALIDPASSWORD
DPNERR_NOCONNECTION
DPNERR_NOTHOST
DPNERR_SESSIONFULL
DPNERR_ALREADYCONNECTED

Remarks

Although multiple enumerations can be run concurrently, and can be run across the duration of a connection, only one connection is allowed per interface. To establish a connection to more than one application, you must create another interface.

When this method is called, a DPN_MSGID_INDICATE_CONNECT message is posted to the server's message handler. On retrieval of this message, the host can pass back connection reply data to the Connect method. Connection reply data can send a message indicating that the host does not approve the connection. The calling application can then handle this reply appropriately.

The hResultCode on the completion will indicate S_OK if the Connect() attempt was successful, or an error otherwise. If the Host player returned anything other than S_OK from the DPN_MSGID_INDICATE_CONNECT message, the likely error code in the completion will be DPNERR_HOSTREJECTEDCONNECTION.

When the connection completes, a DPN_MSGID_CONNECT_COMPLETE message is sent to the application's message handler.

To close the connection established with this method, call the IDirectPlay8Client::Close method.

Note If you set the DPNCONNECT_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider may attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box, or your application will lock.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::EnumHosts

Enumerates applications that host Microsoft® DirectPlay® games. When an application is found that meets the enumeration criteria, the application's message handler is called with a DPN_MSGID_ENUM_HOSTS_RESPONSE system message. The message contains a DPN_APPLICATION_DESC structure describing the applications found.

Any number of enumerations can be run concurrently. The pvUserContext value is provided in the message handler to help differentiate replies to different enumerations.

Because of the variation in the number of ways enumeration can happen, it is not recommended that an application attempt to specify dwEnumPeriod, dwRetryInterval, or dwTimeOut unless the application has some specific media knowledge.

The default enumeration count and timeout values will cause EnumHosts to complete within a reasonable amount of time. These values are set by the service provider, and can be obtained by calling IDirectPlay8Client::GetSPCaps. Asynchronous enumerations can be stopped at any time by calling IDirectPlay8Client::CancelAsyncOperation and either passing the handle returned in the pAsyncHandle parameter or setting the DPENUM_CANCEL flag in the dwFlags parameter. An enumeration can also be stopped by returning anything other than S_OK from the message handler.

HRESULT EnumHosts(
PDPN_APPLICATION_DESC const pApplicationDesc,
IDirectPlay8Address *const pdpaddrHost,
IDirectPlay8Address *const pdpaddrDeviceInfo,
PVOID const pvUserEnumData,
const DWORD dwUserEnumDataSize,
const DWORD dwEnumCount,
const DWORD dwRetryInterval,
const DWORD dwTimeOut,
PVOID const pvUserContext,
HANDLE *const pAsyncHandle,
const DWORD dwFlags
);

Parameters

pApplicationDesc
Pointer to a DPN_APPLICATION_DESC structure that specifies which application hosts to enumerate. You must set the pApplicationDesc.dwSize member to the appropriate value. To reduce the number of responses, set pApplicationDesc.guidApplication to the GUID of the application to be found. If this member is not set, the search will include all applications.
pdpaddrHost
Pointer to an IDirectPlay8Address object that specifies the address of the computer that is hosting the application. If you specify NULL. DirectPlay will create an address. By default, DirectPlay will create the address from the pdpaddrDeviceInfo parameter. If you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in dwFlags, the user can be queried for address information.
pdpaddrDeviceInfo
Pointer to an IDirectPlay8Address object that specifies the service provider and local device settings to use when enumerating.
pvUserEnumData
Pointer to a block of data that is sent in the enumeration request to the host. The size of the data is limited depending on the network type. Call IDirectPlay8Client::GetSPCaps to obtain the exact value.
dwUserEnumDataSize
Variable of type DWORD that specifies the size of the data pointed at in the pvUserEnumData parameter.
dwEnumCount
Value specifying how many times the enumeration data will be sent. Set this parameter to zero to use the default value. You can obtain the default value for dwEnumCount by calling IDirectPlay8Client::GetSPCaps. If dwEnumCount is set to INFINITE, the enumeration will continue until canceled.
dwRetryInterval
Value specifying how many milliseconds between enumeration retries. Set this parameter to zero to use the default value. You can obtain the default value for dwRetryInterval by calling IDirectPlay8Client::GetSPCaps.
dwTimeOut
Variable of type DWORD that specifies the number of milliseconds that DirectPlay will wait for replies after the last enumeration is sent. Set this parameter to zero to use the default value. You can obtain the default value for dwTimeOut by calling IDirectPlay8Client::GetSPCaps If INFINITE is specified, the enumeration continues until it is canceled.
pvUserContext
Context that is provided in the client's message handler when it is called with responses to the enumeration. This can be useful to differentiate replies from concurrent enumerations.
pAsyncHandle
A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Client::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNENUMHOSTS_SYNC flag in dwFlags.
dwFlags
The following flags can be set.
DPNENUMHOSTS_SYNC
Causes the method to process synchronously.
DPNENUMHOSTS_OKTOQUERYFORADDRESSING
Setting this flag will display a standard DirectPlay dialog box, which queries the user for more information if not enough information is passed in this method.
DPNENUMHOSTS_NOBROADCASTFALLBACK
If the service provider supports broadcasting, setting this flag will disable the broadcast capabilities. Check to see if broadcasting is supported by examining the DPN_SP_CAPS structure before setting this flag.

Return Values

Returns S_OK if this method is processed synchronously and is successful. If the request is processed asynchronously, S_OK can return if the method is instantly processed. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDDEVICEADDRESS
DPNERR_INVALIDFLAGS
DPNERR_INVALIDHOSTADDRESS
DPNERR_INVALIDPARAM
DPNERR_ENUMQUERYTOOLARGE

Remarks

If you set the DPNENUMHOSTS_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider may attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box, or your application will lock.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::EnumServiceProviders

Enumerates the registered service providers available to the application.

HRESULT EnumServiceProviders(
const GUID *const pguidServiceProvider,
const GUID *const pguidApplication,
DPN_SERVICE_PROVIDER_INFO *const pSPInfoBuffer,
PDWORD const pcbEnumData,
PDWORD const pcReturned,
const DWORD dwFlags
);

Parameters

pguidServiceProvider
Pointer to a variable of type GUID that specifies a service provider. This optional parameter forces the enumeration of subdevices for the specified service provider. You should normally set this value to NULL, to enumerate all available service providers.
pguidApplication
Pointer to a variable of type GUID that specifies an application. If a pointer is passed in this parameter, only service providers who can be connected to the application are enumerated. You can also pass NULL to enumerate the registered service providers for the system.
pSPInfoBuffer
Pointer to an array of DPN_SERVICE_PROVIDER_INFO structures that will be filled with service provider information.
pcbEnumData
Pointer to DWORD, which is filled with the size of the pEnumData buffer if the buffer is too small.
pcReturned
Pointer to a variable of type DWORD that specifies the number of DPN_SERVICE_PROVIDER_INFO structures returned in the pEnumData array.
dwFlags
The following flag can be specified.
DPNENUMSERVICEPROVIDERS_ALL
Enumerates all the registered service providers for the system, including those that are not available to the application or do not have devices installed.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDPARAM

Remarks

Call this method initially by specifying NULL in the pguidServiceProvider parameter to determine the base service providers available to the system. Specific devices for a service provider can be obtained by passing a pointer to a service provider GUID in the pguidServiceProvider. This is useful, for example, when using the Modem Connection for Microsoft® DirectPlay® service provider. You can choose among different modems for dialing out and select specific modems for hosting.

If the pEnumData buffer is not big enough to hold the requested service provider information, the method returns DPNERR_BUFFERTOOSMALL and the cbEnumData parameter contains the required buffer size. Typically, the best strategy is to call the method once with a zero-length buffer to determine the required size. Then call the method again with the appropriate-sized buffer.

Normally, this method will return only those service providers that can be used by the application. For example, if the IPX networking protocol is not installed, DirectPlay will not return the IPX service provider. To have DirectPlay return all service providers, even those that cannot be used by the application, set the DPNENUMSERVICEPROVIDERS_ALL flag in dwFlags.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::GetApplicationDesc

Retrieves the full application description for the connected application.

HRESULT GetApplicationDesc(
DPN_APPLICATION_DESC *const pAppDescBuffer,
DWORD *const pcbDataSize,
const DWORD dwFlags
);

Parameters

pAppDescBuffer
Pointer to a DPN_APPLICATION_DESC structure where the application description data is written. Set this parameter to NULL to request only the size of data. If pAppDescBuffer is not set to NULL, you must set the pAppDescBuffer.dwSize member to an appropriate value. The pcbDataSize parameter is set to the size required to hold the data.
pcbDataSize
Pointer to a variable of type DWORD that is initialized to the size of the buffer before calling this method. After the method returns, this parameter is set to the size, in bytes, of the session data. If the buffer is too small, this method returns the DPNERR_BUFFERTOOSMALL error value, and this parameter is set to the buffer size required. If this parameter is NULL, the method returns DPNERR_INVALIDPARAM.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_NOCONNECTION

Remarks

Call this method initially by passing NULL in the pvData parameter to obtain the size of the required buffer. When you call the method a second time to fill the buffer, be sure to set the structures dwSize member to the appropriate value.

The returned DPN_APPLICATION_DESC structure will have the guidInstance, guidApplication, and pwszSessionName members set. It will not contain information about other clients that are connected to the session. That information, if available, can be obtained only from the server application. In particular, the dwCurrentPlayers member will always be set to 0.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::GetCaps

Retrieves the DPN_CAPS structure for the current interface.

HRESULT GetCaps(
DPN_CAPS *const pdpCaps,
const DWORD dwFlags
);

Parameters

pdpnCaps
Pointer to a DPN_CAPS structure to receive caps information. You must set the dwSize member of this structure to an appropriate value.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

A successful call to Initialize must be made before this method can be called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::GetConnectionInfo

Retrieves statistical information about the connection between the local client and the server.

HRESULT GetConnectionInfo(
DPN_CONNECTION_INFO *const pdnConnectInfo,
const DWORD dwFlags
);

Parameters

pdnConnectInfo
Pointer to a DPN_CONNECTION_INFO structure to retrieve information about the specified connection. You must set the dwSize member of this structure to an appropriate value.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

This method can be called only after a successful Connect call has completed.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::GetSendQueueInfo

Used by the application to monitor the size of the send queue. Microsoft® DirectPlay® does not send messages faster than the receiving computer can process them. As a result, if the sending computer is sending faster than the receiver can receive, messages accumulate in the sender's queue. If the application registers that the send queue is growing too large, it should decrease the rate that messages are sent.

HRESULT GetSendQueueInfo(
DWORD *const pdwNumMsgs,
DWORD *const pdwNumBytes,
const DWORD dwFlags
);

Parameters

pdwNumMsgs
Pointer to a variable of type DWORD that contains the number of messages currently queued. This value is optional, and may be set to NULL.
pdwNumBytes
Pointer to a variable of type DWORD that specifies the total number of bytes of data of the messages currently queued. This value is optional, and may be set to NULL.
dwFlags
You may specify the DPNGETSENDQUEUEINFO_PRIORITY_NORMAL, DPNGETSENDQUEUEINFO_PRIORITY_HIGH, or DPNGETSENDQUEUEINFO_PRIORITY_LOW flag to inquire about specific messages of that priority.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM

Remarks

You cannot set both pdwNumMsgs and pdwNumBytes to NULL. At least one of them must be set to a valid pointer.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::GetServerAddress

Retrieves the address of the server for the session.

HRESULT GetServerAddress(
IDirectPlay8Address **const ppAddress,
const DWORD dwFlags
);

Parameters

ppAddress
Address of a pointer to an IDirectPlay8Address object that specifies the address of the server. You must release this object when you no longer need it.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::GetServerInfo

Retrieves the data set for the server set by the call to the IDirectPlay8Server::SetServerInfo method.

HRESULT GetServerInfo(
DPN_PLAYER_INFO *const pdpnPlayerInfo,
DWORD *const pdwSize,
const DWORD dwFlags
);

Parameters

pdpnPlayerInfo
Pointer to a DPN_PLAYER_INFO structure to be filled with the server's information. If pdwSize is not set to NULL, you must set pdpnPlayerInfo.dwSize to the size of a DPN_PLAYER_INFO structure.
pdwSize
Pointer to a variable of type DWORD that contains the size of the data returned in the pdpnPlayerInfo parameter. If this value is too small, the method returns DPNERR_BUFFERTOOSMALL, and this parameter is set to the required size of the buffer.
dwFlags
Reserved. Must be set to 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDPARAM

Remarks

Call this method after the client receives a DPN_MSGID_SERVER_INFO message, indicating that the server has updated its information.

Microsoft® DirectPlay® returns the DPN_PLAYER_INFO structure and the pointers assigned to the structure's pwszName and pvData members in a contiguous buffer. If the two pointers were set, you must have allocated enough memory for the structure, plus the two pointers. The most robust way to use this method is to first call it with pdwSize set to NULL. When the method returns, pdwSize will point to the correct value. Use that value to allocate memory for your structure and call the method a second time to retrieve the information.

When the method returns, the dwInfoFlags member of the DPN_PLAYER_INFO structure will always have the DPNINFO_DATA and DPNINFO_NAME flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Server::SetServerInfo, to notify DirectPlay of which values have changed.

Transmission of nonstatic information should be handled with the IDirectPlay8Server::SendTo method because of the high cost of using the IDirectPlay8Server::SetServerInfo method.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::GetSPCaps

Retrieves the DPN_SP_CAPS structure for the specified service provider.

HRESULT GetSPCaps(
const GUID *const pguidSP,
DPN_SP_CAPS *const pdpnSPCaps,
const DWORD dwFlags
);

Parameters

pguidSP
Pointer to a GUID specifying the service provider you want to get information about.
pdpnSPCaps
Pointer to a DPN_SP_CAPS structure to receive the information about the specified service provider. You must set the pdpnSPCaps.dwSize member to the size of a DPN_SP_CAPS structure.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

This method retrieves information about the specified service provider. A successful call to Initialize must be made before this method can be called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::Initialize

Registers an entry point in the client's code that receives the messages from the IDirectPlay8Client interface and from the server. This method must be called before calling any other methods of this interface.

HRESULT Initialize(
PVOID const pvUserContext,
const PFNDPNMESSAGEHANDLER pfn,
const DWORD dwFlags
);

Parameters

pvUserContext
Pointer to the user-provided context value in calls to the message handler. Providing a user-context value can be useful to differentiate messages coming from multiple interfaces to a common message handler.
pfn
Pointer to a PFNDPNMESSAGEHANDLER callback function that receives all messages from the server, and receives indications of session changes from the IDirectPlay8Client interface.
dwFlags
You may specify the following flag.
DPNINITIALIZE_DISABLEPARAMVAL
Disable parameter validation for the current object.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

This is the first method you should call after using CoCreateInstance to obtain the IDirectPlay8Client interface.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::RegisterLobby

Allows launched applications to automatically propagate game status to the lobby.

HRESULT RegisterLobby(
const DPNHANDLE dpnHandle,
IDirectPlay8LobbiedApplication *const pIDP8LobbiedApplication,
const DWORD dwFlags
);

Parameters

dpnHandle
Connection handle used when making the calls to IDirectPlay8LobbiedApplication::UpdateStatus.
pIDP8LobbiedApplication
Pointer to the IDirectPlay8LobbiedApplication object that specifies the application.
dwFlags
One of the following flags:
DPNLOBBY_REGISTER
Registers the lobby with the application.
DPNLOBBY_UNREGISTER
Unregisters the lobby with the application.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::ReturnBuffer

Retrieves message buffers provided to the application through the pReceiveData member of the DPN_MSGID_RECEIVE system message. If the user's message handler returns DPNSUCCESS_PENDING to the RECEIVE callback, Microsoft® DirectPlay® assumes ownership of the buffer has been transferred to the application, and neither frees nor modifies it until ownership is returned to DirectPlay through this call.

HRESULT ReturnBuffer(
const DPNHANDLE hBufferHandle,
const DWORD dwFlags
);

Parameters

hBufferHandle
Variable of type DPNHANDLE that specifies the buffer handle for the message. This is obtained in the hBufferHandle member of the DPN_MSGID_RECEIVE system message.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDHANDLE
DPNERR_INVALIDPARAM

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::Send

Transmits data to the server. The message can be sent synchronously or asynchronously.

HRESULT Send(
const DPN_BUFFER_DESC *const pBufferDesc,
const DWORD cBufferDesc,
const DWORD dwTimeOut,
void *const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

pBufferDesc
Pointer to a DPN_BUFFER_DESC structure that describes the data to send.
cBufferDesc
Number of DPN_BUFFER_DESC structures pointed to by pBufferDesc. There can only be one buffer in this version of Microsoft® DirectPlay®.
dwTimeOut
Number of milliseconds to wait for the message to be sent. If the message has not been sent by the dwTimeOut value, the message is not sent. If you do not want a time out for message sends, set this parameter to 0.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_SEND_COMPLETE system message.
phAsyncHandle
A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Client::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNSEND_SYNC flag in dwFlags.
dwFlags
Flags that describe send behavior. You can set one or more of the following flags.
DPNSEND_SYNC
Process the Send request synchronously.
DPNSEND_NOCOPY
Use the data in the DPN_BUFFER_DESC structure and do not make an internal copy. This may be a more efficient method of sending data to the server. However, it is less robust, because the sender might be able to modify the message before the receiver has processed it. This flag cannot be combined with DPNSEND_NOCOMPLETE.
DPNSEND_NOCOMPLETE
Does not send DPN_MSGID_SEND_COMPLETE to the message handler. This flag may not be used with DPNSEND_NOCOPY or DPNSEND_GUARANTEED. Additionally, when using this flag pvAsyncContext must be NULL.
DPNSEND_COMPLETEONPROCESS
Send DPN_MSGID_SEND_COMPLETE to the message handler when this message has been delivered to the target and the target's message handler returns from indicating its reception. There is additional internal message overhead when this flag is set, and the message transmission process may become significantly slower. If you set this flag, DPNSEND_GUARANTEED must also be set.
DPNSEND_GUARANTEED
Send the message by a guaranteed method of delivery.
DPNSEND_PRIORITY_HIGH
Sets the priority of the message to high. This flag cannot be used with DPNSEND_PRIORITY_LOW.
DPNSEND_PRIORITY_LOW
Sets the priority of the message to low. This flag cannot be used with DPNSEND_PRIORITY_HIGH.
DPNSEND_NOLOOPBACK
Suppress the DPN_MSGID_RECEIVE system message to your message handler if you are sending to yourself.
DPNSEND_NONSEQUENTIAL
If the flag is not set, messages are delivered to the target application in the order that they are sent, which may necessitate buffering out of sequence messages until the missing messages arrive. Messages are simply delivered to the target application in the order that they are received.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_TIMEDOUT

Remarks

This method generates a DPN_MSGID_RECEIVE system message in the server's message handler. The data buffer is contained in the pReceiveData member of the associated structure.

Messages can have one of three priorities: low, normal, and high. To specify a low or high priority for the message, set the appropriate flag in dwFlags. If neither of the priority flags is set, the message will have normal priority. See Basic Networking for a discussion of send priorities.

When the Send request is completed, a DPN_MSGID_SEND_COMPLETE system message is posted to the sender's message handler. The success or failure of the request is contained in the hResultCode member of the associate structure. You can suppress the send completion by setting the DPN_NOCOMPLETE flag in dwflags.

Send completions are typically posted on the source computer as soon as the message is sent. In other words, a send completion does not necessarily mean that the message has been processed on the target. It may still be in a queue. If you want to be certain that the message has been processed by the target, set the DPN_COMPLETEONPROCESS flag in dwFlags. This flag ensures that the send completion will not be sent until the target's message handler has processed the message, and returned.

Note Do not assume that resources such as the data buffer will remain valid until the method has returned. If you call this method asynchronously, the DPN_MSGID_SEND_COMPLETE message may be received and processed by your message handler before the call has returned. If your message handler deallocates or otherwise invalidates a resource such as the data buffer, that resource may become invalid at any time after the method has been called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::SetCaps

Sets the DPN_CAPS structure for the current interface.

HRESULT SetCaps(
const DPN_CAPS *const pdpCaps,
const DWORD dwFlags
);

Parameters

pdpCaps
Pointer to a DPN_CAPS structure used to set the information about the current interface.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER
DPNERR_INVALIDPARAM
DPNERR_UNINITIALIZED

Remarks

This method sets parameters for the specified service provider. A successful call to Initialize must be made before this method can be called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::SetClientInfo

Sets the static settings of a client with an application. Call this method before connecting to relay basic player information to the application. Once the client successfully connects with the application, the server can retrieve information obtained through this method by calling the IDirectPlay8Server::GetClientInfo method.

HRESULT SetClientInfo(
const DPN_PLAYER_INFO *const pdpnPlayerInfo,
PVOID const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

pdpnPlayerInfo
Pointer to a DPN_PLAYER_INFO structure that contains the client information to set.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNSETCLIENTINFO_SYNC
Causes the method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. If the request is processed asynchronously, S_OK can return if the method is instantly processed. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_NOCONNECTION
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

This method can be called at any time during the session.

Transmission of nonstatic information should be handled with the IDirectPlay8Client::Send method because of the high cost of using the IDirectPlay8Client::SetClientInfo method.

You can modify the client information with this method after connecting to the application. Calling this method after connection generates a DPN_MSGID_CLIENT_INFO system message to all players, informing them that data has been updated.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Client::SetSPCaps

Sets the DPN_SP_CAPS structure for the specified service provider.

HRESULT SetSPCaps(
const GUID *const pguidSP,
constDPN_SP_CAPS *const pdpnSPCaps
);

Parameters

pguidSP
Pointer to a GUID specifying the service provider you want to set information about.
pdpnSPCaps
Pointer to a DPN_SP_CAPS structure to set the information about the specified service provider.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

This method sets parameters for the specified service provider. A successful call to Initialize must be made before this method can be called. Currently only the dwNumThreads member can be set by this call; dwFlags must be 0.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server

Applications use the methods of the IDirectPlay8Server interface to create and manage the server for a Microsoft® DirectPlay® client/server transport session

The methods of the IDirectPlay8Server interface can be organized into the following groups.

Session Management | Close
 | EnumServiceProviders
 | GetApplicationDesc
 | GetCaps
 | GetSPCaps
 | GetSendQueueInfo
 | Host
 | Initialize
 | ReturnBuffer
 | SendTo
 | SetApplicationDesc
 | SetCaps
 | SetServerInfo
 | SetSPCaps
Client Management | DestroyClient
 | GetClientInfo
 | GetPlayerContext
Group Management | AddPlayerToGroup
 | CreateGroup
 | DestroyGroup
 | EnumPlayersAndGroups
 | EnumGroupMembers
 | GetGroupContext
 | GetGroupInfo
 | RemovePlayerFromGroup
 | SetGroupInfo
Miscellaneous | CancelAsyncOperation
 | GetClientAddress
 | GetConnectionInfo
 | GetLocalHostAddresses
 | RegisterLobby

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::AddPlayerToGroup

Adds a client to a group. After the client is successfully added to the group, all messages sent to the group are sent to the client.

HRESULT AddPlayerToGroup(
const DPNID idGroup,
const DPNID idClient,
PVOID const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

idGroup
Variable of type DPNID that specifies the identifier of the group to add the client to.
idClient
Variable of type DPNID that specifies the identifier of the client to add to the group.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message. This parameter is optional and can be set to NULL.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNADDPLAYERTOGROUP_SYNC
Causes this method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP
DPNERR_INVALIDPLAYER

Remarks

The server can add itself or a client to an existing group. After a player is successfully added to a group, all messages sent to the group will be received by the player.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::CancelAsyncOperation

Cancels asynchronous requests. Many methods of the IDirectPlay8Server interface run asynchronously by default. Depending on the situation, you might want to cancel requests before they are processed. All the methods of this interface that can be run asynchronously return an hAsyncHandle parameter.

Specific requests are canceled by passing the hAsyncHandle of the request in this method's hAsyncHandle parameter. You can cancel all pending asynchronous operations by calling this method, specifying NULL in the hAsyncHandle parameter, and specifying DPNCANCEL_ALL_OPERATIONS in the dwFlags parameter. If a specific handle is provided to this method, no flags should be set.

HRESULT CancelAsyncOperation(
const DPNHANDLE hAsyncHandle,
const DWORD dwFlags
);

Parameters

hAsyncHandle
Handle of the asynchronous operation to stop. This value can be NULL to stop all requests or a particular type of asynchronous request. If a specific handle for the request to be canceled is specified, the dwFlags parameter must be 0. You will receive this handle when you call one of several methods that support asynchronous operations.
dwFlags
Flag that specifies which asynchronous request to cancel. You can set one of the following flags.
DPNCANCEL_SEND
Cancel an asynchronous IDirectPlay8Server::SendTo request.
DPNCANCEL_ALL_OPERATIONS
Cancel all asynchronous requests.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_CANNOTCANCEL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDHANDLE
DPNSUCCESS_PENDING

Remarks

You can use this method to cancel an asynchronous operation for the IDirectPlay8Server::SendTo method. Microsoft® DirectPlay® 8.0 does not support cancellation of other asynchronous operations.

You can cancel a Send request by providing the handle returned from IDirectPlay8Server::SendTo method. A DPN_MSGID_SEND_COMPLETE system message is still posted to the applications message handler for each asynchronous Send request that is sent without the DPNSEND_NOCOMPLETE flag set. Send requests that are canceled by this method return DPNERR_USERCANCEL in their hResultCode member of the DPN_MSGID_SEND_COMPLETE message.

If you set the DPNCANCEL_ALL_OPERATIONS or DPNCANCEL_SEND flags in dwFlags, DirectPlay will attempt to cancel all matching operations. This method will return an error if any attempted cancellation fails, even though some cancellations may have been successful.

Note The completion message might not arrive until after this method returns. Do not assume that the operation has been terminated until you have received a DPN_MSGID_SEND_COMPLETE, DPN_MSGID_CONNECT_COMPLETE, or DPN_MSGID_ASYNC_OP_COMPLETE message.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::Close

Closes the open connection with a session.

HRESULT Close(
const DWORD dwFlags
);

Parameters

dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_UNINITIALIZED

Remarks

This method must be called on any object successfully initialized with IDirectPlay8Server::Initialize.

This method is a counterpart to IDirectPlay8Server::Host. It closes all active network connections hosted by the server. This method is synchronous, and will not return until the server has processed all DPN_MSGID_DESTROY_PLAYER messages. This feature guarantees that when Close returns, you can safely shut down the server application.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::CreateGroup

Creates a group in the current session. When this method is called, the server's message handler receives a DPN_MSGID_CREATE_GROUP message.

Note Multicasting is not supported for this release.

HRESULT CreateGroup(
const DPN_GROUP_INFO *const pdpnGroupInfo,
VOID *const pvGroupContext,
VOID *const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

pdpnGroupInfo
Pointer to a DPN_GROUP_INFO structure that contains the group description.
pvGroupContext
Pointer to the context value for the group. This value is preset when the local application's message handler processes the DPN_MSGID_CREATE_GROUP message. This parameter is optional and may be set to NULL.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNCREATEGROUP_SYNC
Causes this method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or the following error value.

DPNERR_INVALIDFLAGS

Remarks

Microsoft® DirectPlay® does not maintain hierarchical groups because these can easily be implemented with flat groups and expeditious use of the group data.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::DestroyClient

Deletes a client from the session.

HRESULT DestroyClient(
const DPNID dpnidClient,
const VOID *const pDestroyInfo,
const DWORD dwDestroyInfoSize,
const DWORD dwFlags
);

Parameters

dpnidClient
Variable of type DPNID that specifies the identifier of the client to delete.
pDestroyInfo
Pointer that describes additional delete data information.
dwDestroyInfoSize
Variable of type DWORD that specifies the size of the data in the pDestroyInfo parameter.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDPLAYER
DPNERR_NOTHOST

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::DestroyGroup

Deletes a group created by the IDirectPlay8Server::CreateGroup method.

HRESULT DestroyGroup(
const DPNID idGroup,
PVOID const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

idGroup
DPNID of the group to delete.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message. This parameter is optional and may be set to NULL.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNDESTROYGROUP_SYNC
Causes the method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::EnumPlayersAndGroups

Retrieves a list of all the player and/or group identifiers for the application.

HRESULT EnumPlayersAndGroups(
DPNID *const prgdpnid,
DWORD *const pcdpnid,
const DWORD dwFlags
);

Parameters

prgdpnid
Pointer to an array that will be filled with the session's group and/or player identifiers.
pcdpnid
Pointer to a variable of type DWORD that specifies the number of identifiers in the prgdpnid parameter. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the number of entries that are required.
dwFlags
Flag that describes enumeration behavior. You can set one or both of the following flags.
DPNENUM_PLAYERS
Return a list of player identifiers.
DPNENUM_GROUPS
Return a list of group identifiers.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDFLAGS

Remarks

Because group and player information changes frequently, the required buffer size returned may change between subsequent calls. Check and reallocate the buffer until the method succeeds.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::EnumGroupMembers

Retrieves a list of all players in a group.

HRESULT EnumGroupMembers(
const DPNID dpnid,
DPNID *const prgdpnid,
DWORD *const pcdpnid,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the group that contains the players to enumerate.
prgdpnid
Pointer to an array that contains the identifiers of the group's players.
pcdpnid
Pointer to a variable of type DWORD that contains the number of player identifiers in the prgdpnid parameter. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter is set to the number of entries that are required.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::EnumServiceProviders

Enumerates the registered service providers available to the application.

HRESULT EnumServiceProviders(
const GUID *const pguidServiceProvider,
const GUID *const pguidApplication,
DPN_SERVICE_PROVIDER_INFO *const pSPInfoBuffer,
PDWORD const pcbEnumData,
PDWORD const pcReturned
const DWORD dwFlags
);

Parameters

pguidServiceProvider
Pointer to a variable of type GUID that specifies a service provider. This optional parameter forces the enumeration of subdevices for the specified service provider. You should normally set this value to NULL, to enumerate all available service providers.
pguidApplication
Pointer to a variable of type GUID that specifies an application. If a pointer is passed in this parameter, only service providers who can be connected to the application are enumerated. You can also pass NULL to enumerate the registered service providers for the system.
pSPInfoBuffer
Pointer to an array of DPN_SERVICE_PROVIDER_INFO structures that will be filled with service provider information.
pcbEnumData
Pointer to DWORD, which is filled with the size of the pEnumData buffer if the buffer is too small.
pcReturned
Pointer to a variable of type DWORD that specifies the number of DPN_SERVICE_PROVIDER_INFO structures returned in the pEnumData array.
dwFlags
The following flag can be specified.
DPNENUMSERVICEPROVIDERS_ALL
Enumerates all the registered service providers for the system including those that are not available to the application or do not have devices installed.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDPARAM

Remarks

Call this method initially by specifying NULL in the pguidServiceProvider parameter to determine the base service providers available to the system. Specific devices for a service provider can be obtained by passing a pointer to a specific service provider GUID in the pguidServiceProvider. This is useful, for example, when using the Modem Connection for Microsoft® DirectPlay® service provider. You can choose between different modems for dialing out and select specific modems for hosting.

If the pEnumData buffer is not big enough to hold the requested service provider information, the method returns DPNERR_BUFFERTOOSMALL and the cbEnumData parameter contains the required buffer size. Typically, the best strategy is to call the method once with a zero-length buffer to determine the required size. Then call the method again with the appropriate sized buffer.

Normally, this method will return only those service providers that can be used by the application. For example, if the IPX networking protocol is not installed, DirectPlay will not return the IPX service provider. To have DirectPlay return all service providers, even those that cannot be used by the application, set the DPNENUMSERVICEPROVIDERS_ALL flag in dwFlags.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::GetApplicationDesc

Retrieves the full application description for the connected application.

HRESULT GetApplicationDesc(
DPN_APPLICATION_DESC *const pAppDescBuffer,
DWORD *const pcbDataSize,
const DWORD dwFlags
);

Parameters

pAppDescBuffer
Pointer to a DPN_APPLICATION_DESC structure where the application description data is to be written. Set this parameter to NULL to request only the size of data. If pAppDescBuffer is not set to NULL, you must set the pAppDescBuffer.dwSize member to an appropriate value. The pcbDataSize parameter is set to the size required to hold the data.
pcbDataSize
Pointer to a variable of type DWORD that is initialized to the size of the buffer before calling this method. After the method returns, this parameter is set to the size, in bytes, of the session data. If the buffer is too small, this method returns the DPNERR_BUFFERTOOSMALL error value, and this parameter is set to the buffer size required. If this parameter is NULL, the method returns DPNERR_INVALIDPARAM.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_NOCONNECTION

Remarks

Call this method initially by passing NULL in the pvData parameter to obtain the size of the required buffer. When you call the method a second time to fill the buffer, be sure to set the structures dwSize member to the appropriate value.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::GetCaps

Retrieves the DPN_CAPS structure for the current interface.

HRESULT GetCaps(
DPNCAPS *const pdpnCaps,
const DWORD dwFlags
);

Parameters

pdpnCaps
Pointer to a DPN_CAPS structure to receive caps information. You must set the dwSize member of this structure to an appropriate value.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

A successful call to Initialize must be made before this method can be called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::GetClientAddress

Retrieves the address for the specified player in the session.

HRESULT GetClientAddress(
const DPNID dpnid,
IDirectPlay8Address **const pAddress,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID specifying the identification of the player.
pAddress
Address of a pointer to an IDirectPlay8Address object that specifies the address of the client. You must release this object when you no longer need it.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPLAYER
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

Use the IDirectPlay8Server::GetLocalHostAddresses method to retrieve addresses that can be used to connect to the session.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::GetClientInfo

Retrieves the client information set for the specified client.

HRESULT GetClientInfo(
const DPNID dpnid,
DPN_PLAYER_INFO *const pdpnPlayerInfo,
DWORD *const pdwSize,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the identifier of the client to retrieve the information for.
pdpnPlayerInfo
Pointer to a DPN_PLAYER_INFO structure that is filled with client information. If pdwSize is not set to NULL, you must set pdpnPlayerInfo.dwSize to an appropriate value.
pdwSize
Pointer to a variable of type DWORD that contains the size of the client data returned in the pdpnPlayerInfo parameter. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the size of the required buffer.
dwFlags
Flags describing the information returned for the client. Currently, both of the following flags are returned.
DPNINFO_NAME
The DPN_PLAYER_INFO structure contains the name set for the client.
DPNINFO_DATA
The DPN_PLAYER_INFO structure contains the data set for the client.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDPARAM
DPNERR_INVALIDPLAYER

Remarks

Call this method after the server receives a DPN_MSGID_CLIENT_INFO message from the application. This message indicates that a client has updated its information.

Microsoft® DirectPlay® returns the DPN_PLAYER_INFO structure, and the pointers assigned to the structure's pwszName and pvData members in a contiguous buffer. If the two pointers were set, you must have allocated enough memory for the structure, plus the two pointers. The most robust way to use this method is to first call it with pdwSize set to NULL. When the method returns, pdwSize will point to the correct value. Use that value to allocate memory for the structure and call the method a second time to retrieve the information.

When the method returns, the dwInfoFlags member of the DPN_PLAYER_INFO structure will always have the DPNINFO_DATA and DPNINFO_NAME flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Client::SetClientInfo, to notify DirectPlay of which values have changed.

Transmission of nonstatic information should be handled with the IDirectPlay8Client::Send method because of the high cost of using the IDirectPlay8Client::SetPeerInfo method.

The player sets the information by calling IDirectPlay8Client::SetClientInfo.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::GetConnectionInfo

Retrieves statistical information about the connection between the local server and the specified remote client.

HRESULT GetConnectionInfo(
const DPNID dpnidEndPoint,
DPN_CONNECTION_INFO *const pdnConnectInfo,
const DWORD dwFlags
);

Parameters

dpnidEndPoint
DPNID of the player whose connection information will be retrieved.
pdnConnectInfo
Pointer to a DPN_CONNECTION_INFO structure to retrieve information about the specified connection. The dwSize member of this structure must be set to the size of a DPN_CONNECTION_INFO structure.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

This method can be called only after a successful Host call has completed.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::GetGroupContext

Retrieves the group context value for a group.

HRESULT GetGroupContext(
const DPNID dpnid,
PVOID *const ppvGroupContext,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the identifier of the group to get context data for.
ppvGroupContext
Pointer to the context value of the group.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDGROUP
DPNERR_INVALIDPARAM

Remarks

Group context values are set by pointing the pvGroupContext member of the DPN_MSGID_CREATE_GROUP system message to the context value data.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::GetGroupInfo

Retrieves a block of data associated with a group, including the group name.

This method is typically called after a DPN_MSGID_GROUP_INFO system message is received, indicating that the group data has been modified.

HRESULT GetGroupInfo(
const DPNID dpnid,
DPN_GROUP_INFO *const pdpnGroupInfo,
DWORD *const pdwSize,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the identifier of the group whose data block will be retrieved.
pdpnGroupInfo
Pointer to a DPN_GROUP_INFO structure that describes the group data. If pdwSize is not set to NULL, you must set pdpnGroupInfo.dwSize to the size of a DPN_GROUP_INFO structure.
pdwSize
Pointer to a variable of type DWORD that returns the size of the data in the pdpnGroupInfo parameter. If the buffer is too small, this method returns DPNERR_BUFFERTOOSMALL and this parameter contains the required size.
dwFlags
Flags describing the information returned for the group. Currently, both of the following flags are returned.
DPNINFO_NAME
The DPN_PLAYER_INFO structure contains the name set for the client.
DPNINFO_DATA
The DPN_PLAYER_INFO structure contains the data set for the client.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP

Remarks

Microsoft® DirectPlay® returns the DPN_GROUP_INFO structure, and the pointers assigned to the structure's pwszName and pvData members in a contiguous buffer. If the two pointers were set, you must have allocated enough memory for the structure, plus the two pointers. The most robust way to use this method is to first call it with pdwSize set to NULL. When the method returns, pdwSize will point to the correct value. Use that value to allocate memory for the structure and call the method a second time to retrieve the information.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::GetLocalHostAddresses

Retrieves the local addresses being used to host the session.

HRESULT GetLocalHostAddresses(
IDirectPlay8Address **const prgpAddress,
DWORD *const pcAddress,
constDWORD dwFlags
);

Parameters

prgpAddress
Address of a pointer to an array of IDirectPlay8Address objects that specify the local host addresses. You must release these objects when you no longer need them or you will create memory leaks.
pcAddress
Maximum number of address objects that can be contained in the array pointed to by prgpAddress. If the buffer is too small, the method returns DPNERR_BUFFERTOOSMALL, and pcAddress will be set to the required value.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

The most robust way to use this method is to first call it with pcAddress set to 0. When the method returns, pcAddress will point to the required value. You can use that value when you call the method for a second time to retrieve the information.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::GetPlayerContext

Retrieves the player context value for a client.

HRESULT GetPlayerContext(
const DPNID dpnid,
PVOID *const ppvPlayerContext,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the identifier of the player to get context data for.
ppvPlayerContext
Pointer to the context data of the client.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDPLAYER

Remarks

Player context values are set by pointing the pvPlayerContext member of the DPN_MSGID_CREATE_PLAYER system message to the context value data.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::GetSendQueueInfo

Used by the application to monitor the size of the send queue. Microsoft® DirectPlay® does not send messages faster than the receiving computer can process them. As a result, if the sending computer is sending faster than the receiver can receive, messages accumulate in the sender's queue. If the application registers that the send queue is growing too large, it should slow the rate that messages are sent.

HRESULT GetSendQueueInfo(
const DPNID dpnid,
DWORD *const pdwNumMsgs,
DWORD *const pdwNumBytes,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the identifier of the player to get the send-queue information for.
pdwNumMsgs
Pointer to a variable of type DWORD that contains the number of messages currently queued. This value is optional, and may be set to NULL.
pdwNumBytes
Pointer to a variable of type DWORD that specifies the total number of bytes of data of the messages currently queued. This value is optional, and may be set to NULL.
dwFlags
You may specify the DPNGETSENDQUEUEINFO_PRIORITY_NORMAL, DPNGETSENDQUEUEINFO_PRIORITY_HIGH, or DPNGETSENDQUEUEINFO_PRIORITY_LOW flag to inquire about specific messages of that priority.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM

Remarks

You cannot set both pdwNumMsgs and pdwNumBytes to NULL. At least one of them must be set to a valid pointer.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::GetSPCaps

Retrieves the DPN_SP_CAPS structure for the specified service provider.

HRESULT GetSPCaps(
const GUID *const pguidSP,
DPN_SP_CAPS *const pdpnSPCaps,
const DWORD dwFlags
);

Parameters

pguidSP
Pointer to a GUID specifying the service provider you want to get information about.
pdpnSPCaps
Pointer to a DPN_SP_CAPS structure to receive the information about the specified service provider. You must set the pdpnSPCaps.dwSize member of this structure to an appropriate value.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

This method retrieves information about the specified service provider. A successful call to Initialize must be made before this method can be called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::Host

Creates a new client/server session, hosted by the local computer.

HRESULT Host(
const DPN_APPLICATION_DESC *const pdnAppDesc,
IDirectPlay8Address **const prgpDeviceInfo,
const DWORD cDeviceInfo,
const DPN_SECURITY_DESC *const pdpSecurity,
const DPN_SECURITY_CREDENTIALS *const pdpCredentials,
VOID *const pvPlayerContext,
const DWORD dwFlags
);

Parameters

pdnAppDesc
Pointer to a DPN_APPLICATION_DESC structure that describes the application.
prgpDeviceInfo
Pointer to an array of IDirectPlay8Address objects containing device addresses that should be used to host the application.
cDeviceInfo
Variable of type DWORD that specifies the number of device address objects in the array pointed to by prgpDeviceInfo.
pdpSecurity
Reserved. Must be set to NULL.
pdpCredentials
Reserved. Must be set to NULL.
pvPlayerContext
Pointer to the context value of the player. This value is preset when the local computer handles the DPN_MSGID_CREATE_PLAYER message. This parameter is optional, and may be set to NULL.
dwFlags
The following flag can be specified.
DPNHOST_OKTOQUERYFORADDRESSING
Setting this flag will display a standard Microsoft® DirectPlay® dialog box, which queries the user for more information if not enough information is passed in this method.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_DATATOOLARGE
DPNERR_INVALIDPARAM

Remarks

If you set the DPNHOST_OKTOQUERYFORADDRESSING flag in dwFlags, the service provider may attempt to display a dialog box to ask the user to complete the address information. You must have a visible window present when the service provider tries to display the dialog box, or your application will lock.

The maximum size of the application data that you assign to the pvApplicationReservedData member of the DPN_APPLICATION_DESC structure is limited by the service provider's Maximum Transmission Unit. If your application data is too large, the method will fail and return DPNERR_DATATOOLARGE.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::Initialize

Registers an entry point in the server's code that receives the messages from the IDirectPlay8Server interface and from remote clients. This method must be called before calling any other methods of this interface.

HRESULT Initialize(
PVOID const pvUserContext,
const PFNDPNMESSAGEHANDLER pfn,
const DWORD dwFlags
);

Parameters

pvUserContext
Pointer to the user-provided context value in calls to the message handler. Providing a user-context value is useful to differentiate messages from multiple interfaces to a common message handler.
pfn
Pointer to a PFNDPNMESSAGEHANDLER callback function that receives all messages from remote clients and indications of session changes from the IDirectPlay8Server interface.
dwFlags
You may specify the following flag.
DPNINITIALIZE_DISABLEPARAMVAL
Passing this flag will disable parameter validation for the current object.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

Call this method first after using CoCreateInstance to obtain the IDirectPlay8Server interface.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::RegisterLobby

Allows launched applications to automatically propagate game status to the lobby.

HRESULT RegisterLobby(
const DPNHANDLE dpnHandle,
IDirectPlay8LobbiedApplication *const pIDP8LobbiedApplication,
const DWORD dwFlags
);

Parameters

dpnHandle
Connection handle used when making the calls to IDirectPlay8LobbiedApplication::UpdateStatus.
pIDP8LobbiedApplication
Pointer to the IDirectPlay8LobbiedApplication object that specifies the application.
dwFlags
One of the following flags.
DPNLOBBY_REGISTER
Registers the lobby with the application.
DPNLOBBY_UNREGISTER
Unregisters the lobby with the application.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::RemovePlayerFromGroup

Removes a client from a group.

HRESULT RemovePlayerFromGroup(
const DPNID idGroup,
const DPNID idClient,
PVOID const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

idGroup
Variable of type DPNID that specifies the identifier of the group to remove the client from.
idClient
Variable of type DPNID that specifies the identifier of the client to remove from the group.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNREMOVEPLAYERFROMGROUP_SYNC
Causes this method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP

Remarks

When this method is called, the server's message handler receives a DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::ReturnBuffer

Retrieves message buffers provided to the application through the pReceiveData member of the DPN_MSGID_RECEIVE system message. If the user's message handler returns DPNSUCCESS_PENDING to the RECEIVE callback, Microsoft® DirectPlay® assumes ownership of the buffer has been transferred to the application, and neither frees nor modifies it until ownership is returned to DirectPlay through this call.

HRESULT ReturnBuffer(
const DPNHANDLE hBufferHandle,
const DWORD dwFlags
);

Parameters

hBufferHandle
Variable of type DPNHANDLE that specifies the buffer handle for the message. This is obtained in the hBufferHandle member of the DPN_MSGID_RECEIVE system message.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDHANDLE
DPNERR_INVALIDPARAM

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::SendTo

Transmits data to a client or group within the session. The message can be sent synchronously or asynchronously.

HRESULT SendTo(
const DPNID dpnid,
const DPN_BUFFER_DESC *const pBufferDesc,
const DWORD cBufferDesc,
const DWORD dwTimeOut,
void *const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

dpnid
Identifier of the client or group to receive data. Set this parameter to DPNID_ALL_PLAYERS_GROUP to send a message to all players in the session.
pBufferDesc
Pointer to a DPN_BUFFER_DESC structure that describes the data to send.
cBufferDesc
Number of DPN_BUFFER_DESC structures pointed to by pBufferDesc. There can be only one buffer in this version of Microsoft® DirectPlay®.
dwTimeOut
Number of milliseconds to wait for the message to be sent. If the message has not been sent by the dwTimeOut value, the message is not sent. If you do not want a time out for message sends, set this parameter to 0.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_SEND_COMPLETE system message.
phAsyncHandle
A DPNHANDLE. When the method returns, phAsyncHandle will point to a handle that you can pass to IDirectPlay8Server::CancelAsyncOperation to cancel the operation. This parameter must be set to NULL if you set the DPNSEND_SYNC flag in dwFlags.
dwFlags
Flags that describe send behavior. You can set one or more of the following flags.
DPNSEND_SYNC
Process the SendTo request synchronously.
DPNSEND_NOCOPY
Use the data in the DPN_BUFFER_DESC structure and do not make an internal copy. This may be a more efficient method of sending data. However, it is less robust because the sender might be able to modify the message before the receiver has processed it. This flag cannot be used with DPNSEND_NOCOMPLETE.
DPNSEND_NOCOMPLETE
Do not send the DPN_MSGID_SEND_COMPLETE structure to the message handler. This flag may not be used with DPNSEND_NOCOPY or DPNSEND_GUARANTEED. Additionally, when using this flag pvAsyncContext must be NULL.
DPNSEND_COMPLETEONPROCESS
Send the DPN_MSGID_SEND_COMPLETE to the message handler when this message has been delivered to the target and the target's message handler returns from indicating its reception. There is additional internal message overhead when this flag is set, and the message transmission process may become significantly slower. If you set this flag, DPNSEND_GUARANTEED must also be set.
DPNSEND_GUARANTEED
Send the message by a guaranteed method of delivery.
DPNSEND_PRIORITY_HIGH
Sets the priority of the message to high. This flag cannot be used with DPNSEND_PRIORITY_LOW.
DPNSEND_PRIORITY_LOW
Sets the priority of the message to low. This flag cannot be used with DPNSEND_PRIORITY_HIGH.
DPNSEND_NOLOOPBACK
Suppress the DPN_MSGID_RECEIVE system message to your message handler when you are sending to a group that includes the local player. For example, this flag is useful if you are broadcasting to the entire session.
DPNSEND_NONSEQUENTIAL
If this flag is set, the target application will receive the messages in the order that they arrive at the user's computer. If this flag is not set, messages are delivered sequentially, and will be received by the target application in the order that they were sent. Doing so may require buffering incoming messages until missing messages arrive.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_CONNECTIONLOST
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_INVALIDPLAYER
DPNERR_TIMEDOUT

Remarks

This method generates a DPN_MSGID_RECEIVE system message in the receiver's message handler. The data is contained in the pReceiveData member of the associated structure.

Messages can have one of three priorities: low, normal, and high. To specify a low or high priority for the message set the appropriate flag in dwFlags. If neither of the priority flags is set, the message will have normal priority. See Basic Networking for a discussion of send priorities.

When the SendTo request is completed, a DPN_MSGID_SEND_COMPLETE system message is posted to the sender's message handler. The success or failure of the request is contained in the hResultCode member of the associated structure. You can suppress the send completion by setting the DPNSEND_NOCOMPLETE flag in dwflags.

Send completions are typically posted on the source computer as soon as the message is sent. In other words, a send completion does not necessarily mean that the message has been processed on the target. It may still be in a queue. If you want to be certain that the message has been processed by the target, set the DPNSEND_COMPLETEONPROCESS flag in dwFlags. This flag ensures that the send completion will not be sent until the target's message handler has processed the message, and returned.

Note Do not assume that resources such as the data buffer will remain valid until the method has returned. If you call this method asynchronously, the DPN_MSGID_SEND_COMPLETE message may be received and processed by your message handler before the call has returned. If your message handler deallocates or otherwise invalidates a resource such as the data buffer, that resource may become invalid at any time after the method has been called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::SetApplicationDesc

Changes the settings for the application that is being hosted. Only some settings can be changed.

HRESULT SetApplicationDesc(
const DPN_APPLICATION_DESC *const pad,
const DWORD dwFlags
);

Parameters

pad
Pointer to a DPN_APPLICATION_DESC structure that describes the application settings to modify.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_DATATOOLARGE
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

You can use this method to modify only the following members of the DPN_APPLICATION_DESC structure:

  • dwMaxPlayers
  • pwszSessionName
  • pwszPassword
  • pvApplicationReservedData
  • dwApplicationReservedDataSize

The maximum size of the application data that you assign to the pvApplicationReservedData member of the DPN_APPLICATION_DESC structure is limited by the service provider's Maximum Transmission Unit. If your application data is too large, the method will fail and return DPNERR_DATATOOLARGE.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::SetCaps

Sets the DPN_CAPS structure for the current interface.

HRESULT SetCaps(
const DPNCAPS *const pdpCaps,
const DWORD dwFlags
);

Parameters

pdpCaps
Pointer to a DPN_CAPS structure used to set the information about the current interface.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

This method sets parameters for the specified service provider. A successful call to Initialize must be made before this method can be called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::SetGroupInfo

Sets a block of data associated with a group, including the name of the group.

HRESULT SetGroupInfo(
const DPNID dpnid,
DPN_GROUP_INFO *const pdpnGroupInfo,
PVOID const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

dpnid
Variable of type DPNID that specifies the identifier of the group whose data block will be modified.
pdpnGroupInfo
Pointer to a DPN_GROUP_INFO structure that describes the group data to set. To change the values of the pwszName or pvData members of this structure, you must set the corresponding DPNINFO_NAME OR DPNINFO_DATA flag in the dwInfoFlags member.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNSETGROUPINFO_SYNC
Causes this method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDGROUP

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::SetServerInfo

Sets the static settings of a server with an application. After clients successfully connect to the server, they can retrieve the information set by this method by calling theIDirectPlay8Client::GetServerInfo method.

HRESULT SetServerInfo(
const DPN_PLAYER_INFO *const pdpnPlayerInfo,
PVOID const pvAsyncContext,
DPNHANDLE *const phAsyncHandle,
const DWORD dwFlags
);

Parameters

pdpnPlayerInfo
Pointer to a DPN_PLAYER_INFO structure that contains the server information to set.
pvAsyncContext
Pointer to the user-supplied context, which is returned in the pvUserContext member of the DPN_MSGID_ASYNC_OP_COMPLETE system message.
phAsyncHandle
A DPNHANDLE. A value will be returned. However, Microsoft® DirectPlay® 8.0 does not permit cancellation of this operation, so the value cannot be used.
dwFlags
Flag that controls how this method is processed. The following flag can be set for this method.
DPNSETSERVERINFO_SYNC
Causes this method to process synchronously.

Return Values

Returns S_OK if this method is processed synchronously and is successful. If the request is processed asynchronously, S_OK can return if the method is instantly processed. By default, this method is run asynchronously and generally returns DPNSUCCESS_PENDING or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_NOCONNECTION

Remarks

This method may be called before calling IDirectPlayServer::Host, and at any time during the session.

Handle transmission of nonstatic information with the IDirectPlay8Server::SendTo method because of the high cost of using the IDirectPlay8Server::SetServerInfo method.

You can modify the server information with this method after clients have connected to the application. Calling this method after connection generates a DPN_MSGID_SERVER_INFO system message to all players, informing them that data has been updated.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlay8Server::SetSPCaps

Sets the DPN_SP_CAPS structure for the specified service provider.

HRESULT SetSPCaps(
const GUID *const pguidSP,
const DPN_SP_CAPS *const pdpnSPCaps
);

Parameters

pguidSP
Pointer to a GUID specifying the service provider you want to set information about.
pdpnSPCaps
Pointer to a DPN_SP_CAPS structure to set the information about the specified service provider.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_UNINITIALIZED

Remarks

This method sets parameters for the specified service provider. A successful call to Initialize must be made before this method can be called. Currently only the dwNumThreads member can be set by this call; the dwFlags member must be 0.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


IDirectPlayVoiceClient

Applications use the methods of the IDirectPlayVoiceClient interface to manage clients in a voice session.

The methods of the IDirectPlayVoiceClient interface can be organized into the following groups.

Buffer management | Create3DSoundBuffer
 | Delete3DSoundBuffer
Miscellaneous | GetCaps
 | GetCompressionTypes
 | GetSoundDeviceConfig
 | SetNotifyMask
Session management | Connect
 | Disconnect
 | GetClientConfig
 | GetSessionDesc
 | GetTransmitTargets
 | Initialize
 | SetClientConfig
 | SetTransmitTargets

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::Connect

Connects the client to a Microsoft® DirectPlay® Voice session.

HRESULT Connect(
PDVSOUNDDEVICECONFIG pSoundDeviceConfig,
PDVCLIENTCONFIG pdvClientConfig,
DWORD dwFlags
);

Parameters

pSoundDeviceConfig
Pointer to a DVSOUNDDEVICECONFIG structure that describes the sound device configuration.
pdvClientConfig
Pointer to a DVCLIENTCONFIG structure that describes the general configuration of the client.
dwFlags
Flag. You can specify the following flag.
DVFLAGS_SYNC
The method does not return until the operation is completed.

Return Values

If the method is processed synchronously and is successful, it returns DV_OK. By default, this method is run asynchronously and returns DVERR_PENDING. On error, this method will return one of the following values.

DVERR_ALREADYPENDING
DVERR_COMPRESSIONNOTSUPPORTED
DVERR_INCOMPATIBLEVERSION
DVERR_INVALIDBUFFER
DVERR_INVALIDDEVICE
DVERR_INVALIDFLAGS
DVERR_INVALIDOBJECT
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTINITIALIZED
DVERR_OUTOFMEMORY
DVERR_RUNSETUP
DVERR_SENDERROR
DVERR_SOUNDINITFAILURE
DVERR_TIMEOUT
DVERR_TRANSPORTNOPLAYER
DVERR_TRANSPORTNOSESSION
DVERR_CONNECTED
DVERR_NOVOICESESSION

Remarks

You must test the sound devices selected for playback and capture by invoking the setup wizard before connecting the client to the DirectPlay Voice session. On application startup, check the audio configuration by using IDirectPlayVoiceTest::CheckAudioSetup. If this method returns DVERR_RUNSETUP, the sound configuration specified has not been tested. The setup wizard needs to be run only once for any configuration.

If you specify a buffer that is not the right format, the method will return DVERR_INVALIDBUFFER.

If the buffer or a portion of the buffer is locked when DirectPlay Voice attempts to write to it, the method will return DVERR_INVALIDBUFFER, and DirectPlay Voice will disconnect from the session. You will also receive a DVMSGID_SESSIONLOST message. The hResult member of the associated structure will be set to DVERR_LOCKEDBUFFER. Subsequent method calls will return a DVERR_NOTCONNECTED error code.

If full duplex operation is not supported, DirectPlay Voice falls back to half duplex (listen only) mode. To determine if you are in half-duplex mode, call IDirectPlayVoiceClient::GetSoundDeviceConfig after you have completed the connection. If you are in half-duplex mode, the dwFlags member of the DVSOUNDDEVICECONFIG structure will have the DVSOUNDCONFIG_HALFDUPLEX flag set.

Regardless of how the interfaces are obtained, the DirectPlayVoiceClient object maintains a reference, through a call to AddRef, to the IDirectSound and IDirectSoundCapture interfaces it uses until IDirectPlayVoiceClient::Disconnect is called. When Disconnect is called, the DirectPlayVoiceClient object calls Release on both interfaces.

If this method is called synchronously by setting the DVFLAGS_SYNC flag, the DVMSG_CONNECTRESULT message is not sent to the message handler. In this case, the connection result is determined by the return value of this method.

If this method is called asynchronously (by default), calling this method immediately returns a DVERR_PENDING error value and proceeds to process the connection request in the background. The status of the connection is not be known until the DirectPlay Voice client generates a DVMSG_CONNECTRESULT message with the connection result.

Any calls to IDirectPlayVoiceClient::Connect while a connection is pending return DVERR_ALREADYPENDING. Additionally, only one connection can be pending at a time.

A transport session must be started on the specified DirectPlay object before calling this method. A successful call to IDirectPlayVoiceClient::Initialize must be made before calling the Connect method.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::Create3DSoundBuffer

Retrieves a 3-D sound buffer for a player or group. You can use the methods of the 3-D sound buffer object to change the virtual 3-D position of incoming voice transmissions from the specified group or player.

HRESULT Create3DSoundBuffer(
DVID dvID,
LPDIRECTSOUNDBUFFER lpdsSourceBuffer,
DWORD dwPriority,
DWORD dwFlags,
LPDIRECTSOUND3DBUFFER* lpUserBuffer
);

Parameters

dvID
Variable of type DVID that specifies the identification of the player or group that the user wants to reserve a buffer for. You can also specify DVID_REMAINING to create a 3-D user buffer for all players or groups that do not have a user buffer. If DVID_REMAINING is specified, the lpdsBufferDesc must be NULL and the dwPriority and dwFlags parameters must be set to 0.
lpdsSourceBuffer
Pointer to an IDirectSoundBuffer interface, which is used to create the Microsoft® DirectPlay® Voice main buffer. This can be either NULL or a user-created Microsoft DirectSound® buffer. If this member is set to NULL, then DirectPlay Voice creates a buffer for you.
dwPriority
Direct pass-through. This value is passed in the dwPriority parameter when the call to IDirectSoundBuffer::Play is made. For more information, see IDirectSoundBuffer8::Play. This parameter must be 0 if lpdsMainBufferDesc is NULL.
dwFlags
Direct pass-through. This value is passed to the dwFlags parameter when the call to IDirectSoundBuffer::Play is made. For more information, see IDirectSoundBuffer8::Play. This parameter must be 0 if lpdsMainBufferDesc is NULL.
lpUserBuffer
Pointer to memory where the reserved buffer is placed.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYBUFFERED
DVERR_INVALIDOBJECT
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTALLOWED
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED
DVERR_OUTOFMEMORY
DVERR_SESSIONLOST

Remarks

If the DirectPlay voice session is a mixing server session, this method fails and returns DVERR_NOTALLOWED.

Although you can access all the member functions of the 3-D sound buffer object, because the DirectPlay voice client uses the buffer to stream incoming audio, do not use the Lock, UnLock, or Play methods of the DirectSound3DBuffer object.

If the user specifies a buffer, DirectPlay uses that buffer for the player's or group's buffer. User-created buffers have the following restrictions.

  • The buffer must be 22 kilohertz, 16-bit, Mono format.
  • The buffer must be at least 1 second in length.
  • The buffer must have been created with the DSBCAPS_GETCURRENTPOSITION2 and DSBCAPS_CTRL3D flags.
  • The buffer must not be a primary buffer.
  • The buffer must not be playing when it is passed to DirectPlay.

If the buffer is not the right format, the method will return DVERR_INVALIDBUFFER.

The buffer must not be locked when you pass it to DirectPlay. When the buffer for the individual user is no longer required or when a player leaves the voice session, it is important to call IDirectPlayVoiceClient::Delete3DSoundBuffer to free up resources.

If the buffer or a portion of the buffer is locked when DirectPlay Voice attempts to write to it, the method will return DVERR_INVALIDBUFFER. If you lock the buffer after the method has returned, you will receive a DVMSGID_SESSIONLOST message. The hResult member of the associated structure will be set to DVERR_LOCKEDBUFFER. Subsequent method calls will return a DVERR_NOTCONNECTED error code.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::Delete3DSoundBuffer

Returns exclusive control of the 3-D sound buffer object to the Microsoft® DirectPlay® voice client object.

HRESULT Delete3DSoundBuffer(
DVID dvID
LPDIRECTSOUND3DBUFFER* lpUserBuffer
);

Parameters

dvID
DVID of the player or group that the user wants to delete a buffer for.
lpUserBuffer
Pointer to the user buffer to delete. This must be a user buffer obtained through the IDirectPlayVoiceClient::Create3DSoundBuffer method.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYBUFFERED
DVERR_INVALIDOBJECT
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTALLOWED
DVERR_NOTBUFFERED
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED
DVERR_SESSIONLOST

Remarks

If the DirectPlay Voice session is a mixing server session, this method fails and returns DVERR_NOTALLOWED.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::Disconnect

Disconnects the Microsoft® DirectPlay® Voice client from the existing DirectPlay Voice session.

HRESULT Disconnect(
DWORD dwFlags
);

Parameters

dwFlags
Flag. You can specify the following flag.

DVFLAGS_SYNC

Do not return until the operation is completed.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYPENDING
DVERR_CONNECTABORTING
DVERR_INVALIDFLAGS
DVERR_INVALIDPARAM
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED
DVERR_PENDING
DVERR_SESSIONLOST
DVERR_TIMEOUT

Remarks

On calling this method, all recording and playback is stopped. If a connection is being processed, it is canceled by this call.

Unless the DVFLAGS_SYNC is specified, calling this method immediately returns a DVERR_PENDING error value and proceeds to process the disconnection request in the background. The status of the disconnection is not known until the DirectPlay Voice client generates a DVMSG_DISCONNECTRESULT message that contains the disconnection result. Only one disconnection can be pending at a time. If you call IDirectPlayVoiceClient::Disconnect while a disconnect is pending, DirectPlay will return a DVERR_ALREADYPENDING error value.

If this method is called synchronously by setting the DVFLAGS_SYNC flag, the method does not return until the Disconnect method completes. The result of the disconnection is the return value from this method. No DVMSGID_DISCONNECTRESULT message is generated.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::GetCaps

Retrieves the Microsoft® DirectPlay® Voice capabilities.

HRESULT GetCaps(
PDVCAPS pCaps
);

Parameters

pCaps
Pointer to the DVCAPS structure that contains the capabilities of the DirectPlayVoiceClient object.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::GetClientConfig

Retrieves the client configuration.

HRESULT GetClientConfig(
PDVCLIENTCONFIG pClientConfig
);

Parameters

pClientConfig
Pointer to a DVCLIENTCONFIG structure that contains the configuration of the local client.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED
DVERR_SESSIONLOST

Remarks

Before calling this member, you must set the dwSize member of the DVCLIENTCONFIG structure.

You can call this method only after a connection is successfully established with a Microsoft® DirectPlay® Voice session.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::GetCompressionTypes

Retrieves the available compression types on the system.

HRESULT GetCompressionTypes(
PVOID pData,
PDWORD pdwDataSize,
PDWORD pdwNumElements,
DWORD dwFlags
);

Parameters

pData
Pointer to buffer that receives an array of DVCOMPRESSIONINFO structures, one structure for every compression type supported through this object.
pdwDataSize
Pointer to a DWORD that contains the size of the buffer, in bytes, passed in the pData parameter.
pdwNumElements
Pointer to a DWORD where the method writes the number of elements returned in the array of DVCOMPRESSIONINFO structures. This contains the number of structures only if the buffer specified in the pData is large enough to hold the information.
dwFlags
Reserved. Must be 0.

Return Values

Returns DP_OK if successful, or one of the following error values.

DVERR_BUFFERTOOSMALL
DVERR_INVALIDFLAGS
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER

Remarks

If the buffer passed is not large enough to store the list of compression types, the method returns DVERR_BUFFERTOOSMALL and the pdwDataSize parameter is set to the minimum required size.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::GetSessionDesc

Retrieves the session properties.

HRESULT GetSessionDesc(
PDVSESSIONDESC pvSessionDesc
);

Parameters

pvSessionDesc
Pointer to a DVSESSIONDESC structure to receive the session description.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED
DVERR_SESSIONLOST

Remarks

Before calling this method, make sure to set the dwSize member of the DVSESSIONDESC structure.

This method may be called only after a connection is successfully established with a Microsoft® DirectPlay® Voice session.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::GetSoundDeviceConfig

Retrieves the sound device configuration of the session.

HRESULT GetSoundDeviceConfig(
PDVSOUNDDEVICECONFIG pSoundDeviceConfig,
PDWORD pdwSize
);

Parameters

pSoundDeviceConfig
Pointer to a DVSOUNDDEVICECONFIG structure that is filled with the configuration of the sound device.
pdwSize
Pointer to a DWORD that specifies the size of the buffer in pSoundDeviceConfig parameter. If the buffer is too small, the method returns DVERR_BUFFERTOOSMALL and this parameter contains the size of the required buffer.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED
DVERR_SESSIONLOST

Remarks

You can call this method only after a connection is successfully established with a Microsoft® DirectPlay® Voice session.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::GetTransmitTargets

Retrieves the transmit targets, if any, of the voice stream from this client.

HRESULT GetTransmitTargets(
PDVID pdvIDTargets,
PDWORD pdwNumTargets,
DWORD dwFlags
);

Parameters

pdvIDTargets
Member to fill with an array of DVIDs that specify the targets that were set by the IDirectPlayVoiceClient::SetTransmitTargets or IDirectPlayVoiceServer::SetTransmitTargets method. You can retrieve the number of targets by specifying NULL for this parameter.
pdwNumTargets
Number of DVIDs in the array. When you call this method, this should be the same value as the number of targets set in the IDirectPlayVoiceClient::SetTransmitTargets method. If the call is successful, Microsoft® DirectPlay® returns the number of elements written to the pdvIDTargets array.

If pdvIDTargets is NULL, this must be 0.

dwFlags
Reserved. Must be 0.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_BUFfERTOOSMALL
DVERR_INVALIDFLAGS
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTALLOWED
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED

Remarks

The value returned in the pdvIDTargets parameter can be player or group DVIDs or the DVID_ALLPLAYERS constant.

If the buffer specified in pdvIDTargets is not large enough to store the list of targets, this method returns DVERR_INVALIDPOINTER and pdwNumTargets is set to the required number of elements.

If there is no target specified, pdwNumTargets is set to 0 and the return value is DV_OK.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::Initialize

Initializes the DirectPlayVoiceClient object by associating it with a DirectPlay object. Additionally, this method registers a message handler with the DirectPlayVoiceClient object.

This method must be called successfully before IDirectPlayVoiceClient::Connect method is called.

HRESULT Initialize(
PVOID pVoid,
PDVMESSAGEHANDLER pMessageHandler,
PVOID pUserContext,
PDWORD pdwMessageMask,
DWORD dwMessageMaskElements
);

Parameters

pVoid
Pointer to the IUnknown interface for the DirectPlay object that this DirectPlayVoiceClient object should use.
pMessageHandler
User-defined callback function that is called when there is a DirectPlayVoiceClient message to be processed. Threads within the DirectPlayVoiceClient object call the callback function, so it will not be called in the context of your process's main thread.
pUserContext
Pointer to an application-defined structure that is passed to the callback function each time the function is called.
pdwMessageMask
Array of DWORDs that contain the message identifiers that you want DirectPlay Voice to send to your callback function. If a message identifier is not specified in this array, it is not sent. Each message identifier should appear only once in the array and only valid message identifiers are allowed. For example, DVMSGID_CONNECTRESULT is not valid for the server interface, but is for the client interface. To enable all messages, specify NULL for this value.
dwMessageMaskElements
Number of elements specified in the pdwMessageMask parameter. If pdwMessageMask is NULL, this must be 0.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYINITIALIZED
DVERR_GENERIC
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOCALLBACK
DVERR_TRANSPORTNOTINIT

Remarks

You can call IDirectPlayVoiceClient::SetNotifyMask to change the notify mask during the course of the voice session.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::SetClientConfig

Sets the client configuration.

HRESULT SetClientConfig(
PDVCLIENTCONFIG pClientConfig
);

Parameters

pClientConfig
Pointer to the DVCLIENTCONFIG structure that contains the configuration description to set.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDFLAGS
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED
DVERR_SESSIONLOST

Remarks

You can call this method only after a connection is successfully established with a Microsoft® DirectPlay® Voice session.

Calling this method sets all the parameters in the DVCLIENTCONFIG structure. Therefore, to leave a setting unmodified, you must retrieve the current configuration with IDirectPlayVoiceClient::GetClientConfig. Then modify the parameters to change and call IDirectPlayVoiceClient::SetClientConfig.

If the session is running in half duplex, the members of GetClientConfig related to recording are ignored.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::SetNotifyMask

Specifies which messages are sent to the message handler.

HRESULT SetNotifyMask(
PDWORD pdwMessageMask,
DWORD dwMessageMaskElements
);

Parameters

pdwMessageMask
Pointer to an array of DWORDs containing the message identifiers that you want Microsoft® DirectPlay® Voice to send to your callback function. If a message identifier is not specified in this array, it is not sent. Each message identifier should appear only once in the array, and only valid message identifiers are allowed. For example, DVMSGID_CONNECTRESULT is not valid for the server interface, but is for the client interface. To enable all messages, specify NULL for this value.
dwMessageMaskElements
Number of elements specified in the pdwMessageMask parameter. If pdwMessageMask is NULL, this must be 0.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOCALLBACK
DVERR_NOTINITIALIZED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceClient::SetTransmitTargets

Specifies which players and/or groups receive audio transmissions from the local client.

HRESULT SetTransmitTargets(
PDVID pdvIDTargets,
DWORD dwNumTargets,
DWORD dwFlags
);

Parameters

pdvIDTargets
Pointer an array of DVIDs that specify your targets. To specify no targets, pass NULL for this parameter. Additionally, this parameter can be set to the following value.
DVID_ALLPLAYERS
The client is targeting all players in the session. This must be the only element in the array.
dwNumTargets
Number of DVIDs in the array. This value cannot exceed 64. If pdvIDTargets is NULL, this must be 0.
dwFlags
Reserved. Must be 0.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDFLAGS
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_INVALIDTARGET
DVERR_NOTINITIALIZED

Remarks

For Microsoft® DirectX® 8.0, the number of individual targets that you can transmit to is limited to 64. If you exceed this value, the method will fail, and return DVERR_NOTALLOWED. However, you can transmit to more than 64 players. To do so, form the players into groups, and then use the group as your target.

The pdvIDTargets parameter specifies an array of player and/or group DVIDs. There must be no duplicate targets in this parameter, and all entries must be valid DVIDs. If a target contains a player as its individual DVID and through a group that the target belongs to, Microsoft® DirectPlay® Voice ensures duplicate speech packets are not sent to the player.

If the session was created with the DVSESSION_SERVERCONTROLTARGET flag, only the server can set the targets for this local client. A call to this method returns DVERR_NOTALLOWED.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceServer

Applications use the methods of the IDirectPlayVoiceServer interface to manage the host of the voice session.

The methods of the IDirectPlayVoiceServer interface can be organized into the following groups.

Miscellaneous | GetCaps
 | GetCompressionTypes
 | SetNotifyMask
Session management | GetSessionDesc
 | GetTransmitTargets
 | Initialize
 | SetSessionDesc
 | SetTransmitTargets
 | StartSession
 | StopSession

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceServer::GetCaps

Retrieves the capabilities of the Microsoft® DirectPlay® Voice server for this system.

HRESULT GetCaps(
PDVCAPS pDVCaps
);

Parameters

pDVCaps
Pointer to the DVCAPS structure that contains the capabilities of the DirectPlayVoiceServer object.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDOBJECT
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceServer::GetCompressionTypes

Retrieves available compression types for the system.

HRESULT GetCompressionTypes(
PVOID pData,
PDWORD pdwDataSize,
PDWORD pdwNumElements,
DWORD dwFlags
);

Parameters

pData
Pointer to the buffer that receives an array of DVCOMPRESSIONINFO structures that describe the compression types supported by this object.
pdwDataSize
Pointer to a DWORD that contains the size of the buffer, in bytes, passed in the pData parameter.
pdwNumElements
Pointer to a DWORD where the method writes the number of elements returned in the array of DVCOMPRESSIONINFO structures.
dwFlags
Reserved. Must be 0.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_BUFFERTOOSMALL
DVERR_INVALIDFLAGS
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER

Remarks

If the buffer is not large enough to store the list of compression types, the method returns DVERR_BUFFERTOOSMALL and the pdwDataSize parameter is set to the minimum required size.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceServer::GetSessionDesc

Retrieves the Microsoft® DirectPlay® Voice session settings.

HRESULT GetSessionDesc(
PDVSESSIONDESC pvSessionDesc
);

Parameters

pvSessionDesc
Pointer to a DVSESSIONDESC structure to receive the session description.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDOBJECT
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTHOSTING
DVERR_NOTINITIALIZED
DVERR_SESSIONLOST

Remarks

Before calling this method, make sure to set the dwSize member of the DVSESSIONDESC structure.

A successful call to IDirectPlayVoiceServer::StartSession must be made before this method can be called.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceServer::GetTransmitTargets

Retrieves the transmit targets, if any, of the voice stream for a player in a session.

HRESULT GetTransmitTargets(
DVID dvSource,
PDVID pdvIDTargets,
PDWORD pdwNumTargets,
DWORD dwFlags
);

Parameters

dvSource
DVID of the user or group whose target is returned.
pdvIDTargets
Array of DVIDs that specify the current targets of the player or group that were set by the IDirectPlayVoiceServer::SetTransmitTargets method. You can retrieve the number of targets by specifying NULL for this parameter.
pdwNumTargets
Number of DVIDs in the array. When you call this method, this should be the same value as the number of targets set in the IDirectPlayVoiceServer::SetTransmitTargets method. If the call is successful, Microsoft® DirectPlay® returns the number of elements in the pdvIDTargets array.

If pdvIDTargets is NULL, this must be 0.

dwFlags
Reserved. Must be 0.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_BUFFERTOOSMALL
DVERR_INVALIDFLAGS
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTALLOWED
DVERR_NOTCONNECTED
DVERR_NOTINITIALIZED

Remarks

This method can be used only if the DVSESSION_SERVERCONTROLTARGET flag is specified on creation of the DirectPlay Voice session. If the flag is not specified, this method returns DVERR_NOTALLOWED.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceServer::Initialize

Initializes the DirectPlayVoiceServer object by associating it with a DirectPlay object. Additionally, this method registers a message handler with this interface.

HRESULT Initialize(
LPVOID lpVoid,
PDVMESSAGEHANDLER pMessageHandler,
PVOID pUserContext,
LPDWORD lpdwMessageMask,
DWORD dwMessageMaskElements
);

Parameters

lpVoid
Pointer to the IUnknown interface for the DirectPlay object that this DirectPlayVoiceServer object should use.
pMessageHandler
User-defined callback function that is called when there is a DirectPlayVoiceClient message to process. A thread within the DirectPlayVoiceClient object calls the callback function, so it is not called in the context of your process's main thread.
pUserContext
Pointer to an application-defined structure that is passed to the callback function each time the method is called.
lpdwMessageMask
Array of DWORDs that contain the message identifiers that you want DirectPlay Voice to send to your callback function. If a message identifier is not specified in this array, it is not sent. Each message identifier should appear only once in the array, and only valid message identifiers are allowed. For example, DVMSGID_CONNECTRESULT is not valid for the server interface but is for the client interface. To enable all messages, specify NULL for this value.
dwMessageMaskElements
Number of elements specified in the lpdwMessageMask parameter. If lpdwMessageMask is NULL, this must be 0.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYINITIALIZED
DVERR_GENERIC
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOCALLBACK
DVERR_TRANSPORTNOTINIT

Remarks

You can call IDirectPlayVoiceServer::SetNotifyMask to change the notify mask during the course of the voice session.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceServer::SetNotifyMask

Specifies which messages are sent to the message handler.

HRESULT SetNotifyMask(
PDWORD pdwMessageMask,
DWORD dwMessageMaskElements
);

Parameters

pdwMessageMask
Pointer to an array of DWORDs that contain the message identifiers that you want Microsoft® DirectPlay® Voice to send to your callback function. If a message identifier is not specified in this array, it is not sent. Each message identifier should appear only once in the array, and only valid message identifiers are allowed. For example, DVMSGID_CONNECTRESULT is not valid for the server interface but is for the client interface. To enable all messages, specify NULL for this value.
dwMessageMaskElements
Number of elements specified in the pdwMessageMask parameter. If pdwMessageMask is NULL, this must be 0.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOCALLBACK
DVERR_NOTINITIALIZED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceServer::SetSessionDesc

Sets the session settings.

HRESULT SetSessionDesc(
PDVSESSIONDESC pSessionDesc
);

Parameters

pSessionDesc
Pointer to a DVSESSIONDESC structure that contains the session description.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDOBJECT
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTHOSTING
DVERR_NOTINITIALIZED
DVERR_SESSIONLOST

Remarks

After the Microsoft® DirectPlay® voice session has started, not all the session properties of the DVSESSIONDESC structure can be changed. For more information, see DVSESSIONDESC.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceServer::SetTransmitTargets

Controls the transmission of audio from the client to the specified members of the session.

HRESULT SetTransmitTargets(
DVID dvSource,
PDVID pdvIDTargets,
DWORD dwNumTargets,
DWORD dwFlags
);

Parameters

dvSource
DVID of the user whose targets are set.
pdvIDTargets
List of player DVIDs and/or group DVIDs that are the target for audio transmission. To specify no targets, pass NULL for this parameter. Additionally, this parameter can be set to the following value.
DVID_ALLPLAYERS
This client is targeting all players in the session. This must be the only element in the array.
dwNumTargets
Number of DVIDs in the array. This value cannot exceed 64. If pdvIDTargets is NULL this must be 0.
dwFlags
Reserved. Must be 0.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_INVALIDFLAGS
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_INVALIDTARGET
DVERR_NOTALLOWED
DVERR_NOTINITIALIZED

Remarks

For Microsoft® DirectX® 8.0, the number of individual targets that you can transmit to is limited to 64. If you exceed this value, the method will fail, and return DVERR_NOTALLOWED. However, you can transmit to more than 64 players. To do so, form the players into groups, and then use the group as your target.

There must be no duplicate targets in this parameter, and all entries must be valid DVIDs. If a target contains a player as its individual DVID and through a group that the target belongs to, Microsoft® DirectPlay® Voice ensures duplicate speech packets are not sent to the player.

This method can be used only if the DVSESSION_SERVERCONTROLTARGET flag is specified on creation of the DirectPlay Voice session. If the flag is not specified, this method returns DVERR_NOTALLOWED.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceServer::StartSession

Starts an initialized Microsoft® DirectPlay® Voice session within a running DirectPlay transport session. This method must be successfully called before the clients can complete a connection-to-the-voice session.

HRESULT StartSession(
PDVSESSIONDESC pSessionDesc,
DWORD dwFlags
);

Parameters

pSessionDesc
Pointer to a DVSESSIONDESC structure that contains the session description.
dwFlags
Reserved. Must be 0.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYPENDING
DVERR_HOSTING
DVERR_INVALIDFLAGS
DVERR_INVALIDOBJECT
DVERR_INVALIDPARAM
DVERR_INVALIDPOINTER
DVERR_NOTINITIALIZED

Remarks

The IDirectPlayVoiceServer::Initialize method must be called before this method is called. The voice session can be hosted on any client in the session if the voice session is peer-to-peer. If the voice session is not peer-to-peer, it must be hosted on the transport client, which is the host of a active transport session.

The DVSESSIONDESC structure contains the type of voice session to start. The type of voice session can have a dramatic effect on the CPU and bandwidth usage for both the client and the server. You can set the guidCT member of DVSESSIONDESC to DPVCTGUID_DEFAULT.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceServer::StopSession

Stops the Microsoft® DirectPlay® Voice session.

HRESULT StopSession(
DWORD dwFlags
);

Parameters

dwFlags
Flag. The following flag can be set.
DVFLAGS_NOHOSTMIGRATE
The host will not migrate regardless of session and transport settings. Use this flag when you want to shut down the voice session completely.

Return Values

Returns DV_OK if successful, or one of the following error values.

DVERR_ALREADYPENDING
DVERR_INVALIDFLAGS
DVERR_INVALIDOBJECT
DVERR_INVALIDPARAM
DVERR_NOTHOSTING
DVERR_NOTINITIALIZED
DVERR_SESSIONLOST

Remarks

This method returns DVERR_ALREADYPENDING if it is called while another thread is processing a StopSession request.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceTest

Applications use the CheckAudioSetup method of the IDirectPlayVoiceTest interface to test the Microsoft® DirectPlay® Voice audio configuration.

Audio Configuration CheckAudioSetup

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlayVoiceTest::CheckAudioSetup

Runs the Audio Setup Wizard on the specified devices. This wizard runs a series of tests on the devices to determine if they are capable of full duplex audio and to ensure that the microphone is plugged in and working correctly on the capture device.

HRESULT CheckAudioSetup(
const GUID * pguidPlaybackDevice,
const GUID * pguidCaptureDevice,
HWND hwndParent,
DWORD dwFlags
);

Parameters

pguidPlaybackDevice
Pointer to the GUID that identifies the playback device to test. If NULL is passed for this parameter, Microsoft® DirectPlay® Voice tests the system default playback device defined by Microsoft® DirectSound®. You can also pass one of the DirectSound default GUIDs:
DSDEVID_DefaultPlayback
The system default playback device.
DSDEVID_DefaultVoicePlayback
The default voice playback device.
pguidCaptureDevice
Pointer to the GUID that identifies the capture device to test. If NULL is passed for this parameter, DirectPlay Voice tests the system default capture device defined by DirectSound. You can also pass one of the DirectSound default GUIDs:
DSDEVID_DefaultCapture
The default system capture device. You can also specify this device by passing a NULL pointer in the device GUID parameter.
DSDEVID_DefaultVoiceCapture
The default voice communications capture device. Typically, this is a secondary device such as a USB headset with microphone.
hwndParent
The test wizard invoked by this method is modal. If the calling application has a window that should be the parent window of the wizard, it should pass a handle to that window in this parameter. If the calling application does not have a window, it can pass NULL. If the DVFLAGS_QUERYONLY flag is specified, this parameter is not used and the application can pass NULL.
dwFlags
Flags. The following flags can be set.
DVFLAGS_QUERYONLY
Audio setup is not run. Instead, the method checks the registry to see if the devices have been tested. If the devices have not been tested, the method returns DVERR_RUNSETUP. If the devices have been tested, the method returns DV_FULLDUPLEX if the devices support full duplex audio, or DV_HALFDUPLEX if the devices do not support full duplex audio.
DVFLAGS_ALLOWBACK
Passing this flag enables the Back button on the wizard's Welcome page. If the user clicks the Back button on the Welcome page, the wizard exits, and CheckAudioSetup returns DVERR_USERBACK.

Return Values

Returns DV_OK, DV_FULLDUPLEX, DV_HALFDUPLEX if successful, or one of the following error values.

DVERR_INVALIDPARAM
DVERR_RUNSETUP
DVERR_INVALIDDEVICE

Remarks

This method contains user interface (UI) elements and displays dialog boxes. If the DVFLAGS_QUERYONLY flag is specified, the tests are not actually run and no UI is raised. Instead, the registry is checked to determine the results of a previous test of these devices.

If the user cancels the wizard, the CheckAudioSetup call returns DVERR_USERCANCEL. The calling application can then handle the situation appropriately. For example, in DirectPlay Voice part of the gaming options control panel application, if the user clicks Cancel, the dialog box displays a message indicating that voice cannot be used because the wizard has been canceled.

This method might return DVERR_INVALIDDEVICE if the device specified does not exist. Also, if you specify the default device and this method still returns this error, then there are no sound devices on the system.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


IDirectPlay8LobbyClient

The IDirectPlay8LobbyClient interface is used by a lobby client application and is responsible for enumerating and launching lobby-enabled game applications on the local computer, and communicating with them once they are running. The lobby client must register a message handler routine to process messages from the lobby and the lobbied game application.

The methods of the IDirectPlay8LobbyClient interface are:

IDirectPlay8LobbyClient Methods | Close
 | ConnectApplication
 | EnumLocalPrograms
 | Initialize
 | ReleaseApplication
 | Send
 | GetConnectionSettings
 | SetConnectionSettings

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbyClient::Close

Deletes the lobby client.

HRESULT Close(
const DWORD dwFlags
);

Parameters

dwFlags
Reserved, must be 0.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_UNINITIALIZED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbyClient::ConnectApplication

Connects a lobby-enabled application to the session specified in the DPL_CONNECT_INFO structure. If the application is not running, this method can be used to launch the application.

When the connection is successfully established, the lobbied application generates a DPL_MSGID_CONNECT system message to the message handler.

HRESULT ConnectApplication(
DPL_CONNECT_INFO *const pdplConnectionInfo,
const PVOID pvUserApplicationContext,
DPNHANDLE *const phApplication,
const DWORD dwTimeOut,
const DWORD dwFlags
);

Parameters

pdplConnectionInfo
Pointer to a DPL_CONNECT_INFO structure, which describes the connection parameters, including the GUID of the application to connect to.
pvUserApplicationContext
Pointer to a context value defined for the lobby client that is passed in calls to the lobby client's message handler.
phApplication
Pointer to a DPNHANDLE that specifies the application connect handle that is set if this method succeeds. This handle is used for further communication with the application. Additionally, this handle is used in the phApplication parameter in the IDirectPlay8LobbyClient::ReleaseApplication method.
dwTimeOut
Variable of type DWORD that specifies the number of milliseconds to wait for the connection to process.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_CANTLAUNCHAPPLICATION
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM
DPNERR_TIMEDOUT

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbyClient::EnumLocalPrograms

Enumerates the lobbied applications that are registered on the system.

HRESULT EnumLocalPrograms(
GUID *const pGuidApplication,
BYTE *const pEnumData,
DWORD *const pdwEnumData,
DWORD *const pdwItems.
const DWORD dwFlags
);

Parameters

pGuidApplication
Pointer to a variable of type GUID that specifies the lobbied application to enumerate. This parameter is optional, and passing NULL enumerates all available lobbied applications.
pEnumData
Pointer to a variable of type BYTE, which is filled with a description of the lobbied application.
pdwEnumData
Pointer to variable of type DWORD that specifies the number of bytes contained in the pEnumData buffer. If the buffer in pEnumData is too small, this method returns DPNERR_BUFFERTOOSMALL and sets this parameter to the size of the required buffer.
pdwItems
Pointer to a variable of type DWORD that contains the number of DPL_APPLICATION_INFO structures in the pEnumData buffer. This parameter is filled only if the method succeeds.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

This method is generally called twice—once to obtain the size of the required buffer, and then with the correct buffer size.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbyClient::Initialize

Registers an entry point in the lobby client's code that receives notifications on changes of state for any launched applications. The message handler also receives messages from the lobbied application. This method must be called before calling any other methods of this interface.

HRESULT Initialize(
const PVOID pvUserContext,
const PFNDPNMESSAGEHANDLER pfn,
const DWORD dwFlags
);

Parameters

pvUserContext
Pointer to the user-provided context value provided in calls to the message handler. Providing a user-context value is useful to differentiate messages from multiple interfaces to a common message handler.
pfn
Pointer to a PFNDPNMESSAGEHANDLER callback function that receives all messages from the IDirectPlay8LobbyClient interface and indications of session changes from the IDirectPlay8LobbiedApplication interface.
dwFlags
The following flag can be specified.
DPLINITIALIZE_DISABLEPARAMVAL
Disables parameter validation.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

Call this is method first after using CoCreateInstance to obtain the IDirectPlay8LobbyClient interface.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbyClient::ReleaseApplication

Releases a lobbied application and closes the connection between the lobby client and the application. This method should be called whenever a lobby client has finished its session with an application.

HRESULT ReleaseApplication(
const DPNHANDLE hApplication.
const DWORD dwFlags
);

Parameters

hApplication
The DPNHANDLE of the lobbied application to release. This value is set in the phApplication parameter of the IDirectPlay8LobbyClient::ConnectApplication method. You may also specify the following flag.
DPLHANDLE_ALLAPPLICATIONS
All application connections will be released.
dwFlags
Reserved, must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDHANDLE
DPNERR_INVALIDPARAM

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbyClient::Send

Sends a message to a lobbied application that was launched by this lobby client or was connected by this lobby client.

This method sends a DPL_MSGID_RECEIVE system message to the target's message handler.

HRESULT Send(
const DPNHANDLE hConnection,
BYTE *const pBuffer,
const DWORD pBufferSize,
const DWORD dwFlags
);

Parameters

hConnection
Variable of type DPNHANDLE that specifies the target for the message transmission. You may also specify the following flag.
DPLHANDLE_ALLAPPLICATIONS
The message you have specified will be sent to all lobbied applications that are connected to your lobby client application.
pBuffer
Pointer to an array of bytes that contains the message.
pBufferSize
Variable of type DWORD that specifies the size of the message buffer in the pBuffer parameter, in bytes. This parameter must be at least 1 byte and no more than 64 KB.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDHANDLE
DPNERR_INVALIDPARAM
DPNERR_SENDTOOLARGE

Remarks

If the buffer size is larger than 64 KB, the method returns DPNERR_SENDTOOLARGE. If the buffer size is set to 0, the method returns DPNERR_INVALIDPARAM.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbyClient::GetConnectionSettings

Retrieves the set of connection settings for the specified connection. These settings can be set through a call to the IDirectPlay8LobbyClient::ConnectApplication, IDirectPlay8LobbyClient::SetConnectionSettings, or IDirectPlay8LobbiedApplication::SetConnectionSettings method.

When you get connection settings, a reference will be added for each address object that is returned to the user. Therefore, users must be sure to call Release on each address object when they are finished with the structure.

HRESULT GetConnectionSettings(
const DPNHANDLE hConnection,
DPL_CONNECTION_SETTINGS *const pdplConnectSettings,
DWORD*pdwDataSize,
const DWORD dwFlags
);

Parameters

hConnection
Handle to the connection for which to retrieve the settings.
pdplConnectSettings
Pointer to a buffer to receive the connection settings for the specified connection.
pdwDataSize
Pointer to a DWORD containing the size, in bytes, of the buffer specified in the pdplConnectSettings structure. If the buffer is not large enough to hold the connection settings, DPNERR_BUFFERTOOSMALL is returned and this value is set to the required buffer size. On success, this value contains the number of bytes written to the specified buffer.
dwFlags
Reserved, must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDOBJECT
DPNERR_INVALIDFLAGS

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbyClient::SetConnectionSettings

Sets the connection settings to be associated with the specified connection. Calling this method will generate a DPL_MSGID_CONNECTION_SETTINGS message to be sent to the client specified by hConnection.

When you set connection settings, the lobby application will add a reference to each of the address objects specified in the call.

HRESULT SetConnectionSettings(
const DPNHANDLE hConnection,
const DPL_CONNECTION_SETTINGS *const pdplConnectSettings,
const DWORD dwFlags
);

Parameters

hConnection
Handle to the connection to set the settings for. You may also specify the following flag.
DPLHANDLE_ALLAPPLICATIONS
The connection settings will be updated for all the lobbied applications you are connected to.
pdplConnectSettings
Pointer to a DPL_CONNECTION_SETTINGS structure containing the settings associated with the specified connection.
dwFlags
Reserved, must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDOBJECT
DPNERR_INVALIDFLAGS

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbiedApplication

The IDirectPlay8LobbiedApplication interface is used by an application that supports lobbying. This interface allows the application to register with the system so that it can be lobby launched. Additionally, it also lets the application get the connection information necessary to launch a game without querying the user. Lastly, this interface allows the lobbied application to send messages and notifications to the lobby client that launched the application.

The methods of the IDirectPlay8LobbiedApplication interface are:

IDirectPlay8LobbiedApplication Methods | Close
 | SetAppAvailable
 | Initialize
 | RegisterProgram
 | Send
 | UnRegisterProgram
 | UpdateStatus
 | GetConnectionSettings
 | SetConnectionSettings

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbiedApplication::Close

Deletes the lobbied application.

HRESULT Close(
const DWORD dwFlags
);

Parameters

dwFlags
Reserved, must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_UNINITIALIZED
DPNERR_INVALIDOBJECT
DPNERR_OUTOFMEMORY

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbiedApplication::SetAppAvailable

Makes an application available or unavailable for a lobby client to connect to. This method is typically called if a lobbied application is independently launched, that is, not launched by a lobby client. Additionally, this method should be called if a game has ended and the lobbied application needs to be available to connect to a lobby client at the start of another game.

HRESULT SetAppAvailable(
const BOOL fAvailable,
const DWORD dwFlags
);

Parameters

fAvailable
Boolean value that sets the availability of the application. Set this value to TRUE to indicate that your application is available, or to FALSE to indicate that it is not available.
dwFlags
The following flag can be set for this method.
DPLAVAILABLE_ALLOWMULTIPLECONNECT
The default behavior for this method is to automatically mark the interface as Unavailable when the first connection is established. By specifying this flag, the interface is not automatically marked unavailable after the first connection is established, thereby allowing multiple connections.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDOBJECT
DPNERR_UNINITIALIZED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbiedApplication::Initialize

Registers a message handler function that receives notifications about changes in the state of the lobby client and receives messages from the lobby client.

HRESULT Initialize(
const PVOID pvUserContext,
const PFNDPNMESSAGEHANDLER pfn,
DPNHANDLE *const pdpnhConnection,
const DWORD dwFlags
);

Parameters

pvUserContext
Pointer to the user-provided context value in calls to the message handler. Providing a user-context value is useful to differentiate messages from multiple interfaces to a common message handler.
pfn
Pointer to a PFNDPNMESSAGEHANDLER callback function that receives all messages from the IDirectPlay8LobbyClient interface and indications of session changes from the IDirectPlay8LobbiedApplication interface.
pdpnhConnection
Value used to detect if your application was lobby launched. If your application was lobby launched, this parameter will be set to the connection handle for the lobby client. If your process was not lobby launched, this parameter is set to NULL.
dwFlags
The following flag can be specified.
DPLINITIALIZE_DISABLEPARAMVAL
Disables parameter validation.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

Call this method first after using CoCreateInstance to obtain the IDirectPlay8LobbiedApplication interface.

This method automatically establishes a connection to the lobby client if you were lobby launched. If you call Initialize and you were lobby launched and the lobbied application interface is unable to contact the lobby client process, Initialize will time out after four seconds. In this case, Initialize will return DPNERR_TIMEDOUT but will still succeed.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbiedApplication::RegisterProgram

Registers a lobby-aware application with DirectPlay. Applications must be registered to enable lobby launching.

HRESULT RegisterProgram(
PDPL_PROGRAM_DESC pdplProgramDesc,
const DWORD dwFlags
);

Parameters

pdplProgramDesc
Pointer to the DPL_PROGRAM_DESC structure that describes the lobby-aware application to register.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Remarks

The application needs to register only once. It should be unregistered with a call to the IDirectPlay8LobbiedApplication::UnRegisterProgram method when it is uninstalled.

In Microsoft DirectX® 8.0, RegisterProgram must be used. You cannot manually enter application information in the registry. Failure to use this interface makes your application nonportable and incompatible with future versions of DirectPlay.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbiedApplication::Send

Sends a message from the lobbied application to the lobby client.

HRESULT Send(
const DPNHANDLE hConnection,
BYTE *const pBuffer,
const DWORD pBufferSize,
const DWORD dwFlags
);

Parameters

hConnection
Variable of type DPNHANDLE that specifies the lobby client that the message is sent to. You may also specify the following flag.
DPLHANDLE_ALLAPPLICATIONS
The message you have specified will be sent to all lobby clients to which you are connected.
pBuffer
Pointer to a variable of type BYTE that contains the message buffer.
pBufferSize
Variable of type DWORD that specifies the size of the message buffer in the pBuffer parameter, in bytes. This parameter must be at least 1 byte and no more than 64 KB.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDHANDLE
DPNERR_INVALIDPARAM
DPNERR_SENDTOOLARGE

Remarks

If the buffer size is larger than 64 KB, the method returns DPNERR_SENDTOOLARGE. If the buffer size is set to 0, the method returns DPNERR_INVALIDPARAM.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbiedApplication::UnRegisterProgram

Unregisters a lobby-aware application that was registered through the IDirectPlay8LobbiedApplication::RegisterProgram method.

HRESULT UnRegisterProgram(
GUID* pguidApplication,
const DWORD dwFlags

);

Parameters

pguidApplication
Pointer to the GUID of the application to unregister.
dwFlags
Reserved. Must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDFLAGS
DPNERR_INVALIDPARAM

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbiedApplication::UpdateStatus

Updates the status of a connected lobby client.

HRESULT UpdateStatus(
const DPNHANDLE hConnection,
const DWORD dwStatus,
const DWORD dwFlags
);

Parameters

hConnection
Variable of type DPNHANDLE that specifies the lobby client. You may also specify the following flag.
DPLHANDLE_ALLAPPLICATIONS
The status update will be sent to all lobby clients to which you are connected.
dwStatus
Variable of type DWORD that is filled with one of the following values that indicate the status between the lobby client and the lobbied application.
DPLSESSION_CONNECTED
The lobby client and lobbied application are currently connected.
DPLSESSION_COULDNOTCONNECT
The lobby client was not able to connect to the lobbied application.
DPLSESSION_DISCONNECTED
The lobby client and lobbied application are currently disconnected.
DPLSESSION_TERMINATED
The connection between the lobby client and lobbied application has been terminated.
DPLSESSION_HOSTMIGRATED
The peer object associated with the connection is involved in a session where a host migration takes place and the local client is not the new host.
DPLSESSION_HOSTMIGRATEDHERE
The peer object associated with the connection is involved in a session where a host migration takes place and the local client becomes the new host.
dwFlags
Reserved, must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDHANDLE
DPNERR_INVALIDPARAM

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbiedApplication::GetConnectionSettings

Retrieves the set of connection settings for the specified connection. These settings can be set through a call to the IDirectPlay8LobbyClient::ConnectApplication, IDirectPlay8LobbyClient::SetConnectionSettings, or IDirectPlay8LobbiedApplication::SetConnectionSettings method.

When you get connection settings, a reference will be added for each address object that is returned to the user. Therefore, users must be sure to call Release on each address object when they are done with the structure.

HRESULT GetConnectionSettings(
const DPNHANDLE hLobbyClient,
DPL_CONNECTION_SETTINGS *const pdplSessionInfo,
DWORD* pdwInfoSize,
const DWORD dwFlags
);

Parameters

hLobbyClient
Handle to the connection for which to retrieve the settings.
pdplSessionInfo
Pointer to a DPL_CONNECTION_SETTINGS structure to receive the connection settings for the specified connection.
pdwInfoSize
Pointer to a DWORD containing the size, in bytes, of the buffer specified in the pdplSessionInfo structure. If the buffer is not large enough to hold the connection settings, DPNERR_BUFFERTOOSMALL is returned and this value will be set to the required buffer size. On success, this value will contain the number of bytes written to the specified buffer.
dwFlags
Reserved, must be 0.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPARAM
DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDOBJECT
DPNERR_INVALIDFLAGS

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8LobbiedApplication::SetConnectionSettings

Sets the connection settings to be associated with the specified connection. Calling this method generates a DPL_MSGID_CONNECTION_SETTINGS message to be sent to the client specified by hConnection.

When you set connection settings, the lobby application will add a reference to each of the address objects specified in the call.

HRESULT SetConnectionSettings(
const DPNHANDLE hConnection,
const DPL_CONNECTION_SETTINGS *const pdplConnectSettings,
const DWORD dwFlags
);

Parameters

hConnection
Handle to the connection to set the settings for. You may also specify the following flag.
DPLHANDLE_ALLAPPLICATIONS
The connection settings will be updated for all the lobby clients to which you are connected.
pdplConnectSettings
Pointer to a DPL_CONNECTION_SETTINGS structure containing the settings associated with the specified connection.
dwFlags
Reserved, must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDOBJECT
DPNERR_INVALIDFLAGS

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


IDirectPlay8Address

The IDirectPlay8Address interface contains generic addressing methods used to create and manipulate addresses for Microsoft® DirectPlay®. This interface is one of the interfaces available through the CLSID_DirectPlayAddress COM object. To create an object that supports this interface, use the CoCreateInstanceEx method for the CLSID CLSID_DirectPlayAddress that specifies the IID_IDirectPlayAddress8 interface.

The IDirectPlay8Address interface contains the following methods.

IDirectPlay8Address Methods | BuildFromURLW
 | BuildFromURLA
 | Duplicate
 | SetEqual
 | IsEqual
 | Clear
 | GetURLW
 | GetURLA
 | GetSP
 | GetUserData
 | SetSP
 | SetUserData
 | GetNumComponents
 | GetComponentByName
 | GetComponentByIndex
 | AddComponent
 | GetDevice
 | SetDevice
 | BuildFromDPADDRESS

Remarks

In order to deliver messages, each participant in a multiplayer game must have a unique address. Addresses can refer either to the computer that your application is running on (device address), or a computer that your application needs to communicate with (host address).

DirectPlay represents addresses as URLs. These URLs are then encapsulated in the address object so that they can be passed to or from the DirectPlay API. In general, address URLs are strings that consist of three basic components in the following order: scheme, scheme separator, and data string.

All DirectPlay addresses use "x-directplay" as the scheme, and ":/" as the scheme separator. Using ":/" as a separator implies that the data that follows is opaque. In other words, the data string does not conform to any Internet standard, and should simply be passed on to the receiving application without modification. All DirectPlay URLs thus have the following general form:

x-directplay:/[data string]

There are two basic approaches to handling address objects:

  • Handle the data string directly, using normal string manipulation techniques.
  • Use the methods exposed by IDirectPlay8Address to obtain or modify the individual elements of the data string.

For more information on DirectPlay addresses, see DirectPlay Addressing.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::BuildFromURLW

Sets the object equal to the address in the DirectPlay 8 URL. It erases the contents of the object.

HRESULT BuildFromURLW(
WCHAR* pwszSourceURL
);

Parameters

pwszSourceURL
Pointer to a NULL-terminated Unicode string that contains a properly formatted DirectPlay 8 address.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPOINTER
DPNERR_INVALIDURL
DPNERR_NOTALLOWED

Remarks

The Dpaddr.h header file defines a number of standard strings that you can use to construct your URL instead using a literal string. All of the string names have the form DPNA_XXX. For example, DPNA_HEADER can be used in place of L"x-directplay:/" for the URL header.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::BuildFromURLA

Sets the object equal to the specified in the DirectPlay 8 URL. It erases the contents of the object.

HRESULT BuildFromURLA(
CHAR* pszSourceURL
);

Parameters

pszSourceURL
Pointer to a NULL-terminated ANSI string that contains a properly formatted DirectPlay 8 address.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPOINTER
DPNERR_INVALIDURL
DPNERR_NOTALLOWED

Remarks

The Dpaddr.h header file defines a number of standard strings that you can use to construct your URL instead using a literal string. All of the string names have the form DPNA_XXX. For example, DPNA_HEADER can be used in place of L"x-directplay:/" for the URL header.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::Duplicate

Creates a DirectPlay Address object that duplicates the address in this object.

HRESULT Duplicate(
PDIRECTPLAY8ADDRESS* ppdpaNewAddress
);

Parameters

ppdpaNewAddress
Address of a pointer to receive the IDirectPlay8Address pointer for the duplicate object. DirectPlay increments the reference count for this interface. You must release the interface when you no longer need it.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_GENERIC

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::SetEqual

Sets the contents of the object it is called on to match the contents of the address object passed to the method.

HRESULT SetEqual(
PDIRECTPLAY8ADDRESS pdpaAddress
);

Parameters

pdpaAddress
Pointer to a DirectPlay8Address object that this object will be set to.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDADDRESSFORMAT
DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::IsEqual

Compares two addresses to see if they are equal.

HRESULT IsEqual(
PDIRECTPLAY8ADDRESS pdpaAddress
);

Parameters

pdpaAddress
Address to compare to the address contained within the object.

Return Values

If the method is successful, one of the following values is returned.

DPNSUCCESS_EQUAL
The two addresses are equal.
DPNSUCCESS_NOTEQUAL
The two addresses are not equal.

If the method fails, one of the following error values may be returned.

DPNERR_INVALIDADDRESSFORMAT
DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER

Remarks

This method checks the contents of the address specified by the pdpaAddress parameter and compares it to the address contained within the object this method was called on. This method does not affect the contents of either address.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::Clear

Resets the address object to an empty address.

HRESULT Clear();

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_NOTALLOWED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::GetURLW

Retrieves the DirectPlay 8 address URL string represented by this object.

HRESULT GetURLW(
WCHAR* pwszURL,
PDWORD pdwNumChars
);

Parameters

pwszURL
Address of a pointer to receive the URL represented by this object. This parameter can be NULL if pdwNumChars points to a DWORD containing 0.
pdwNumChars
Pointer to a DWORD that contains the number of characters the specified buffer can hold, including NULL terminator. On success this value contains the number of characters written to the specified buffer, including NULL terminator. On failure this value contains the number of characters, including NULL terminator, required to hold the URL and the method returns DPNERR_BUFFERTOOSMALL.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_GENERIC
DPNERR_INVALIDURL
DPNERR_OUTOFMEMORY

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::GetURLA

Retrieves the Microsoft® DirectPlay® address URL string represented by this object. (ANSI Version.)

HRESULT GetURLA(
CHAR* pszURL,
PDWORD pdwNumChars
);

Parameters

pszURL
Address of a pointer to receive the URL represented by this object. This parameter can be NULL if pdwNumChars points to a DWORD containing 0.
pdwNumChars
Pointer to a DWORD that contains the number of characters the specified buffer can hold, including NULL terminator. On success this value contains the number of characters written to the specified buffer, including NULL terminator. On failure this value contains the number of characters, including NULL terminator, required to hold the URL and the method returns DPNERR_BUFFERTOOSMALL.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_GENERIC
DPNERR_INVALIDURL
DPNERR_OUTOFMEMORY

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::GetSP

Retrieves the service provider GUID in the address object. If no service provider is specified, this method returns DPNERR_DOESNOTEXIST.

HRESULT GetSP(
GUID* pguidSP
);

Parameters

pguidSP
Pointer to a GUID to receive the service provider in the address object.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_DOESNOTEXIST
DPNERR_INVALIDPOINTER

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::GetUserData

Retrieves the user data in the address object. If no user data exists in this address object, this method returns DPNERR_DOESNOTEXIST.

HRESULT GetUserData(
void* pvUserData,
PDWORD pdwBufferSize
);

Parameters

pvUserData
Pointer to a buffer to receive the user data from this address. To retrieve the required size, set this parameter to NULL and the DWORD in pdwBufferSize to 0.
pdwBufferSize
Size in bytes of the buffer pointed to by pvUserData. If pvUserData is NULL, this parameter must point to a DWORD containing 0. On output, the contained DWORD is set to the number of bytes written to the buffer. On failure, this contains the number of bytes required to retrieve the user data and the method returns DPNERR_BUFFERTOOSMALL.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_DOESNOTEXIST
DPNERR_INVALIDPOINTER

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::SetSP

Sets the service provider GUID in the address object. If a service provider is specified for this address, it is overwritten by this call.

HRESULT SetSP(
const GUID *const pguidSP
);

Parameters

pguidSP
Pointer to the service provider GUID.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPOINTER
DPNERR_NOTALLOWED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::SetUserData

Sets the user data in the address object. If there is user data in this address, it is overwritten by this call.

HRESULT SetUserData(
const void *const pvUserData,
const DWORD dwDataSize
);

Parameters

pvUserData
Pointer to a buffer that contains the data to place in the user data section of the address. Set to NULL to clear the user data.
dwDataSize
Size, in bytes, of the data in pvUserData. If pvUserData is NULL, this must be 0.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPOINTER
DPNERR_NOTALLOWED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::GetNumComponents

Retrieves the number of components in the address.

HRESULT GetNumComponents(
PDWORD pdwNumComponents
);

Parameters

pdwNumComponents
Pointer to a DWORD to receive the number of components in this address object.

Return Values

Returns S_OK if successful, or the following error value.

DPNERR_INVALIDPOINTER

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::GetComponentByName

Retrieves information on the component at the specified key. Values for the component are retrieved in their native format. If the component key is not found, DPNERR_DOESNOTEXIST is returned.

The value of the component is retrieved in its native format. Therefore, if the component's value is a DWORD, a DWORD is retrieved by this call. So buffer size = 4 and pvBuffer should be a recast PDWORD.

HRESULT GetComponentByName(
const WCHAR *const pwszName,
void* pvBuffer,
PDWORD pdwBufferSize,
PDWORD pdwDataType
);

Parameters

pwszName
String specifying the name of the component you want to retrieve.
pvBuffer
Buffer to retrieve the data stored in the value of the component. To retrieve the size required, specify NULL for this parameter and 0 for the DWORD pointed to by pdwBufferSize. The method returns DPNERR_BUFFERTOOSMALL in this case.
pdwBufferSize
On input, a pointer to a DWORD that contains the size of the buffer, in bytes, pointed to by pvBuffer. On output, a pointer to a DWORD that contains the number of bytes written to the buffer on success and on failure, the number of bytes required to store the data.
pdwDataType
DWORD pointed to by this parameter that is set to the type of data that is stored in this component. This can be one of the following:
DPNA_DATATYPE_STRING
Data is a NULL-terminated string.
DPNA_DATATYPE_DWORD
Data is a DWORD.
DPNA_DATATYPE_GUID
Data is a GUID.
DPNA_DATATYPE_BINARY
Data is raw binary.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_DOESNOTEXIST
DPNERR_INVALIDPARAM

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::GetComponentByIndex

Retrieves information on the component at the specified index. Values for the component are retrieved in their native format. If the component key is not found, the method returns DPNERR_DOESNOTEXIST.

The value of the component is retrieved in its native format. Therefore, if the component's value is a DWORD, a DWORD is retrieved by this call. So buffer size = 4 and pvBuffer should be a recast PDWORD.

HRESULT GetComponentByIndex(
const DWORD dwComponentID,
WCHAR* pwszName,
PDWORD pdwNameLen,
void* pvBuffer,
PDWORD pdwBufferSize,
PDWORD pdwDataType
);

Parameters

dwComponentID
Index of the component to retrieve. This value is zero-based and should be in the range of [0..GetNumComponents()-1].
pwszName
Buffer to retrieve the name of the component on a successful call. To retrieve the size required, specify NULL for this parameter and 0 for the DWORD pointed to by pdwNameBufferSize. The method returns DPNERR_BUFFERTOOSMAL in this case.
pdwNameLen
On input, a pointer to a DWORD that contains the size of the buffer, in characters including NULL terminator, pointed to by pwszName. On output, a pointer to a DWORD that contains the number of characters written to the buffer, including NULL terminator, on success and on failure, the number of characters required, including NULL terminator, to store this value.
pvBuffer
Buffer to retrieve the data stored in the value of the component. To retrieve the size required, specify NULL for this parameter and 0 for the DWORD pointed to by pdwBufferSize. The method returns DPNERR_BUFFERTOOSMALL in this case.
pdwBufferSize
On input, a pointer to a DWORD containing the size of the buffer, in bytes, pointed to by pvBuffer. On output, a pointer to a DWORD that contains the number of bytes written to the buffer on success and on failure, the number of bytes required to store the data.
pdwDataType
DWORD pointed to by this parameter that is set to the type of data that is stored in this component. This can be one of the following:
DPNA_DATATYPE_STRING
Data is a NULL-terminated string.
DPNA_DATATYPE_DWORD
Data is a DWORD.
DPNA_DATATYPE_GUID
Data is a GUID.
DPNA_DATATYPE_BINARY
Data is raw binary.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_DOESNOTEXIST
DPNERR_INVALIDPARAM

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::AddComponent

Adds a component to the address. If the component is part of the address, then it is replaced by the new value in this call.

Values are specified in native formats when making this call. Therefore, the lpvData parameter should be a recast pointer to a variable that holds the data in the native format. For example, if the component is a GUID, the lpvData parameter should be a recast pointer to a GUID.

This method validates that the predefined component types are the right format.

HRESULT AddComponent(
const WCHAR *const pwszName,
const void *const lpvData,
const DWORD dwDataSize,
const DWORD dwDataType
);

Parameters

pwszName
NULL-terminated Unicode string that contains the key for the component.
lpvData
Pointer to a buffer that contains the value associated with the specified key. Data should be specified in its native format.
dwDataSize
Size, in bytes, of the data in the buffer located at lpvData. The size depends on the data type. If the size is not specified correctly, the method returns DPNERR_INVALIDPARAM.
DWORD
Size = sizeof( DWORD )
GUID
Size = sizeof( GUID )
String
Size = size of the string in bytes, including NULL terminator.
dwDataType
Data type of the value associated with this key. The data type can be one of the following:
DPNA_DATATYPE_STRING
Data is a NULL-terminated string.
DPNA_DATATYPE_DWORD
Data is a DWORD.
DPNA_DATATYPE_GUID
Data is a GUID.
DPNA_DATATYPE_BINARY
Data is in raw binary format.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_NOTALLOWED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::GetDevice

Retrieves the local device GUID in the address object. If no device is specified, this method returns DPNERR_DOESNOTEXIST.

HRESULT GetDevice(
GUID* pguidDevice
);

Parameters

pguidDevice
Pointer to a GUID to receive the device in the address object.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_DOESNOTEXIST
DPNERR_INVALIDPOINTER

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::SetDevice

Sets the local device GUID in the address object. If a local device is specified for this address, it is overwritten by this call.

HRESULT SetDevice(
const GUID *const pguidDevice
);

Parameters

pguidDevice
Pointer to a GUID of the local device.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPOINTER
DPNERR_NOTALLOWED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8Address::BuildFromDPADDRESS

Sets the current object's internal address to be the DirectPlay 8 equivalent of the specified DirectPlay 4 address. The purpose of this method is to allow lobby developers to launch games with the new Microsoft® DirectPlay® interface using the old lobby code.

This method enumerates the address components in the specified address and adds the corresponding element to the DirectPlay 8 address.

HRESULT BuildFromDPADDRESS(
LPVOID pvAddress,
DWORD dwDataSize
);

Parameters

pvAddress
Pointer to a DirectPlay4 address that will be converted to the DirectPlay 8 address format.
dwDataSize
Size of data contained in the pvAddress parameter.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDADDRESSFORMAT
DPNERR_INVALIDOBJECT
DPNERR_INVALIDPOINTER

Remarks

This method builds a DirectPlay 8 address from a DirectPlay4 address. This method will clear the current address of all elements before building the new address.

This method has the following limitations.

  • The method cannot map the DPAID_Modem address element because DirectPlay 4 used modem names, while DirectPlay 8 uses GUIDs to identify modems.
  • Elements of the DirectPlay 4 address that are not part of the predefined DirectPlay 4 address elements will result in an error and a return value of DPNERR_INVALIDADDRESSFORMAT. See DirectPlay 4 documentation on DirectPlay addresses for a complete list of the DirectPlay 4 address elements.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8AddressIP

The IDirectPlay8AddressIP interface is available through the CLSID_DirectPlayAddress COM object. This interface is used for IP provider-specific addressing services.

The IDirectPlay8AddressIP interface contains the following methods.

IDirectPlay8AddressIP Methods | BuildFromSockAddr
 | BuildAddress
 | BuildLocalAddress
 | GetSockAddress
 | GetLocalAddress
 | GetAddress

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8AddressIP::BuildFromSockAddr

Builds a remote DirectPlay 8 IP address from a valid SOCKADDR structure. The SOCKADDR structure must specify an IP address. If the address is not in the correct format, DPNERR_INVALIDPARAM is returned.

The result of a successful call is a valid remote address with the following elements.

  • DPNA_KEY_PROVIDER = CLSID_DP8SP_TCPIP
  • DPNA_KEY_HOSTNAME = specified host name
  • DPNA_KEY_PORT = specified port

All addressing information contained in the object before the call is erased.

HRESULT BuildFromSockAddr(
const SOCKADDR *const pSockAddr
);

Parameters

pSockAddr
Valid UDP address specified in SOCKADDR form.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_NOTALLOWED

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8AddressIP::BuildAddress

Builds a remote DirectPlay 8 IP address from a host name and a port. The result of a successful call is a valid remote address with the following elements.

  • DPNA_KEY_PROVIDER = CLSID_DP8SP_TCPIP
  • DPNA_KEY_HOSTNAME = specified host name
  • DPNA_KEY_PORT = specified port

All addressing information contained in the object before the call is erased.

HRESULT BuildAddress(
const WCHAR *const wszAddress,
const USHORT usPort
);

Parameters

wszAddress
Remote host address can be a dotted Internet address—for example, 127.0.0.1—or a valid host name—for example, example.microsoft.com.
usPort
Port on the remote host to which to connect.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_NOTALLOWED

Remarks

Note The DPNSVR is a DirectPlay feature that allows multiple processes to share a single port for enumeration. Do not use the DPNA_DPNSVR_PORT flag when constructing a device address, or when making a connection. This flag should only be used for enumerations. If you do not add a port element to the enumeration address, the port represented by the flag will be automatically added to that address. See Using the DirectPlay DPNSVR Application for a further discussion of DPNSVR.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8AddressIP::BuildLocalAddress

Builds a local DirectPlay 8 IP address from a device and port. The result of a successful call is a valid remote address with the following elements.

  • DPNA_KEY_PROVIDER = CLSID_DP8SP_TCPIP
  • DPNA_KEY_DEVICE= specified device
  • DPNA_KEY_PORT = specified port

All addressing information contained in the object before the call is erased.

HRESULT BuildLocalAddress(
const GUID *const pguidAdapter,
const USHORT usPort
);

Parameters

pguidAdapter
Local device identifier to host on.
usPort
Port on the local device to host on. This value can be set to 0 to allow DirectPlay 8.0 to automatically select the port.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER
DPNERR_NOTALLOWED

Remarks

Note The DPNSVR is a DirectPlay feature that allows multiple processes to share a single port for enumeration. Do not use the DPNA_DPNSVR_PORT flag when constructing a device address, or when making a connection. This flag should only be used for enumerations. If you do not add a port element to the enumeration address, the port represented by the flag will be automatically added to that address. See Using the DirectPlay DPNSVR Application for a further discussion of DPNSVR.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8AddressIP::GetSockAddress

Retrieves a list of SOCKADDR structures describing the addresses represented by this object. If the host name specified in the object requires a DNS lookup, it is performed. Therefore, this method may block while the DNS is queried. It is also possible for a host name to resolve to multiple addresses.

To succeed, the contained address must have at least the following elements.

  • DPNA_KEY_PROVIDER
  • DPNA_KEY_HOSTNAME
  • DPNA_KEY_PORT = specified port
HRESULT GetSockAddress(
SOCKADDR* psockAddress,
PDWORD pdwAddressBufferSize
);

Parameters

psockAddress
Pointer to buffer to retrieve the array of SOCKADDR structures. There is one SOCKADDR structure for each address the host resolves to.
pdwAddressBufferSize
Size, in bytes, of the buffer specified in psockAddresses. On success, this parameter contains the number of bytes written to the specified buffer. On failure, this parameter contains the number of bytes required to retrieve the array of SOCKADDR structures. You can divide the value of this parameter by the size of the SOCKADDR structure to determine the number of items present in the returned array.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8AddressIP::GetLocalAddress

Retrieves the local address information from a DirectPlay 8 IP address. To succeed, the contained address must have at least the following elements.

  • DPNA_KEY_PROVIDER
  • DPNA_KEY_DEVICE
  • DPNA_KEY_PORT
HRESULT GetLocalAddress(
GUID* pguidAdapter,
USHORT* pusPort
);

Parameters

pguidAdapter
Pointer to a GUID to retrieve the GUID of the local device specified in this address.
pusPort
Pointer to a USHORT to contain the port specified in this local address.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


IDirectPlay8AddressIP::GetAddress

Retrieves the remote address information from a remote DirectPlay 8 IP address. To succeed, the contained address must have at least the following elements.

  • DPNA_KEY_PROVIDER
  • DPNA_KEY_HOSTNAME
  • DPNA_KEY_PORT = specified port
HRESULT GetAddress(
WCHAR* wszAddress,
PDWORD pdwAddressLength,
USHORT* psPort
);

Parameters

wszAddress
Pointer to a buffer to receive the host name. This parameter can be NULL to retrieve the required size.
pdwAddressLength
Size, in characters, of the buffer specified in wszAddress, including NULL terminator. On success, this parameter contains the number of characters, including NULL terminator, written to the specified buffer. On failure, this parameter contains the number of characters, including NULL terminator, required to retrieve the host name.
psPort
Pointer to a USHORT to contain the port specified in this local address.

Return Values

Returns S_OK if successful, or one of the following error values.

DPNERR_BUFFERTOOSMALL
DPNERR_INVALIDPARAM
DPNERR_INVALIDPOINTER

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


Functions

The Microsoft® DirectPlay® functions are:

  • DirectPlay8Create
  • DirectPlay8LobbyCreate
  • DirectPlay8AddressCreate
  • DirectPlayVoiceCreate


DirectPlay8Create

The DirectPlay8Create function is an external creation function used to create interfaces defined in the Dplay8.h header file.

HRESULT WINAPI DirectPlay8Create(
  GUID* pcIID,
  void** ppvInterface,
  IUnknown* pUnknown
);

Parameters

pcIID
Pointer to the interface ID you want to create. You may specify the IID_IDirectPlay8Client, IID_IDirectPlay8Server or IID_IDirectPlay8Peer interface ID.
ppvInterface
Address of a variable to receive the new interface pointer.
pUnknown
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DirectPlay8LobbyCreate

The DirectPlay8LobbyCreate function is an external creation function used to create one of the lobby interfaces defined in the Dplobby8.h header file.

HRESULT WINAPI DirectPlay8LobbyCreate(
  GUID* pcIID,
  void** ppvInterface,
  IUnknown* pUnknown
);

Parameters

pcIID
Pointer to the interface ID you want to create. You may specify the IID_IDirectPlay8LobbiedApplication or IID_IDirectPlay8LobbyClient interface ID.
ppvInterface
Address of a variable to receive the new interface pointer.
pUnknown
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


DirectPlay8AddressCreate

The DirectPlay8AddressCreate function is an external creation function used to create one of the addressing interfaces defined in the Dpaddr.h header file.

HRESULT WINAPI DirectPlay8AddressCreate(
  GUID* pcIID,
  void** ppvInterface,
  IUnknown* pUnknown
);

Parameters

pcIID
Pointer to the interface ID you want to create. You may specify the IID_IDirectPlay8Address or IID_IDirectPlay8AddressIP interface ID.
ppvInterface
Address of a variable to receive the new interface pointer.
pUnknown
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dpaddr.h.


DirectPlayVoiceCreate

The DirectPlayVoiceCreate function is an external creation function used to create one of the interfaces used in Microsoft® DirectPlay® Voice that are defined in the Dvoice.h header file.

HRESULT WINAPI DirectPlayVoiceCreate(
  GUID* pcIID,
  void** ppvInterface,
  IUnknown* pUnknown
);

Parameters

pcIID
Pointer to the interface ID you want to create. You may specify the IID_IDirectPlayVoiceTest, IID_IDirectPlayVoiceClient or IID_IDirectPlayVoiceServer interface ID.
ppvInterface
Address of a variable to receive the new interface pointer.
pUnknown
Address of the controlling object's IUnknown interface for COM aggregation. Must be NULL.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


Callback Functions

The Microsoft® DirectPlay® callback functions are:

  • PFNDPNMESSAGEHANDLER
  • PDVMESSAGEHANDLER


PFNDPNMESSAGEHANDLER

PFNDPNMESSAGEHANDLER is an application-defined callback function used by the IDirectPlay8Peer, IDirectPlay8Client, and IDirectPlay8Server IDirectPlay8LobbyClient and IDirectPlay8LobbiedApplication interfaces to process messages.

typedef HRESULT (WINAPI *PFNDPNMESSAGEHANDLER)(
  PVOID pvUserContext,
  DWORD dwMessageType,
  PVOID pMessage
);

Parameters

pvUserContext
Pointer to the application-defined structure that will be passed to this callback function. This is defined in the pvUserContext parameter of the Initialize method.
dwMessageType
One of the following message types that are generated by the IDirectPlay8Peer, IDirectPlay8Client, and IDirectPlay8Server interfaces. Each interface uses a different subset of the available messages. Refer to the interface documentation for details.
  • DPN_MSGID_ADD_PLAYER_TO_GROUP
  • DPN_MSGID_ASYNC_OP_COMPLETE
  • DPN_MSGID_CLIENT_INFO
  • DPN_MSGID_CONNECT_COMPLETE
  • DPN_MSGID_CREATE_GROUP
  • DPN_MSGID_CREATE_PLAYER
  • DPN_MSGID_DESTROY_GROUP
  • DPN_MSGID_DESTROY_PLAYER
  • DPN_MSGID_ENUM_HOSTS_QUERY
  • DPN_MSGID_ENUM_HOSTS_RESPONSE
  • DPN_MSGID_GROUP_INFO
  • DPN_MSGID_HOST_MIGRATE
  • DPN_MSGID_INDICATE_CONNECT
  • DPN_MSGID_INDICATED_CONNECT_ABORTED
  • DPN_MSGID_PEER_INFO
  • DPN_MSGID_RECEIVE
  • DPN_MSGID_REMOVE_PLAYER_FROM_GROUP
  • DPN_MSGID_RETURN_BUFFER
  • DPN_MSGID_SEND_COMPLETE
  • DPN_MSGID_SERVER_INFO
  • DPN_MSGID_TERMINATE_SESSION

    Additionally, if the application supports Microsoft® DirectPlay® lobby functionality, this parameter can specify one of the following message types that are generated by the IDirectPlay8LobbyClient and IDirectPlay8LobbiedApplication interfaces. Each interface uses a different subset of the available messages. Refer to the interface documentation for details.

  • DPL_MSGID_CONNECT
  • DPL_MSGID_CONNECTION_SETTINGS
  • DPL_MSGID_DISCONNECT
  • DPL_MSGID_RECEIVE
  • DPL_MSGID_SESSION_STATUS
pMessage
Structure containing message information.

Return Values

See the documentation for the individual messages for appropriate return values. Unless otherwise noted, this function should return S_OK.

Remarks

This function must be threadsafe because it might be called reentrantly through multiple threads.

Callback messages from the same player are serialized. Once you receive a message from a player, you will not receive another until you have handled the first message, and the callback function has returned.

The message structures have the same name as the message type except the "DPN_MSGID" is replaces with "DPNMSG". For example, the DPN_MSGID_CONNECTION_TERMINATED message type uses the DPNMSG_CONNECTION_TERMINATED message structure to convey the actual message information.

When implementing this callback function, first look at the message type returned in the dwMessageType parameter and then cast the message structure (pMessage) to that type to obtain message information. Some messages don't have a defined structure because they have no parameters. For these messages, the pMessage parameter is NULL.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


PDVMESSAGEHANDLER

PDVMESSAGEHANDLER is an application-defined callback function used by the IDirectPlayVoiceClient and IDirectPlayVoiceServer interfaces to send messages to the user.

typedef HRESULT (FAR PASCAL *PDVMESSAGEHANDLER)(
  LPVOID pvUserContext,
  DWORD dwMessageType,
  LPVOID lpMessage
);

Parameters

pvUserContext
Pointer to the application-defined structure that will be passed to this callback function. This is defined in the lpUserContext parameter of the IDirectPlayVoiceServer::Initialize and IDirectPlayVoiceClient::Initialize methods.
dwMessageType
One of the following message types.
DVMSGID_CONNECTRESULT
DVMSGID_CREATEVOICEPLAYER
DVMSGID_DELETEVOICEPLAYER
DVMSGID_DISCONNECTRESULT
DVMSGID_GAINFOCUS
DVMSGID_HOSTMIGRATED
DVMSGID_INPUTLEVEL
DVMSGID_LOCALHOSTSETUP
DVMSGID_LOSTFOCUS
DVMSGID_OUTPUTLEVEL
DVMSGID_PLAYEROUTPUTLEVEL
DVMSGID_PLAYERVOICESTART
DVMSGID_PLAYERVOICESTOP
DVMSGID_RECORDSTART
DVMSGID_RECORDSTOP
DVMSGID_SESSIONLOST
DVMSGID_SETTARGETS
lpMessage
Structure containing message information.

Return Values

See the documentation for the individual messages for appropriate return values. Unless otherwise noted, this function should return DV_OK.

Remarks

When implementing this callback function, you must first look at the message type returned in the dwMessageType parameter and then cast the message structure (lpMessage) to that type to obtain message information. Some messages don't have a defined structure because they have no parameters. For these messages, the lpMessage parameter is NULL.

Note This function may be called on multiple different threads at the same time. It must thus be threadsafe and reentrant.

All message structures have the same name as the corresponding message types except the prefix is DVMSG_ instead of DVMSGID_. For example, the structure for DVMSGID_RECORDSTART is DVMSG_RECORDSTART.

The structure sent to the message handler is valid only for the duration of the call. Therefore, if you want to use any of the information passed into the function after the handler function has returned you must make a copy of the data.

Callback messages from the same player are serialized. Once you receive a message from a player, you will not receive another until you have handled the first message, and the callback function has returned.

Only messages that are specified in the message mask through a call to the IDirectPlayVoiceClient::Initialize, IDirectPlayVoiceServer::Initialize, IDirectPlayVoiceClient::SetNotifyMask and IDirectPlayVoiceServer::SetNotifyMask methods are sent to this callback function.

The DVMSGID_GAINFOCUS and DVMSGID_LOSTFOCUS message structures have not been implemented in this release of Microsoft® DirectPlay®.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


System Messages

Microsoft® DirectPlay® messages are received by a DirectPlay callback message handler. DirectPlay uses these messages to convey information from the system to a DirectPlay application.

  • DirectPlay Server Messages
  • DirectPlay Client Messages
  • DirectPlay Lobby Messages
  • DirectPlay Voice Messages

DirectPlay Server Messages

The following messages should be processed by all Microsoft® DirectPlay® server callback message handlers.

  • DPN_MSGID_CREATE_PLAYER
  • DPN_MSGID_DESTROY_PLAYER
  • DPN_MSGID_INDICATE_CONNECT
  • DPN_MSGID_INDICATED_CONNECT_ABORTED
  • DPN_MSGID_RECEIVE
  • DPN_MSGID_RETURN_BUFFER

The following messages can be processed by DirectPlay server callback message handlers, but are not required.

  • DPN_MSGID_ADD_PLAYER_TO_GROUP
  • DPN_MSGID_ASYNC_OP_COMPLETE
  • DPN_MSGID_CLIENT_INFO
  • DPN_MSGID_CREATE_GROUP
  • DPN_MSGID_DESTROY_GROUP
  • DPN_MSGID_GROUP_INFO
  • DPN_MSGID_ENUM_HOSTS_QUERY
  • DPN_MSGID_REMOVE_PLAYER_FROM_GROUP
  • DPN_MSGID_SEND_COMPLETE
  • DPN_MSGID_SERVER_INFO

DirectPlay Client Messages

The following messages should be processed by all DirectPlay client callback message handlers.

  • DPN_MSGID_RECEIVE
  • DPN_MSGID_TERMINATE_SESSION
  • DPN_MSGID_RETURN_BUFFER

The following messages can be processed by DirectPlay client callback message handlers, but are not required.

  • DPN_MSGID_ASYNC_OP_COMPLETE
  • DPN_MSGID_CLIENT_INFO
  • DPN_MSGID_CONNECT_COMPLETE
  • DPN_MSGID_ENUM_HOSTS_RESPONSE
  • DPN_MSGID_SEND_COMPLETE
  • DPN_MSGID_SERVER_INFO
  • DPN_MSGID_GROUP_INFO

DirectPlay Lobby Messages

The following messages are handled by lobby client and lobbied application callback message handlers.

  • DPL_MSGID_CONNECT
  • DPL_MSGID_CONNECTION_SETTINGS
  • DPL_MSGID_DISCONNECT
  • DPL_MSGID_RECEIVE
  • DPL_MSGID_SESSION_STATUS

DirectPlay Voice Messages

The following messages are handled by Microsoft® DirectPlay® voice callback message handlers.

  • DVMSGID_CONNECTRESULT
  • DVMSGID_CREATEVOICEPLAYER
  • DVMSGID_DELETEVOICEPLAYER
  • DVMSGID_DISCONNECTRESULT
  • DVMSGID_GAINFOCUS
  • DVMSGID_HOSTMIGRATED
  • DVMSGID_INPUTLEVEL
  • DVMSGID_LOCALHOSTSETUP
  • DVMSGID_LOSTFOCUS
  • DVMSGID_OUTPUTLEVEL
  • DVMSGID_PLAYEROUTPUTLEVEL
  • DVMSGID_PLAYERVOICESTART
  • DVMSGID_PLAYERVOICESTOP
  • DVMSGID_RECORDSTART
  • DVMSGID_RECORDSTOP
  • DVMSGID_SESSIONLOST
  • DVMSGID_SETTARGETS


DPL_MSGID_CONNECT

Microsoft® DirectPlay® generates a DPL_MSGID_CONNECT message when a lobby client connects to the lobbied application through the IDirectPlay8LobbyClient::ConnectApplication method.

DPL_MESSAGE_CONNECT

The DPL_MESSAGE_CONNECT structure is passed with the DPL_MSGID_CONNECT message.

typedef struct _DPL_MESSAGE_CONNECT{
    DWORD     dwSize;
    DPNHANDLE hConnectId;
    PDPL_CONNECTION_SETTINGS  pdplConnectionSettings;
    PVOID     pvLobbyConnectData;
    DWORD     dwLobbyConnectDataSize;
    PVOID     pvConnectionContext;
} DPL_MESSAGE_CONNECT, *PDPL_MESSAGE_CONNECT;
dwSize
Size of the DPL_MESSAGE_CONNECT message structure. The application must set this member before it uses the structure.
hConnectId
Handle used to identify the connection. This handle is used in subsequent calls to IDirectPlay8LobbyClient::Send and IDirectPlay8LobbyClient::ReleaseApplication.
pdplConnectionSettings
Pointer to a DPL_CONNECTION_SETTINGS structure with connection information.
pvLobbyConnectData
Pointer to lobby connection data.
dwLobbyConnectDataSize
Variable of type DWORD specifying the size of the data contained in the pvLobbyConnectData member.
pvConnectionContext
Context value associated with this connection. For lobbied applications, set this parameter when this message is received in your message handler to associate the context value with the connection. This may be set to NULL to disable context values.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


DPL_MSGID_CONNECTION_SETTINGS

The DPL_MSGID_CONNECTION_SETTINGS message is sent from the lobby client to the lobby application when IDirectPlay8LobbyClient::SetConnectionSettings is called. It is also sent from the lobby application to the lobby client when IDirectPlay8LobbiedApplication::SetConnectionSettings is called. The contents of the message are valid only for the duration of the message callback. Therefore, if you want to use the data contained in the message, you must make a copy before returning. In addition, if you want to use the addressing objects you must call AddRef on each address to ensure you retain a reference.

DPL_MESSAGE_CONNECTION_SETTINGS

The DPL_MESSAGE_CONNECTION_SETTINGS structure is passed with the DPL_MSGID_CONNECTION_SETTINGS message.

typedef struct _DPL_MESSAGE_CONNECTION_SETTINGS{
    DWORD               dwSize;
    DPNHANDLE           hSender;
    PDPL_CONNECTION_SETTINGS   pdplConnectionSettings;
    PVOID               pvConnectionContext
} DPL_MESSAGE_CONNECTION_SETTINGS, *PDPL_MESSAGE_CONNECTION_SETTINGS;
dwSize
Contains the size of the DPL_MESSAGE_CONNECTION_SETTINGS structure. It should be set to sizeof( DPL_MESSAGE_CONNECTION_SETTINGS ).
hSender
Contains the handle for the connection that sent this message.
pdplConnectionSettings
Contains a pointer to a DPL_CONNECTION_SETTINGS structure describing the connection settings for the specified connection.
pvConnectionContext
Pointer to a context value that has been set for the connection.

Remarks

For lobbied applications, the context value is set through the pvConnectionContext member of the DPL_MESSAGE_CONNECT message structure. When your message handler receives this message, whatever you set this member to before returning will be the context value for that connection.

For lobby clients, the pvConnectionContext parameter in the IDirectPlay8LobbyClient::ConnectApplication method will be used as the connection's context value if the connection is successful.

Context values are not shared between lobby client and lobbied application. For example, if you set your context value for a lobby connection in your IDirectPlay8LobbyClient interface to pointer A and in your IDirectPlay8LobbiedApplication interface you set it to pointer B, indications in your IDirectPlay8LobbyClient interface will have pointer A as their context value and in your IDirectPlay8LobbiedApplication interface pointer B will be the context value.

You can also set your context values to NULL if you do not want to use this feature.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


DPL_MSGID_DISCONNECT

Microsoft® DirectPlay® generates a DPL_MSGID_DISCONNECT message when a lobby client disconnects from a lobbied application through the IDirectPlay8LobbyClient::ReleaseApplication method.

DPL_MESSAGE_DISCONNECT

The DPL_MESSAGE_DISCONNECT structure contains information for the DPL_MSGID_DISCONNECT system message.

typedef struct _DPL_MESSAGE_DISCONNECT{
    DWORD     dwSize;
    DPNHANDLE hDisconnectId;
    HRESULT   hrReason;
    PVOID     pvConnectionContext;
} DPL_MESSAGE_DISCONNECT, *PDPL_MESSAGE_DISCONNECT;
dwSize
Size of the DPL_MESSAGE_DISCONNECT message structure. The application must set this member before it uses the structure.
hDisconnectId
Handle specifying the disconnection ID.
hrReason
Reason for the disconnection.
S_OK
It was a standard disconnection.
DPNERR_CONNECTIONLOST
This will be set if the process running the client or application exited abnormally.
pvConnectionContext
Context value that has been set for the connection.

Remarks

For lobbied applications, the context value is set through the pvConnectionContext member of the DPL_MESSAGE_CONNECT message structure. When your message handler receives this message, whatever you set this member to before returning will be the context value for that connection.

For lobby clients, the pvConnectionContext parameter in the IDirectPlay8LobbyClient::ConnectApplication method will be used as the connection's context value if the connection is successful.

Context values are not shared between lobby client and lobbied application. For example, if you set your context value for a lobby connection in your IDirectPlay8LobbyClient interface to pointer A and in your IDirectPlay8LobbiedApplication interface you set it to pointer B, indications in your IDirectPlay8LobbyClient interface will have pointer A as their context value and in your IDirectPlay8LobbiedApplication interface pointer B will be the context value.

You can also set your context values to NULL if you do not want to use this feature.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


DPL_MSGID_RECEIVE

Microsoft® DirectPlay® generates the DPL_MSGID_RECEIVE message when the target receives a message sent by the IDirectPlay8LobbyClient::Send or IDirectPlay8LobbiedApplication::Send method.

DPL_MESSAGE_RECEIVE

The DPL_MESSAGE_RECEIVE structure contains information for the DPL_MSGID_RECEIVE system message.

typedef struct _DPL_MESSAGE_RECEIVE{
    DWORD     dwSize;
    DPNHANDLE hSender;
    BYTE*     pBuffer;
    DWORD     dwBufferSize;
    PVOID     pvConnectionContext;
} DPL_MESSAGE_RECEIVE, *PDPL_MESSAGE_RECEIVE;
dwSize
Size of the DPL_MESSAGE_RECEIVE message structure. The application must set this member before it uses the structure.
hSender
Handle of the client that sent the message.
pBuffer
Pointer to message data.
dwBufferSize
Size of the message data contained in the pBuffer member.
pvConnectionContext
Context value that has been set for the connection.

Remarks

For lobbied applications, the context value is set through the pvConnectionContext member of the DPL_MESSAGE_CONNECT message structure. When your message handler receives this message, whatever you set this member to before returning will be the context value for that connection.

For lobby clients, the pvConnectionContext parameter in the IDirectPlay8LobbyClient::ConnectApplication method will be used as the connection's context value if the connection is successful.

Context values are not shared between lobby client and lobbied application. For example, if you set your context value for a lobby connection in your IDirectPlay8LobbyClient interface to pointer A and in your IDirectPlay8LobbiedApplication interface you set it to pointer B, indications in your IDirectPlay8LobbyClient interface will have pointer A as their context value and in your IDirectPlay8LobbiedApplication interface pointer B will be the context value.

You can also set your context values to NULL if you do not want to use this feature.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


DPL_MSGID_SESSION_STATUS

Microsoft® DirectPlay® generates the DPL_MSGID_SESSION_STATUS message when the session has been updated with a call to the IDirectPlay8LobbiedApplication::UpdateStatus method.

DPL_MESSAGE_SESSION_STATUS

The DPL_MESSAGE_SESSION_STATUS structure contains information for the DPL_MSGID_SESSION_STATUS system message.

typedef struct _DPL_MESSAGE_SESSION_STATUS{
    DWORD dwSize;
    DPNHANDLE hSender;
    DWORD dwStatus;
    PVOID pvConnectionContext;
} DPL_MESSAGE_SESSION_STATUS, *PDPL_MESSAGE_SESSION_STATUS;
dwSize
Size of the DPL_MESSAGE_SESSION_STATUS message structure. The application must set this member before it uses the structure.
hSender
The handle of the application that sent the status update message.
dwStatus
Updated status of the session. This member can be set to one of the following values.
DPLSESSION_CONNECTED
The lobbied application is currently connected to a session.
DPLSESSION_COULDNOTCONNECT
The lobbied application could not connect to the session.
DPLSESSION_DISCONNECTED
The lobbied application is currently disconnected from the session.
DPLSESSION_TERMINATED
The connection between session host and the lobbied application has been terminated.
DPLSESSION_HOSTMIGRATED
The host of a peer-to-peer session has migrated. The local client is not the new host.
DPLSESSION_HOSTMIGRATEDHERE
The host of a peer-to-peer session has migrated. The local client is the new host.
pvConnectionContext
Context value that has been set for the connection.

Remarks

For lobbied applications, the context value is set through the pvConnectionContext member of the DPL_MESSAGE_CONNECT message structure. When your message handler receives this message, whatever you set this member to before returning will be the context value for that connection.

For lobby clients, the pvConnectionContext in the IDirectPlay8LobbyClient::ConnectApplication method will be used as the connection's context value if the connection is successful.

Context values are not shared between lobby client and lobbied application. For example, if you set your context value for a lobby connection in your IDirectPlay8LobbyClient interface to pointer A and in your IDirectPlay8LobbiedApplication interface you set it to pointer B, indications in your IDirectPlay8LobbyClient interface will have pointer A as their context value and in your IDirectPlay8LobbiedApplication interface pointer B will be the context value.

You can also set your context values to NULL if you do not want to use this feature.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


DPN_MSGID_APPLICATION_DESC

This message indicates that the application description has been changed. There is no accompanying structure. To determine the new application description, call the GetApplicationDesc method exposed by IDirectPlay8Peer, IDirectPlay8Client, or IDirectPlay8Server interfaces.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


DPN_MSGID_ADD_PLAYER_TO_GROUP

Microsoft® DirectPlay® generates the DPN_MSGID_ADD_PLAYER_TO_GROUP message when a player has been added to a group in a peer-to-peer or client/server session.

DPNMSG_ADD_PLAYER_TO_GROUP

The DPNMSG_ADD_PLAYER_TO_GROUP structure contains information for the DPN_MSGID_ADD_PLAYER_TO_GROUP system message.

typedef struct _DPNMSG_ADD_PLAYER_TO_GROUP{
    DWORD  dwSize;
    DPNID  dpnidGroup;
    PVOID  pvGroupContext;
    DPNID  dpnidPlayer;
    PVOID  pvPlayerContext;
} DPNMSG_ADD_PLAYER_TO_GROUP, *PDPNMSG_ADD_PLAYER_TO_GROUP;
dwSize
Size of this structure.
dpnidGroup
DPNID of the group to add the player.
pvGroupContext
Group context value.
dpnidPlayer
DPNID of the player added to the group.
pvPlayerContext
Player context value.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_ASYNC_OP_COMPLETE

Microsoft® DirectPlay® generates the DPN_MSGID_ASYNC_OP_COMPLETE message when an asynchronous request has completed.

DPNMSG_ASYNC_OP_COMPLETE

The DPNMSG_ASYNC_OP_COMPLETE structure contains information for the DPN_MSGID_ASYNC_OP_COMPLETE system message.

typedef struct _DPNMSG_ASYNC_OP_COMPLETE{
    DWORD      dwSize;
    DPNHANDLE  hAsyncOp;
    PVOID      pvUserContext;
    HRESULT    hResultCode;
} DPNMSG_ASYNC_OP_COMPLETE, *PDPNMSG_ASYNC_OP_COMPLETE;
dwSize
Size of this structure.
hAsyncOp
Asynchronous operation handle.
pvUserContext
Supplied user context.
hResultCode
HRESULT indicating the result of the asynchronous operation.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_CLIENT_INFO

Microsoft® DirectPlay® generates the DPN_MSGID_CLIENT_INFO message when client data is modified during a client/server session.

DPNMSG_CLIENT_INFO

The DPNMSG_CLIENT_INFO structure contains information for the DPN_MSGID_CLIENT_INFO system message.

typedef struct _DPNMSG_CLIENT_INFO{
    DWORD  dwSize;
    DPNID  dpnidClient;
    PVOID  pvPlayerContext;
} DPNMSG_CLIENT_INFO, *PDPNMSG_CLIENT_INFO;
dwSize
Size of this structure.
dpnidClient
DPNID of the client for client information.
pvPlayerContext
Player context value.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_CONNECT_COMPLETE

Microsoft® DirectPlay® generates the DPN_MSGID_CONNECT_COMPLETE message when the connection attempt has been completed in a peer-to-peer or client/server session. This message is generated whether or not the connection was successful.

DPNMSG_CONNECT_COMPLETE

The DPNMSG_CONNECT_COMPLETE structure contains information for the DPN_MSGID_CONNECT_COMPLETE system message.

typedef struct _DPNMSG_CONNECT_COMPLETE{
    DWORD      dwSize;
    DPNHANDLE  hAsyncOp;
    PVOID      pvUserContext;
    HRESULT    hResultCode;
    PVOID      pvApplicationReplyData;
    DWORD      dwApplicationReplyDataSize;
} DPNMSG_CONNECT_COMPLETE, *PDPNMSG_CONNECT_COMPLETE;
dwSize
Size of this structure.
hAsyncOp
Asynchronous operation handle.
pvUserContext
User context supplied when the IDirectPlay8Peer::Connect or IDirectPlay8Client::Connect methods are called.
hResultCode
HRESULT describing the result of the connection attempt. See the Return Values section in the IDirectPlay8Peer::Connect or IDirectPlay8Client::Connect method for more information. Additionally, DPNERR_PLAYERNOTREACHABLE will be returned if a player has tried to join a peer-to-peer session where at least one other existing player in the session cannot connect to the joining player.
pvApplicationReplyData
Connection reply data returned from the host or server.
dwApplicationReplyDataSize
Size of the data, in bytes, of the pvApplicationReplyData member.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_CREATE_GROUP

Microsoft® DirectPlay® generates the DPN_MSGID_CREATE_GROUP message when a group is created.

DPNMSG_CREATE_GROUP

The DPNMSG_CREATE_GROUP structure contains information for the DPN_MSGID_CREATE_GROUP system message.

typedef struct _DPNMSG_CREATE_GROUP{
    DWORD  dwSize;
    DPNID  dpnidGroup;
    DPNID  dpnidOwner;
    PVOID  pvGroupContext;
} DPNMSG_CREATE_GROUP, *PDPNMSG_CREATE_GROUP;
dwSize
Size of this structure.
dpnidGroup
DPNID of the of the created group.
dpnidOwner
DPNID of the of the group's owner. This value is only set for groups that have the DPNGROUP_AUTODESTRUCT flag set in the dwGroupFlags member of the DPN_GROUP_INFO structure.
pvGroupContext
Group context value.

Remarks

The only method of setting the group context value is through this system message. Group context values once set cannot be changed.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_CREATE_PLAYER

Microsoft® DirectPlay® generates the DPN_MSGID_CREATE_PLAYER message when a player is added to a peer-to-peer or client/server session.

DPNMSG_CREATE_PLAYER

The DPNMSG_CREATE_PLAYER structure contains information for the DPN_MSGID_CREATE_PLAYER system message.

typedef struct _DPNMSG_CREATE_PLAYER{
    DWORD  dwSize;
    DPNID  dpnidPlayer;
    PVOID  pvPlayerContext;
} DPNMSG_CREATE_PLAYER, *PDPNMSG_CREATE_PLAYER;
dwSize
Size of this structure.
dpnidPlayer
DPNID of the player that was added to the session.
pvPlayerContext
Player context value.

Remarks

The only method of setting the player context value is through this system message. You can either set the player context value directly, through this message, or indirectly through DPN_MSGID_INDICATE_CONNECT. Once a player context value has been set, it cannot be changed.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_DESTROY_PLAYER

Microsoft® DirectPlay® generates the DPN_MSGID_DESTROY_PLAYER message when a player leaves a peer-to-peer or client/server session.

DPNMSG_DESTROY_PLAYER

The DPNMSG_DESTROY_PLAYER structure contains information for the DPN_MSGID_DESTROY_PLAYER system message.

typedef struct _DPNMSG_DESTROY_PLAYER{
    DWORD  dwSize;
    DPNID  dpnidPlayer;
    PVOID  pvPlayerContext;
    DWORD  dwReason;
} DPNMSG_DESTROY_PLAYER, *PDPNMSG_DESTROY_PLAYER;
dwSize
Size of this structure.
dpnidPlayer
DPNID of the player deleted from the session.
pvPlayerContext
Player context value.
dwReason
One of the following flags indicating why the player was destroyed.
DPNDESTROYPLAYERREASON_NORMAL
The player is being deleted for normal reasons.
DPNDESTROYPLAYERREASON_CONNECTIONLOST
The player is being deleted because the connection was lost.
DPNDESTROYPLAYERREASON_SESSIONTERMINATED
The player is being deleted because the session was terminated.
DPNDESTROYPLAYERREASON_HOSTDESTROYEDPLAYER
The player is being deleted because the host called IDirectPlay8Peer::DestroyPeer.

Remarks

In client/server mode, this message is received only by the server. In peer-to-peer mode, all players receive this message.

You may receive DPN_MSGID_CREATE_PLAYER and DPN_MSGID_DESTROY_PLAYER messages on different threads. However, you will not receive a DPN_MSGID_DESTROY_PLAYER message before your callback function has returned from receiving a DPN_MSGID_CREATE_PLAYER message.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_DESTROY_GROUP

Microsoft® DirectPlay® generates the DPN_MSGID_DESTROY_GROUP message when a group is destroyed from a peer-to-peer or client/server session.

DPNMSG_DESTROY_GROUP

The DPNMSG_DESTROY_GROUP structure contains information for the DPN_MSGID_DESTROY_GROUP system message.

typedef struct _DPNMSG_DESTROY_GROUP{
    DWORD  dwSize;
    DPNID  dpnidGroup;
    PVOID  pvGroupContext;
    DWORD  dwReason;
} DPNMSG_DESTROY_GROUP, *PDPNMSG_DESTROY_GROUP;
dwSize
Size of this structure.
dpnidGroup
DPNID of the group deleted from the session.
pvGroupContext
Group context value.
dwReason
One of the following flags indicating why the player was destroyed.
DPNDESTROYGROUPREASON_SESSIONTERMINATED
The group is being destroyed because the session was terminated.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_ENUM_HOSTS_QUERY

Microsoft® DirectPlay® sends the DPN_MSGID_ENUM_HOSTS_QUERY message to the host's message handler when a peer or client is enumerating the available hosts.

DPNMSG_ENUM_HOSTS_QUERY

The DPNMSG_ENUM_HOSTS_QUERY structure contains information for the DPN_MSGID_ENUM_HOSTS_QUERY system message.

typedef struct _DPNMSG_ENUM_HOSTS_QUERY{
    DWORD                dwSize;
    IDirectPlay8Address* pAddressSender;
    IDirectPlay8Address* pAddressDevice;
    PVOID                pvReceivedData;
    DWORD                dwReceivedDataSize;
    DWORD                dwMaxResponseDataSize;
    PVOID                pvResponseData;
    DWORD                dwResponseDataSize;
    PVOID                pvResponseContext;
} DPNMSG_ENUM_HOSTS_QUERY, *PDPNMSG_ENUM_HOSTS_QUERY;
dwSize
Size of this structure.
pAddressSender
Pointer an IDirectPlay8Address interface specifying the address of the sender. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.
pAddressDevice
Pointer an IDirectPlay8Address interface specifying the address of the device. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.
pvReceivedData
Pointer to the data received from the enumeration.
dwReceivedDataSize
Size of the data pointed to in the pvReceivedData member.
dwMaxResponseDataSize
Maximum allowed size for the enumeration response.
pvResponseData
Pointer to the response data from the enumeration. This data must be valid beyond the scope of the callback message handler. It cannot be stack-based. You will receive a DPN_MSGID_RETURN_BUFFER message when Microsoft® DirectPlay® is finished with this buffer.
dwResponseDataSize
Size of the data pointed to in the pvResponseData member.
pvUserContext
Pointer to a response context value. This value will be passed to the host's message handler with the DPN_MSGID_RETURN_BUFFER message as the pvUserContext member of the associated structure.

Remarks

When you respond normally to this query, DirectPlay will send you a DPN_MSGID_RETURN_BUFFER message once the buffer is no longer needed. You can then safely free the buffer.

You can reject the query by returning a value that is not equal to S_OK. However, when you reject a query, DirectPlay does not send a reply, does not need a reply buffer, and does not generate a DPN_MSGID_RETURN_BUFFER message.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_ENUM_HOSTS_RESPONSE

Microsoft® DirectPlay® sends the DPN_MSGID_ENUM_HOSTS_RESPONSE message to a peer or client's message handler to convey the host's response to an enumeration request.

DPNMSG_ENUM_HOSTS_RESPONSE

The DPNMSG_ENUM_HOSTS_RESPONSE structure contains information for the DPN_MSGID_ENUM_HOSTS_RESPONSE system message.

typedef struct _DPNMSG_ENUM_HOSTS_RESPONSE{
    DWORD                         dwSize;
    IDirectPlay8Address*          pAddressSender;
    IDirectPlay8Address*          pAddressDevice;
    const DPN_APPLICATION_DESC*   pApplicationDescription;
    PVOID                         pvResponseData;
    DWORD                         dwResponseDataSize;
    PVOID                         pvUserContext;
    DWORD                         dwRoundTripLatencyMS;
} DPNMSG_ENUM_HOSTS_RESPONSE, *PDPNMSG_ENUM_HOSTS_RESPONSE;
dwSize
Size of this structure.
pAddressSender
Pointer to an IDirectPlay8Address interface specifying the address of the host responding to the enumeration. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.
pAddressDevice
Pointer an IDirectPlay8Address interface specifying the address of the device. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.
pApplicationDescription
Pointer to a DPN_APPLICATION_DESC structure containing the application description.
pvResponseData
Pointer to the response data from the enumeration.
dwResponseDataSize
Size of the data pointed to in the pvResponseData member.
pvUserContext
Pointer to the user context value. This value is the same as the user context value passed to IDirectPlay8Peer::EnumHosts or IDirectPlay8Client::EnumHosts.
dwRoundTripLatencyMS
Latency measured in milliseconds.

Remarks

Because there is no buffer to fill, this message does not generate a DPN_MSGID_RETURN_BUFFER message.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_GROUP_INFO

Microsoft® DirectPlay® generates the DPN_MSGID_GROUP_INFO message when group data is modified during a peer-to-peer or client/server session.

DPNMSG_GROUP_INFO

The DPNMSG_GROUP_INFO structure contains information for the DPN_MSGID_GROUP_INFO system message.

typedef struct _DPNMSG_GROUP_INFO{
    DWORD  dwSize;
    DPNID  dpnidGroup;
    PVOID  pvGroupContext;
} DPNMSG_GROUP_INFO, *PDPNMSG_GROUP_INFO;
dwSize
Size of this structure.
dpnidGroup
DPNID of the group for group information.
pvGroupContext
Group context value.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_HOST_MIGRATE

Microsoft® DirectPlay® generates the DPN_MSGID_HOST_MIGRATE message if the DPNSESSION_MIGRATE_HOST flag is set in the DPN_APPLICATION_DESC structure and the host has migrated.

DPNMSG_HOST_MIGRATE

The DPNMSG_HOST_MIGRATE structure contains information for the DPN_MSGID_HOST_MIGRATE system message.

typedef struct _DPNMSG_HOST_MIGRATE{
    DWORD  dwSize;
    DPNID  dpnidNewHost;
    PVOID  pvPlayerContext;
} DPNMSG_HOST_MIGRATE, *PDPNMSG_HOST_MIGRATE;
dwSize
Size of this structure.
dpnidNewHost
DPNID of the player that is now hosting the session.
pvPlayerContext
Player context value.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_INDICATE_CONNECT

Microsoft® DirectPlay® generates the DPN_MSGID_INDICATE_CONNECT message when a player attempts to connect to a peer-to-peer or client/server session.

DPNMSG_INDICATE_CONNECT

The DPNMSG_INDICATE_CONNECT structure contains information for the DPN_MSGID_INDICATE_CONNECT system message.

This structure gives the opportunity for the host application to allow or reject the connection based on user data and provide reply information to the connecting application.

typedef struct {
    DWORD     dwSize;
    PVOID     pvUserConnectData;
    DWORD     dwUserConnectDataSize;
    PVOID     pvReplyData;
    DWORD     dwReplyDataSize;
    PVOID     pvReplyContext;
    PVOID     pvPlayerContext;
    IDirectPlay8Address*  pAddressPlayer;
    IDirectPlay8Address*  pAddressDevice;
} DPNMSG_INDICATE_CONNECT, *PDPNMSG_INDICATE_CONNECT;
dwSize
Size of this structure.
pvUserConnectData
Data of the connecting player.
dwUserConnectDataSize
Size of the data, in bytes, contained in the pvUserConnectData member.
pvReplyData
Connection reply data. This data must be valid beyond the scope of the callback message handler. You will receive a DPN_MSGID_RETURN_BUFFER message when Microsoft® DirectPlay® is finished with this buffer.
dwReplyDataSize
Size of the data, in bytes, contained in the pvReplyData member.
pvReplyContext
Buffer context for pvReplyData. This value will be passed to the host's message handler with the DPN_MSGID_RETURN_BUFFER message as the pvUserContext member of the associated structure.
pvPlayerContext
Player context preset.
pAddressPlayer
Pointer to an IDirectPlay8Address interface for the connecting player. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.
pAddressDevice
Pointer to an IDirectPlay8Address interface for the device receiving the connect attempt. You must call IDirectPlay8Address::AddRef to increment the interface's reference count. Call IDirectPlay8Address::Release when you no longer need the interface.

Remarks

Return S_OK to allow the player to join the session. Any other return value will reject the requested connection. The hResultCode member of the structure associated with the DPN_MSGID_CONNECT_COMPLETE message that is sent to the player requesting a connection will be set to S_OK if the connection was successful. If the connection is rejected, hResultCode will be set to DPNERR_HOSTREJECTEDCONNECTION, not the value you return from this message.

When an DPN_MSGID_INDICATE_CONNECT notification arrives on the host player's message handler, setting pvPlayerContext before returning the thread will preset the player context value on the respective DPN_MSGID_CREATE_PLAYER notification. This feature allows you to pass a player context value to DPN_MSGID_CREATE_PLAYER.

If you set a player context value, that value is not frozen until the subsequent DPN_MSGID_CREATE_PLAYERmessage has been processed. You thus have the option of modifying this player context value when you process DPN_MSGID_CREATE_PLAYER.

If a client drops the connection after the server has processed the DPN_MSGID_INDICATE_CONNECT message but before it has processed DPN_MSGID_CREATE_PLAYER, the server will receive a DPN_MSGID_INDICATED_CONNECT_ABORTED message. If you receive this message, free any memory that you allocated while processing DPN_MSGID_INDICATE_CONNECT. Once DPN_MSGID_CREATE_PLAYER has been processed, this memory should be freed when you process DPN_MSGID_DESTROY_PLAYER.

If you specify a value for pvUserConnectData, you will subsequently be sent a DPN_MSGID_RETURN_BUFFER message to notify you that you can safely free the buffer.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_INDICATED_CONNECT_ABORTED

Microsoft® DirectPlay® generates the DPN_MSGID_INDICATED_CONNECT_ABORTED message if a player's connection drops after it was indicated on the host, but prior to being added to the session though DPN_MSGID_CREATE_PLAYER.

DPNMSG_INDICATED_CONNECT_ABORTED

The DPNMSG_INDICATED_CONNECT_ABORTED structure contains information for the DPN_MSGID_INDICATED_CONNECT_ABORTED system message.

typedef struct {
    DWORD  dwSize;
    PVOID  pvPlayerContext;
} DPNMSG_INDICATED_CONNECT_ABORTED, *PDPNMSG_INDICATED_CONNECT_ABORTED;
dwSize
Size of this structure.
pvPlayerContext
Player context value.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_PEER_INFO

Microsoft® DirectPlay® generates the DPN_MSGID_PEER_INFO message when peer data is modified during a peer-to-peer session.

DPNMSG_PEER_INFO

The DPNMSG_PEER_INFO structure contains information for the DPN_MSGID_PEER_INFO system message.

typedef struct {
    DWORD  dwSize;
    DPNID  dpnidPeer;
    PVOID  pvPlayerContext;
} DPNMSG_PEER_INFO, *PDPNMSG_PEER_INFO;
dwSize
Size of this structure.
dpnidPeer
DPNID of the peer for peer information.
pvPlayerContext
Player context value.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_RECEIVE

Microsoft® DirectPlay® generates the DPN_MSGID_RECEIVE message when a message has been processed by the receiver.

DPNMSG_RECEIVE

The DPNMSG_RECEIVE structure contains information for the DPN_MSGID_RECEIVE system message.

typedef struct {
    DWORD      dwSize;
    DPNID      dpnidSender;
    PVOID      pvPlayerContext;
    PBYTE      pReceiveData;
    DWORD      dwReceiveDataSize;
    DPNHANDLE  hBufferHandle;
} DPNMSG_RECEIVE, *PDPNMSG_RECEIVE;
dwSize
Size of this structure.
dpnidSender
DPNID of the player that sent the message.
pvPlayerContext
Player context value of the player that sent the message.
pReceiveData
PBYTE pointer to the message data buffer. This buffer is normally only valid while the DPN_MSGID_RECEIVE message is being processed by the callback message handler. Because you should not spend large amounts of time processing messages, you should copy this data, and process the message. Alternatively, you can return DPNSUCCESS_PENDING from the callback message handler. Doing so transfers ownership of the buffer to the application. If you return DPNSUCCESS_PENDING, you must call IDirectPlay8Peer::ReturnBuffer, IDirectPlay8Client::ReturnBuffer, or IDirectPlay8Server::ReturnBuffer when you are finished with the buffer. Pass the method the value you receive in the hBufferHandle member to identify the buffer. If you fail to call ReturnBuffer, you will create a memory leak.
dwReceiveDataSize
Size of the data, in bytes, of the pReceiveData member.
hBufferHandle
Buffer handle for the pReceiveData member. If you have returned DPNSUCCESS_PENDING , pass this value to ReturnBuffer to notify Microsoft® DirectPlay® to free the buffer.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_REMOVE_PLAYER_FROM_GROUP

Microsoft® DirectPlay® generates the DPN_MSGID_REMOVE_PLAYER_FROM_GROUP message when a player has been deleted from a group in a peer-to-peer or client/server session.

DPNMSG_REMOVE_PLAYER_FROM_GROUP

The DPNMSG_REMOVE_PLAYER_FROM_GROUP structure contains information for the DPN_MSGID_REMOVE_PLAYER_FROM_GROUP system message.

typedef struct _DPNMSG_REMOVE_PLAYER_FROM_GROUP{
    DWORD  dwSize;
    DPNID  dpnidGroup;
    PVOID  pvGroupContext;
    DPNID  dpnidPlayer;
    PVOID  pvPlayerContext;
} DPNMSG_REMOVE_PLAYER_FROM_GROUP, *PDPNMSG_REMOVE_PLAYER_FROM_GROUP;
dwSize
Size of this structure.
dpnidGroup
DPNID of the group that the player was deleted from.
pvGroupContext
Group context value.
dpnidPlayer
DPNID of the player deleted from the group.
pvPlayerContext
Player context value.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_RETURN_BUFFER

Microsoft® DirectPlay® generates the DPN_MSGID_RETURN_BUFFER message when DirectPlay is done with a user buffer.

DPNMSG_RETURN_BUFFER

The DPNMSG_RETURN_BUFFER structure contains information for the DPN_MSGID_RETURN_BUFFER system message.

typedef struct {
    DWORD      dwSize;
    HRESULT    hResultCode;
    PVOID      pvBuffer;
    PVOID      pUserContext;
} DPNMSG_RETURN_BUFFER, *PDPNMSG_RETURN_BUFFER;
dwSize
Size of this structure.
hResultCode
Return value of the operation. This will be set to DPNERR_ENUMRESPONSETOOLARGE if the response to a DPN_MSGID_ENUM_HOSTS_QUERY message is too large.
pvBuffer
Pointer to the buffer being returned.
pUserContext
Context value associated with the buffer.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_SEND_COMPLETE

Microsoft® DirectPlay® generates the DPN_MSGID_SEND_COMPLETE message when a send message request has completed.

DPNMSG_SEND_COMPLETE

The DPNMSG_SEND_COMPLETE structure contains information for the DPN_MSGID_SEND_COMPLETE system message.

typedef struct {
    DWORD      dwSize;
    DPNHANDLE  hAsyncOp;
    PVOID      pvUserContext;
    HRESULT    hResultCode;
    DWORD      dwSendTime;
} DPNMSG_SEND_COMPLETE, *PDPNMSG_SEND_COMPLETE;
dwSize
Size of this structure.
hAsyncOp
Asynchronous operation handle.
pvUserContext
User context supplied in the IDirectPlay8Client::Send, IDirectPlay8Peer::SendTo and IDirectPlay8Server::SendTo methods.
hResultCode
HRESULT indicating the result of the send message request.
dwSendTime
Total time, in milliseconds, between send call and completion.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_SERVER_INFO

Microsoft® DirectPlay® generates the DPN_MSGID_SERVER_INFO message when server data is modified during a client/server session.

DPNMSG_SERVER_INFO

The DPNMSG_SERVER_INFO structure contains information for the DPN_MSGID_SERVER_INFO system message.

typedef struct {
    DWORD  dwSize;
    DPNID  dpnidServer;
    PVOID  pvPlayerContext;
} DPNMSG_SERVER_INFO, *PDPNMSG_SERVER_INFO;
dwSize
Size of this structure.
dpnidServer
DPNID of the server for server information.
pvPlayerContext
Player context value.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_MSGID_TERMINATE_SESSION

Microsoft® DirectPlay® generates the DPN_MSGID_TERMINATE_SESSION message when a session is terminated by the host.

DPNMSG_TERMINATE_SESSION

The DPNMSG_TERMINATE_SESSION structure contains information for the DPN_MSGID_TERMINATE_SESSION system message.

typedef struct {
    DWORD   dwSize;
    HRESULT hResultCode;
    PVOID   pvTerminateData;
    DWORD   dwTerminateDataSize;
} DPNMSG_TERMINATE_SESSION, *PDPNMSG_TERMINATE_SESSION;
dwSize
Size of this structure.
hResultCode
Specifies how the session was terminated. This member is set to DPNERR_HOSTTERMINATEDSESSION if the session was peer-to-peer, and the host called IDirectPlay8Peer::TerminateSession. If the session was ended by the host calling Close, or if the host stops responding, hResultCode is set to DPNERR_CONNECTIONLOST.
pvTerminateData
Termination data. If hResultCode is set to DPNERR_HOSTTERMINATEDSESSION, pvTerminateData points to the data block that the host passed through the pvTerminateData parameter of IDirectPlay8Peer::TerminateSession.
dwTerminateDataSize
Size of the data block pointed to by pvTerminateData. This member will be zero if pvTerminateData is set to NULL.

Remarks

In a peer-peer game that permits host-migration, if the current host calls Close or stops responding, the session does not terminate. Instead, the host migrates and all nonhost players receive a DPN_MSGID_DESTROY_PLAYER message for the host's players, and a DPN_MSGID_HOST_MIGRATE message for the new host. To prevent host migration, the host must shut down the session by calling IDirectPlay8Peer::TerminateSession. When the host terminates a session this way, all players receive a DPN_MSGID_TERMINATE_SESSION message with hResultCode set to DPNERR_HOSTTERMINATEDSESSION. The session will terminate, generating DPN_MSGID_DESTROY_PLAYER messages for every player.

In a peer-peer game that does not permit host-migration, the session is terminated if the host calls IDirectPlay8Peer::Close, or stops responding. In that case, DPN_MSGID_TERMINATE_SESSION is sent to all players with hResultCode set to DPNERR_CONNECTIONLOST. The session will terminate, generating DPN_MSGID_DESTROY_PLAYER messages for every player.

In a client/server game, the session is also terminated if the host calls IDirectPlay8Server::Close or stops responding. In that case, DPN_MSGID_TERMINATE_SESSION is sent to all connected clients with hResultCode set to DPNERR_CONNECTIONLOST. The DPN_MSGID_DESTROY_PLAYER message not sent to clients. If the server disconnected by calling IDirectPlay8Server::Close, it will receive DPN_MSGID_DESTROY_PLAYER messages for all players, including its own. Otherwise, the server will only receive DPN_MSGID_DESTROY_PLAYER for the clients' players.

Note The DPN_MSGID_TERMINATE_SESSION message typically arrives before any DPN_MSGID_DESTROY_PLAYER messages. However, the order of arrival is not guaranteed.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DVMSGID_CONNECTRESULT

Microsoft® DirectPlay® Voice generates the DVMSGID_CONNECTRESULT message when the connect request generated through a call to the IDirectPlayVoiceClient::Connect method has completed. This message is sent only if the Connect method is called asynchronously.

DVMSG_CONNECTRESULT

The DVMSG_CONNECTRESULT structure contains information for the DVMSGID_CONNECTRESULT system message.

typedef struct {
    DWORD    dwSize;
    HRESULT  hrResult;
} DVMSG_CONNECTRESULT, *LPDVMSG_CONNECTRESULT, *PDVMSG_CONNECTRESULT;
dwSize
Size of the DVMSG_CONNECTRESULT message structure.
hrResult
Result of the connection attempt.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_CREATEVOICEPLAYER

Microsoft® DirectPlay® Voice generates the DVMSGID_CREATEVOICEPLAYER message when a new player joins the voice session.

Upon connecting to a voice session, clients will receive one of these messages for each player in the voice session. These messages are sent only to clients in peer-to-peer voice sessions.

The host receives these messages when players join the voice session.

Players do not join the voice session until they have called IDirectPlayVoiceClient::Connect. Therefore, it is possible for a player to be in the transport session but not part of the voice session.

DVMSG_CREATEVOICEPLAYER

The DVMSG_CREATEVOICEPLAYER structure contains information for the DVMSGID_CREATEVOICEPLAYER system message.

typedef struct {
    DWORD  dwSize;
    DVID   dvidPlayer;
    DWORD  dwFlags;
    PVOID  pvPlayerContext;
} DVMSG_CREATEVOICEPLAYER, *LPDVMSG_CREATEVOICEPLAYER, *PDVMSG_CREATEVOICEPLAYER;
dwSize
Size of the this message structure.
dvidPlayer
DVID of the player who connected.
dwFlags
Flag specifying information about the player:
DVPLAYERCAPS_HALFDUPLEX
The specified player is running in half duplex mode. The player will only be able to receive voice, not transmit it.
DVPLAYERCAPS_LOCAL
The player is the local player.
pvPlayerContext
Player context value for the player in the voice session. This value is set through this parameter when this message is received.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_DELETEVOICEPLAYER

For clients, Microsoft® DirectPlay® Voice generates the DVMSGID_DELETEVOICEPLAYER message when a player quits the voice session. This message is available only to clients in peer-to-peer voice sessions.

For the host, Microsoft® DirectPlay® Voice generates the DVMSGID_DELETEVOICEPLAYER message when a player quits the voice session.

Players do not leave the voice session until they have called IDirectPlayVoiceClient::Disconnect or they have disconnected from the transport session. Therefore, a client might be part of the transport session but not part of the voice session.

DVMSG_DELETEVOICEPLAYER

The DVMSG_DELETEVOICEPLAYER structure contains information for the DVMSGID_DELETEVOICEPLAYER system message.

typedef struct {
    DWORD  dwSize;
    DVID   dvidPlayer;
    PVOID  pvPlayerContext;
} DVMSG_DELETEVOICEPLAYER, *LPDVMSG_DELETEVOICEPLAYER, *PDVMSG_DELETEVOICEPLAYER;
dwSize
Size of the DVMSG_DELETEVOICEPLAYER message structure.
dvidPlayer
DVID of player who disconnected.
pvPlayerContext
Pointer to the context value set for the player. This value is set through the pvPlayerContext member of the DVMSG_CREATEVOICEPLAYER message structure.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_DISCONNECTRESULT

Microsoft® DirectPlay® Voice generates the DVMSGID_DISCONNECTRESULT message when the disconnect request generated through a call to the IDirectPlayVoiceClient::Disconnect method has completed. This message is sent only if the Disconnect method is called asynchronously.

DVMSG_DISCONNECTRESULT

The DVMSG_DISCONNECTRESULT structure contains information for the DVMSGID_DISCONNECTRESULT system message.

typedef struct {
    DWORD   dwSize;
    HRESULT hrResult;
} DVMSG_DISCONNECTRESULT, *LPDVMSG_DISCONNECTRESULT, *PDVMSG_DISCONNECTRESULT;
dwSize
Size of the DVMSG_DISCONNECTRESULT message structure.
hrResult
Result of the disconnect request.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_GAINFOCUS

The DVMSGID_GAINFOCUS message is sent to notify you that you have begun capturing audio. It is sent when an application that has lost capture focus recovers it. There is no data associated with this message. Refer to the Microsoft® DirectSound® documentation for more information on capturing audio.


DVMSGID_HOSTMIGRATED

Microsoft® DirectPlay® Voice generates the DVMSGID_HOSTMIGRATED message when the voice host has changed.

DVMSG_HOSTMIGRATED

The DVMSG_HOSTMIGRATED structure contains information for the DVMSGID_HOSTMIGRATED system message.

typedef struct {
    DWORD                   dwSize;
    DVID                    dvidNewHostID;
    LPDIRECTPLAYVOICESERVER pdvServerInterface;
} DVMSG_HOSTMIGRATED, *LPDVMSG_HOSTMIGRATED, *PDVMSG_HOSTMIGRATED;
dwSize
Size of the DVMSG_HOSTMIGRATED message structure.
dvidNewHostID
DVID of the new host.
pdvServerInterface
If the local client has become the new voice session host, this member will point to a newly created IDirectPlayVoiceServer object that can be used by the local client for providing host services. If the local client is not the new host, then this member will be NULL. If this parameter points to an IDirectPlayVoiceServer interface, you must call IDirectPlayVoiceServer::AddRef to increment the interface's reference count. Call IDirectPlayVoiceServer::Release when you no longer need the interface.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_INPUTLEVEL

Microsoft® DirectPlay® Voice generates the DVMSGID_INPUTLEVEL message periodically to notify the user of the input level from the microphone. The period of notification is set by the dwNotifyPeriod member of the DVCLIENTCONFIG structure. If the notification period is set to 0, this message will not be sent. In addition, if the client is running in half duplex mode, this message is not available.

DVMSG_INPUTLEVEL

The DVMSG_INPUTLEVEL structure contains information for the DVMSGID_INPUTLEVEL system message.

typedef struct {
    DWORD dwSize;
    DWORD dwPeakLevel;
    LONG  lRecordVolume;
    PVOID pvLocalPlayerContext;
} DVMSG_INPUTLEVEL, *LPDVMSG_INPUTLEVEL, *PDVMSG_INPUTLEVEL;
dwSize
Size of the DVMSG_INPUTLEVEL message structure.
dwPeakLevel
Integer representing peak level across the current frame, which corresponds to approximately 1/10 second of audio stream. The current frame typically lags 50-200 ms behind real-time. This value can range from 0 through 99, with 0 being completely silent and 99 being the highest possible input level.
lRecordVolume
Current recording volume for the client. The value can range from -10,000 to 0. This member is available even when automatic gain control is active.
pvLocalPlayerContext
Pointer to the context value set for the local player. This value is set through the pvPlayerContext member of the DVMSG_CREATEVOICEPLAYER message structure.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_LOCALHOSTSETUP

The DVMSGID_LOCALHOSTSETUP message is sent when the local client is elected to become the new voice host during host migration. The message is sent before the DVMSGID_HOSTMIGRATED message and gives you the chance to set the callback function and context value that will be used when creating the new host object. If you do not set either of the values, then the new server interface will have no callback function. Once the application returns from handling this message it will receive the DVMSGID_HOSTMIGRATED message. The new message has the following associated structure, which is passed in the void * field of the message handler.

DVMSG_LOCALHOSTSETUP

The DVMSG_LOCALHOSTSETUP structure contains information for the DVMSGID_LOCALHOSTSETUP system message.

typedef struct {
    DWORD dwSize;
    PVOID pvContext;
    PDVMESSAGEHANDLER pMessageHandler;
} DVMSG_LOCALHOSTSETUP, *LPDVMSG_LOCALHOSTSETUP, *PDVMSG_LOCALHOSTSETUP;
dwSize
Size of the DVMSG_LOCALHOSTSETUP message structure.
pvContext
Set to the context value you want to set for the new server.
pMessageHandler
Set to the callback function to be used for the new server.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_LOSTFOCUS

The DVMSGID_LOSTFOCUS message is sent to notify you that you have stopped capturing audio. It is sent when an application that has capture focus loses it to another application. There is no data associated with this message. Refer to the Microsoft® DirectSound® documentation for more information on capturing audio.


DVMSGID_OUTPUTLEVEL

Microsoft® DirectPlay® Voice generates the DVMSGID_OUTPUTLEVEL message periodically to notify the user of the output level of playback. The period of notification is set by the dwNotifyPeriod member of the DVCLIENTCONFIG structure. If the notification period is set to 0, this message will not be sent.

DVMSG_OUTPUTLEVEL

The DVMSG_OUTPUTLEVEL structure contains information for the DVMSGID_OUTPUTLEVEL system message.

typedef struct {
    DWORD  dwSize;
    DWORD  dwPeakLevel;
    LONG   lOutputVolume;
    PVOID  pvLocalPlayerContext;
} DVMSG_OUTPUTLEVEL, *LPDVMSG_OUTPUTLEVEL, *PDVMSG_OUTPUTLEVEL;
dwSize
Size of the DVMSG_OUTPUTLEVEL message structure.
dwPeakLevel
Integer representing the current output level of playback. This value is in the range from 0 through 99, with 0 being completely silent and 99 being the highest possible output level.
lOutputVolume
Current playback volume for the client.
pvLocalPlayerContext
Pointer to the context value set for the local player. This value is set through the pvPlayerContext member of the DVMSG_CREATEVOICEPLAYER message structure.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_PLAYEROUTPUTLEVEL

Microsoft® DirectPlay® Voice generates the DVMSGID_PLAYEROUTPUTLEVEL message periodically to notify the user of the output level of an individual player's voice stream. It is generated while voice is being played back for an individual player. If multiple player voices are being played, one message for each player speaking will be sent each notification period.

The period of notification is set by the dwNotifyPeriod member of the DVCLIENTCONFIG structure. If the notification period is set to 0, this message will not be sent.

DVMSG_PLAYEROUTPUTLEVEL

The DVMSG_PLAYEROUTPUTLEVEL structure contains information for the DVMSGID_PLAYEROUTPUTLEVEL system message.

typedef struct {
    DWORD  dwSize;
    DVID   dvidSourcePlayerID;
    DWORD  dwPeakLevel;
    PVOID  pvPlayerContext;
} DVMSG_PLAYEROUTPUTLEVEL, *LPDVMSG_PLAYEROUTPUTLEVEL, *PDVMSG_PLAYEROUTPUTLEVEL;
dwSize
Size of the DVMSG_PLAYEROUTPUTLEVEL message structure.
dvidSourcePlayerID
DVID of the player whose voice is being played back.
dwPeakLevel
Integer representing the current output level of the player's voice stream. This value is in the range from 0 through 99, with 0 being completely silent and 99 being the highest possible output level.
pvPlayerContext
Pointer to the context value set for the player. This value is set through the pvPlayerContext member of the DVMSG_CREATEVOICEPLAYER message structure.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_PLAYERVOICESTART

Microsoft® DirectPlay® Voice generates the DVMSGID_PLAYERVOICESTART message when an incoming audio stream begins playing back.

DVMSG_PLAYERVOICESTART

The DVMSG_PLAYERVOICESTART structure contains information for the DVMSGID_PLAYERVOICESTART system message.

typedef struct {
    DWORD  dwSize;
    DVID   dvidSourcePlayerID;
    PVOID  pvPlayerContext;
} DVMSG_PLAYERVOICESTART, *LPDVMSG_PLAYERVOICESTART, *PDVMSG_PLAYERVOICESTART;
dwSize
Size of the DVMSG_PLAYERVOICESTART message structure.
dvidSourcePlayerID
DVID of the player where the voice transmission originated.
pvPlayerContext
Pointer to the context value set for the player. This value is set through the pvPlayerContext member of the DVMSG_CREATEVOICEPLAYER message structure.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_PLAYERVOICESTOP

Microsoft® DirectPlay® Voice generates the DVMSGID_PLAYERVOICESTOP message when an incoming audio stream stops.

DVMSG_PLAYERVOICESTOP

The DVMSG_PLAYERVOICESTOP structure contains information for the DVMSGID_PLAYERVOICESTOP system message.

typedef struct {
    DWORD  dwSize;
    DVID   dvidSourcePlayerID;
    PVOID  pvPlayerContext;
} DVMSG_PLAYERVOICESTOP, *LPDVMSG_PLAYERVOICESTOP, *PDVMSG_PLAYERVOICESTOP;
dwSize
Size of the DVMSG_PLAYERVOICESTOP message structure.
dvidSourcePlayerID
DVID of the player where the voice transmission originated.
pvPlayerContext
Pointer to the context value set for the player. This value is set through the pvPlayerContext member of the DVMSG_CREATEVOICEPLAYER message structure.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_RECORDSTART

Microsoft® DirectPlay® Voice generates the DVMSGID_RECORDSTART message when audio input on the local client begins. This can be caused by the voice activation sensitivity level being exceeded or when a valid target is specified in push-to-talk mode.

DVMSG_RECORDSTART

The DVMSG_RECORDSTART structure contains information for the DVMSGID_RECORDSTART system message.

typedef struct {
    DWORD  dwSize;
    DWORD  dwPeakLevel;
    PVOID pvLocalPlayerContext;
} DVMSG_RECORDSTART, *LPDVMSG_RECORDSTART, *PDVMSG_RECORDSTART;
dwSize
Size of the DVMSG_RECORDSTART message structure.
dwPeakLevel
Voice activation level that caused the transmission to begin. In push-to-talk mode, this value is 0.
pvLocalPlayerContext
Pointer to the context value set for the local player. This value is set through the pvPlayerContext member of the DVMSG_CREATEVOICEPLAYER message structure.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_RECORDSTOP

Microsoft® DirectPlay® Voice generates the DVMSGID_RECORDSTOP message when audio input on the local client stops. This can be caused by the voice activation sensitivity level not being reached or when a target is deselected in push-to-talk mode.

DVMSG_RECORDSTOP

The DVMSG_RECORDSTOP structure contains information for the DVMSGID_RECORDSTOP system message.

typedef struct {
    DWORD dwSize;
    DWORD dwPeakLevel;
    PVOID pvLocalPlayerContext;
} DVMSG_RECORDSTOP, *LPDVMSG_RECORDSTOP, *PDVMSG_RECORDSTOP;
dwSize
Size of the DVMSG_RECORDSTOP message structure.
dwPeakLevel
Voice activation level that caused the transmission to stop. In push-to-talk mode, this value is 0.
pvLocalPlayerContext
Pointer to the context value set for the local player. This value is set through the pvPlayerContext member of the DVMSG_CREATEVOICEPLAYER message structure.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_SESSIONLOST

Microsoft® DirectPlay® Voice generates the DVMSGID_SESSIONLOST message when the voice session terminates.

DVMSG_SESSIONLOST

The DVMSG_SESSIONLOST structure contains information for the DVMSGID_SESSIONLOST system message.

typedef struct {
    DWORD   dwSize;
    HRESULT hrResult;
} DVMSG_SESSIONLOST, *LPDVMSG_SESSIONLOST, *PDVMSG_SESSIONLOST;
dwSize
Size of the DVMSG_SESSIONLOST message structure.
hrResult
HRESULT indicating why the session was terminated.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


DVMSGID_SETTARGETS

Microsoft® DirectPlay® Voice generates the DVMSGID_SETTARGETS message when the IDirectPlayVoiceClient::SetTransmitTargets or IDirectPlayVoiceServer::SetTransmitTargets methods are called.

DVMSG_SETTARGETS

The DVMSG_SETTARGETS structure contains information for the DVMSGID_SETTARGETS system message.

typedef struct {
    DWORD dwSize;
    DWORD dwNumTargets;
    PDVID pdvidTargets;
} DVMSG_SETTARGETS, *LPDVMSG_SETTARGETS, *PDVMSG_SETTARGETS;
dwSize
Size of the DVMSG_SETTARGETS message structure.
dwNumTargets
Number of DVIDs contained in the pdvidTargets member.
pdvidTargets
Array of DVIDs specifying the set targets. This can also be set to NULL if there are no targets.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice.h.


Structures

The Microsoft® DirectPlay® structures are:

  • DPL_APPLICATION_INFO
  • DPL_CONNECT_INFO
  • DPL_CONNECTION_SETTINGS
  • DPL_PROGRAM_DESC
  • DPN_APPLICATION_DESC
  • DPN_BUFFER_DESC
  • DPN_CAPS
  • DPN_CONNECTION_INFO
  • DPN_GROUP_INFO
  • DPN_PLAYER_INFO
  • DPN_SECURITY_CREDENTIALS
  • DPN_SECURITY_DESC
  • DPN_SERVICE_PROVIDER_INFO
  • DPN_SP_CAPS
  • DVCAPS
  • DVCLIENTCONFIG
  • DVCOMPRESSIONINFO
  • DVSESSIONDESC
  • DVSOUNDDEVICECONFIG


DPL_APPLICATION_INFO

Used in the pEnumData parameter of the IDirectPlay8LobbyClient::EnumLocalPrograms method to describe the lobbied application.

typedef struct _DPL_APPLICATION_INFO {
    GUID  guidApplication;
    PWSTR pwszApplicationName;
    DWORD dwNumRunning;
    DWORD dwNumWaiting;
    DWORD dwFlags;
} DPL_APPLICATION_INFO,  *PDPL_APPLICATION_INFO;

Members

guidApplication
Variable of type GUID specifying the lobbied application.
pwszApplicationName
Pointer to a variable of type WSTR containing the name of the lobbied application.
dwNumRunning
Number of instances of the application.
dwNumWaiting
Number of clients waiting to connect to the lobbied application.
dwFlags
Reserved. Must be 0.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


DPL_CONNECT_INFO

Used to specify connection information for a lobby client when connecting to the lobby application in the IDirectPlay8LobbyClient::ConnectApplication method.

typedef struct _DPL_CONNECT_INFO {
    DWORD dwSize;
    DWORD dwFlags;
    GUID  guidApplication;
    PDPL_CONNECTION_SETTINGS pdplConnectionSettings;
    PVOID pvLobbyConnectData;
    DWORD dwLobbyConnectDataSize;
} DPL_CONNECT_INFO,  *PDPL_CONNECT_INFO;

Members

dwSize
Size of the DPL_CONNECT_INFO structure. The application must set this member before it uses the structure.
dwFlags
One of the following flags, which determine connection behavior.
DPLCONNECT_LAUNCHNEW
Launches a new instance of the application.
DPLCONNECT_LAUNCHNOTFOUND
Launches a new instance of the application only if there is currently no application running that can supply launch settings.
guidApplication
Variable of type GUID specifying the application.
pdplConnectionSettings
Contains the connection settings you want to associate with the connection when it is established.
pvLobbyConnectData
Pointer to connection data passed to the lobbied application.
dwLobbyConnectDataSize
Variable of type DWORD specifying the size of the data buffer in the pvLobbyConnectData member.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


DPL_CONNECTION_SETTINGS

Used to specify the settings you want to associate with a connection. These settings contain all the information required to create, initialize and connect/host a Microsoft® DirectPlay® object.

typedef struct _DPL_CONNECTION_SETTINGS {
    DWORD                   dwSize;
    DWORD                   dwFlags;
    DPN_APPLICATION_DESC    dpnAppDesc;
    IDirectPlay8Address*    pdp8HostAddress;
    IDirectPlay8Address**   ppdp8DeviceAddresses;
    DWORD                   cNumDeviceAddresses;
    PWSTR                   pwszPlayerName
} DPL_CONNECTION_SETTINGS, *PDPL_CONNECTION_SETTINGS;

Members

dwSize
Size of the DPL_CONNECTION_SETTINGS structure. The application must set this to sizeof( DPL_CONNECTION_SETTINGS ) before using this structure.
dwFlags
Combination of the following flags.
DPLCONNECTSETTINGS_CLIENTSERVER
The application should be launched with a client/server session.
DPLCONNECTSETTINGS_HOST
The application should host the session.
dpnAppDesc
Pointer to the application description that should be passed to the Connect or Host call when DirectPlay initialized.
pdp8HostAddress
If DPLCONNECTSETTINGS_HOST is not specified, this is the address of the session the client should connect to. If DPLCONNECTSETTINGS_HOST is specified, this member must be NULL.
ppdp8DeviceAddresses
This structure contains an array of pointers to device addresses. If DPLCONNECTSETTINGS_HOST is specified, this member will contain the addresses the host should listen on. If DPLCONNECTSETTINGS_HOST is not specified, this member will contain the address of the devices the client should use when connecting.
cNumDeviceAddresses
Number of addresses specified in the ppdp8DeviceAddresses member.
pwszPlayerName
Can be used to pass the player name you want the DirectPlay object to use when launching. This member can be NULL.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


DPL_PROGRAM_DESC

Describes a Microsoft® DirectPlay® lobby-aware application.

typedef struct _DPL_PROGRAM_DESC {
    DWORD dwSize;
    DWORD dwFlags;
    GUID  guidApplication;
    PWSTR pwszApplicationName;
    PWSTR pwszCommandLine;
    PWSTR pwszCurrentDirectory;
    PWSTR pwszDescription;
    PWSTR pwszExecutableFilename;
    PWSTR pwszExecutablePath;
    PWSTR pwszLauncherFilename;
    PWSTR pwszLauncherPath;
} DPL_PROGRAM_DESC, *PDPL_PROGRAM_DESC;

Members

dwSize
Size of the DPL_PROGRAM_DESC structure. The application must set this member before it uses the structure.
dwFlags
Reserved. Must be 0.
guidApplication
Variable of type GUID specifying the application.
pwszApplicationName
Pointer to the application name.
pwszCommandLine
Pointer to the command-line arguments.
pwszCurrentDirectory
Pointer to the directory that should be set as the application's working directory..
pwszDescription
Pointer to the application description.
pwszExecutableFilename
Pointer to the file name of the application executable.
pwszExecutablePath
Pointer to the path of the application executable.
pwszLauncherFilename
Pointer to the file name of the launcher executable.
pwszLauncherPath
Pointer to the path of the launcher executable.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplobby8.h.


DPN_APPLICATION_DESC

Describes the settings for a Microsoft® DirectPlay® application.

typedef struct _DPN_APPLICATION_DESC{
    DWORD  dwSize;
    DWORD  dwFlags;
    GUID   guidInstance;
    GUID   guidApplication;
    DWORD  dwMaxPlayers;
    DWORD  dwCurrentPlayers;
    WCHAR* pwszSessionName;
    WCHAR* pwszPassword;
    PVOID  pvReservedData;
    DWORD  dwReservedDataSize;
    PVOID  pvApplicationReservedData;
    DWORD  dwApplicationReservedDataSize;
} DPN_APPLICATION_DESC, *PDPN_APPLICATION_DESC;

Members

dwSize
Size of the DPN_APPLICATION_DESC structure. The application must set this member before it uses the structure.
dwFlags
One of the following flags describing application behavior.
DPNSESSION_CLIENT_SERVER
This type of session is client/server. This flag cannot be combined with DPNSESSION_MIGRATE_HOST.
DPNSESSION_MIGRATE_HOST
Used in peer-to-peer sessions, enables host migration. This flag cannot be combined with DPNSESSION_CLIENT_SERVER.
DPNSESSION_NODPNSVR
You do not want enumerations forwarded to your host from DPNSVR. See Using the DirectPlay DPNSVR Application.
DPNSESSION_REQUIREPASSWORD
The session is password protected. If this flag is set, pwszPassword must be a valid string.
guidInstance
Globally unique identifier (GUID) that is generated by DirectPlay at startup representing the instance of this application. This member is an [out] parameter when calling the GetApplicationDesc method exposed by the IDirectPlay8Peer, IDirectPlay8Client, and IDirectPlay8Server interfaces. It is an optional [in] parameter when calling the Connect method exposed by the IDirectPlay8Peer and IDirectPlay8Client interfaces. It must be set to NULL when you call the SetApplicationDesc method exposed by the IDirectPlay8Server and IDirectPlay8Peer interfaces. You can not obtain this GUID by calling the IDirectPlay8Server::Host or IDirectPlay8Peer::Host methods. You must obtain the GUID by calling a GetApplicationDesc method.
guidApplication
Application GUID.
dwMaxPlayers
Variable of type DWORD specifying the maximum number of players allowed in the session. Set this member to 0 to specify an unlimited number of players.
dwCurrentPlayers
Variable of type DWORD specifying the number of players currently connected to the session. This member is an [out] parameter that is set only by the GetApplicationDescription method exposed by IDirectPlay8Peer, IDirectPlay8Client, and IDirectPlay8Server.
pwszSessionName
Pointer to a variable of type WCHAR specifying the Unicode™ name of the session. This member is set by the host or server only for informational purposes. A client cannot use this name to connect to a host or server.
pwszPassword
Pointer to a variable of type WCHAR specifying the Unicode password that is required to connect to the session. This must be NULL if the DPNSESSION_REQUIREPASSWORD is not set in the dwFlags member.
pvReservedData
Pointer to DirectPlay reserved data. An application should never modify this value.
dwReservedDataSize
Variable of type DWORD specifying the size of data contained in the pvReservedData member. An application should never modify this value.
pvApplicationReservedData
Pointer to application-specific reserved data. This value is optional and may be set to NULL.
dwApplicationReservedDataSize
Variable of type DWORD specifying the size of the data in the pvApplicationReservedData member. This value is optional and may be set to 0.

Remarks

The dwMaxPlayers, pvApplicationReservedData, dwApplicationReservedDataSize, pwszPassword, and pwszSessionName members can be set when calling the Host or SetApplicationDesc methods exposed by the IDirectPlay8Server and IDirectPlay8Peer interfaces.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_BUFFER_DESC

Used by Microsoft® DirectPlay® for generic buffer information.

typedef struct _BUFFERDESC{
    DWORD  dwBufferSize;
    BYTE*  pBufferData;
} BUFFERDESC, DPN_BUFFER_DESC;

Members

dwBufferSize
Variable of type DWORD that specifies the size of the data buffer in the pBufferData member.
pBufferData
Pointer to a variable of type BYTE that contains the buffer data.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_CAPS

Used to set and retrieve general parameters for DirectPlay.

typedef struct _DPN_CAPS{
    DWORD dwSize;
    DWORD dwFlags;
    DWORD dwConnectTimeout;
    DWORD dwConnectRetries;
    DWORD dwTimeoutUntilKeepAlive;
} DPN_CAPS, *PDPN_CAPS;

Members

dwSize
This value must be set to the size of the structure.
dwFlags
Reserved, this must be 0.
dwConnectTimeout
Number of milliseconds DirectPlay should wait before it retries a connection request.
dwConnectRetries
Number of connection retries DirectPlay should make during the connection process.
dwTimeoutUntilKeepAlive
Number of milliseconds DirectPlay should wait since the last time it received a packet from an endpoint, before it sends a keep-alive message.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_CONNECTION_INFO

Used to retrieve statistics for the connection between you and a remote computer that you are connected to.

typedef struct _DPN_CONNECTION_INFO{
    DWORD   dwSize;
    DWORD   dwRoundTripLatencyMS;
    DWORD   dwThroughputBPS;
    DWORD   dwPeakThroughputBPS;
    DWORD   dwBytesSentGuaranteed;
    DWORD   dwPacketsSentGuaranteed;
    DWORD   dwBytesSentNonGuaranteed;
    DWORD   dwPacketsSentNonGuaranteed;
    DWORD   dwBytesRetried;
    DWORD   dwPacketsRetried;
    DWORD   dwBytesDropped;
    DWORD   dwPacketsDropped;
    DWORD   dwMessagesTransmittedHighPriority;
    DWORD   dwMessagesTimedOutHighPriority;
    DWORD   dwMessagesTransmittedNormalPriority;
    DWORD   dwMessagesTimedOutNormalPriority;
    DWORD   dwMessagesTransmittedLowPriority;
    DWORD   dwMessagesTimedOutLowPriority;
    DWORD   dwBytesReceivedGuaranteed;
    DWORD   dwPacketsReceivedGuaranteed;
    DWORD   dwBytesReceivedNonGuaranteed;
    DWORD   dwPacketsReceivedNonGuaranteed;
    DWORD   dwMessagesReceived;
} DPN_CONNECTION_INFO, *PDPN_CONNECTION_INFO;

Members

dwSize
Size of the structure.
dwRoundTripLatencyMS
Approximate time, in milliseconds (ms), it takes a packet to reach the remote computer and be returned to the local computer. This number will change throughout the session as link conditions change.
dwThroughputBPS
Approximate throughput, in bytes per second (Bps), for the link. This number will change throughout the session as link conditions change. This value is approximate, and you may want to calculate your own value for greater accuracy.
dwPeakThroughputBPS
Peak throughput, in bytes per second (Bps) for the link. This number will change throughout the session as link conditions change. This value is approximate, and you may want to calculate your own value for greater accuracy.
dwBytesSentGuaranteed
Amount, in bytes, of guaranteed messages that have been sent.
dwPacketsSentGuaranteed
Number of packets of guaranteed messages that have been sent.
dwBytesSentNonGuaranteed
Amount, in bytes, of nonguaranteed messages that have been sent.
dwPacketsSentNonGuaranteed
Number of packets of nonguaranteed messages that have been sent.
dwBytesRetried
Amount, in bytes, of messages that have been retried.
dwPacketsRetried
Amount of packets that have been retried.
dwBytesDropped
Amount, in bytes, of messages that have been dropped.
dwPacketsDropped
Number of packets that have been dropped.
dwMessagesTransmittedHighPriority
Number of high-priority messages that have been transmitted.
dwMessagesTimedOutHighPriority
Number of high-priority messages that have timed out.
dwMessagesTransmittedNormalPriority
Number of normal-priority messages that have been transmitted.
dwMessagesTimedOutNormalPriority
Number of normal-priority messages that have timed out.
dwMessagesTransmittedLowPriority
Number of low-priority messages that have been transmitted.
dwMessagesTimedOutLowPriority
Number of low priority messages that have timed out.
dwBytesReceivedGuaranteed
Amount, in bytes, of guaranteed messages that have been received.
dwPacketsReceivedGuaranteed
Number of packets of guaranteed messages that have been received.
dwBytesReceivedNonGuaranteed
Amount, in bytes, of nonguaranteed messages that have been received.
dwPacketsReceivedNonGuaranteed
Number of packets of nonguaranteed messages that have been received.
dwMessagesReceived
Number of messages that have been received.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_GROUP_INFO

Describes static group information.

typedef struct _DPN_GROUP_INFO{
    DWORD  dwSize;
    DWORD  dwInfoFlags;
    PWSTR  pwszName;
    PVOID  pvData;
    DWORD  dwDataSize;
    DWORD  dwGroupFlags;
} DPN_GROUP_INFO, *PDPN_GROUP_INFO;

Members

dwSize
Variable of type DWORD describing the size of this structure.
dwInfoFlags

Variable of type DWORD containing flags that specify the type of information contained in this structure. When a GetGroupInfo method returns, the dwInfoFlags member of the DPN_GROUP_INFO will always have both flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Peer::SetGroupInfo , to notify Microsoft® DirectPlay® of which values have changed.

DPNINFO_NAME
The pwszName member contains valid data.
DPNINFO_DATA
The pvData member contains valid data.
pwszName
Pointer to a variable of type PWSTR specifying the Unicode name of the group.
pvData
Pointer to the data describing the group.
dwDataSize
Variable of type DWORD that specifies the size of the data contained in the pvData member.
dwGroupFlags
Variable of type DWORD that can be set to the following description flag.
DPNGROUP_AUTODESTRUCT
Causes the group to be automatically destroyed when the group creator leaves the group.

Remarks

When using this structure in the IDirectPlay8Peer::GetGroupInfo and IDirectPlay8Server::GetGroupInfo methods, dwInfoFlags must be set to 0.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_PLAYER_INFO

Describes static player information.

typedef struct _DPN_PLAYER_INFO{
    DWORD  dwSize;
    DWORD  dwInfoFlags;
    PWSTR  pwszName;
    PVOID  pvData;
    DWORD  dwDataSize;
    DWORD  dwPlayerFlags;
} DPN_PLAYER_INFO, *PDPN_PLAYER_INFO;

Members

dwSize
Variable of type DWORD describing the size of this structure.
dwInfoFlags
Variable of type DWORD containing flags that specify the type of information contained in this structure. When a GetPlayerInfo method returns, the dwInfoFlags member of the DPN_PLAYER_INFO will always have both flags set, even if the corresponding pointers are set to NULL. These flags are used when calling IDirectPlay8Peer::SetPeerInfo , to notify Microsoft® DirectPlay® which values have changed.
DPNINFO_NAME
The pwszName member contains valid data.
DPNINFO_DATA
The pvData member contains valid data.
pwszName
Pointer to a variable of type PWSTR specifying the Unicode name of the player.
pvData
Pointer to the data describing the player.
dwDataSize
Variable of type DWORD that specifies the size of the data contained in the pvData member.
dwPlayerFlags
Variable of type DWORD that may contain one of the following flags.
DPNPLAYER_LOCAL
This information is for the local player.
DPNPLAYER_HOST
This player is the host for the application.

Remarks

When using this structure in the IDirectPlay8Peer::GetPeerInfo and IDirectPlay8Server::GetClientInfo methods, dwInfoFlags must be set to 0.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_SECURITY_CREDENTIALS

Not implemented.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_SECURITY_DESC

Not implemented.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_SERVICE_PROVIDER_INFO

Used when enumerating information for a specific service provider.

typedef struct _DPN_SERVICE_PROVIDER_INFO{
    DWORD  dwFlags;
    GUID  Guid;
    WCHAR* pwszName;
    PVOID  pvReserved;
    DWORD  dwReserved;
} DPN_SERVICE_PROVIDER_INFO, *PDPN_SERVICE_PROVIDER_INFO;

Members

dwFlags
Reserved. Must be 0.
pGuid
GUID for the service provider.
pwszName
Name of the service provider.
pvReserved
Reserved. Must be 0.
dwReserved
Reserved. Must be 0.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DPN_SP_CAPS

Used to set and retrieve parameters for service providers.

typedef struct _DPN_SP_CAPS{
    DWORD  dwSize;
    DWORD  dwFlags;
    DWORD  dwNumThreads;
    DWORD  dwDefaultEnumCount;
    DWORD  dwDefaultEnumRetryInterval;
    DWORD  dwDefaultEnumTimeout;
    DWORD  dwMaxEnumPayloadSize;
    DWORD  dwBuffersPerThread;
    DWORD  dwSystemBufferSize;

} DPN_SP_CAPS, *PDPN_SP_CAPS;

Members

dwSize
This value must be set to the size of the structure.
dwFlags
This can be a combination of the following flags.
DPNSPCAPS_SUPPORTSDPNSRV
DPNSVR.EXE will provide port sharing for the given SP. Currently this flag is available on IP and IPX only. See Using the DirectPlay DPNSVR Application for a further discussion of DPNSVR.
DPNSPCAPS_SUPPORTSBROADCAST
On IP and IPX applications, the service provider has the ability to broadcast to find games if not enough addressing information is passed.
DPNSPCAPS_SUPPORTSALLADAPTERS
The service provider will use all devices on the system. There is no need to specify a device element.
dwNumThreads
Number of threads the service provider will use for servicing network requests. The default value for this is based on an algorithm that takes into account the number of processors on the system. Most applications will not need to modify this value.

After a service provider is active in your process, you may only increase this value. Decreasing the value will have no effect. The setting is process wide, which means it will affect your current DirectPlay object and any other DirectPlay objects in your process.

You may specify a lower value than the default if you call the SetSPCaps method before you call an EnumHosts, Connect, or Host method.

dwDefaultEnumCount
Default enumeration count.
dwDefaultEnumRetryInterval
Default retry interval, in milliseconds.
dwDefaultEnumTimeout
Default enumeration timeout value, in milliseconds.
dwMaxEnumPayloadSize
Maximum size of the payload information that can be sent in the pvResponseData member of the structures that accompany the DPN_MSGID_ENUM_HOST_QUERY and DPN_MSGID_ENUM_HOST_RESPONSE messages..
dwBuffersPerThread
The number of outstanding receive buffers allocated for each DirectPlay thread. If you increase the number of receive buffers, DirectPlay can pull more data out of the operating system buffers. However, you may also increase latency if data is arriving faster than your application can process it.
dwSystemBufferSize
The size of the operating system buffer. This buffer holds data from the communications device when your application cannot process data as fast as it arrives. The purpose of this buffer is to prevent data loss if you receive a sudden burst of data, or if the receive threads are momentarily stalled. Increasing dwSystemBufferSize may increase latency if your application cannot process the received data fast enough. You can eliminate the operating system buffer by setting dwSystemBufferSize to 0. However, if you do so, you run the risk of losing data if you cannot process the received data as fast as it arrives.

Remarks

For DirectX 8.0, the dwBuffersPerThread and dwSystemBufferSize members are used only by IP and IPX service providers. The default values for these members are set by the service provider. To determine the default value, call the appropriate GetSPCaps method. Most applications should use the default values for these two members. They are intended primarily for use by developers writing server applications for massively-multiplayer games.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dplay8.h.


DVCAPS

Describes the capabilities of the Microsoft® DirectPlay® VoiceClient object.

typedef struct{
    DWORD dwSize;
    DWORD dwFlags;
} DVCAPS, *LPDVCAPS, *PDVCAPS;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
dwFlags
Reserved. Must be 0.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice8.h.


DVCLIENTCONFIG

Controls the run-time parameters for the client. The structure is first used in the call to IDirectPlayVoiceClient::Connect, where it sets the initial state of these parameters. The structure can be retrieved after a connection has been made by calling IDirectPlayVoiceClient::GetClientConfig, and set using IDirectPlayVoiceClient::SetClientConfig.

typedef struct {
    DWORD  dwSize;
    DWORD  dwFlags;
    LONG   lRecordVolume;
    LONG   lPlaybackVolume;
    DWORD  dwThreshold;
    DWORD  dwBufferQuality;
    DWORD  dwBufferAggressiveness;
    DWORD  dwNotifyPeriod;
} DVCLIENTCONFIG, *LPDVCLIENTCONFIG, *PDVCLIENTCONFIG;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
dwFlags
Combination of the following flags.
DVCLIENTCONFIG_AUTORECORDVOLUME
Activates automatic gain control. With automatic gain control, Microsoft® DirectPlay® Voice adjusts the hardware input volume on your sound card automatically to get the best input level possible. You can determine the current input volume by looking at the lRecordVolume member after a call to IDirectPlayVoiceClient::GetClientConfig, or by looking at the lRecordVolume member of DVMSG_INPUTLEVEL messages.
DVCLIENTCONFIG_ECHOSUPPRESSION
Activates the echo suppression mode. This mode reduces echo introduced by configurations with external speakers and extremely sensitive microphones. While remote players' voices are being played back on the local speaker, the microphone is automatically muted. If the local player is transmitting, the playback of remote player voices is buffered until local input stops. After local input stops, playback resumes.
DVCLIENTCONFIG_MUTEGLOBAL
Mutes playback of the main sound buffer. Only sound buffers created through calls to IDirectPlayVoiceClient::Create3DSoundBuffer will be heard.
DVCLIENTCONFIG_PLAYBACKMUTE
Mutes playback of all DirectPlay Voice output and stops playback. This also stops decompression of incoming packets so CPU usage is reduced. Packets are effectively discarded while this flag is specified.
DVCLIENTCONFIG_RECORDMUTE
Mutes input from the microphone and stops recording. This also stops compression so CPU usage is reduced.

In addition to the preceding flags, the method of transmission is controlled by setting only one of the following flags or by not specifying either flag.

DVCLIENTCONFIG_AUTOVOICEACTIVATED
Places the transmission control system into automatic voice activation mode. In this mode, the sensitivity of voice activation is determined automatically by the system. The input level is adaptive, adjusting itself automatically to the input signal. For most applications this should be the setting used. This flag is mutually exclusive with the DVCLIENTCONFIG_MANUALVOICEACTIVATED flag.
DVCLIENTCONFIG_MANUALVOICEACTIVATED
Places the transmission control system into manual voice activation mode. In this mode, transmission of voice begins when the input level passes the level specified by the dwThreshold member. When input levels drop below the specified level, transmission stops. This flag is mutually exclusive with the DVCLIENTCONFIG_AUTOVOICEACTIVATED flag.

If you do not specify either DVCLIENTCONFIG_MANUALVOICEACTIVATED or DVCLIENTCONFIG_AUTOVOICEACTIVATED, the system will operate in push-to-talk mode. In push-to-talk mode, as long as there is a valid target specified the input from the microphone will be transmitted. Voice transmission stops when a NULL target is set or the current target leaves the session or is destroyed.

lRecordVolume
Value indicating what the volume of the recording should be set to. See the IDirectSoundBuffer8::SetVolume method for valid values.

If automatic gain control is enabled, this value can be set to DVRECORDVOLUME_LAST, which tells the system to use the current volume as determined by the automatic gain control algorithm. If a value other than DVRECORDVOLUME_LAST is specified in combination with automatic gain control, this value will be used to restart the algorithm at the specified value.

On return from a call to IDirectPlayVoiceClient::GetClientConfig, this value will contain the current recording volume. When adjusting the recording volume, DirectPlay Voice will adjust the volume for the microphone (if a microphone volume is present for the card) and the master recording volume (if one is present on the card). If neither a microphone volume nor a master record volume is present, DirectPlay Voice will be unable to adjust the recording volume.

lPlaybackVolume
Value indicating what the volume of the playback should be set to. Adjusting this volume adjusts both the main buffer and all 3-D sound buffers. See the IDirectSoundBuffer8::SetVolume method for valid values. You can specify DVPLAYBACKVOLUME_DEFAULT to use a default value that is appropriate for most situations (full volume).
dwThreshold
Input level used to trigger voice transmission if the DVCLIENTCONFIG_MANUALVOICEACTIVATED flag is specified in the dwFlags member. When the flag is specified, this value can be set to anywhere in the range of DVTHRESHOLD_MIN to DVTHRESHOLD_MAX. Additionally, DVTHRESHOLD_DEFAULT can be set to use a default value.

If DVCLIENTCONFIG_MANUALVOICEACTIVATED or DVCLIENTCONFIG_AUTOVOICEACTIVATED is not specified in the dwFlags member of this structure (indicating push-to-talk mode) this value must be set to DVTHRESHOLD_UNUSED.

dwBufferQuality
Buffer quality setting for the adaptive buffering algorithm. For most applications, this should be set to DVBUFFERQUALITY_DEFAULT. It can be set to anything in the range of DVBUFFERQUALITY_MIN to DVBUFFERQUALITY_MAX. In general, the higher the value, the higher the quality of the voice but the higher the latency. The lower the value, the lower the latency but the lower the quality.
dwBufferAggressiveness
Buffer aggressiveness setting for the adaptive buffer algorithm. For most applications, this can be set to DVBUFFERAGGRESSIVENESS_DEFAULT. It can also be set to anything in the range of DVBUFFERAGGRESSIVENESS_MIN and DVBUFFERAGGRESSIVENESS_MAX. In general, the higher the value, the quicker the adaptive buffering adjusts to changing conditions. The lower the value, the slower the adaptive buffering adjusts to changing conditions.
dwNotifyPeriod
Value indicating how often you want to receive DVMSGID_OUTPUTLEVEL and DVMSGID_INPUTLEVEL (if session is full duplex) messages. If this value is set to 0, these messages are disabled. The value specifies the number of milliseconds between these messages. DVNOTIFYPERIOD_MINPERIOD specifies the minimum period between messages that is allowed.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice8.h.


DVCOMPRESSIONINFO

Describes the attributes of a specific Microsoft® DirectPlay® Voice compression type.

typedef struct{
    DWORD           dwSize;
    GUID            guidType;
    LPWSTR          lpszName;
    LPWSTR          lpszDescription;
    DWORD           dwFlags;
    DWORD           dwMaxBitsPerSecond;
} DVCOMPRESSIONINFO, *LPDVCOMPRESSIONINFO, *PDVCOMPRESSIONINFO;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
guidType
GUID used to identify this compression type by DirectPlay Voice.
lpszName
Pointer to a name describing the codec.
lpszDescription
Pointer to a longer name of the codec.
dwFlags
Reserved; must be 0.
dwMaxBitsPerSecond
Maximum number of bits per second claimed by the codec.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice8.h.


DVSESSIONDESC

Describes the desired or current session settings for the Microsoft® DirectPlay® Voice server. This structure is used by the voice session host to configure the session, and by the session host and clients to retrieve information about the current session. The dwFlags, dwSessionType, and guidCT members can only be set when the host starts the voice session. The host can change the buffer settings at any time.

typedef struct {
    DWORD  dwSize;
    DWORD  dwFlags;
    DWORD  dwSessionType;
    GUID   guidCT;
    DWORD  dwBufferQuality;
    DWORD  dwBufferAggresiveness;
} DVSESSIONDESC, *LPDVSESSIONDESC, *PDVSESSIONDESC;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
dwFlags
Combination of the following flags.
DVSESSION_NOHOSTMIGRATION
The voice host will not migrate regardless of the transport settings. If this flag is not specified, the voice host will migrate if the transport supports it.
DVSESSION_SERVERCONTROLTARGET
The clients are unable to control the target of their speech. Only the server player can control the target of their speech. If the server does not specify this flag, only the clients can control the target of their speech. This flag can be specified only in multicast and mixing sessions.
dwSessionType
The type of DirectPlay Voice session to run. The DVSESSIONTYPE_PEER flag is not available in client/server sessions; all other flags are valid for all session types. This member can be one of the following values.
DVSESSIONTYPE_PEER
Voice messages will be sent directly between players.
DVSESSIONTYPE_MIXING
Voice session will use a mixing server. In this mode of operation, all voice messages are sent to the server, which mixes them and then forwards a single, premixed stream to each client. This reduces the bandwidth and CPU usage on clients significantly at the cost of increased bandwidth and CPU usage on the server.
DVSESSIONTYPE_FOWARDING
Voice messages will be routed through the session host. This will save bandwidth on the clients at the expense of bandwidth usage on the server. This option is only useful if the session host has a high-speed connection.
guidCT
GUID specifying the compression type of the session.
dwBufferQuality
The buffer quality setting. This member is unused for all session types except mixing sessions. For all sessions except mixing sessions, set this member to DVBUFFERQUALITY_DEFAULT.

Allowable values are between DVBUFFERQUALITY_MIN and DVBUFFERQUALITY_MAX. Additionally, this member can be set to the following value.

DVBUFFERQUALITY_DEFAULT
Specifying this value tells DirectPlay Voice to use the system default for this value, which is adjustable through a registry entry that can also be set through Sounds and Multimedia in Control Panel.
dwBufferAggresiveness
Buffer aggressiveness setting. This member is unused for all session types except mixing sessions. For all sessions except mixing sessions, set this member to DVBUFFERAGGRESIVENESS_DEFAULT.

Allowable values are between DVBUFFERAGGRESIVENESS _MIN and DVBUFFERAGGRESIVENESS _MAX. Additionally, this member can be set to the following value.

DVBUFFERAGGRESIVENESS_DEFAULT
Specifying this value tells DirectPlay Voice to use the system default for this value, which is adjustable through a registry entry that can also be set through Control Panel.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice8.h.


DVSOUNDDEVICECONFIG

Used to set and retrieve information about the sound device configuration and cannot be changed once a connection has been made. After a connection is made, you can retrieve the current sound device configuration by calling IDirectPlayVoiceClient::GetSoundDeviceConfig.

typedef struct {
    DWORD                dwSize;
    DWORD                dwFlags;
    GUID                 guidPlaybackDevice;
    LPDIRECTSOUND        lpdsPlaybackDevice;
    GUID                 guidCaptureDevice;
    LPDIRECTSOUNDCAPTURE lpdsCaptureDevice;
    HWND                 hwndAppWindow;
    LPDIRECTSOUNDBUFFER  lpdsMainBuffer;
    DWORD                dwMainBufferFlags;
    DWORD                dwMainBufferPriority;
} DVSOUNDDEVICECONFIG, *LPDVSOUNDDEVICECONFIG, *PDVSOUNDDEVICECONFIG;

Members

dwSize
Must be set the to size of this structure, in bytes, before using this structure.
dwFlags
A combination of the following flags.
DVSOUNDCONFIG_AUTOSELECT
Tells Microsoft® DirectPlay® Voice to attempt to automatically select (or unmute) the microphone line in the mixer for the specified recording device.
DVSOUNDCONFIG_HALFDUPLEX
Tells DirectPlay Voice to initialize itself in half-duplex mode. In half-duplex mode no recording takes place. If the initialization of the sound system fails in full-duplex mode, this flag will be set by the system.
DVSOUNDCONFIG_NORMALMODE
Tells DirectPlay Voice to use Microsoft® DirectSound® Normal Mode when initializing the DirectSound object. If this flag is not specified, the DirectSound object is initialized with DirectSound Priority Mode. See documentation for IDirectSound8::SetCooperativeLevel for more information. If a valid DirectSound object is specified in the lpdsPlaybackDevice member, this flag is ignored.
DVSOUNDCONFIG_SETCONVERSIONQUALITY
Enables better quality audio at the expense of higher CPU usage.
DVSOUNDCONFIG_NORECVOLAVAILABLE
Set by DirectPlay Voice if there are no volume controls available on the recording device you specified. You cannot set this flag.
DVSOUNDCONFIG_NOFOCUS
The voice application will never go out of focus. In other words, the application will never release the sound capture device. Use of this flag is not recommended.
DVSOUNDCONFIG_STRICTFOCUS
The voice application will lose focus whenever its window is not the foreground window.

Note Applications should set the DVSOUNDCONFIG_NOFOCUS or DVSOUNDCONFIG_STRICTFOCUS flags only when strictly necessary. Instead, you should normally use the default behavior that results when neither flag is set.

guidPlaybackDevice
When this structure is used in the IDirectPlayVoiceClient::Connect method, this member specifies the GUID of the device used for playback. This must be specified even if the lpdsPlaybackDevice member is used. You can also specify the following default GUIDs provided by DirectSound.
DSDEVID_DefaultPlayback
The system default playback device.
DSDEVID_DefaultVoicePlayback
The default voice playback device.

When this structure is used in the IDirectPlayVoiceClient::GetSoundDeviceConfig method, this member contains the actual device GUID used for playback.

lpdsPlaybackDevice
When this structure is used in the IDirectPlayVoiceClient::Connect method, this member specifies the DirectSound object you want DirectPlay Voice to use for playback. The GUID specified in guidPlaybackDevice must match the one used to create the device specified by this parameter. If you used NULL when specifying the device when you created your DirectSound object, pass DSDEVID_DefaultPlayback for this member.

When this structure is used in the IDirectPlayVoiceClient::GetSoundDeviceConfig method, this member contains a pointer to the DirectSound object being used by DirectPlay Voice. This will either be a pointer to the object specified when Connect was called or a pointer to a newly created and initialized DirectSound object. If you want to use this DirectSound object, you must store the pointer and increment the reference count by calling AddRef on the DirectSound interface.

guidCaptureDevice
When this structure is used in IDirectPlayVoiceClient::Connect method, this member specifies the GUID of the device used for capture. This must be specified even if the lpdsCaptureDevice member is used. If you used NULL when specifying the device when you created your DirectSoundCapture object, pass DSDEVID_DefaultCapture for this member.

When this structure is used in the IDirectPlayVoiceClient::GetSoundDeviceConfig method, this member will contain the actual device GUID used for capture.

lpdsCaptureDevice
When this structure is used in the IDirectPlayVoiceClient::Connect method, this member specifies the DirectSound object you want DirectPlay Voice to use for capture. The GUID specified in guidCaptureDevice must match the one used to create the device specified by this parameter. If you want to have DirectPlay Voice create the DirectSoundCapture object for you, specify NULL for this member.

When this structure is used in the IDirectPlayVoiceClient::GetSoundDeviceConfig method, this member contains a pointer to the DirectSoundCapture object being used by DirectPlay Voice. This will either be a pointer to the object specified when Connect was called or a pointer to a newly created and initialized DirectSoundCapture object. If you want to use this DirectSoundCapture object, you must store the pointer and increment the reference count by calling AddRef on the IDirectSoundCapture8 interface. If the DirectPlay Voice object is operating in half duplex mode, this member will be NULL.

hwndAppWindow
Must be set to the handle of the window that will be used to determine focus for sound playback. See IDirectSound8::SetCooperativeLevel for information on DirectSound focus. If you do not have a window to use for focus, use GetDesktopWindow to use the desktop window.
lpdsMainBuffer
Pointer to an IDirectSoundBuffer8 interface, which is used to create the DirectPlay Voice main buffer. This can be either NULL or a user-created DirectSound buffer. If this member is set to NULL, DirectPlay Voice will create a buffer for the main voice buffer. If users specify a buffer here, DirectPlay Voice will use their buffer for the main voice buffer. User-created buffers have the following restrictions.
  • The buffer must be 22 kilohertz, 16-bit, Mono format.
  • The buffer must be at least 1 second in length.
  • The buffer must have been created with the DSBCAPS_GETCURRENTPOSITION2 and DSBCAPS_CTRL3D flags.
  • The buffer must not be a primary buffer.
  • The buffer must not be playing when it is passed to the DirectPlay Voice software.
  • The buffer must not be locked when it is passed to the DirectPlay Voice software.
dwMainBufferFlags
Passed directly to the dwFlags parameter of the IDirectSoundBuffer8::Play method when Play is called for the main buffer. The DSBPLAY_LOOPING flag is automatically added to this field. See the documentation on IDirectSoundBuffer8::Play for details. This parameter must be 0 if the lpdsMainBufferDesc member of this structure is NULL.
dwMainBufferPriority
Passed directly to the dwPriority parameter of the IDirectSoundBuffer8::Play method when Play is called on the main buffer. See documentation for IDirectSoundBuffer8::Play for more information. This member must be set to 0 if lpdsMainBufferDesc is NULL.

Requirements

Windows NT/2000: Available as a redistributable for Windows 2000 and later.
Windows 95/98: Available as a redistributable for Windows 95 and later.
Header: Declared in Dvoice8.h.


Return Values

Errors are represented by negative values and cannot be combined.

The following table lists the interfaces to which the error values listed below apply.

Interface | Interface
IDirectPlay8Address | IDirectPlay8Peer
IDirectPlay8AddressIP | IDirectPlay8Server
IDirectPlay8Client | IDirectPlayVoiceClient
IDirectPlay8LobbiedApplication | IDirectPlayVoiceServer
IDirectPlay8LobbyClient | IDirectPlayVoiceTest

For a list of the error values each method can return, see the individual method descriptions.

Many of the Microsoft® DirectPlay® samples include a GetDirectPlayErrStr function that converts HRESULT values to string names for the DirectPlay errors. You can copy this code into your own applications for diagnostic traces or error reports.

Success Codes

DPNSUCCESS_PENDING
An asynchronous operation has reached the point where it is successfully queued.
S_OK
The operation completed successfully.

Error Codes

DPNERR_ABORTED
The operation was canceled before it could be completed.
DPNERR_ADDRESSING
The address specified is invalid.
DPNERR_ALREADYCONNECTED
The object is already connected to the session.
DPNERR_ALREADYCLOSING
An attempt to call the Close method on a session has been made more than once.
DPNERR_ALREADYDISCONNECTING
The client is already disconnecting from the session.
DPNERR_ALREADYINITIALIZED
The object has already been initialized.
DPNERR_BUFFERTOOSMALL
The supplied buffer is not large enough to contain the requested data.
DPNERR_CANNOTCANCEL
The operation could not be canceled.
DPNERR_CANTCREATEGROUP
A new group cannot be created.
DPNERR_CANTCREATEPLAYER
A new player cannot be created.
DPNERR_CANTLAUNCHAPPLICATION
The lobby cannot launch the specified application.
DPNERR_CONNECTING
The method is in the process of connecting to the network.
DPNERR_CONNECTIONLOST
The service provider connection was reset while data was being sent.
DPNERR_DATATOOLARGE
The application data is too large for the service provider's Maximum Transmission Unit.
DPNERR_DOESNOTEXIST
Requested element is not part of the address.
DPNERR_ENUMQUERYTOOLARGE
The query data specified is too large.
DPNERR_ENUMRESPONSETOOLARGE
The response to an enumeration query is too large.
DPNERR_EXCEPTION
An exception occurred when processing the request.
DPNERR_GENERIC
An undefined error condition occurred.
DPNERR_GROUPNOTEMPTY
The specified group is not empty.
DPNERR_HOSTREJECTEDCONNECTION
The DPN_MSGID_INDICATE_CONNECT system message returned something other than S_OK in response to a connect request.
DPNERR_HOSTTERMINATEDSESSION
The host in a peer session (with host migration enabled) terminated the session.
DPNERR_INCOMPLETEADDRESS
The address specified is not complete.
DPNERR_INVALIDADDRESSFORMAT
Address format is invalid.
DPNERR_INVALIDAPPLICATION
The GUID supplied for the application is invalid.
DPNERR_INVALIDCOMMAND
The command specified is invalid.
DPNERR_INVALIDDEVICEADDRESS
The address for the local computer or adapter is invalid.
DPNERR_INVALIDFLAGS
The flags passed to this method are invalid.
DPNERR_INVALIDGROUP
The group ID is not recognized as a valid group ID for this game session.
DPNERR_INVALIDHANDLE
The handle specified is invalid.
DPNERR_INVALIDHOSTADDRESS
The specified remote address is invalid.
DPNERR_INVALIDINSTANCE
The GUID for the application instance is invalid.
DPNERR_INVALIDINTERFACE
The interface parameter is invalid. This value will be returned in a connect request if the connecting player was not a client in a client/server game or a peer in a peer-to-peer game.
DPNERR_INVALIDOBJECT
The DirectPlay object pointer is invalid.
DPNERR_INVALIDPARAM
One or more of the parameters passed to the method are invalid.
DPNERR_INVALIDPASSWORD
An invalid password was supplied when attempting to join a session that requires a password.
DPNERR_INVALIDPLAYER
The player ID is not recognized as a valid player ID for this game session.
DPNERR_INVALIDPOINTER
Pointer specified as a parameter is invalid.
DPNERR_INVALIDPRIORITY
The specified priority is not within the range of allowed priorities, which is inclusively from 0 through 65535.
DPNERR_INVALIDSTRING
String specified as a parameter is invalid.
DPNERR_INVALIDURL
Specified string is not a valid DirectPlay URL.
DPNERR_INVALIDVERSION
There was an attempt to connect to an invalid version of DirectPlay.
DPNERR_NOCAPS
The communication link that DirectPlay is attempting to use is not capable of this function.
DPNERR_NOCONNECTION
No communication link was established.
DPNERR_NOHOSTPLAYER
There is currently no player acting as the host of the session.
DPNERR_NOINTERFACE
The interface is not supported.
DPNERR_NORESPONSE
There was no response from the specified target.
DPNERR_NOTALLOWED
Object is read-only; this function is not allowed on this object.
DPNERR_NOTHOST
An attempt by the client to connect to a nonhost computer. Additionally, this error value may be returned by a nonhost that tries to set the application description.
DPNERR_OUTOFMEMORY
There is insufficient memory to perform the requested operation.
DPNERR_PENDING
Not an error, this return indicates that an asynchronous operation has reached the point where it is successfully queued. SUCCEEDED(DPNERR_PENDING) will return TRUE. This error value has been superseded by DPNERR_SUCCESS, which should be used by all new applications. DPNERR_PENDING is only included for backward compatibility.
DPNERR_PLAYERLOST
A player has lost the connection to the session.
DPNERR_PLAYERNOTREACHABLE
A player has tried to join a peer-peer session where at least one other existing player in the session cannot connect to the joining player.
DPNERR_SESSIONFULL
The request to connect to the host or server failed because the maximum number of players allotted for the session has been reached.
DPNERR_TIMEDOUT
The operation could not complete because it has timed out.
DPNERR_UNINITIALIZED
The requested object has not been initialized.
DPNERR_UNSUPPORTED
The function or feature is not available in this implementation or on this service provider.
DPNERR_USERCANCEL
The user canceled the operation.
DV_OK
The request completed successfully.
DV_FULLDUPLEX
The sound card is capable of full-duplex operation.
DV_HALFDUPLEX
The sound card can only be run in half-duplex mode.
DVERR_BUFFERTOOSMALL
The supplied buffer is not large enough to contain the requested data.
DVERR_EXCEPTION
An exception occurred when processing the request.
DVERR_GENERIC
An undefined error condition occurred.
DVERR_INVALIDFLAGS
The flags passed to this method are invalid.
DVERR_INVALIDOBJECT
The DirectPlay object pointer is invalid.
DVERR_INVALIDPARAM
One or more of the parameters passed to the method are invalid.
DVERR_INVALIDPLAYER
The player ID is not recognized as a valid player ID for this game session.
DVERR_INVALIDGROUP
The group ID is not recognized as a valid group ID for this game session.
DVERR_INVALIDHANDLE
The handle specified is invalid.
DVERR_OUTOFMEMORY
There is insufficient memory to perform the requested operation.
DVERR_PENDING
Not an error, this return indicates that an asynchronous operation has reached the point where it is successfully queued.
DVERR_NOTSUPPORTED
The operation is not supported.
DVERR_NOINTERFACE
The specified interface is not supported. Could indicate using the wrong version of DirectPlay.
DVERR_SESSIONLOST
The transport has lost the connection to the session.
DVERR_NOVOICESESSION
The session specified is not a voice session.
DVERR_CONNECTIONLOST
The connection to the voice session has been lost.
DVERR_NOTINITIALIZED
The IDirectPlayVoiceClient::Initialize or IDirectPlayVoiceServer::Initialize method must be called before calling this method.
DVERR_CONNECTED
The DirectPlayVoice object is connected.
DVERR_NOTCONNECTED
The DirectPlayVoice object is not connected.
DVERR_CONNECTABORTING
The connection is being disconnected.
DVERR_NOTALLOWED
The object does not have the permission to perform this operation.
DVERR_INVALIDTARGET
The specified target is not a valid player ID or group ID for this voice session.
DVERR_TRANSPORTNOTHOST
The object is not the host of the voice session.
DVERR_COMPRESSIONNOTSUPPORTED
The specified compression type is not supported on the local computer.
DVERR_ALREADYPENDING
An asynchronous call of this type is already pending.
DVERR_ALREADYINITIALIZED
The object has already been initialized.
DVERR_SOUNDINITFAILURE
A failure was encountered initializing the sound card.
DVERR_TIMEOUT
The operation could not be performed in the specified time.
DVERR_CONNECTABORTED
The connect operation was canceled before it could be completed.
DVERR_NO3DSOUND
The local computer does not support 3-D sound.
DVERR_ALREADYBUFFERED
There is already a user buffer for the specified ID.
DVERR_NOTBUFFERED
There is no user buffer for the specified ID.
DVERR_HOSTING
The object is the host of the session.
DVERR_NOTHOSTING
The object is not the host of the session.
DVERR_INVALIDDEVICE
The specified device is invalid.
DVERR_RECORDSYSTEMERROR
An error in the recording system occurred.
DVERR_PLAYBACKSYSTEMERROR
An error in the playback system occurred.
DVERR_SENDERROR
An error occurred while sending data.
DVERR_USERCANCEL
The user canceled the operation.
DVERR_UNKNOWN
An unknown error occurred.
DVERR_RUNSETUP
The specified audio configuration has not been tested. Call the IDirectPlayVoiceTest::CheckAudioSetup method.
DVERR_INCOMPATIBLEVERSION
The client connected to a voice session that is incompatible with the host.
DVERR_INITIALIZED
The Initialize method failed because the object has already been initialized.
DVERR_INVALIDPOINTER
The pointer specified is invalid.
DVERR_NOTRANSPORT
The specified object is not a valid transport.
DVERR_NOCALLBACK
This operation cannot be performed because no callback function was specified.
DVERR_TRANSPORTNOTINIT
Specified transport is not yet initialized.
DVERR_TRANSPORTNOSESSION
Specified transport is valid but is not connected/hosting.
DVERR_TRANSPORTNOPLAYER
Specified transport is connected/hosting but no local player exists.


DirectShow

The Microsoft® DirectShow® application programming interface (API) is a media-streaming architecture for the Microsoft® Windows® platform. Using DirectShow, your applications can perform high-quality video and audio playback or capture. The DirectShow documentation is divided into the following sections:

  • Introduction to DirectShow
  • Getting Started
  • About DirectShow
  • Using DirectShow
  • Decoder Development
  • DirectShow Tutorials
  • DirectShow Reference
  • DirectShow Samples
  • DirectX Media Objects
  • Media Parameters
  • Appendixes
  • Glossary

Note The icon external link indicates that a link takes you to a URL outside the microsoft.com site. Most of these external links point to sites that are not under Microsoft's control. Please read Microsoft's official statement regarding other sites.


Introduction to DirectShow

Microsoft® DirectShow® is an architecture for streaming media on the Microsoft® Windows® platform. DirectShow provides for high-quality capture and playback of multimedia streams. It supports a wide variety of formats, including Advanced Streaming Format (ASF), Motion Picture Experts Group (MPEG), Audio-Video Interleaved (AVI), MPEG Audio Layer-3 (MP3), and WAV files. It supports capture using Windows Driver Model (WDM) devices or older Video for Windows devices. DirectShow is integrated with other DirectX technologies. It automatically detects and uses video and audio acceleration hardware when available, but also supports systems without acceleration hardware.

DirectShow simplifies media playback, format conversion, and capture tasks. At the same time, it provides access to the underlying stream control architecture for applications that require custom solutions. You can also create your own DirectShow components to support new formats or custom effects.

Examples of the types of applications you can write with DirectShow include DVD players, video editing applications, AVI to ASF converters, MP3 players, and digital video capture applications.

DirectShow is based on the Component Object Model (COM). To write a DirectShow application, you must understand COM client programming. For most applications, you do not need to implement your own COM objects. DirectShow provides the components you need. (If you want to extend DirectShow by writing your own components, however, you must implement them as COM objects.)

This section contains the following topics.

  • Roadmap
  • What's New in DirectShow?
  • Supported Formats in DirectShow
  • DirectShow FAQ


Roadmap

This section describes how the Microsoft® DirectShow® documentation is organized.

  • If you have previous experience with DirectShow, read What's New in DirectShow?. It describes new features introduced in Microsoft® DirectX® 8.
  • If you are new to DirectShow, begin with the section Getting Started. Then read the articles in Using DirectShow that apply to the kind of application you want to write (such as playback, capture, or DVD). For more detailed information about the DirectShow architecture, read the section About DirectShow.
  • If you are interested in writing a video editing application, you can start with the introductory material in DirectShow Editing Services, and then read other parts of the documentation later.
  • In the past, to implement a custom data transform, you had to write a DirectShow filter. Now you can accomplish the same task in a simpler manner by writing a DirectX Media Object. Read DirectX Media Objects for more information. (You can still write a DirectShow filter, too. See Writing DirectShow Filters.)

Information on DirectShow is presented in the following sections.

Getting Started
Introduces DirectShow application development. Describes basic concepts and presents a series of simple applications to get you started with DirectShow programming. Read this section if you are new to DirectShow.
About DirectShow
Provides high-level background information about the DirectShow architecture, as well as application development topics such as graph building.
Using DirectShow
Contains the information you need to write DirectShow applications. The sections within this topic are organized around specific application areas, such as video capture, DVD playback, digital video, and video editing.
Decoder Development
Contains information for developers who are writing software decoders.
DirectShow Tutorials
Contains step-by-step tutorials about DirectShow application programming. This section describes a number of basic tasks that you will need to know when you write a DirectShow application, such as device enumeration.
DirectShow Reference
Contains the complete DirectShow application programming interface (API) reference. It also documents the filters that DirectShow provides.
DirectShow Samples
Describes the sample applications and filters that are included with the SDK.
DirectX Media Objects
DirectX Media Objects (DMOs) are a new way to write data-streaming components. Like DirectShow filters, DMOs take input data and use it to produce output data. However, DMOs are easier to create, test, and use than DirectShow filters.
Media Parameters
Media parameters are a new set of APIs that support run-time changes to an object's properties. They offer precise control over properties that change rapidly and require both high performance and repeatability.
Appendixes
Contains miscellaneous technical information, including information about debugging, information on using C to write DirectShow applications, Country/region codes, and a list obsolete features.
Glossary
Defines terms and concepts used in DirectShow.


What's New in DirectShow?

This article describes what's new in Microsoft® DirectShow® for Microsoft® DirectX® 8.0.

  • Windows Media Format Support
  • DirectShow Editing Services
  • New DVD Support
  • New MPEG-2 Transport and Program Stream Support
  • Microsoft TV Technologies (Broadcast Driver Architecture)
  • DirectX Video Acceleration
  • New Filters
  • New Filter Graph Features
  • Changes to the Build Environment
  • New GraphEdit Features
  • DirectX Media Objects
  • Media Parameters

Windows Media Format Support

Two new filters enable DirectShow applications to read and write files in Microsoft® Windows Media™ Format. The ASF Reader filter reads and parses Windows Media Format files. The ASF Writer filter writes Windows Media Format files; it also does the necessary multiplexing and compressing. DirectShow and the Windows Media Software Development Kit offer complementary solutions for writing applications that create and playback Windows Media Format stream. For more information, see Windows Media Applications.

DirectShow Editing Services

DirectShow Editing Services is an API that supports video editing and sequenced video playback. You can use DES to create a wide range of applications. For example, with just a few method calls, you can sequence together audio and video clips, add an effect, and play back the result. Or, you can create a entire video editing system. DES is built on top of the core DirectShow architecture. It provides a set of interfaces designed specifically for nonlinear video editing.

DES replaces cutlists, which are no longer supported.

New DVD Support

Two new interfaces, IDVDControl2 and IDVDInfo2, greatly expand the functionality of the DVD Navigator. The new MSWebDVD ActiveX® control makes this functionality available to script-based applications. New DVD features include the following, among others:

  • Karaoke multichannel audio support.
  • AC-3 support for S/PDIF out.
  • Audio volume control through the IBasicAudio interface.
  • Support for frame stepping and frame-accurate seeking.
  • Simplified access to DVD text information strings.
  • Improved support for parental management controls.

For more information, see DVD Application Development in DirectShow.

New MPEG-2 Transport and Program Stream Support

A new filter, the MPEG-2 Demultiplexer, provides support for MPEG-2 transport streams and program streams in push-mode (for receiving data from live sources). For more information, see MPEG-2 Demultiplexer and Writing Digital TV Applications.

Microsoft® TV Technologies (Broadcast Driver Architecture)

Microsoft® TV Technologies includes support for the new Broadcast Driver Architecture (BDA) and the Microsoft Tuning Model. The Broadcast Driver Architecture defines a framework that supports various component topologies for receiving digital and analog television. It includes software components for network configuration and control, demultiplexing, table parsing and IP Data delivery for the main digital TV standards including DVB and ATSC. The Tuning Model is a set of objects that enables applications to easily tune across various network types in a simple and uniform manner. For more information, see Writing Digital TV Applications.

DirectX Video Acceleration

For decoder developers: DirectX Video Acceleration is an Application Programming Interface (API) and a corresponding Device Driver Interface (DDI) for hardware acceleration of digital video decoding processing, with support of alpha blending for such purposes as DVD subpicture support. It provides an interface definition focused on support of MPEG-2 "main profile" video (formally ITU-T H.262 | ISO/IEC 13818-2), but is also intended to support other key video codecs (e.g., ITU-T Recommendations H.263 and H.261, and MPEG-1 and MPEG-4). For more information, see DirectX Video Acceleration.

New Filters

DirectShow includes several new filters:

  • ASF Writer: Writes Windows Media Format files.
  • ASF Reader: Reads and parses Windows Media Format files.
  • MJPEG Decompressor: Decodes a video stream from motion JPEG to uncompressed video
  • MJPEG Compressor: Compresses an uncompressed video stream using motion JPEG compression.
  • MPEG-2 Demultiplexer: Demultiplexes MPEG-2 transport and program streams from live sources.
  • Null Renderer: Discards samples without displaying or rendering the sample data. Applications can use this filter to discard data from a stream.
  • Sample Grabber: Retrieves media samples as they move through the filter graph. Applications can use this filter to obtain poster frames or other media data.

New Filter Graph Features

The filter graph manager supports several new features:

  • Dynamic Graph Building. You can now make changes to the filter graph while the graph is running. Previously, to add or remove filters, an application had to stop the graph, which interrupts the flow of data. For more information, see Dynamic Graph Building.
  • Live Source Synchronization. DirectShow now supports synchronization of live sources. For example, a live audio stream can be synchronized with a live video stream. For more information, see Time and Clocks in DirectShow.
  • Frame Stepping. The filter graph manager exposes the new IVideoFrameStep interface, which enables an application to step through a video file one frame at a time.

Changes to the Build Environment

  • A new header file, DShow.h, replaces the previous header file, Streams.h
  • The filter base classes now appear in the \Samples\BaseClasses directory under the SDK root directory. To use them, you must build the base-class library and link to it in your project. For more information, see Using the DirectShow Base Classes.

New GraphEdit Features

GraphEdit includes some new features that enhance its use as a testing and debugging tool.

  • "Graph Spy": Now GraphEdit can load a filter graph created by an external process. With this feature, you can see exactly what filter graph your application builds, with only a minimal amount of additional code in your application. For more information about this feature, see Loading a Graph From an External Process.
  • Filter Information: When you choose Insert Filters from the Graph menu, the list of filters now includes each filter's registration information, including merit, number of pins, and the media types registered for each pin. To see this information, click the plus (+) symbol next to each filter in the tree view.

For more information about GraphEdit, see Simulating Graph Building with GraphEdit.

DirectX Media Objects

DirectX Media Objects (DMOs) are a new way to write data-streaming components. Like DirectShow filters, DMOs take input data and use it to produce output data. However, the application programming interfaces (APIs) for DMOs are much simpler than the corresponding APIs for DirectShow. As a result, DMOs are easier to create, test, and use than DirectShow filters.

DMOs are fully compatible with DirectShow. You can use a DMO like a filter when you need the services that DirectShow provides, such as graph synchronization, intelligent connection, automatic handling of data flow, and thread management. However, DMOs do not require a filter graph, so applications can use DMOs without using DirectShow.

For more information, see DirectX Media Objects.

Media Parameters

Media parameters are a new set of APIs that support run-time changes to an object's properties. They offer precise control over properties that change rapidly and require both high performance and repeatability. They enable a property to follow an exact curve, such as a sine wave or inverse-square curve, in real time.

Using media parameters, data transform objects can support a standard interface for controlling run-time behavior. They are particularly useful for audio effect DMOs and filters. For example, in an echo effect, the ratio of wet (processed) signal to dry (unprocessed) signal can follow a smooth curve. This type of behavior is critical in audio engineering, to avoid introducing artifacts into the recording.

For more information, see Media Parameters.


Supported Formats

Microsoft DirectX 8.0

Supported Formats in DirectShow

DirectShow® is an open architecture, which means that it can support any format as long as there are filters to parse and decode it. The filters provided by Microsoft, either as redistributables through DirectShow or as Windows operating system components, provide default support for the following file and compression formats.

Note An asterisk (*) indicates that DirectShow applications must use the Windows Media Format SDK to support this format. For more information, see the article Windows Media and DirectShow: Choices for Windows-based Media Applications.

File formats:

  • Windows Media™ Audio (WMA)*
  • Windows Media™ Video (WMV)*
  • Advanced Streaming Format (ASF)*
  • Motion Picture Experts Group (MPEG)
  • Audio-Video Interleaved (AVI)
  • QuickTime (version 2 and lower)
  • WAV
  • AIFF
  • AU
  • SND
  • MIDI

Compression formats:

  • Microsoft Windows Media Video codec version 7.0*
  • ISO MPEG-4 video version 1.0*
  • Microsoft MPEG-4 version 3*
  • Sipro Labs ACELP*
  • Windows Media Audio*
  • MPEG Audio Layer-3 (MP3) (decompression only)
  • Digital Video (DV)
  • MPEG-1
  • MJPEG
  • Indeo
  • Voxware*
  • Cinepak

Microsoft does not provide an MPEG-2 decoder. Several DirectShow-compatible hardware and software MPEG-2 decoders are available from third parties.

For information on the availability of particular third-party codecs for redistribution with DirectShow applications, contact the codec manufacturer.


DirectShow FAQ

This article answers many frequently asked questions about Microsoft® DirectShow®. It contains the following sections:

  • General Questions
  • Programming Questions

General Questions

Q: What operating systems does DirectShow support?

A: DirectShow supports Microsoft® Windows® 9x, Microsoft® Microsoft® Windows® 2000, and Microsoft® Windows® Me.

Q: How much COM knowledge do I need to program with DirectShow?

A: For application development, you need to understand the basics of working with COM objects: how to instantiate them, how to access the interfaces they expose, and how to properly manage reference counts on those interfaces. Filter developers may require a bit more COM knowledge. For more information, see the topic entitled Programming DirectX with C/C++ under the Introducing DirectX 8.0 node in this help file.

Q: What formats does DirectShow support?

A: See Supported Formats in DirectShow.

Q: Is there a DirectShow Hardware Compatibility List (HCL)?

A: No. DirectShow uses Microsoft® DirectDraw® and Microsoft® DirectSound® hardware capabilities if they are available. When no special hardware is available, DirectShow uses GDI to draw video and the waveOut* multimedia APIs to play audio.

Q: What languages can I use to write a DirectShow application?

A: DirectShow is designed primarily for C++ development. (You can also use C.) With Microsoft® Visual Basic®, you can access a large subset of the DirectShow API, but support for Visual Basic is not complete. DirectShow supports script-based DVD applications, using Microsoft® JScript® or Visual Basic Scripting Edition. It is also possible to write DirectShow applications using Borland Delphi; however, the SDK documentation does not address this topic.

For more information, see the following topics:

  • Controlling Filter Graphs Using C
  • Using DirectShow with Visual Basic
  • Writing a Script-Based DVD Application

Q: What compiler do I need for DirectShow development?

A: Any compiler capable of generating Component Object Model (COM) objects should work once the compiler's environment has been configured correctly. If you use a compiler other than Microsoft® Visual C++®, you might need to rebuild the base class libraries, because of differences between compilers.

Q: How does DirectShow relate to Microsoft® Windows Media™?

A: See Windows Media Applications.

Q: How does DirectShow relate to the other components in Microsoft® DirectX®?

A: Internally, DirectShow uses DirectSound and DirectDraw when the hardware supports it. (The video renderer uses DirectDraw 7 surfaces. It does not use the new Microsoft® Direct3D® APIs.) You do not need to use the other DirectX APIs to write a DirectShow application, although it is possible to combine them. For an example, see the Texture3D sample application.

The previous version of DirectShow was 6.0. It originally shipped with the DirectX Media SDK. When the DirectX Media SDK was deprecated, DirectShow moved to the DirectX SDK, and so DirectShow's version number jumped from 6.0 to 8.0.

Q: How does DirectShow relate to Microsoft® ActiveMovie®?

A: ActiveMovie was the original name for DirectShow. The term ActiveMovie is no longer used.

Q: Is DirectShow limited to multimedia applications?

A: The default components included with DirectShow are designed for multimedia. However, the DirectShow architecture is useful for other kinds of data-streaming solutions.

Q: Is the source to the GraphEdit utility available? Can GraphEdit be redistributed?

A: No, the source is not available, and Graphedt.exe is not redistributable.

Q: Do DMOs replace DirectShow filters?

A: Microsoft® DirectX® Media Objects (DMOs) can be used in a DirectShow application. For encoders, decoders, and effects, you are encouraged to write a DMO instead of a DirectShow filter. For other purposes, a DirectShow filter might be more appropriate. For more information, see DirectX Media Objects.

Q: Where can I get more information?

  • World Wide Web:MSDN DirectX Developer Center
  • Mailing list: http://discuss.microsoft.com/archives/DIRECTXAV.html. A portion of its charter is below:

    The primary function of this list is to provide a forum where Developers and content creators using Microsoft's audio and streaming video technologies (DirectSound, DirectMusic, DirectShow) can exchange information and ideas. The list caters for all levels of DirectX expertise, from novice to advanced developer.

    While it is expected that various members of the Microsoft DirectX development team will review and possibly comment on list topics, DirectXAV is not intended as a Microsoft support forum and there is no guarantee that Microsoft personnel will respond directly to inquiries. Often, your best source of help will be other members of the DirectXAV community who have faced similar issues themselves in the past.

    Topics that are appropriate to this list include: compositional techniques using DirectMusic Producer; audio, music or streaming video programming techniques; sound design techniques; general issues or information about the relevant APIs; code snippets; suggestions; hints and tips; device driver quality; future feature requests; real-life experiences using the APIs, etc.

    To subscribe to DirectX DEV, send an email to LISTSERV@discuss.microsoft.com with a message body of subscribe directxdev. To subscribe to DirectX A/V, send an email to LISTSERV@discuss.microsoft.com with a message body of subscribe directxav.

  • UseNet: microsoft.public.multimedia.directx.dshow.programming

Q: I'm facing a difficult problem in developing my application / filter. Where can I get developer support?

A: You should contact DirectX SDK support for specific developer support issues:

  • For DirectX SDK support call (800) 936-5800. If you are an MSDN subscriber you can use an MSDN support incident (4 free with an MSDN subscription or free if you have a premier or priority contract with Microsoft). Otherwise there is a fee for this service. See The MSDN Online Support Home Page for more information.

  • You can have the charge made to a phone bill by calling 900-555-2300. You can also submit the question via the web at http://support.microsoft.com/support/webresponse.asp.

Q: Is there a good book that explains DirectShow?

A: Currently, DirectShow does not have its own dedicated book; however, it is discussed briefly in some existing DirectX books, including:

  • Sams Teach Yourself DirectX in 24 Hours by Robert Dunlop, Dale Shepherd, and Mark Martin (Sams)
  • DirectX, RDX, RSX, and MMX Technology by Rohan Coelho and Maher Hawash (Addison Wesley)

Although DirectShow is mentioned in these books, the best source of information is the DirectShow documentation set and sample code provided with the DirectX SDK.

Q: How do I contact Microsoft with feedback and bug reports?

A: The address for general DirectX issues is directx@microsoft.com. Send bug reports to dxbugs@microsoft.com.

Q: I have some ideas on how Microsoft could improve DirectShow.

A: Microsoft welcomes suggestions, questions, and comments. Let us know what you think. What are we missing? What areas would you most like to see improved? What types of tutorials and samples would you most like to see? Your input will help us to prioritize future work. If you have questions or suggestions pertaining to the new DirectShow documentation, please send a message to askdshow@microsoft.com.

Q: I'm playing an AVI format file with Windows Media Player. I can hear the audio, but there doesn't seem to be any video—instead, I just see black. What's wrong?

A: Probably the file was encoded with a codec that is not present on your system. Although the AVI file format is common, AVI files can be created with many different codecs (coder/decoder). If you try to play an AVI file that uses an unsupported codec, you might hear the audio component, but the video will display as a black screen or the screen contents will remain unchanged.

Note The Windows Media Player often attempts to download and install a codec if it is not present on your system.

Some common codecs included in Windows 2000 are Radius Cinepak, Duck TrueMotion, Intel Indeo, Microsoft RLE, and Microsoft Video 1. To view the list of video codecs on your system in Windows 2000, do the following:

  1. Open Control Panel.
  2. Click Sounds and Multimedia.
  3. Click the Hardware tab.
  4. Select Video Codecs.
  5. Click Properties.
  6. Click the Properties tab.

Q: How do I know what codec a media file is using?

A: Do the following:

  • Right-click the file in Explorer
  • Click Properties.
  • Click the Summary tab.

Programming Questions

Q: How do I build my application? What libraries and header files do I need?

A: See Setting Up the Build Environment.

Q: GraphEdit displays a lot of filters that aren't documented. What are these filters?

A: GraphEdit enumerates all of the filters that are registered on your system in a filter category. This might include filters installed by third-party applications, or installed by other Microsoft technologies, such as Windows Media. Also, some DirectShow filters act as wrappers for codecs or hardware devices, with each codec or device appearing as a distinct filter. For more information, see Enumerating Devices and Filters.

Q: I'm having trouble building my custom graph by adding and connecting filters programmatically. How can I get help with this?

A: First try building everything with the Filter Graph Editor (GraphEdit). The tool will allow you to simulate lots of possibilities quickly and correct problems visually. GraphEdit is always a great place to build the graph before attempting to build it with source code.

Additional information: When you do an intelligent connect between the source and the video renderer, you are instructing DirectShow to insert a set of filters between the source and renderer that will do the correct media type conversions. The source filter has one output, which contains audio and video. Therefore, some filter must be added which will split (demultiplex) the audio and video into separate streams. So what you need to do is connect the audio renderer to the audio pin on the demultiplexer. Depending on the source media type, the demultiplexer being used could be one of several filters. For AVI, the AVI splitter will do the job. For MPEG2, it will be the MPEG2 Splitter or MPEG-2 Demultiplexer. If you're using smart connect, you'll have to find the demultiplexer, find its audio pin, and then connect that to the renderer.

If you want the easy way:

  • Add your source filter
  • Add any application-specific renderers you have
  • Call "Render" on the output pin.

This will do the equivalent of "Connect" in cases where you have a renderer for the output type already in the graph, but will add the renderer if you don't have one. So you'd have both the audio and video connected.

Q: How can I detect whether DirectShow is installed on a given machine?

A: Call CoCreateInstance to create an instance of the filter graph manager. If this call succeeds, DirectShow is installed on the machine. The following code shows how to do this:

IGraphBuilder *pGraph;

HRESULT hr = CoCreateInstance(CLSID_FilterGraph,
    NULL, CLSCTX_INPROC_SERVER,
    IID_IGraphBuilder, (void **) &pGraph);

Q: How do I change a filter's settings without displaying the property page?

A: Most filters expose one or more interfaces for setting properties on the filter. Consult the reference page for the filter in question. (See Filters.)

Q: Why can't I use the ASF Writer and ASF Reader filters?

A: You must provide a software certificate when you build your application. For more information, see Creating ASF Files in DirectShow and the Windows Media Format SDK. Also, you cannot use these filters in GraphEdit.

Q: Can DirectShow notify an application of its current playback position on a regular basis?

A: There is no callback notification of position. Use a timer and retrieve the current position by using the IMediaSeeking::GetCurrentPosition method.

Q: I wrote a filter. How do I install it?

A: See How to Register DirectShow Filters.

Q: Can I test my filter with GraphEdit?

A: While you are developing a filter, GraphEdit can help you to visualize the connections between filters. It can also provide a quick test of a filter's functionality. However, it is not meant as a robust test platform. For more information, see Simulating Graph Building with GraphEdit.

Q: How can I determine the number of pins on a filter?

A: Call the IBaseFilter::EnumPins method, and then call the IEnumPins::Next method until it returns a value other than S_OK. For more information, see Enumerating Objects in a Filter Graph.

Q: At what privilege ring do filters run?

A: Filters run at ring 3, although some filters control streaming devices that run at ring 0. For more information, see How Hardware Devices Participate in the Filter Graph.


Getting Started

This section contains articles covering basic Microsoft® DirectShow® concepts needed for application development. You can use this section as a high-level introduction to DirectShow. You need only a general understanding of programming and media to understand the topics in this section.

  • Introduction to DirectShow Application Programming
  • Setting Up the Build Environment
  • How to Play a File
  • Setting the Video Window
  • Responding to Events


Basic Concepts

Microsoft DirectX 8.0

Introduction to DirectShow Application Programming

This article introduces the basic terms and concepts needed to write a Microsoft® DirectShow® application. It also introduces some of the terminology used in DirectShow. After reading this section, you will be ready to write your first DirectShow application.

This article contains the following sections.

  • Filter Graphs
  • Writing a DirectShow Application

Filter Graphs

The basic building block of DirectShow is a software component called a filter. A filter generally performs a single operation on a multimedia stream. For example, there are DirectShow filters that

  • Read files.
  • Get video from a video capture device.
  • Decode a particular stream format, such as MPEG-1 video.
  • Pass data to the graphics or sound card.

Filters receive input and produce output. For example, if a filter decodes MPEG-1 video, the input is the MPEG-encoded stream and the output is an uncompressed RGB video stream.

To perform a given task, an application connects several filters so that the output from one filter becomes the input for another. A set of connected filters is called a filter graph. As an illustration of this concept, the following diagram shows a filter graph for playing an AVI file.

Filter Graph to Play an AVI File

Your application does not have to manage the individual filters in a filter graph. Instead, DirectShow provides a high-level component called the Filter Graph Manager. The Filter Graph Manager controls the flow of data through the graph. Your application makes high-level API calls such as "Run" (to move data through the graph) or "Stop" (to stop the flow of data). If you require more direct control of stream operations, you can access the filters directly through COM interfaces. The Filter Graph Manager also passes event notifications to the application, so that your application can respond to events, such as the end of a stream.

In addition, the Filter Graph Manager simplifies the process of building a filter graph. For example, you can specify a file name, and the Filter Graph Manager will build a graph to play that file.

Writing a DirectShow Application

A typical DirectShow application performs three basic steps, as illustrated in the following diagram.

Typical DirectShow Application

  1. Creates an instance of the Filter Graph Manager, using the CoCreateInstance function.
  2. Uses the Filter Graph Manager to build a filter graph. (You might use other DirectShow helper components as well.)
  3. Controls the filter graph and responds to events.

To get started with DirectShow, read How to Play a File. It presents a simple console application that plays a file. This application is the DirectShow equivalent of the classic "Hello World" program. Setting the Video Window and Responding to Events expand the program into a simple Windows application.


Setting Up the Build Environment

This article describes how to build Microsoft® DirectShow® applications and filters. You can build a project from the command line, or from within the Microsoft® Visual Studio® environment that comes with Microsoft® Visual C++®:

  • Building DirectShow Applications
  • Building DirectShow Filters

Building DirectShow Applications

Header Files

All DirectShow applications use the header file shown in the following table.

Header File | Required For
Dshow.h | All DirectShow applications.

Some DirectShow interfaces require additional header files. These requirements are noted in the interface reference.

Library Files

DirectShow uses the library files shown in the following table.

Library File | Description
Strmiids.lib | Exports class identifiers (CLSIDs) and interface identifiers (IIDs). All DirectShow applications require this library.
Quartz.lib | Exports the AMGetErrorText function. If you do not call this function, this library is not required.
Strmbase.lib | Required only if you use the DirectShow base classes.

In your build environment, the SDK Include and Lib directories should be the first directories in the search path. This ensures that you are using the most recent versions of these files.

Building DirectShow Filters

If you build a DirectShow filter, you must perform the following steps in addition to the ones described in the previous section:

  • Use the __stdcall calling convention.
  • For retail builds, add the preprocessor flag RELEASE. For debug builds, add the preprocessor flag DEBUG.
  • Set the entry-point symbol to DllEntryPoint@12.
  • If you implement the filter as a DLL, include a definition (.def) file that exports the DLL functions. The following is an example of a definition file. The filter's output file is assumed to be Filter.dll.
    LIBRARY FILTER.DLL
DESCRIPTION 'Description of my filter'
PROTMODE
EXPORTS
    DllGetClassObject
    DllCanUnloadNow
    DllRegisterServer
    DllUnregisterServer
  • If your filter uses the filter base classes from the SDK, you must build the base classes and link to them. For more information, see Using the DirectShow Base Classes.


How To Play a File

This section describes how to play a media file in Microsoft® DirectShow®. It presents a sample C++ program that plays a media file using only a few lines of code. The program is the DirectShow equivalent of the classic "Hello World" program.

This article contains the following sections:

  • Playing the File
  • Sample Code

Playing the File

Playing a file using DirectShow is a four-step process:

  1. Create an instance of the filter graph manager.
  2. Use the filter graph manager to create a filter graph.
  3. Use the filter graph manager to run the filter graph.
  4. Wait for playback to complete.

To accomplish this, you need to use the following COM interfaces:

  • IGraphBuilder: Constructs the filter graph.
  • IMediaControl: Handles media streaming in the filter graph.
  • IMediaEvent: Handles filter graph events.

The filter graph manager implements all of these interfaces.

Start by calling the CoInitialize function, which initializes the COM library. Then call the CoCreateInstance function to create the filter graph manager:

IGraphBuilder *pGraph;
CoInitialize(NULL);
CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
                    IID_IGraphBuilder, (void **)&pGraph);

The CoCreateInstance function returns a pointer to the filter graph manager's IGraphBuilder interface. Use this interface pointer to query for the other two interfaces that are needed, IMediaControl and IMediaEvent:

IMediaControl *pMediaControl;
IMediaEvent   *pEvent;
pGraph->QueryInterface(IID_IMediaControl, (void **)&pMediaControl);
pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);

Now comes the heart of the program:

pGraph->RenderFile(L"C:\\Hello_World.avi", NULL);
pMediaControl->Run();
pEvent->WaitForCompletion(INFINITE, &evCode);

The IGraphBuilder::RenderFile method constructs a filter graph that will play the specified file. The first parameter is the file name, represented as a wide character (2-byte) Unicode™ string. For simplicity, the example program specifies a literal string, rather than have the user select a file name. The "L" prefix converts an ASCII string to a wide character string. The second parameter is reserved and must equal NULL.

After the filter graph manager has constructed a filter graph, it is ready to begin playback. The IMediaControl::Run method switches the graph into running mode. When the application invokes this method, media data begins to move through the filter graph and is rendered as video, audio, or both.

The IMediaEvent::WaitForCompletion method blocks until the file is done playing. Playback continues on a separate thread. In a real application, you should avoid setting the wait interval to INFINITE, as this can block indefinitely. Also, you might want to respond to other filter graph events. For more information on event handling, see Responding to Events.

Also, in a real application, you should test the return value of RenderFile to confirm that it created the filter graph successfully. For example, if the specified file does not exist, RenderFile fails and returns the error code VFW_E_NOT_FOUND.

Finally, clean up by releasing all the interface pointers and the COM library:

pMediaControl->Release();
pEvent->Release();
pGraph->Release();
CoUninitialize();

Sample Code

The following sample code plays a file:

#include <dshow.h>

void main(void)
{
    IGraphBuilder *pGraph;
    IMediaControl *pMediaControl;
    IMediaEvent   *pEvent;
    CoInitialize(NULL);

    // Create the filter graph manager and query for interfaces.
    CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
                        IID_IGraphBuilder, (void **)&pGraph);
    pGraph->QueryInterface(IID_IMediaControl, (void **)&pMediaControl);
    pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);

    // Build the graph. IMPORTANT: Change string to a file on your system.
    pGraph->RenderFile(L"C:\\Hello_World.avi", NULL);

    // Run the graph.
    pMediaControl->Run();

    // Wait for completion.
    long evCode;
    pEvent->WaitForCompletion(INFINITE, &evCode);

    // Clean up.
    pMediaControl->Release();
    pEvent->Release();
    pGraph->Release();
    CoUninitialize();
}


Setting the Video Window

This article describes how to attach video playback to a particular window. It presents a sample program and explains the concepts required to understand the sample. The sample program builds on the one presented in How to Play a File.

This article contains the following sections:

  • The Video Window
  • Using the IVideoWindow Interface
  • Sample Code

The Video Window

When you render a video file, the filter graph will contain a video renderer filter. The video renderer takes uncompressed video data as input and renders it to the screen inside a window. Unless you specify otherwise, the video playback window is a top-level window with its own borders and title bar. It is more likely, however, that you will want the video to appear in a particular window created by your application. The solution is to make the renderer's video window a child of the application window. You can accomplish this by setting properties on the video window to specify the owner, style, and position of the window.

The video renderer filter supports the IVideoWindow interface, which contains methods for setting and retrieving properties on the video window. However, if you constructed your filter graph using the filter graph manager, you will not necessarily have a pointer to the video renderer filter. Therefore, the filter graph manager also supports IVideoWindow. It keeps a list of which filters in the graph expose IVideoWindow. When you call an IVideoWindow method on the filter graph manager, the filter graph manager distributes the call to those filters. In this way, the filter graph manager can support operations on individual filters, without the application needing to locate the right filter.

The filter graph manager uses the same mechanism to expose the IBasicVideo2 and IBasicAudio interfaces. These interfaces contain methods for setting audio and video properties. Call these methods on the filter graph manager, rather than calling them on individual filters.

Using the IVideoWindow Interface

This section describes how to use the IVideoWindow interface to set properties on the video window, including the owner and style of the window.

Note In the sample program presented in this article, most of the code performs standard windowing operations, and is not discussed in this section. In particular, the functions WindowProc and WinMain contain a typical framework for Microsoft® Windows® applications. The application-defined functions PlayFile and CleanUp are the ones of interest.

First, create an instance of the filter graph manager and construct the filter graph (through a call to the IGraphBuilder::RenderFile method). For more information on how to do this, see How to Play a File.

Then, before starting playback, set the properties on the video window, as follows:

  1. Attach the video playback window to the desired parent window. To do this, call the IVideoWindow::put_Owner method and pass it a handle to the owner window. This method takes a variable of type OAHWND, so cast the handle to this type, if necessary:
    IVideoWindow    *pVidWin = NULL;
pGraph->QueryInterface(IID_IVideoWindow, (void **)&pVidWin);
pVidWin->put_Owner((OAHWND)g_hwnd);
  2. Change the style of the video window to a child window. To do this, call the IVideoWindow::put_WindowStyle method and pass it a combination of style flags. The WS_CHILD flag indicates that the window is a child window; the WS_CLIPSIBLINGS flag prevents the window from drawing inside the client area of another child window.
    pVidWin->put_WindowStyle(WS_CHILD | WS_CLIPSIBLINGS);
  3. Set the position of the video window by calling the IVideoWindow::SetWindowPosition method. This method takes device coordinates specifying the left edge (x-axis), top edge (y-axis), width, and height of the window. The sample program stretches the video window to fill the entire parent window:
    RECT grc;
GetClientRect(g_hwnd, &grc);
pVidWin->SetWindowPosition(0, 0, grc.right, grc.bottom);

    The GetClientRect function fills a RECT structure with the coordinates of the window's client area. The coordinates are relative to the upper-left corner of the client area, so the left and top members are both zero and the right and bottom members define the width and height, respectively.

Before the application exits, it is important that you set the visibility of the video window to false. Otherwise, a video image remains on the screen and the user cannot get rid of it. Then, reset the owner to NULL; otherwise, messages are sent to the wrong window, likely causing errors.

HRESULT hr = pVidWin->put_Visible(OAFALSE);
hr = pVidWin->put_Owner(NULL);

Sample Code

The following sample program renders a file named Test.avi inside an application window. For brevity, it omits the following features:

  • It does not resize the video window when the parent window is resized. To accomplish this, call IVideoWindow::SetWindowPosition again in response to a WM_SIZE message on the parent window.
  • It performs no error checking.
  • It stretches the video window without regard to the aspect ratio of the source. To determine the aspect ratio, use the IBasicVideo interface.
  • It does not handle end-of-stream events. For information on how to do this, see Responding to Events.
#include <windows.h>
#include <dshow.h>

#define CLASSNAME "VideoWindow"

IGraphBuilder   *pGraph = NULL;
IMediaControl   *pMediaControl = NULL;
IVideoWindow    *pVidWin = NULL;
HWND            g_hwnd;

void PlayFile(void)
{
    // Create the filter graph manager.
    CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC,
        IID_IGraphBuilder, (void **)&pGraph);
    pGraph->QueryInterface(IID_IMediaControl, (void **)&pMediaControl);
    pGraph->QueryInterface(IID_IVideoWindow, (void **)&pVidWin);

    // Build the graph.
    pGraph->RenderFile(L"Test.avi", NULL);

    //Set the video window.
    pVidWin->put_Owner((OAHWND)g_hwnd);
    pVidWin->put_WindowStyle(WS_CHILD | WS_CLIPSIBLINGS);

    RECT grc;
    GetClientRect(g_hwnd, &grc);
    pVidWin->SetWindowPosition(0, 0, grc.right, grc.bottom);

    // Run the graph.
    pMediaControl->Run();
}

void CleanUp(void)
{
    pVidWin->put_Visible(OAFALSE);
    pVidWin->put_Owner(NULL);
    pMediaControl->Release();
    pVidWin->Release();
    pGraph->Release();
}

// Message handler.
long FAR PASCAL WindowProc( HWND hwnd, UINT msg, UINT wParam, LONG lParam)
{
    switch (msg)
    {
        case WM_DESTROY:
            CleanUp();
            PostQuitMessage(0);
            break;
        default:
            return (DefWindowProc(hwnd, msg, wParam, lParam));
    }
    return(NULL);
}

// Main.
int PASCAL WinMain( HINSTANCE hInst, HINSTANCE hPrevInst, LPSTR  lpCmdLine,
    int nCmdShow )
{
    MSG         msg;
    WNDCLASS    wc;

    CoInitialize(NULL);

    ZeroMemory(&wc, sizeof wc);
    wc.lpfnWndProc  = WindowProc;
    wc.hInstance    = hInst;
    wc.hIcon        = LoadIcon( NULL, IDI_APPLICATION );
    wc.hCursor      = LoadCursor( NULL, IDC_ARROW );
    wc.hbrBackground = (HBRUSH)GetStockObject( BLACK_BRUSH );
    wc.lpszMenuName = NULL;
    wc.lpszClassName = CLASSNAME;
    RegisterClass( &wc );

    g_hwnd = CreateWindow(
        CLASSNAME,
        "DirectShow Sample",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        CW_USEDEFAULT,
        NULL,
        NULL,
        hInst,
        NULL);

    ShowWindow( g_hwnd, nCmdShow );
    UpdateWindow( g_hwnd );
    PlayFile();

    while( GetMessage( &msg, NULL, 0, 0 ) )
    {
        TranslateMessage( &msg );
        DispatchMessage( &msg );
    }

    CoUninitialize();
    return msg.wParam;
}


Responding to Events

This section describes how to respond to events that occur in a Microsoft® DirectShow® application. It presents a sample program that builds on the sample given in Setting the Video Window. This article does not repeat all the code from that sample; rather, it describes what you need to add, which comes to about 25 lines of new code.

This article contains the following sections:

  • How Event Notification Works
  • Using Event Notification
  • Sample Code

How Event Notification Works

At various times while a DirectShow application is running, the status of a filter might change. For example, it might go from paused to running, encounter an error in the stream, or request that the video window be repainted. To alert the filter graph manager of a change, the filter sends an event notification, which consists of an event code that indicates the type of event, and two parameters that supply additional information. The meaning of the parameters depends on the event code. For a complete list of event codes and their parameters, see Event Notification Codes.

The filter graph manager handles some events without notifying the application, such as a request to repaint the video window. It places other events into a queue, from which the application retrieves and processes them in order. DirectShow event notification is similar in this respect to Microsoft® Windows® message queuing. In fact, you can have the filter graph manager send a Windows message to a designated window when a new event occurs. That way, the application can handle the events from within the window's message loop.

An application might need to handle a number of event codes, depending on the purpose of the application. This article focuses on two: EC_COMPLETE and EC_USERABORT:

  • Renderer filters signal EC_COMPLETE when they reach the end of a data stream. A filter graph might contain more than one stream; for example, a video stream and an audio stream. Each stream is associated with its own renderer and therefore generates a separate EC_COMPLETE event. Rather than forward all the EC_COMPLETE events to the application, the filter graph manager waits until it receives one EC_COMPLETE notification for every stream in the graph. At that point, it sends a single EC_COMPLETE event to the application. When the application receives the EC_COMPLETE event, all the streams have finished.
  • The EC_USERABORT event indicates that the user has interrupted playback. Video renderers send this event if the user closes the video window.

Using Event Notification

The sample application handles events from within the main window message loop. It works by having the filter graph manager post a message when a new event occurs. The application responds by retrieving the event and taking the appropriate action.

To handle events from the main window message loop, define the message that will be sent to the application window when a new event occurs. Applications can use message numbers in the range from WM_APP through 0xBFFF as private messages, as shown in the following example:

#define WM_GRAPHNOTIFY  WM_APP + 1

Next, set the filter graph manager to deliver this message to the application's main window:

pEvent->SetNotifyWindow((OAHWND)g_hwnd, WM_GRAPHNOTIFY, 0);

The IMediaEventEx::SetNotifyWindow method designates the specified window (g_hwnd) as the recipient of the message. Call this method after you create the filter graph and specify the owner window, but before running the graph. For details, see Sample Code. The IMediaEventEx interface is exposed by the filter graph manager.

When the application receives the WM_GRAPHNOTIFY message, the message's lParam parameter is equal to the third parameter passed to SetNotifyWindow. This parameter enables you to send instance data with the message. The sample code does not use this data, so it passes a value of zero. The message's wParam parameter is always zero.

In the window's WindowProc function, add a case statement for the WM_GRAPHNOTIFY message:

case WM_GRAPHNOTIFY:
    HandleEvent();
    break;

WM_GRAPHNOTIFY is an ordinary Windows message, and is posted separately from the DirectShow event notification queue. The sequence of events is as follows:

  1. A filter sends an event notification to the filter graph manager.
  2. If the filter graph manager does not handle the event, it places the event in the event queue.
  3. The filter graph manager posts a WM_GRAPHNOTIFY message to the application window.
  4. The application responds to the message from within the window's message loop.
  5. The application retrieves the event notification from the queue.

In the event handler function, call the IMediaEvent::GetEvent method to retrieve events from the queue:

long evCode, param1, param2;
HRESULT hr;
while (hr = pEvent->GetEvent(&evCode, &param1, &param2, 0), SUCCEEDED(hr))
{
    hr = pEvent->FreeEventParams(evCode, param1, param2);
    if ((EC_COMPLETE == evCode) || (EC_USERABORT == evCode))
    {
        CleanUp();
        break;
    }
}

The GetEvent method retrieves the event code and the two event parameters. The last parameter to GetEvent specifies how long the method will wait for an event. Because the application calls this method in response to a WM_GRAPHNOTIFY message, the event is already queued, so use a time-out value of zero.

Because event notification and the message loop are both asynchronous, the queue might hold more than one event by the time your application responds to the message. Also, the filter graph manager can clear events from the queue, if they become invalid. Therefore, call GetEvent until it returns a failure code, indicating that the queue is empty.

If the sample program receives an EC_COMPLETE or EC_USERABORT event, it invokes the application-defined CleanUp function, which causes the application to quit gracefully. It ignores the two event parameters (param1 and param2). After you retrieve an event, call IMediaEvent::FreeEventParams to free resources associated with the event parameters. For example, the parameter may be a BSTR, whose memory was allocated by the filter graph manager.

When an EC_COMPLETE event occurs, the filter graph does not automatically switch to a stopped state. The application must stop or pause the graph. When the graph stops, filters release any resources they hold. When it pauses, they continue to hold resources. Also, when a video renderer pauses, it displays a static image of the most recent frame. The sample program stops the graph.

Sample Code

The following code does not include the functions WinMain or WindowProc. See the sample code in Setting the Video Window for these functions.

#include <windows.h>
#include <dshow.h>

#define WM_GRAPHNOTIFY  WM_APP + 1
#define CLASSNAME "EventNotify"

IGraphBuilder   *pGraph = NULL;
IMediaControl   *pMediaControl = NULL;
IMediaEventEx   *pEvent = NULL;
IVideoWindow    *pVidWin = NULL;
HWND            g_hwnd;

void PlayFile(void)
{
    // Create the filter graph manager and render the file.
    CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC, IID_IGraphBuilder, (void **)&pGraph);
    pGraph->RenderFile(L"C:\\Media\\Boys.avi", NULL);

    // Specify the owner window.
    pGraph->QueryInterface(IID_IVideoWindow, (void **)&pVidWin);
    pVidWin->put_Owner((OAHWND)g_hwnd);
    pVidWin->put_WindowStyle( WS_CHILD | WS_CLIPSIBLINGS);

    // Set the owner window to receive event notices.
    pGraph->QueryInterface(IID_IMediaEventEx, (void **)&pEvent);
    pEvent->SetNotifyWindow((OAHWND)g_hwnd, WM_GRAPHNOTIFY, 0);

    // Run the graph.
    pGraph->QueryInterface(IID_IMediaControl, (void **)&pMediaControl);
    pMediaControl->Run();
}

void CleanUp(void)
{
    pVidWin->put_Visible(OAFALSE);
    pVidWin->put_Owner(NULL);

    // Stop the graph.
    pMediaControl->Stop();

    pMediaControl->Release();
    pVidWin->Release();
    pEvent->Release();
    pGraph->Release();
    PostQuitMessage(0);
}

void HandleEvent()
{
    long evCode, param1, param2;
    HRESULT hr;
    while (hr = pEvent->GetEvent(&evCode, &param1, &param2, 0), SUCCEEDED(hr))
    {
        hr = pEvent->FreeEventParams(evCode, param1, param2);
        if ((EC_COMPLETE == evCode) || (EC_USERABORT == evCode))
        {
            CleanUp();
            break;
        }
    }
}

/* WindowProc goes here. Add the following case statement:
        case WM_GRAPHNOTIFY:
            HandleEvent();
            break;
*/

// WinMain goes here.


About DirectShow

This section contains the following topics:

  • DirectShow System Overview
  • The Filter Graph and Its Components
  • Building the Filter Graph
  • Data Flow in the Filter Graph
  • Event Notification in DirectShow
  • How Hardware Devices Participate in the Filter Graph
  • Dynamic Graph Building
  • Plug-in Distributors


DirectShow System Overview

The Challenge of Multimedia

Working with multimedia presents several major challenges:

  • Multimedia streams contain large amounts of data that must be processed very quickly.
  • The audio, video and any additional streams must all be synchronized to start and stop at the same time and play at the same rate.
  • Streams can come from many various sources, including local media files, computer networks, terrestrial broadcasts, video cameras, and other media devices.
  • Streams come in a variety of formats, such as Audio-Video Interleaved (AVI), Advanced Streaming Format (ASF), Motion Picture Experts Group (MPEG), Digital Video (DV), and Motion JPEG (MJPEG).
  • An application has no way of knowing which hardware devices will be present on the end-user's system.

The DirectShow Solution

DirectShow is designed to address each of these challenges. Its main design goal is to simplify the task of creating multimedia applications on the Windows® platform by isolating applications from the complexities of data transports, hardware differences, and synchronization issues.

To achieve the throughput necessary for streaming video and audio, DirectShow uses DirectDraw® and DirectSound® to render data efficiently to the system's sound and graphics cards. Synchronization is achieved by encapsulating the multimedia data in time-stamped media samples. To handle the variety of sources, formats, and hardware devices, DirectShow uses a modular architecture in which operating system components called filters can be mixed and matched to provide support for many different scenarios.

DirectShow includes filters that support cutting-edge multimedia capture and tuning devices based on the Windows Driver Model (WDM) as well as filters that support legacy Video for Windows (VfW) capture cards and older codecs written for the Audio Compression Manager (ACM) and Video Compression Manager (VCM) interfaces.

The following diagram shows the relationship between an application, the DirectShow components, and some of the hardware and software components that DirectShow supports.

High Level Architecture

As illustrated here, DirectShow enables applications to play files and streams from various sources, including local files, local CD and DVD drives, remote files on a network, newer TV-tuner and video capture cards based on the Windows Driver Model (WDM), and legacy Video For Windows® video capture cards. DirectShow has native compressors and decompressors for some file formats, and many third-party hardware and software decoders are compatible with DirectShow. In addition, DirectShow supports legacy VfW codecs based on the Video Compression Manager (VCM) and Audio Compression Manager (ACM) interfaces. Playback makes full use of DirectDraw hardware acceleration and DirectSound capabilities when the hardware supports it.


The Filter Graph And Its Components

This article provides a high-level overview of the components that make up Microsoft® DirectShow® filter graphs. It is intended as an introduction for developers who will write their own custom DirectShow filters, and also for DirectShow application developers who want to know something of what is going on behind the scenes when their application uses DirectShow. It is important to understand, however, that applications often have no need to deal with the inner workings of a DirectShow filter graph; in most situations the details such as adding filters, connecting pins, setting a synchronization source, and so on, are handled automatically by the Filter Graph Manager and by the filters and pins themselves. Note for Filter Developers: To use your own custom transform or effect in DirectShow, it is no longer necessary to write a native DirectShow filter. You can now write a DirectX Media Object (DMO) that does the transform, and use it in a filter graph through the DMO Wrapper filter. This frees you completely from all the details of the filter connection and synchronization mechanisms.

The Filter Graph

Whenever a media file or stream is played, recorded, captured, broadcast, or processed in any way, it is done by means of connecting one or more filters together in a configuration called a filter graph. The graph-building process can be done manually by an application or automatically by the Graph Builder or Filter Graph Manager. In either case the process usually begins with the source filter and is always based on two main factors: the number of streams and their media types that a filter expects as input, and the number of streams and their media types that it outputs. The following illustration shows a simple filter graph for playing back an AVI file with compressed video.

The arrows in the graph depict the direction in which data is flowing. The source filter here is the Async File Source. This filter simply reads the bytes from the file and passes them on to the AVI Splitter filter, which recognizes the Audio-Video Interleaved (AVI) format, including the video compression scheme. The AVI Splitter parses the data into time-stamped media samples and passes the video samples downstream to the AVI Decompressor. For video, each sample contains one frame of video. The AVI Decompressor finds the correct codec to decompress the samples and passes the decompressed video frames to the video renderer filter, which displays the video on the computer screen. Because the audio samples are uncompressed, the AVI Splitter can connect directly to the Default DirectSound Device filter.

Filters

Filters are the basic building blocks of DirectShow. DirectShow separates the processing of multimedia data into discrete steps, and a filter represents one (or sometimes more than one) processing step. This enables applications to "mix and match" filters to perform many different kinds of operations on many different media formats using many different classes of hardware and software devices. For example, the Async File Source filter reads a file from a disk, the TV Tuner filter changes the channel on a TV-capture card, and the MPEG-2 Splitter filter parses the audio and video data in an MPEG stream so that it can be decoded. Although each of these filters does something very unique internally, from the point of view of an application, each is just a DirectShow filter with certain standard characteristics: support for the IBaseFilter interface and one or more input and/or output pins which represent its connection(s) to one or more other DirectShow filters.

All DirectShow filters fall into one of these three categories: source filters, transform filters, and renderer filters.

Source Filters

Source filters present the raw multimedia data for processing. They may get it from a file on a hard disk (like the Async File Source source filter in the diagram above), or from a CD or DVD drive, or they may get it from a "live" source such as a television receiver card or a capture card connected to a digital camera. (Source filters for all these scenarios are included with DirectShow and ship with every copy of Microsoft Windows 9x and Windows 2000.) Some source filters simply pass on the raw data to a parser or splitter filter, while other source filters also perform the parsing step themselves.

Transform Filters

Transform filters accept either raw or partially-processed data and process it further before passing it on. There are many types of transform filters including (to name a few) parsers that split raw byte streams into samples or frames, compressors and decompressors, and format converters. DirectShow includes many popular codecs. In the diagram above, the AVI Splitter and the AVI decompressor are both transform filters. (One transform filter that DirectShow does not provide is an MPEG-2 decoder. These are available in either hardware or software implementations from third-parties.)

Renderer Filters

Renderer filters generally accept fully-processed data and play it on the system's monitor or through the speakers or possibly through some external device. Also included in this category are "file-writer" filters that save data to disk or other persistent storage. The video renderer filters that come with DirectShow use DirectDraw to display video and the default audio renderer filter uses DirectSound to play audio, as illustrated in the diagram above.

Filters for playing, converting, and capturing many different media formats are supplied with DirectShow and ship with every copy of Windows 9x and Windows 2000. Developers can also build their own custom filters for handling either custom or standard data formats. And for DirectX 8, DirectShow simplifies the process of "filter" development by enabling developers to write DirectX Media Objects (DMOs) and let the DMO Wrapper filter handle all the synchronization and pin connection details. DMOs are easier to develop and test than filters, and are not dependent on the DirectShow filter graph architecture. You can write a DMO once and reuse it wherever you need it, whether it is a DirectShow application or not.

Pins

As illustrated in the preceding diagram, the multimedia data in a filter graph moves downstream from a source filter through zero or more intermediate filters and finally to a renderer filter. Pins handle the low-level details of the data transfer between filters. A pin is a COM object which supports the IPin COM interface, has a direction (input or output), and is associated with a particular filter in the graph. A pin represents the point of connection with another filter. An output pin on an upstream filter connects to an input pin on the next filter downstream. Pins know what media types they can support and they negotiate the media type when two filters initially connect. Once the media type is agreed upon, the pins negotiate the details of how they will transfer data once the filter graph starts running.

Media Samples

After raw bytes have been pulled into the graph, either from a local file or capture card or some other source, the bytes must be parsed into meaningful units, called media samples. Sometimes a source filter does the parsing, and sometimes a separate parsing filter performs this task. In DirectShow, a media sample is wrapped in a COM object that implements IMediaSample2. In addition to the actual multimedia data, the object contains information including the specific media type and the synchronization times. A media sample object containing video data holds the data for one video frame. For audio, a media sample object holds the data for several audio samples. In either case, when data moves downstream through a graph from one filter to the next, it is in the form of media sample objects.

Allocators

When two filters connect, their pins must agree on the details of how the media sample objects will be transported from the upstream filter to the downstream filter. To "connect" means to determine the size, location and number of samples that will be used. The size of the samples will depend on the media type and format, and the buffer location may be either in main memory or else on a hardware device such as a video capture card. The creation and management of the samples is handled by an allocator, a COM object that is itself usually created by the input pin on the downstream filter.

See Writing DirectShow Filters for details of allocator creation and the negotiations that input and output pins perform when connecting. In certain video capture scenarios, an application may need to specify the size of buffers that should be allocated, and interfaces are provided for this purpose. For the vast majority of cases, the details of buffer allocation will be completely transparent to applications. It should be noted, however, that the "movement" of data in a filter graph does not always involve a copy operation. In the connection process, pins will "reuse" upstream buffers whenever possible in order to maximize throughput.

Clocks

In any operation related to multimedia, it is vital to synchronize the samples so that video frames are displayed at the proper rate, so that the audio stream does not get ahead of the video, and so on. A DirectShow filter graph therefore always contains exactly one clock that all filters use to either timestamp, process or render media samples. The Filter Graph Manager selects a clock (or provides one if needed) and instructs all the filters to use that clock as the synchronization source.


Building the Filter Graph

The previous article, The Filter Graph and Its Components, describes the basic building blocks of a DirectShow filter graph. This article examines how these building blocks are created and connected together so that they can begin to process some type of multimedia data. The first section, General Graph Building, describes the general techniques of filter graph construction. The second section, Capture Graph Building, describes a separate technique used for building capture graphs, which are filter graphs that process data from a video capture device such as a DV camcorder, USB camera, or TV tuner card.

General Graph Building

To create a filter graph, you always begin by creating an instance of the Filter Graph Manager and obtaining a pointer to its IGraphBuilder interface, as illustrated here:

IGraphBuilder* pIGB;
HRESULT hr;
hr = CoCreateInstance(CLSID_FilterGraph,
                    NULL,
                    CLSCTX_INPROC_SERVER,
                    IID_IGraphBuilder,
                    (void **)&pIGB);

The IGraphBuilder interface, as its name suggests, contains the methods for building filter graphs. These methods provide three basic approaches to building the graph:

  1. The application instructs the Filter Graph Manager to build the entire graph automatically.
  2. The application and Filter Graph Manager share the graph building work.
  3. The application builds the entire graph itself by individually adding and connecting each filter.

Approach #1: The Filter Graph Manager builds the entire graph

Approach #1 is for scenarios when you simply want to play a file of some recognized format, such as AVI, MPEG, WAV, MP3, and so on. This technique is demonstrated in the article How to Play a File. In DirectShow, the term render is often used instead of play to describe the process of displaying video data on the monitor or audio data through the system's speakers. To instruct the Filter Graph Manager to automatically create a filter graph that can render a specified file, an application uses the IGraphBuilder::RenderFile method. The following sections describe the basic steps taken by the Filter Graph Manager to construct the graph.

Finding the Filters

The first step in creating a filter graph is to find and create an instance of the needed filters. The filter selection process is primarily based on the media type of the data to be processed. This is because pins on two filters cannot connect unless they can agree on a common media type that they both can handle. The Filter Graph Manager can determine the media type of the data by searching the registry for the media types associated with various file name extensions (.wma, .avi, .wav, and so on). If no association exists for an extension, then the Filter Graph Manager searches for special check bytes in the file. From these check bytes the Filter Graph Manager can determine the corresponding DirectShow media type, and then begin its search for a source filter that can read it. Internally, the RenderFile logic calls IGraphBuilder::AddSourceFilter to perform this task.

All DirectShow filters are uniquely identified in the Windows registry with a GUID, along with other information, including the filter's category, the supported media types, and the filter's merit. The Filter Graph Manager examines all this information to determine which filter to create an instance of. The filter category identifies the general functionality of the filter and is used to initially narrow the search criteria. The media type information describes what kind of data the filter can accept as input, and what it can deliver as output to the next filter in the graph. The merit value indicates whether a filter should be considered during the automatic graph building process. If two filters on the system have similar media type information, the Filter Graph Manager selects the one with the highest merit value. (Some filters are purposely given a low merit value because they are designed solely for use in specialized filter graphs. Such filters must be added to a graph individually by the application.)

To search the registry, the Filter Graph Manager creates an instance of the DirectShow Filter Mapper object and calls the IFilterMapper2::EnumMatchingFilters method to perform the search. This method can enumerate DirectShow filters (as well as hardware devices, such as decoders) by category or by media type, and it returns a standard COM IEnumMoniker object containing monikers to all the filters and/or hardware devices that match the search criteria. (The use of COM monikers enables this method to query objects without actually creating an instance of them, and also to create paths and enumerate things which are not actually COM objects, such as hardware devices.)

Adding Filters to the Graph

If a moniker is found for a source filter that can read a file of the specified type, the Filter Graph Manager uses CoCreateInstance to create an instance of the filter by using the returned GUID. For most file types, the source filter will be the File Source (Async) filter. The Filter Graph Manager then calls the IGraphBuilder::AddFilter method to add the filter to the filter graph. When the filter is notified that it has been added to a graph, it creates one or more output pins configured for the type of file it will be reading. After the pin(s) are created, the Filter Graph Manager examines the media type that each pin supports and then looks again in the registry for a filter that can accept that media type on its input pin. When it finds a suitable filter, it adds it to the graph.

Connecting the Filters

When the downstream filter is added, it configures its pins and is now ready to be connected to the previous (upstream) filter. The Filter Graph Manager queries each filter to determine the appropriate pins, and then calls the IGraphBuilder::Connect method to connect the output pin of the upstream filter to the input pin of the downstream filter. The two pins then perform a process of negotiation to determine the media type of the data and to determine which pin will provide the object that allocates memory for the media sample objects and the buffers that will hold the samples' data. The details of the pin connection process are discussed in more detail in the Filter Developer's Guide.

Completing the Graph

After the two pins are connected, the Filter Graph Manager examines the media type or types supported on the new filter's output pin, and searches for a filter that can handle that media type. The same process is repeated until all the necessary filters have been added to the graph. In a file playback graph, the second filter will typically be a parser or splitter filter, which reads a raw stream of data, such as AVI or MPEG, and splits it into separate audio and video streams, creating an output pin for each stream. If the data for either stream is compressed, the next filter on each stream will be a decompressor, followed by a renderer filter.

After the graph is built, the application only needs to obtain the IMediaControl interface from the Filter Graph Manager and call its Run method to start playing the file.

Approach #2: The application and Filter Graph Manager share the graph building work

When your filter graph is required to do something other than simply render a file, then your application must perform at least some of the graph building work. For example, if you are building a filter graph that converts AVI files to MPEG files, you could still have the Filter Graph Manager create an AVI playback graph by calling IGraphBuilder::RenderFile, but you must then modify the graph to output to an MPEG file instead of to the monitor and speakers. This involves disconnecting and removing the video and audio renderer filters (by using IGraphBuilder::Disconnect and IGraphBuilder::RemoveFilter) and replacing them with MPEG video and audio compressor filters, the MPEG Multiplexer filter, and a file writer filter.

It may also be necessary to add an intermediary filter to convert the media type into one that the MPEG compressor can accept. The application can either add this intermediary filter directly, or it can use the IGraphBuilder::Connect method. When this method is called, the Filter Graph Manager will first try to connect the filters directly, and if they cannot agree on a media type, then the Filter Graph Manager will search for intermediary filters. Whenever the Filter Graph Manager searches for a filter that can handle a given media type, it will first try filters that have already been added to the graph. To prevent the Filter Graph Manager from attempting to insert intermediary filters, use the IGraphBuilder::ConnectDirect method.

In the previous example, the application built the downstream portion of the graph. In other scenarios, the application might need to build the upstream portion of the graph. In that case, once you have added and connected the filters that must be added manually, you can use the IGraphBuilder::Render method to instruct the Filter Graph Manager to complete the graph automatically from the specified output pin. If a filter has two output pins, for example an audio pin and a video pin, then the application must call Render for each pin.

Approach #3: The application builds the entire graph itself

In some scenarios, your application may need to build the entire graph by individually adding and connecting each filter. In this case, you probably know specifically which filters should be added to the graph, so there is no need to use the Filter Mapper object to discover the filters. Just add each filter to the graph using the IGraphBuilder::AddFilter method and then connect them using either Connect or ConnectDirect.

Capture Graph Building

The process of building video capture graphs can be somewhat complex due to the differences in the various types of capture devices provided by Independent Hardware Vendors and consumer electronics manufacturers. To shield application developers from much of this complexity, DirectShow provides a separate object, the Capture Graph Builder. Video capture applications create an instance of this object and use its ICaptureGraphBuilder2 interface methods to build the filter graph. After you understand the general principles of graph building, you will see that capture graph building works in much the same way. For more detailed information, see How to Write a Capture Application.


Data Flow in the Filter Graph

This article describes how data moves through a Microsoft® DirectShow® filter graph. It contains the following topics.

  • Samples and Buffers
  • Delivering Samples
  • Stop, Pause, and Run
  • Live Capture
  • Further Reading

Samples and Buffers

When two pins are connected, data can move from the output pin to the input pin. The output pin delivers data, while the input pin receives data. The direction of data flow, from output to input, is called downstream, and the opposite direction is called upstream.

The type of data that moves between two pins depends on the implementation of the pins. In the most common case, pins work with media data that is held in main memory. However, other arrangements are possible. For example, if two filters control a piece of video hardware, the hardware might handle all of the video data, with the pins exchanging control information. The type of data, and how it moves between pins, is called the transport. This article focuses on the case where media data is held in main memory, called the local memory transport.

In the local memory transport, data is packaged into discrete objects called media samples. A media sample is a COM object that holds a pointer to an allocated memory buffer. Media samples support the IMediaSample interface, and possibly the IMediaSample2 interface.

Another COM object, the memory allocator, is responsible for allocating buffers and creating media samples. At connection time, the allocator reserves memory for the buffers. The allocator also creates a set of media samples, and gives each sample a pointer to an address within the memory block. Until the buffers are freed, the allocator maintains a list of which samples are available. Whenever a filter needs a new sample, it requests one from the allocator. After a sample is processed, the sample returns to the list.

This mechanism reduces the amount of memory allocation, because filters re-use the same buffers. It also prevents filters from accidentally writing over data that has not been processed, because the allocator maintains the list of available samples. Finally, it provides an efficient way to move data through the graph: When an output pin delivers a sample, it passes a pointer to the sample's IMediaSample interface. It does not have to copy any data.

The following illustration shows the relationship between the allocator, the media samples, and the filter.

Connected pins share a memory allocator. A filter might use different allocators for its input and output. This is typical when the filter expands the data, as happens with a decompression filter. If the output is not larger than the input, the filter might process the data in place, without moving it to a new buffer. In that case, two or more pin connections can share one allocator.

Delivering Samples

Input pins that support local memory expose the IMemInputPin interface. The output pin delivers a sample by calling the IMemInputPin::Receive method on the input pin. The input pin does one of the following:

  • Rejects the sample.
  • Blocks until it finishes processing the sample.
  • Returns immediately and processes the sample on another thread.

The IMemInputPin::ReceiveCanBlock method determines whether the input pin might block on the call to Receive. The output pin can call this method to determine an appropriate threading strategy. Some filters create a worker thread, so that they can deliver samples in the background while doing other work. Other filters simply block until the downstream filter is ready to accept another sample.

There is also a method for delivering more than one sample at a time, IMemInputPin::ReceiveMultiple. It works like Receive, but with an array of samples.

Stop, Pause, and Run

Filters have three states—stopped, paused, and running. For most filters, paused and running are equivalent:

  • When a filter is stopped, it does not process samples. It rejects any samples from upstream filters.
  • When a filter is paused or running, it accepts samples and processes them. If it is a source filter, it generates new samples and delivers them downstream.

Renderer filters are an exception. When a renderer filter goes from stopped to paused, it does not complete the transition until it receives one media sample. At that point, it holds the sample and blocks on the call to Receive. Video renderers paint the sample as a still frame. Audio renderers do not render the sample until they run. (There is nothing equivalent to a "still frame" for audio.) In either case, the renderer does not accept any more samples until it goes from paused to running.

The filter graph manager controls the state of the filter graph as a whole. The valid state transitions are between stopped and paused, and between paused and running. Transitions between stopped and running must go through paused. (If you call IMediaControl::Run on a stopped graph, or IMediaControl::Stop on a running graph, the filter graph manager pauses the graph first.)

When the filter graph goes from stopped to paused, the following sequence occurs:

  • The filter graph manager calls IMediaFilter::Pause on each filter, starting from the renderer filter and working upstream.
  • As each filter switches to paused, it is ready to accept samples from its upstream neighbor. It can safely deliver samples downstream, because the downstream filters are also paused.
  • The source filter is the last to be paused. At that point, it starts delivering samples.
  • As the samples move downstream, the intermediate filters process them.
  • When the first sample reaches the renderer, the renderer completes its state transition and blocks.

These events can take an arbitrary amount of time to complete—usually not much, but the delay could be noticeable, especially if the source requires decompression. Once the graph has finished pausing, however, it is able to start rendering data immediately. Thus, pausing the graph has the effect of "cueing" the data. An application can do this ahead of time, and then quickly switch the graph to running, in response to a command by the user.

Live Capture

Unlike other source filters, live capture filters do not deliver samples while paused. Between the pause command and the run command, any amount of time might elapse. Samples that were delivered at the time of the pause command would be outdated. If the user waits for an hour before issuing the run command, the graph should produce new video frames, not frames that were captured an hour ago. Therefore, capture filters deliver samples only when running.

However, this behavior could cause a problem for the graph. Before the filter graph manager runs the graph, it waits for all of the filters to pause. But the renderer never completes this transition, because it is waiting for a sample from the capture filter. To get around this problem, the capture filter's IMediaFilter::GetState method returns VFW_S_CANT_CUE. This return code notifies the filter graph manager that the capture filter is not delivering samples, and therefore not to wait on the renderer.

Further Reading

For more information about data flow, see Data Flow for Filter Developers.


Event Notification in DirectShow

This article describes how events are raised in a Microsoft® DirectShow® filter graph, and how an application can retrieve event notifications and respond to them. It contains the following sections.

  • Overview of Event Notification
  • Retrieving Events
  • Learning When an Event Occurs

Overview of Event Notification

A filter notifies the Filter Graph Manager about an event by posting an event notification. The event could be something expected, such as the end of a stream, or it could represent an error, such as a failure to render a stream. The Filter Graph Manager handles some filter events by itself, and it leaves others for the application to handle. If the Filter Graph Manager does not handle a filter event, it places the event notification into a queue. The filter graph can also queue its own event notifications for the application.

An application retrieves events from the queue and responds to them based on the type of event. Event notification in DirectShow is therefore similar to the Microsoft® Windows® message queuing scheme. An application can also cancel the Filter Graph Manager's default behavior for a given event type. The Filter Graph Manager then puts those events directly into the queue for the application to handle.

This mechanism enables

  • The Filter Graph Manager to communicate with the application.
  • Filters to communicate with both the application and the Filter Graph Manager.
  • The application to determine its degree of involvement in handling events.

Retrieving Events

The Filter Graph Manager exposes three interfaces that support event notification.

  • IMediaEventSink contains the method for filters to post events.
  • IMediaEvent contains methods for applications to retrieve events.
  • IMediaEventEx inherits from and extends the IMediaEvent interface.

Filters post event notifications by calling the IMediaEventSink::Notify method on the Filter Graph Manager. An event notification consists of an event code, which defines the type of event, and two DWORD parameters that give additional information. Depending on the event code, the parameters might contain pointers, return codes, reference times, or other information. For a complete list of event codes and parameters, see Event Notification Codes.

To retrieve an event from the queue, the application calls the IMediaEvent::GetEvent method on the Filter Graph Manager. This method blocks until there is an event to return or until a specified time elapses. Assuming there is a queued event, the method returns with the event code and the two event parameters. After calling GetEvent, an application should always call the IMediaEvent::FreeEventParams method to release any resources associated with the event parameters. For example, a parameter might be a BSTR value that was allocated by the filter graph.

The following code example provides an outline of how to retrieve events from the queue.

long evCode, param1, param2;
HRESULT hr;
while (hr = pEvent->GetEvent(&evCode, &param1, &param2, 0), SUCCEEDED(hr))
{
    switch(evCode)
    {
        // Call application-defined functions for each
        // type of event that you want to handle.
    }

    hr = pEvent->FreeEventParams(evCode, param1, param2);
}

To override the Filter Graph Manager's default handling for an event, call the IMediaEvent::CancelDefaultHandling method with the event code as a parameter. You can reinstate the default handling by calling the IMediaEvent::RestoreDefaultHandling method. If the filter graph performs no default handling for the specified event code, calling these methods has no effect.

Learning When an Event Occurs

In addition to retrieving event notifications from the queue, as discussed above, an application needs a way to find out when events are waiting in the queue. The Filter Graph Manager provides two ways to do this.

  • Using window notification, the Filter Graph Manager sends a Windows message to an application window whenever there is a new event.
  • Using event handles, the application retrieves a handle to a Windows manual-reset event. The Filter Graph Manager signals the manual-reset event when there are event notifications in the queue and resets it when the queue is empty.

The following sections describe each technique.

  • Window Notification
  • Event Handles

Window Notification

To set up window notification, call the IMediaEventEx::SetNotifyWindow method and specify a private message. Applications can use message numbers in the range from WM_APP through 0xBFFF as private messages. Whenever the Filter Graph Manager places a new event notification in the queue, it posts this message to the designated window. The application responds to the message from within the window's message loop.

The following code example shows how to set the notification window.

#define WM_GRAPHNOTIFY WM_APP + 1   // Private message.

pEvent->SetNotifyWindow((OAHWND)g_hwnd, WM_GRAPHNOTIFY, 0);

The message is an ordinary Windows message, and is posted separately from the DirectShow event notification queue. The advantage of this approach is that most applications already implement a message loop. Therefore, you can incorporate DirectShow event handling without much additional work.

The following code example shows an outline of how to respond to the notification message. For a complete example, see Responding to Events.

LRESULT CALLBACK WindowProc( HWND hwnd, UINT msg, UINT wParam, LONG lParam)
{
    switch (msg)
    {
        case WM_GRAPHNOTIFY:
            HandleEvent();  // Application-defined function.
            break;

        // Handle other Windows messages here too.
    }
    return (DefWindowProc(hwnd, msg, wParam, lParam));
}

Because event notification and the message loop are both asynchronous, the queue might contain more than one event by the time your application responds to the message. Also, events can sometimes be cleared from the queue if they become invalid. Therefore, in your event handling code, call GetEvent until it returns a failure code, indicating that the queue is empty.

Event Handles

The filter graph keeps a manual-reset event that reflects the state of the event queue. If the queue contains pending event notifications, the filter graph signals the manual-reset event. If the queue is empty, a call to the IMediaEvent::GetEvent method resets the event. An application can use this event to determine the state of the queue.

Note The terminology can be confusing here. The manual-reset event is the type of event created by the Windows CreateEvent function; it has nothing to do with the event notifications defined by DirectShow.

The IMediaEvent::GetEventHandle method retrieves a handle to the manual-reset event. Wait for the event to be signaled by calling a function such as WaitForMultipleObjects. Once the event is signaled, call the IMediaEvent::GetEvent method to retrieve the event notification.

The following code example illustrates this approach. It retrieves the event handle, then waits in 100-millisecond intervals for the event to be signaled. If the event is signaled, it calls GetEvent and prints the event code and event parameters to the console window. The loop terminates when the EC_COMPLETE event occurs, indicating that playback has completed.

HANDLE  hEvent;
long    evCode, param1, param2;
BOOLEAN bDone = FALSE;
HRESULT hr = S_OK;

hr = pEvent->GetEventHandle((OAEVENT*)&hEv);

while(!bDone)
{
    if (WAIT_OBJECT_0 == WaitForSingleObject(hEvent, 100))
    {
        while (hr = pEvent->GetEvent(&evCode, &param1, &param2, 0), SUCCEEDED(hr))
        {
            printf("Event code: %#04x\n    Params: %d, %d\n", evCode, param1, param2);
            hr = pEvent->FreeEventParams(evCode, param1, param2);
            bDone = (EC_COMPLETE == evCode);
        }
    }
}

Because the filter graph automatically sets or resets the event when appropriate, your application should not do so. Also, when you release the filter graph, the filter graph closes the event handle, so do not use the event handle after that point.


How Hardware Devices Participate in the Filter Graph

Wrapper Filters

All Microsoft® DirectShow® filters are user mode software components. For a kernel mode hardware device such as a capture card, TV Tuner, hardware decoder, or sound card to join a DirectShow filter graph, the device must be represented as a user mode filter in the filter graph. This function is performed for various types of devices by specialized "wrapper filters" provided with DirectShow. These filters include the Audio Capture filter, the VFW Capture filter, the TV Tuner filter, the Analog Video Crossbar filter, and the TV Audio filter. In addition to these wrapper filters, DirectShow also provides the KsProxy filter, which can represent any type of Windows Driver Model® (WDM) streaming device and which can be extended by independent hardware vendors (IHVs) to support custom functionality. This is done by means of a Ksproxy plug-in, which is a COM object that is aggregated by KsProxy.

The wrapper filters work by supporting COM interfaces that represent the expected capabilities of the device. The application uses these interfaces to pass information to and from the filter, the filter translates the interface calls into information the device driver can understand, and then the filter passes that information to and from the driver in kernel mode. (KsProxy works in a similar manner, although the interfaces it exposes to the filter graph vary depending on the device it is representing.) For filters such as the VfW Capture Filter and Audio Capture filter, the interfaces are non-extensible. The TV Tuner filter and Analog Video Crossbar and TV Audio filters, although not based on KsProxy, support the IKSPropertySet interface, which is a generic way of handling custom property sets through a single interface.

For application developers, the principle of wrapping hardware devices as user mode filters means that applications control devices in the same way they control any other DirectShow filter. No special programming is required on the part of the application; all the details involved in communicating with the kernel mode device are encapsulated within the filter itself.

Video for Windows Devices

To support earlier Video for Windows (VfW) capture cards, DirectShow provides the VFW Capture Filter. When a VfW card is present on the target system, it can be discovered using the DirectShow System Device Enumerator. The Enumerator is also used to add the VfW Capture Filter to the graph and associate it with the card that was found. The rest of the filter graph can then be constructed in the usual ways. See Enumerating Devices and Filters for more details.

Audio Capture and Mixing Devices (Sound Cards)

Newer sound cards have input jacks for microphones and other types of devices. These cards also typically have on-board mixing capabilities for controlling the volume, treble, and bass of each individual input. In DirectShow, the sound card's inputs and mixer are wrapped in the Audio Capture filter. Each sound card in the local system can be discovered with the system device enumerator as described in Enumerating Devices and Filters. To view the sound cards in your system, open open the GraphEdit utility program that installs with the SDK and select from the Audio Capture Sources category. Each filter represented here is a separate instance of the Audio Capture filter.

WDM Streaming Devices

Newer hardware decoders and capture cards conform to the Windows Driver Model (WDM) specification. These devices have greater functionality compared to VfW devices and are portable between Windows NT/Windows 2000 and Windows 98/Me. WDM video capture cards are capable of supporting features not available under VfW, including capture format enumeration, programmatic control of video parameters (such as hue/brightness), programmatic input selection, TV Tuner support, and VBI support.

To support WDM streaming devices, DirectShow provides a filter called KsProxy (ksproxy.ax). KsProxy has been called the "Swiss Army Knife filter" because it does so many different things. It has also been called the "chameleon filter" because the number of pins and interfaces supported on the filter as a whole and on individual pins depends on the capabilities of the underlying kernel mode driver. It never appears in a filter graph by the name "KsProxy." It always takes the "friendly" name of the device that it finds in the registry. (This name is originally specified in the driver's .inf file.) If you have a WDM device on your system, you can open the GraphEdit utility program, click Graph, select Insert Filters, and scroll down to the WDM Streaming devices nodes. Even if you have only one WDM card on your system, that card might contain more than one device. Each device is represented as a separate filter, and each of these filters is actually KsProxy.

When an application uses the System Device Enumerator to programmatically find a WDM device moniker on the target system; for example, a TV Tuning card, KsProxy (using a "friendly name" provided by the driver) is instantiated in the subsequent call to the BindToObject method. Because KsProxy can represent all kinds of WDM audio or video devices and does not know in advance what kind of device it will be representing, it must query the driver to see which property sets are supported. Property sets are collections of data structures used by WDM Stream Class drivers as well as some user mode filters such as MPEG-2 software decoders. KsProxy then configures itself dynamically to expose the appropriate interfaces to the filter graph and the application. When applications and other filters call into these interfaces, KsProxy translates the method parameters into property sets and sends these to the driver. IHVs can extend KsProxy by supplying plug-ins, which are vendor-specific interfaces that expose the special capabilities of a device. All these details are hidden from applications; the application controls and receives events from the WDM device, by way of KsProxy, in the same way as any other DirectShow user mode filter.

Kernel Streaming

WDM devices support the kernel streaming model by which data can be streamed entirely in kernel mode without ever having to transition to user mode. Passing between kernel mode and user mode is a computationally expensive operation; kernel streaming provides the benefit of high bitrates without burdening the host CPU. WDM-based filters can use kernel streaming to pass multimedia data directly from one hardware device to another (either on the same card or on a different card) without ever copying the data into the system's main memory.

From an application's point of view, it appears as if the multimedia data in the graph is moving from one user mode filter to the next. In reality, the data might never pass into user mode at all, but is streamed directly from one kernel mode device to another until it is rendered on the video graphics card. Of course, in some scenarios, such as capture to a file, the data must actually pass from kernel mode to user mode at some point in the filter graph, but transfer to user mode access does not necessarily require that the data be copied to a new location in memory. Applications can take explicit control when building capture graphs to make sure the data follows a desired path, either from one hardware device to another, or from a hardware device to a user mode filter. See the sections on Video Capture for more information.

Application developers generally do not need to be concerned with the details of kernel streaming, except as background information. See the Microsoft DDK for more detailed documentation on WDM, kernel streaming, KsProxy, and related topics.


Dynamic Graph Building

If you need to modify an existing filter graph, you can stop the graph, make the changes, and restart the graph. This is usually the best approach. However, under some circumstances, you might want to alter a graph while it is still running. For example:

  • The application inserts a video effects filter during playback.
  • A source filter switches media types midstream, possibly requiring a new decompression filter.
  • The application adds a new video stream to the graph.

These are all examples of dynamic graph building, a term that covers any kind of change to a filter graph while the graph continues to run. Dynamic graph building can be initiated by an application or by a filter in the graph. Three distinct scenarios are possible:

  • Dynamic format change: Changing the connection type between two filters, without removing or replacing any filters.
  • Dynamic reconnection: Changing the topology of the graph by adding or removing filters.
  • Filter chains: Adding, removing, and controlling chains of filters.

This article contains the following sections:

  • Dynamic Format Change
  • Dynamic Reconnection
  • Filter Chains

Dynamic Format Change

If a filter switches output formats, it may be possible for the downstream filter to accept the new format without reconnecting any pins, stopping the graph, or replacing any filters. To determine whether the pin can accept the new media type while the graph is running, the filter (or an application) calls IPinConnection::DynamicQueryAccept on the input pin connected to the filter's output pin. This method differs from the IPin::QueryAccept method, because QueryAccept does not guarantee that the pin will accept a media type once the filter starts running.

If the new format cannot be accepted with the current connection, the next solution is a dynamic reconnection, described in the following section.

Dynamic Reconnection

Dynamic reconnection is a change to the topology of the graph. In order not to lose data, an application or filter that initiates dynamic reconnection must be careful about the sequence of events. The section of the graph being reconfigured must not have any media data flowing through it. For example, suppose that an application dynamically replaces Filter 2 in the following filter graph.

Dynamic Graph Building Diagram

To safely remove this filter and reconnect the graph, the application must perform the following steps:

  1. Block the data flow on Pin A.
  2. Push pending data through the filter graph, from Pin B to Pin D.
  3. Reconfigure the graph by removing Filter 2 and inserting a new filter.
  4. Unblock pin A so that data starts flowing again.

Three interfaces support these operations:

  • IPinFlowControl on the upstream output pin (pin A).
  • IPinConnection on the downstream input pin (pin D).
  • IGraphConfig on the filter graph manager.

The following sections describe the process in greater detail:

  • Blocking the Data Flow
  • Pushing Data Through the Graph
  • Reconfiguring the Graph
  • Example Code

Blocking the Data Flow

To block the data flow, call IPinFlowControl::Block on the upstream output pin (pin A). You can call this method either asynchronously or synchronously:

  • Asynchronously: Call the CreateEvent function to create an event object and pass the event handle to the Block method. The method returns immediately, and the pin signals the event when the operation has completed. Call a wait function such as WaitForSingleObject to wait for the event, as shown in the following code:

    HANDLE hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
pFlowControl->Block(AM_PIN_FLOW_CONTROL_BLOCK, hEvent);
WaitForSingleObject(hEvent, dwMilliseconds);
  • Synchronously: Pass NULL instead of an event handle. The method does not return until the operation completes. This might not happen until the pin is ready to deliver a sample; and if the filter is paused, the method might block indefinitely. Therefore, do not call Block synchronously from your main application thread.

After the graph is reconfigured, unblock the data flow by calling IPinFlowControl::Block with a value of zero for the first parameter.

If an upstream filter initiates the reconnection, it might be able to control the data flow internally, rather than by calling IPinFlowControl::Block.

Pushing Data Through the Graph

By default, the filter graph manager automatically pushes data through the graph when you call the IGraphConfig::Reconnect method, which is described in the next section. However, if you do not use this method—for example, if you use the IGraphConfig::Reconfigure method—you must handle this operation yourself. In any case, it is useful to understand the process.

To push the data through the graph, perform the following steps:

  1. Call IPinConnection::NotifyEndOfStream on the downstream input pin (pin D). This method requests notification from the pin when the next end-of-stream condition occurs. The pin will notify the caller by signaling an event.
  2. Call IPin::EndOfStream on the input pin immediately connected to the upstream output pin (pin B). As the remaining data travels downstream through any intermediate filters, those filters propagate the end-of-stream notification. In this example, the only intermediate filter is Filter 2.
  3. Wait for the event. When the downstream input pin (pin D) receives the end-of-stream notification, it signals the event. At this point, there is no more pending data and it is safe for the caller to reconfigure the graph.

Reconfiguring the Graph

To reconfigure the graph, call the IGraphConfig::Reconnect method. This method performs the following actions:

  • Stops intermediate filters and removes them from the graph.
  • Adds new intermediate filters, connecting their input and output pins.
  • Starts the new filters.

If the IGraphConfig::Reconnect method is not suitable for some reason, you can reconfigure the graph in a callback method. Implement the IGraphConfigCallback interface, and then call the IGraphConfig::Reconfigure method, which calls your callback method. In that case, you are responsible for pushing the data through the filter graph. Call the IGraphConfig::PushThroughData method.

Example Code

The following example shows an outline of how an application might insert an effect filter, pointed to by the variable pFX, between a source filter and a renderer filter. Other scenarios are possible, and the IGraphConfig::Reconnect method takes several parameters that control its behavior. See the IGraphConfig reference for more information.

// Assume the graph is running.
    IGraphConfig *pConfig;
    pGraph->QueryInterface(IID_IGraphConfig, (void **)&pConfig);

    // Block the data flow.
    IPinFlowControl *pFlowControl;
    pOutPin->QueryInterface(IID_IPinFlowControl, (void **)&pFlowControl);
    pFlowControl->Block(AM_PIN_FLOW_CONTROL_BLOCK, NULL);

    // Reconfigure the graph.
    pGraph->AddFilter(pFX, L"Effect Filter");
    pConfig->Reconnect(
            pOutPin,    // Start from this output pin.
            NULL,       // Search downstream for a suitable input pin.
            NULL,       // First connection is unspecified.
            pFX,        // Use this filter.
            NULL,
            0);

    pFlowControl->Block(0, NULL);   // Unblock the data flow.

Note pOutPin is assumed to be a pointer to an output pin on the source filter. For information on retrieving pointers to pins on a filter, see Enumerating Pins.

If dynamic reconnection is performed by a filter, rather than an application, there are potential threading issues. Specifically, if another process tries to stop the filter, it can deadlock while the graph waits for the filter to stop, and the filter waits for data to be pushed through the graph. To prevent this situation, some methods described previously take a handle to an event, which the filter should signal if it receives a call to its IMediaFilter::Stop method. For more information, see IGraphConfig and IPinConnection.

Filter Chains

A filter chain is a sequence of filters that meets the following conditions:

  • Each filter in the chain has at most one connected input pin and one connected output pin.
  • It is possible to traverse every filter in the chain without traversing filters outside the chain.

For example, in the following diagram, filters A–B, C–D, and F–G–H are filter chains. Each subchain in F–G–H (F–G and G–H) is also a filter chain. A filter chain can consist of a single filter, so filters A, B, C, D, F, G, and H are also distinct filter chains. Filter E has two input connections, so any sequence of filters that includes filter E is not a filter chain.

Filter Chain (Example 1)

The IFilterChain interface provides the following methods for controlling filter chains:

IFilterChain::StartChain | Starts a chain.
IFilterChain::StopChain | Stops a chain.
IFilterChain::PauseChain | Pauses a chain.
IFilterChain::RemoveChain | Removes a chain from the graph.

There is no specific method for adding a chain. To add a chain, insert the new filters using the IFilterGraph::AddFilter method. Then connect the filters by calling IGraphBuilder::Connect, IGraphBuilder::Render, or similar methods.

When the graph is running, a filter chain can switch between running and stopped. When the graph is paused, it can switch between paused and stopped. These are the only state transitions possible with filter chains.

Filter Chain Guidelines

When you use IFilterChain methods, it is important to make sure that the filters in the graph can support filter chaining operations. Otherwise, you might cause deadlocks or graph errors. Filters connected to the chain must function correctly after the chain changes state.

The best way to use IFilterChain is with a set of filters that you have designed specifically for chaining. Use the following guidelines to ensure that your filters are safe for filter chain operations. These points refer to the following diagram:

Filter Chain (Example 2)

  • Before the filter chain's state changes, all data processing calls at the boundary of the filter chain must be completed. This rule applies to the methods IMemInputPin::Receive, IPin::NewSegment, and IPin::EndOfStream. Filters in the chain must return from calls to these methods made by filters outside the chain; and filters outside the chain must return from calls made by filters within the chain.

    For example, in the previous diagram, filter B must complete any data processing calls from filter A, and filter E must finish any calls from filter D. If the pins expose the IPinFlowControl and IPinConnection interfaces, you can push the data through the graph by calling the IPinFlowControl::Block and IGraphConfig::PushThroughData methods, as described in Dynamic Reconnection. Filters might also support private methods for pushing the data.

  • Upstream filters must expect the chain's state to change. For example, in the previous diagram, suppose the chain is stopped but filter A calls IMemInputPin::Receive. The call fails and the response of filter A is to stop streaming. When the application restarts the chain, it has no effect because filter A is no longer streaming data.
  • Downstream filters must also expect the chain's state to change. If not, the downstream filter might block while it waits for samples that never arrive. For example, multiplexer (MUX) filters often require data from all of their input pins. Halting the flow of data from one input pin might block the other streams from processing. This can cause the graph to deadlock.
  • Each pin connection from a filter outside the chain to a filter within the chain should have its own allocator, which is not shared by other connections. When the chain changes state or is removed from the graph, the allocator might be decommitted. If other connections were using the same allocator, they can no longer process samples.
  • Do not remove a chain unless the filters connected to the chain support dynamic disconnection. Typically, the connected filters will support the IPinConnection or IPinFlowControl interface, but might support private interfaces instead.


Plug-in Distributors

Plug-in distributors (PIDs) are a way to extend the functionality of the filter graph manager. A plug-in distributor is a COM object that the filter graph manager aggregates at run time. Applications obtain access to the PID through the filter graph manager.

When the filter graph manager is queried for an interface that it does not support, it searches the registry for a key with the following form:

HKEY_CLASSES_ROOT\Interface\IID\Distributor

IID is a string containing the interface identifier. If the registry entry exists, the value of the entry defines the class identifier (CLSID) of a PID that supports the interface. The filter graph manager aggregates the PID and returns an interface pointer, thereby acting as the outer IUnknown for the PID. When the application calls methods on the interface, it is actually calling them on the PID. However, the existence of the PID is transparent to the application.

The term distributor stems from the fact that a PID can query its outer IUnknown pointer for interfaces on the filter graph manager. By calling the IFilterGraph::EnumFilters method, the PID can enumerate the filters in the graph and distribute method calls to those filters. In this way, a PID can serve as a single control point for the application to call methods on filters.

When the filter graph manager aggregates a PID, it queries the PID for the IDistributorNotify interface. If the PID supports this interface, the filter graph manager uses it to notify the PID about changes in the graph:

  • When the filter graph switches between run, paused, and stopped states, it calls IDistributorNotify::Run, IDistributorNotify::Pause, or IDistributorNotify::Stop.
  • When a reference clock is set, the filter graph manager calls IDistributorNotify::SetSyncSource.
  • When filters are added or removed, or pin connections are changed, the filter graph manager calls IDistributorNotify::NotifyGraphChange.

To implement a custom PID, create a COM object that supports aggregation. It must support an interface that the filter graph manager does not already support. Optionally, it can support the IDistributorNotify interface.

If the PID obtains any interface pointers from the filter graph manager, it should release them immediately. Otherwise, it might create a circular reference count, which could prevent the filter graph manager from being destroyed. Holding a reference count on the filter graph manager is unnecessary in any case, because the filter graph manager controls the PID's lifetime.

Because a PID is designed specifically for aggregation by the filter graph manager, you might want to enforce this in the PID's constructor method. Check whether the outer IUnknown pointer is NULL, and if so, return the error code VFW_E_NEED_OWNER. Also, to prevent other objects from aggregating the PID, you can query the outer IUnknown pointer for the IGraphBuilder interface. Return an error code if the object does not expose IGraphBuilder.


Using DirectShow

This section contains the following topics:

  • Simulating Graph Building with GraphEdit
  • File Playback
  • Audio Capture
  • Video Capture
  • DirectShow Editing Services
  • DVD Applications
  • Windows Media Applications
  • Microsoft TV Technologies
  • Writing DirectShow Filters
  • Debugging with DirectShow
  • Programming Tips


Simulating Graph Building with GraphEdit

The Microsoft® DirectX® SDK provides a debugging utility called GraphEdit, which you can use to create and test filter graphs.

This article contains the following sections:

  • Overview of GraphEdit
  • Using GraphEdit
  • Loading a Graph From an External Process

Overview of GraphEdit

GraphEdit is a visual tool for building filter graphs. Using GraphEdit, you can experiment with a filter graph before you write any application code. You can also load a filter graph that your application creates, to verify that your application is building the correct graph. If you develop a custom filter, GraphEdit provides a quick way to test it: Simply load a graph with your custom filter and try running the graph. If you are new to DirectShow, GraphEdit is a good way to become familiar with filter graphs and the DirectShow architecture.

The following illustration shows how GraphEdit represents a simple filter graph.

Simple Filter Graph in GraphEdit

Each filter is represented as a rectangle. Smaller squares along the edges of the filters represent pins. Input pins are on the left side of the filter, and output pins are on the right side. The arrows represent the connections between pins.

With GraphEdit, you can:

  • Create and modify filter graphs using a visual, drag-and-drop interface.
  • Simulate programmatic calls to build a graph, such as IGraphBuilder::RenderFile.
  • Run, pause, stop, and seek a graph.
  • See what filters are registered on your computer, and view registry information for each filter.
  • View filter property pages.
  • View the media types of pin connections.

Using GraphEdit

When you install the DirectX SDK, GraphEdit appears in the Start menu under Microsoft DirectX 8 SDK, in the submenu DX Utilities. The executable file is GraphEdt.exe. By default, it is installed in the folder Mssdk\Bin\DXUtils. You can open GraphEdit from either of these locations.

What follows are brief descriptions of some things you can do using GraphEdit. For more detailed information about these features—and others—consult the GraphEdit application help.

Build a File Playback Graph

GraphEdit can build a filter graph for file playback. This feature is equivalent to calling the IGraphBuilder::RenderFile method in an application. From the File menu, click Render Media File. GraphEdit displays an Open File dialog box. Select a multimedia file and click Open. GraphEdit builds a filter graph to play the file you've selected.

You can also render a media file located at a URL. From the File menu, click Render URL. GraphEdit displays a dialog box in which to type the URL.

Build a Custom Filter Graph

GraphEdit can build a custom filter graph, using any of the filters registered on your system. From the Graph menu, click Insert Filters. A dialog box appears with a list of the filters on your system, organized by filter category. GraphEdit builds this list from information in the registry. The following illustration shows the dialog box.

Which filters do you want to insert?

To add a filter to the graph, select the name of the filter and click the Insert Filters button, or double-click the filter name. After you have added the filters, you can connect two filters by dragging the mouse from one filter's output pin to another filter's input pin. If the pins accept the connection, GraphEdit draws an arrow connecting them.

Connecting Two Filters

Run the Graph

Once you have built a filter graph in Graph Edit, you can run the graph to see whether it works as you expect. The Graph menu contains the menu commands Play, Pause, and Stop. These commands invoke to the IMediaControl methods Run, Pause, and Stop, respectively. The GraphEdit toolbar has buttons for these commands, as well:

Play, Pause, and Stop Buttons

Note The GraphEdit Stop command first pauses the graph and seeks to time zero (assuming the graph is seekable). For file playback, this action resets the video window to the first frame. Then GraphEdit calls IMediaControl::Stop.

If the graph is seekable, you can seek it by dragging the slider bar that appears below the toolbar. Dragging the slider bar invokes the IMediaSeeking::SetPositions method.

View Property Pages

Some filters support custom property pages, which provide a user interface for setting properties on the filter. To view a filter's property page in GraphEdit, right-click the filter and select Properties from the pop-up window. GraphEdit displays a property page that contains the property sheets defined by the filter (if any). In addition, GraphEdit includes a property sheet for each pin on the filter. The pin property sheets are defined by GraphEdit, not by the filter. If the pin is connected, the pin property sheet displays the media type for the connection. Otherwise, it lists the pin's preferred media types.

Loading a Graph From an External Process

GraphEdit can load a filter graph created by an external process. With this feature, you can see exactly what filter graph your application builds, with only a minimal amount of additional code in your application.

The application must register the filter graph instance in the Running Object Table (ROT). The ROT is a globally accessible look-up table that keeps track of running objects. Objects are registered in the ROT by moniker. To connect to the graph, GraphEdit searches the ROT for monikers whose display name matches a particular format:

!FilterGraph X pid Y

X and Y are hexadecimal numbers, representing the address of the filter graph and the process id, respectively.

When your application first creates the filter graph, call the following function:

HRESULT AddToRot(IUnknown *pUnkGraph, DWORD *pdwRegister)
{
    IMoniker * pMoniker;
    IRunningObjectTable *pROT;
    if (FAILED(GetRunningObjectTable(0, &pROT))) {
        return E_FAIL;
    }
    WCHAR wsz[256];
    wsprintfW(wsz, L"FilterGraph %08p pid %08x", (DWORD_PTR)pUnkGraph, GetCurrentProcessId());
    HRESULT hr = CreateItemMoniker(L"!", wsz, &pMoniker);
    if (SUCCEEDED(hr)) {
        hr = pROT->Register(0, pUnkGraph, pMoniker, pdwRegister);
        pMoniker->Release();
    }
    pROT->Release();
    return hr;
}

This function creates a moniker and a new ROT entry for the filter graph. The first parameter is a pointer to the filter graph. The second parameter receives a value that identifies the new ROT entry. Before the application releases the filter graph, call the following function to remove the ROT entry. The pdwRegister parameter is the identifier returned by the AddToRot function.

void RemoveFromRot(DWORD pdwRegister)
{
IRunningObjectTable *pROT;
    if (SUCCEEDED(GetRunningObjectTable(0, &pROT))) {
        pROT->Revoke(pdwRegister);
        pROT->Release();
    }
}

The following code example shows how to call these functions. In this example, the code that adds and removes ROT entries is conditionally compiled, so that it is included only in debug builds.

IGraphBuilder *pGraph;
DWORD dwRegister;

// Create the filter graph manager.
CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
                        IID_IGraphBuilder, (void **)&pGraph);
#ifdef DEBUG
hr = AddToRot(pGraph, &dwRegister);
#endif

// Rest of the application (not shown).

#ifdef DEBUG
RemoveFromRot(dwRegister);
#endif
pGraph->Release();

To view the filter graph in GraphEdit, run your application and GraphEdit at the same time. In the GraphEdit File menu, click Connect. In the Connect To Graph dialog box, select the process id (pid) of your application and click OK. GraphEdit loads the filter graph and displays it. Don't use any other GraphEdit features on this graph—it might cause unexpected results. For example, don't add or remove filters, or stop and start the graph. Close GraphEdit before exiting your application.

Note Your application might hit various asserts when it exits.

The following illustration shows the Connect To Graph dialog box.

Connect To Graph


File Playback

The basic steps involved in file playback are discussed in How To Play A File.

The PlayWnd sample application illustrates these basic steps and also shows how to manage the video window size and position and how to add the application's filter graph to the Running Object Table to enable GraphEdit to "spy" on the graph while it is running.


Audio Capture

Using Microsoft® DirectShow®, an application can capture audio data from devices such as microphones or tape players via the inputs on a system's sound card. Typical scenarios include:

  • Recording a voiceover narration for later dubbing over a video stream
  • Conversion of legacy analog audio content to digital format
  • Capture of voice or music for transmission over a network
End users have several options for capturing audio from the sound card to the hard drive. Most cards provide applications for mixing and recording from their audio inputs. The Microsoft® Windows® operating system provides Sound Recorder, a simple utility application for recording from a microphone. Microsoft® Windows Media™ Tools includes the Windows Media Encoder stand-alone application that can perform these tasks. The Windows Media Encoder can also be incorporated into a DirectShow application as a Microsoft® DirectX® Media Object (DMO). This section describes how to integrate audio capture functionality within your own application using DirectShow.

The Audio Capture Filter

Audio capture from the analog inputs on sound cards is enabled through the Audio Capture filter. This filter uses the Microsoft® Platform SDK waveInXXX APIs (waveInOpen, waveInStart, waveInGetID, etc.) to enable any device whose driver supports these APIs to participate in a DirectShow filter graph. The Audio Capture filter exposes all inputs on the card, such as the microphone and line-in input. You can also capture from the CD-Audio input, but this audio stream has already gone through the digital-to-analog converter, so there will be a loss of sound quality from the original CD. For direct digital capture from the CD, see the Windows Media 7 SDK.

The number, type, characteristics and name of each input pin are dependent on the sound card and its driver. To fully understand and exploit the capabilities of a particular sound card, you will need the documentation from the card's manufacturer.

The Audio Capture filter represents the inputs on the card as regular DirectShow input pins. These pins represent what the driver exposes as input mixer lines. No data streams through these pins; they simply provide a means to enable and set the levels for each line. The type of control available on each line is driver-dependent; for example, a pin can only be used to control the bass and treble on an input line if the driver supports it.

To view the Audio Capture Filter in the GraphEdit utility program, do the following:

  • From the Graph menu, choose Insert Filters.
  • Expand the Audio Capture Sources category.
  • Select a filter.
  • Click Insert Filters.

Each card on the system is represented by a separate instance of the filter. The pins you see on your filter may be different or have different names, depending on the sound card driver on your system. Each of these pins supports the IAMAudioInputMixer interface, which enables an application to select the input or inputs it is interested in by using the IAMAudioInputMixer::put_Enable method.

In addition to enabling or disabling each individual input, an application can also set the individual bass, treble and volume levels. If multiple inputs are being captured simultaneously, the overall mixing, bass, treble and volume levels can be controlled through the IAMAudioInputMixer interface that is implemented on the filter itself. The filter also implements IAMBufferNegotiation, which is useful for controlling latency in audio preview. The Audio Capture filter defaults to a half-second buffer size, which is optimal for capturing, but will cause a half-second delay in the rendering of the stream if you are previewing the live audio as you capture it. To reduce this latency period, use the IAMBufferNegotiation::SuggestAllocatorProperties method to specify a smaller size for the cbBuffer member of the ALLOCATOR_PROPERTIES structure. An 80 millisecond buffer is generally safe, but buffers of 30 or 40 milliseconds may also be sufficient. If the buffers are too small, the sound quality will be degraded.

The available sampling rates and audio formats for capture are determined by the driver. Use the IAMStreamConfig interface on the Audio Capture Filter's output pin to enumerate the available sampling rates and formats. The filter can connect downstream to any filter that accepts the output pin's media type. The audio data can then be rendered through the speakers, transformed with custom transform filters, compressed and/or written to a file.

Audio Capture Filter Graphs

The following are some possible filter graphs for various audio capture solutions:

  • Audio Capture > AVI Mux > File Writer (To create an audio-only AVI file.)
  • Audio Capture > WavDest > File Writer (To create a WAV file.)
  • Audio Capture > ASF Writer (To create a Windows Media Audio file.)

Note The WavDest filter is provided as a sample that you must build and register yourself.

Creating an Audio Capture Filter Graph

Creating an audio capture filter graph involves three basic tasks:

  1. Building the graph
  2. Enumerating the audio capture sources
  3. Enabling the user to select an input line

Building the Graph

The technique for building an audio capture graph that writes to a file depends on the format of the file you wish to create. If you will be saving to AVI format, use the Capture Graph Builder to build the graph. This is the simplest audio capture scenario. The resulting file will have one audio stream and no video stream. If you are saving to ASF format, you can also use the Capture Graph Builder, but you must first install the Windows Media SDK and obtain a software key to unlock it. See How to Write a Capture Application for more information on using the Capture Graph Builder. Much of the information in that article applies equally to audio-only graphs.

If you are writing to a WAV file, you cannot use the Capture Graph Builder because it does not know about the WaveDest filter. DirectShow supplies this filter only as a sample that you must compile and register. Once the WaveDest is registered on the local system, you must build the graph manually by adding the Audio Capture filter, the WavDest filter and the File Writer filter to the graph using the IFilterGraph::AddFilter method and then using IFilterGraph::ConnectDirect to connect the pins.

Enumerating the audio capture sources

After you have created an instance of the Filter Graph Manager and/or Capture Graph Builder, use the System Device Enumerator to retrieve a list of all the available audio capture devices on the system. See the article on Enumerating Devices and Filters for details on how to do this. The first device in the returned list is the one that the user has selected as the preferred sound recording device. (To select the preferred device, click Sounds and Multimedia in Control Panel.) The device enumeration tutorial also shows how to retrieve the friendly name string identifying the device. These strings can then be inserted into a list box to enable the user to select from among multiple devices.

Enabling the user to select an input line

After the Audio Capture filter is added to the graph, you can use the IAMAudioInputMixer interface methods to select the lines you want to enable, as well as the volume, bass and treble settings for that line (if the driver supports it). The filter also has a property page that enables the user to select from the available pins and set the various levels. For more information, see Displaying A Filter's Property Page and Audio Capture Filter. Alternatively, an application can enumerate the pins programmatically and create its own user interface. For information on enumerating pins, see Enumerating Pins.


Video Capture

This section describes how to use Microsoft® DirectShow® to write video capture applications.

  • How to Write a Capture Application
  • Digital Video (DV)
  • About WDM Video Capture
  • Improving Capture Performance
  • Advanced Capture Topics


How to Write a Capture Application

This topic describes how to write a video capture application using Microsoft® DirectShow®. It contains the following topics:

  • Overview of Capture in DirectShow
  • Building a Capture Graph
  • Setting Graph Properties
  • Controlling a Capture Graph
  • Device Removal

Overview of Capture in DirectShow

The term capture can mean writing to a file, but also includes preview or any other use of captured data. Capture is not limited to video cameras—for example, a TV tuner card is a capture device. This topic discusses audio and video capture, but keep in mind that capture data might include closed-captioned or vertical blanking interval (VBI) data.

Capture Graphs

DirectShow handles capture as it does any other task: through filter graphs. This type of graph is called a capture graph. Because of the variety of hardware devices and data formats available, there are many ways to configure a capture graph. Most capture graphs have the following features in common:

  • To capture data, the graph requires one or more capture filters. Each capture filter represents a hardware device, such as a video camera.
  • To preview data, the graph needs audio and video renderer filters.
  • For file capture, the graph needs a filter that writes the file, and possibly one or more multiplexer (mux) filters, such as the AVI Mux filter.
  • If a capture device uses a Windows Driver Model (WDM) driver, the graph may require certain filters upstream from the capture filter. These filters, called stream class driver filters, support additional functionality provided by the hardware. For example, a TV tuner card has functionality for setting the channel. The corresponding filter is the TV Tuner filter.

The following diagram shows the types of filters in a typical capture graph. Dashed lines indicate where additional filters might be required, such as decoder filters or splitter filters.

To simplify the process of building capture graphs, DirectShow provides a component called the capture graph builder. It exposes the ICaptureGraphBuilder2 interface, which has methods for building and controlling capture graphs. This topic assumes you will use the capture graph builder in your capture applications.

Capture Filters

A capture filter delivers data through one or more output pins. An output pin can be classified by what media type it delivers, and by its pin category.

The media type is represented by a major type GUID. The most common media types are shown in the following table.

Media type | Major type GUID
Audio | MEDIATYPE_Audio
Interleaved digital video (DV) | MEDIATYPE_Interleaved
MPEG Stream | MEDIATYPE_Stream
Video | MEDIATYPE_Video

The pin category describes the purpose or function of the pin, and is represented by a property set GUID. There are several pin categories; this topic discusses two of them:

  • PIN_CATEGORY_CAPTURE: The pin provides data for file capture.
  • PIN_CATEGORY_PREVIEW: The pin provides data for preview.

For a list of all the pin categories, see Pin Property Set.

You can query a pin directly for its media type and pin category. To retrieve the media type, call the IPin::EnumMediaTypes method. To retrieve the pin category, call the IKsPropertySet::Get method. Using ICaptureGraphBuilder2 methods, however, you can limit operations to a specific media type or pin category, without querying each pin.

Building a Capture Graph

To build a capture graph, perform the following steps:

  1. Create the required components.
  2. Select a capture device.
  3. Build the file-writing section.
  4. Render the streams.

Creating the Required Components

The first step in building a capture graph is to create an empty filter graph and a capture graph builder. Then call ICaptureGraphBuilder2::SetFiltergraph to associate the filter graph with the capture graph builder. The following code example shows these steps:

IGraphBuilder *pGraph = NULL;
ICaptureGraphBuilder2 *pBuilder = NULL;

// Create the filter graph.
CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC,
    IID_IGraphBuilder, (void **)&pGraph);

// Create the capture graph builder.
CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC,
    IID_ICaptureGraphBuilder2, (void **)&pBuilder);

pBuilder->SetFiltergraph(pGraph);

Selecting a Capture Device

The second step is to select a capture device, by using the system device enumerator. For more information, see Using the System Device Enumerator. The following code example enumerates the video capture devices and chooses the first device in the enumeration sequence:

// Create the system device enumerator.
ICreateDevEnum *pDevEnum = NULL;
CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
    IID_ICreateDevEnum, (void **)&pDevEnum);

// Create an enumerator for video capture devices.
IEnumMoniker *pClassEnum = NULL;
pDevEnum->CreateClassEnumerator(CLSID_VideoInputDeviceCategory, &pClassEnum, 0);

ULONG cFetched;
IMoniker *pMoniker = NULL;
IBaseFilter *pSrc = NULL;
if (pClassEnum->Next(1, &pMoniker, &cFetched) == S_OK)
{
    // Bind the first moniker to a filter object.
    pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&pSrc);
    pMoniker->Release();
}
pClassEnum->Release();
pDevEnum->Release();

It would be more typical to have the user choose a device—for example, by displaying a list box with the names of available devices. To do this, call the IMoniker::BindToStorage method to obtain a property bag for the device moniker, and call the IPropertyBag::Read method to retrieve the device's friendly name. For more information, see Using the System Device Enumerator.

Now add the capture filter to the graph:

// pSrc is the capture filter from the previous code example.
pGraph->AddFilter(pSrc, L"Video Capture");

Note A device that captures both audio and video appears in two categories: Audio Capture Sources and Video Capture Sources. After you select a device from one category, check the media types on the filter's output pins. If the device falls into both categories, don't add a second device. This also applies to digital video (DV) cameras that produce interleaved audio/video.

Building the File-Writing Section

To perform file capture, add a file-writing section to the filter graph. (If you just want preview functionality, skip this step.) Use the ICaptureGraphBuilder2::SetOutputFileName method. This method adds the required mux and file-writing filters to the graph. It takes input parameters that specify the name and format of the output file. For the format, you can use any of the following values:

  • MEDIASUBTYPE_Avi: Writes an AVI file.
  • MEDIASUBTYPE_Asf: Writes an ASF file.
  • Class identifier (CLSID) of a multiplexer or file-writer filter.

The third option is for using third-party filters. For example, some capture devices deliver MPEG data. DirectShow does not include an MPEG writer filter, so you would need a third-party filter to write an MPEG file.

The following example sets the output file name to Example.avi and sets the format to AVI:

IBaseFilter     *ppf = NULL;
IFileSinkFilter *pSink = NULL;
pBuilder->SetOutputFileName(&MEDIASUBTYPE_Avi, L"C:\\Example.avi", &ppf, &pSink);

When the method returns, it sets the ppf parameter to the multiplexer's IBaseFilter interface, and it sets the pSink parameter to the file writer's IFileSinkFilter interface. These might be the same filter. For example, the ASF Writer filter does both file writing and multiplexing.

The following diagram shows the filters used to write an AVI file (left) and an ASF file (right).

Filters used to write AVI and ASF files

The AVI Mux filter exposes the IConfigAviMux and IConfigInterleaving interfaces, and the ASF Writer filter exposes the IConfigAsfWriter interface. You can use these interfaces to configure the output file format. For ASF files, you must also provide a software certificate. For more information, see Creating ASF Files in DirectShow.

Note It is recommended that you preallocate your capture file using the ICaptureGraphBuilder2::AllocCapFile method. Capturing to a large preallocated file can improve capture performance.

Rendering the Streams

The final step in building a capture graph is to render the streams in the graph. For file capture, the capture pin connects to the file-writing section described in the preceding section. For preview, the preview pin connects to audio and video renderers. However, if the capture filter lacks a preview pin, you must use the capture pin instead. In order to use the same pin for capture and preview, the capture pin must be connected to the Smart Tee filter. This filter splits the data into two streams, a capture stream and a preview stream.

The following diagram shows a graph that uses the Smart Tee filter.

The ICaptureGraphBuilder2::RenderStream method handles all of these tasks, including adding the Smart Tee filter if necessary. In addition, this method automatically adds any supporting filters that are needed for WDM devices. The following code example renders a video stream for file capture:

pBuilder->RenderStream(
        &PIN_CATEGORY_CAPTURE,  // Pin category
        &MEDIATYPE_Video,       // Media type
        pSrc,                   // Capture filter
        NULL,                   // Compression filter (optional)
        ppf                     // Multiplexer or renderer filter
    );

The first two parameters specify the pin category and media type. The next three parameters are pointers to the following filters:

  • The capture filter.
  • An optional compression filter, to compress the stream (not used in this example).
  • The multiplexer or renderer filter. Use the pointer that was returned in the ppf parameter of the SetOutputFileName method, as described in Building the File-Writing Section.

To render a stream for preview, use PIN_CATEGORY_PREVIEW for the pin category and NULL for the last two parameters. If the capture filter does not have a preview pin, the capture graph builder automatically uses the Smart Tee filter. The following code example renders the video preview stream:

pBuilder->RenderStream(
        &PIN_CATEGORY_PREVIEW,
        &MEDIATYPE_Video,
        pSrc,
        NULL,   // No compression filter.
        NULL    // Default renderer.
    );

Repeat these calls to RenderStream for each media type that you want to render.

Note Some DV capture filters have one pin for interleaved data (MEDIATYPE_Interleaved) and another for video-only data (MEDIATYPE_Video). Render one of them, not both. If you render the video-only pin, your capture data will not have audio.

Setting Graph Properties

Various filters and pins in the graph might expose interfaces for setting and retrieving properties. Use the ICaptureGraphBuilder2::FindInterface method to obtain pointers to these interfaces.

Depending on your application, the interfaces shown in the following table might be useful.

IAMAudioInputMixer | Sets audio input properties.
IAMDroppedFrames | Retrieves dropped-frame information.
IAMVfwCaptureDialogs | Displays dialog boxes provided for Microsoft® Video for Windows® capture drivers.
IAMVideoCompression | Sets compression parameters.

The following code example retrieves the IAMDroppedFrames interface from an interleaved audio/video pin:

IAMDroppedFrames *pDropped = NULL;
pBuilder->FindInterface(&PIN_CATEGORY_CAPTURE, &MEDIATYPE_Interleaved,
    pSrc, IID_IAMDroppedFrames, (void **)&pDropped);

However, do not call the FindInterface method to obtain the IVideoWindow interface, which contains methods for controlling the video playback window. Instead, query the filter graph for this interface. Otherwise, the filter graph will not respond correctly to events such as a change in the screen resolution. You can use IVideoWindow to make the preview window a child of your application window. For more information, see Setting the Video Window.

Note The capture graph builder might add a preview window even when you don't render a preview stream. Some hardware devices use video port extensions (VPE) for video capture, and these devices require a preview window. Therefore, it's always a good idea to query the filter graph for IVideoWindow. If it exposes the interface, make the video window a child of your application window.

Controlling a Capture Graph

The filter graph's IMediaControl interface has methods for running, stopping, and pausing the entire graph. However, if the graph has multiple streams, you might want independent control over them. For example, you might want the preview stream to run while the capture stream is stopped. Or, you might want to mute the audio during preview but enable it during file capture.

The ICaptureGraphBuilder2::ControlStream method provides a way to set the start and stop times on individual streams. Call this method before you call IMediaControl::Run. When you call Run, any streams not included in your call to ControlStream start immediately.

The following code example starts the video capture stream at 2 seconds and stops it at 5 seconds:

IMediaControl   *pControl;
REFERENCE_TIME  rtStart = 20000000,
                rtStop = 50000000;

pBuilder->ControlStream(
        &PIN_CATEGORY_CAPTURE,
        &MEDIATYPE_Video,
        pSrc,       // Source filter
        &rtStart,   // Start time
        &rtStop,    // Stop time
        0,          // Start cookie
        0           // Stop cookie
    );
pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
pControl->Run();

The first three parameters specify the stream to control, by pin category, media type, and capture filter. The last two parameters are cookies—arbitrary values defined in your application—which you can use to identify the stop and start events. For more information, see ICaptureGraphBuilder2::ControlStream.

To control several streams at once, omit the media type and source filter. The following example controls all capture streams in the graph:

pBuilder->ControlStream(&PIN_CATEGORY_CAPTURE, NULL, NULL,
    &rtStart, &rtStop, 0, 0);
pControl->Run();

Device Removal

If the user removes a Plug and Play device that the graph was using, the filter graph manager posts an EC_DEVICE_LOST event. If the device becomes available again, the filter graph manager posts another EC_DEVICE_LOST event. However, the previous state of the capture filter is no longer valid. The application must rebuild the graph to use the device. For more information, see Event Notification in DirectShow.


Digital Video

This section how to use Microsoft® DirectShow® for digital video (DV) applications. It contains the following articles:

  • Digital Video in DirectShow
  • Controlling a DV Camcorder


Digital Video in DirectShow

This section provides an overview of using digital video (DV) in Microsoft® DirectShow®. It contains the following sections:

  • DV Scenarios
  • Type-1 vs. Type-2 Files
  • DirectShow DV Filters
  • MSDV Driver

DV Scenarios

When you work with DV, the data typically follows a life cycle from the device to the computer and then back again. DirectShow provides support at each stage, as shown in the following table.

Stage | DirectShow Support | See Also
Capture video from the camera to a file. | ICaptureGraphBuilder2 | How to Write a Capture Application
Edit the file. | DirectShow Editing Services |
Play the file. | IGraphBuilder::RenderFile | How to Play a File
Transmit from file to tape. | Device control interfaces on the WDM Video Capture filter | Controlling a DV Camcorder

Type-1 vs. Type-2 Files

DV cameras produce interleaved audio-video; each frame of video also contains the audio information. If you save DV data to an AVI file, you have a choice. You can:

  • Include the native interleaved data as a single stream in the AVI file, with type ivas. This is known as a type-1 file.
  • Split the DV data into separate audio and video streams, with types auds and vids. This is known as a type-2 file.

For video capture, where maximum throughput is crucial, it is better to save the data as type-1. This is because type-2 files carry redundant data: the video stream in a type-2 file still contains the audio data, but it is hidden by labeling the stream as video. Also, it takes a certain amount of processor time to split the interleaved stream.

On the other hand, type-1 format can present problems for real-time editing. The application must extract the audio from the interleaved stream, make the edits, and interleave the data again. Also, the type-1 format is not compatible with Microsoft® Video for Windows® (VFW). DirectShow can handle both types of files.

DirectShow DV Filters

DirectShow provides the following filters for manipulating DV data:

  • DV Splitter: Splits an interleaved stream into separate audio and video streams.
  • DV Muxer: Combines audio and video streams into one interleaved stream.
  • DV Video Decoder: Decodes a DV video stream into uncompressed video.
  • DV Video Encoder: Encodes an uncompressed video stream into DV video.

These filters work in pairs, as shown in the following diagrams. The DV Splitter splits type-1 into type-2, and the DV Video Decoder converts the type-2 video to uncompressed video.

In the other direction, the DV Video Encoder converts uncompressed video to type-2 video, and the DV Muxer combines type-2 streams into a type-1 stream.

The DV Video Encoder exposes the IDVEnc interface, which contains methods for setting the encoding standard (NTSC or PAL). The DV Video Decoder exposes the IIPDVDec interface, which contains methods for setting the decoding resolution.

MSDV Driver

Microsoft® Windows® provides a WDM driver for DV camcorders, called MSDV (Msdv.sys). This driver is exposed to applications as the WDM Video Capture filter. MSDV supports a subset of the interfaces described on the filter's reference page. If a DV camcorder is available on the user's system, it appears in the video capture sources category (CLSID_VideoInputDeviceCategory) when you enumerate the system devices. It also appears as a rendering device. The friendly name is "Microsoft DV Camera and VCR." For more information, see Enumerating Devices and Filters.

MSDV has two output pins. One delivers interleaved audio-video data, and the other delivers video data with no audio. MSDV also has one input pin, which transmits data to the camcorder. MSDV will not accept simultaneous input and output connections, because a camcorder cannot capture and transmit at the same time.

Some tips on using MSDV:

  • You cannot use the IGraphBuilder::Render method to connect an output pin on MSDV. The filter graph manager tries to connect the output pin to MSDV's own input pin. MSDV rejects the connection, and the method call fails. Instead, use IGraphBuilder::Connect or ICaptureGraphBuilder2::RenderStream.
  • When MSDV is in a filter graph, it should always act as the reference clock for the graph. As of DirectX 8.0, the filter graph manager will automatically choose MSDV as the reference clock. With earlier versions, you should call the IMediaFilter::SetSyncSource method on the filter graph manager. For more information, see Time and Clocks in DirectShow.


Controlling a DV Camcorder

This article describes how to control a digital video (DV) camcorder using Microsoft® DirectShow®. It contains the following sections:

  • Overview
  • Device Information
  • Device Control
  • Transmit
  • Further Reading

For a general overview of DV in DirectShow, see Digital Video in DirectShow.

Overview

The WDM Video Capture filter exposes three interfaces for controlling a camcorder.

IAMExtDevice | The base interface for external device control.
IAMExtTransport | Controls the VCR functions.
IAMTimeCodeReader | Reads timecode from the device.

After you select a capture device and create an instance of the capture filter, query the filter for these interfaces. The following example declares a custom structure that holds the interface pointers, along with Boolean values that specify the availability of each interface:

struct _MyDevCap
{
    IAMExtDevice       *pDevice;
    IAMExtTransport    *pTransport;
    IAMTimecodeReader  *pTimecode;
    BOOL                bHasDevice;
    BOOL                bHasTransport;
    BOOL                bHasTimecode;
} MyDevCap;

HRESULT hr;
IBaseFilter *pDVCam;  // Pointer to the capture filter.

// Create an instance of the capture filter (not shown).

hr = pDVCam->QueryInterface(IID_IAMExtDevice, (void **)&MyDevCap.pDevice);
MyDevCap.bHasDevice = (SUCCEEDED(hr));

hr = pDVCam->QueryInterface(IID_IAMExtTransport, (void **)&MyDevCap.pTransport);
MyDevCap.bHasTransport = (SUCCEEDED(hr));

hr = pDVCam->QueryInterface(IID_IAMTimecodeReader, (void **)&MyDevCap.pTimecode);
MyDevCap.bHasTimecode = (SUCCEEDED(hr));

Note To use these interfaces with Msdv.sys, the DV camcorder driver, include the header file XPrtDefs.h in your project. You can obtain this file at msdn.microsoft.com/library/techart/dvsupport.htm.

Device Information

The device control interfaces enable you to query the device for its status and capabilities. This section describes a few of the more useful items you can retrieve. For more information, refer to the interface references.

Device Type

The most important piece of information about a capture device is its type—whether it has VCR functions, or is strictly a camera. To retrieve the device type, call the IAMExtDevice::GetCapability method with the value ED_DEVCAP_DEVICE_TYPE. If the method returns the value ED_DEVTYPE_VCR, the device is a VCR and has functions such as pause, stop, fast-forward, and rewind. The following code example shows how to query the device type:

if (MyDevCap.bHasDevice)
{
    LONG lDeviceType = 0;
    MyDevCap.pDevice->GetCapability(ED_DEVCAP_DEVICE_TYPE, &lDeviceType, 0);

    if (lDeviceType == ED_DEVTYPE_VCR) {
        // Device is a VCR. Enable all VCR functions.
    }
    else {
        // Device is a camera.
        // Enable record and record-pause; disable other functions.
    }
}

Note Typically, a camcorder can switch between VCR and camera functions. It returns the corresponding device type. If the camcorder goes offline, you should query it again the next time it becomes available. The filter graph manager posts an EC_DEVICE_LOST event when the device is removed. For more information, see How to Write a Capture Application.

Device Transport State

To retrieve the current state of the device, such as play, pause, or stop, call the IAMExtTransport::get_Mode method. The method retrieves a constant that indicates the device state:

Value | Device State
ED_MODE_PLAY | Play
ED_MODE_STOP | Stop
ED_MODE_FREEZE | Pause
ED_MODE_FF | Fast-forward
ED_MODE_REW | Rewind
ED_MODE_RECORD | Record
ED_MODE_RECORD_FREEZE | Record-pause

Timecode

While a DV tape is playing or is in record-pause mode, you can retrieve the SMPTE timecode or the absolute track number. To do this, call the IAMTimecodeReader::GetTimecode method. This method takes a pointer to a TIMECODE_SAMPLE structure, which describes the timecode. Before calling the method, initialize the dwFlags member of the structure. Use the value ED_DEVCAP_TIMECODE_READ to retrieve the timecode or the value ED_DEVCAP_ATN_READ to retrieve the absolute track number.

The timecode member of the TIMECODE_SAMPLE structure is a TIMECODE structure. When the method returns, the dwFrames member of the TIMECODE structure contains the timecode or track number. For timecode, the hours, minutes, seconds, and frames are packed into a DWORD as binary coded decimal (BCD) values, with the format hhmmssff. Use bitmasks to extract the individual values.

The following example retrieves the timecode and track number. The functions DisplayTimecode and DisplayTrackNum are assumed to be application-defined functions that display the information.

if (MyDevCap.bHasTimecode)
{
    TIMECODE_SAMPLE TimecodeSample;
    TimecodeSample.timecode.dwFrames = 0;
    char szBuf[32];

    TimecodeSample.dwFlags = ED_DEVCAP_TIMECODE_READ;
    if (hr = MyDevCap.pTimecode->GetTimecode(&TimecodeSample), SUCCEEDED(hr))
    {
        wsprintf(szBuf, "TIMECODE %.2x : %.2x : %.2x : %.2x",
                (TimecodeSample.timecode.dwFrames & 0xFF000000) >> 24,
                (TimecodeSample.timecode.dwFrames & 0x00FF0000) >> 16,
                (TimecodeSample.timecode.dwFrames & 0x0000FF00) >> 8,
                (TimecodeSample.timecode.dwFrames & 0x000000FF));
        DisplayTimecode(szBuf);
    }

    TimecodeSample.dwFlags = ED_DEVCAP_ATN_READ;
    if (hr = MyDevCap.pTimecode->GetTimecode(&TimecodeSample), SUCCEEDED(hr))
    {
        wsprintf(szBuf, "%d", TimecodeSample.timecode.dwFrames);
        DisplayTrackNum(szBuf);
    }
}

Device Control

To control the device, call the IAMExtTransport::put_Mode method. Specify the new state by using one of the constants listed in the previous section. For example, to stop the device, use the following:

MyDevCap.pTransport->put_Mode(ED_MODE_STOP);

Because the camcorder is a physical device, however, there might be a lag between when the command is issued and when it completes. Your application should create a secondary thread that waits for the command to finish. When the command finishes, the thread can update the user interface. Use a critical section to serialize the state change.

Some camcorders can notify the application when the state of the device changes. If the device supports this feature, the secondary thread can wait for the notification. If not, the application must poll the device at periodic intervals.

Notification

First declare a critical section variable, an event, and a thread handle. The critical section is used to synchronize the device state. The event is used to end the secondary thread when the application exits:

CRITICAL_SECTION csIssueCmd;
HANDLE           hThreadEndEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
HANDLE           hThread = 0;

After you create an instance of the capture filter, create the secondary thread:

DWORD ThreadId;
hThread = CreateThread(NULL, 0, ThreadProc, 0, 0, &ThreadId);

Within the secondary thread, make two calls to the IAMExtTransport::GetStatus method. In the first call, pass the value ED_NOTIFY_HEVENT_GET. This call retrieves a handle to an event that will be signaled when an operation completes:

HANDLE hEvent = NULL;
hr = MyDevCap.pTransport->GetStatus(ED_NOTIFY_HEVENT_GET, (long *)&hEvent);

In the second call, pass the value ED_MODE_CHANGE_NOTIFY, along with a pointer to a variable that will receive the device state:

LONG State;
hr = MyDevCap.pTransport->GetStatus(ED_MODE_CHANGE_NOTIFY, &State);

If the device supports notification, the return value from this call is E_PENDING. Now wait for the event to be signaled. When the next operation completes, the event is signaled and the value of State specifies the new device state. At this point, you can update the user interface to reflect the new state.

The following code shows the complete thread procedure. The function UpdateTransportState is assumed to be an application-defined function that updates the user interface. Note that the thread waits for two events: the notification event (hEvent) and the thread-termination event (hThreadEndEvent). Also note where the critical section is used to protect the device state variable.

DWORD WINAPI ThreadProc(void *pParam)
{
    HRESULT hr;
    HANDLE  EventHandles[2];
    HANDLE  hEvent = NULL;
    DWORD   WaitStatus;
    LONG    State;

    // Get an event, which will be signaled when the next operation completes.
    hr = MyDevCap.pTransport->GetStatus(ED_NOTIFY_HEVENT_GET, (long *) &hEvent);

    while (hThread && hEvent && hThreadEndEvent) {
        EnterCriticalSection(&csIssueCmd);
            State = 0;
            hr = MyDevCap.pTransport->GetStatus(ED_MODE_CHANGE_NOTIFY, &State);
        LeaveCriticalSection(&csIssueCmd);

        if(hr == E_PENDING) {             // Device supports notification.
            EventHandles[0] = hEvent;
            EventHandles[1] = hThreadEndEvent;
            WaitStatus = WaitForMultipleObjects(2, EventHandles, FALSE, INFINITE);
            if(WAIT_OBJECT_0 == WaitStatus) {
                UpdateTransportState(State);
            }
            else {
                break;  // End this thread.
            }
        }
        else {
            break;  // End this thread. (Device does not support notification.)
        }

    } // while

    // Cancel notification.
    hr = MyDevCap.pTransport->GetStatus(ED_NOTIFY_HEVENT_RELEASE, (long *) &hEvent);
    return 1;
}

Also use the critical section when you issue commands to the device, as follows:

// Issue the "stop" command.
EnterCriticalSection(&csIssueCmd);
    if(hr = MyDevCap.pTransport->put_Mode(ED_MODE_STOP), SUCCEEDED(hr))
        UpdateTransportState(ED_MODE_STOP);
LeaveCriticalSection(&csIssueCmd);

Before the application exits, end the secondary thread:

if (hThread)
{
    // Signaling this event will cause the thread to end.
    if (SetEvent(ThreadEndEvent)) {
        // Wait for it to end.
        WaitForSingleObjectEx(hThread, INFINITE, FALSE);
}
CloseHandle(hThreadEndEvent);
CloseHandle(hThread);

Polling the Device

If the device does not support notification, then calling IAMExtTransport::GetStatus with the value ED_MODE_CHANGE_NOTIFY will return a value other than E_PENDING. In that case, you must poll the device to determine its state.

You should still use a secondary thread and a critical section, as described earlier. The thread queries the device for its state at a regular interval. The following example shows one way to implement the thread:

DWORD WINAPI ThreadProc(void *pParam)
{
    HRESULT hr;
    LONG State;
    DWORD WaitStatus;

    while (hThread && hThreadEndEvent)
    {
        EnterCriticalSection(&csIssueCmd);
            State = 0;
            hr = MyDevCap.pTransport->get_Mode(&State);
        LeaveCriticalSection(&csIssueCmd);
        UpdateTransportState(State);

        // Wait for a while, or until the thread ends.
        WaitStatus = WaitForSingleObjectEx(hThreadEndEvent, 200, FALSE);
        if (WaitStatus == WAIT_OBJECT_0)
            break; // Exit thread now.
                   // Otherwise, the wait timed out. Time to poll again.
    }
    return 1;
}

Transmit

Use the device control interfaces to transmit video from the DV tape to a computer file, or from a file to the tape:

  • Tape to file: To transmit from tape to file, create a capture graph exactly as you would for capturing live video. For information on how to build a capture graph, see How to Write a Capture Application. Run the filter graph, and then play the tape. To stop transmitting, stop the tape and the filter graph.
  • File to tape: To transmit from file to tape, connect the Async File Source filter to the device filter. Put the device into record-pause mode and then pause the filter graph. While the filter graph is paused, it sends a continuous stream that repeats the first frame of video. To start transmitting, put the device into record mode and then run the filter graph. It takes the device a certain amount of time until the recording head is able to record, so wait for about two seconds before running the graph. This might result in a few duplicated frames at the beginning of the tape, but it ensures that no data is lost.

The following diagram shows the filter graph for transmitting from file to tape.

Further Reading

Digital Video Camcorder Support in Windows 98 and Windows 2000 (www.microsoft.com/hwdev/vidcap/DVCam.htm) is a white paper that discusses DV camcorder control.


About WDM Video Capture

This article provides an overview of video capture using the Microsoft® Windows® Driver Model (WDM) and Microsoft® DirectShow®. It describes the close association between WDM video capture and DirectShow.

This article also briefly describes the close association between the Stream class and WDM Connection and Streaming Architecture (CSA) and video capture minidrivers (which are clients of the Stream class driver). However, you should have a basic understanding of these topics before reading this article. For background information, see http://www.microsoft.com/hwdev/desinit/.

This article contains the following sections.

  • A Brief History of Windows Video Capture
  • WDM Overview
  • WDM Video Capture Architecture
  • Filter Graph Configuration
  • WDM Capture Interfaces and Filters

A Brief History of Windows Video Capture

Microsoft released Video for Windows 1.x in November 1992 for Windows 3.1 and optimized it for capturing movies to disk. Since then, video capture rates have risen dramatically due to use of the PCI bus, bus mastering controllers, NT striped sets, Fast/Wide SCSI, and direct transfer of captured video from adapter memory to disk without data copies. Despite capture rates that now exceed 20 MB per second, and a large number of clients for Video for Windows, deficiencies in the Video for Windows architecture exposed by the emergence of video conferencing required development of a new video capture technology.

The Video for Windows architecture lacks features important to video conferencing, television viewing, capture of video fields, and additional data streams such as vertical blanking interval (VBI). Vendors have extended Video for Windows by implementing proprietary extensions, which are product specific, to circumvent these limitations. However, without standardized interfaces, applications that use these features must include hardware-dependent code. The tight coupling between Video for Windows capture drivers and display drivers means that changes made to capture drivers require changes to display drivers as well.

In addition, the Video for Windows interface, AVICap, doesn't work well with DirectShow because AVICap allocates buffers. If DirectShow is accessed through AVICap, the buffers must be copied at the transition point, which is very inefficient. With the integration of DVD, MPEG decoders, video decoders and tuners, video port extensions (VPE), and audio codecs on single adapters, a unified driver model that supports all of these devices and handles resource contention is needed.

WDM Overview

WDM video capture was designed to resolve the problems inherent in the Video for Windows architecture. The main advantages of WDM video capture are:

  • 32 bit drivers.
  • Synergy between DirectShow and CSA.
  • Single class driver architecture for hardware (such as video ports and chip sets) that is shared between video capture devices and DVD/MPEG devices.
  • Television tuner, input selection, and support for fields, VBI, and video port extensions (VPE).
  • One driver works on Windows 98, Windows NT® 4.x, and Windows 2000 platforms.

Because of the large installed base of Video for Windows applications, Video for Windows drivers will continue to be used for devices that are primarily used for capturing movies. Version 1.1e of Video for Windows currently ships in Windows 98 to provide operating system support for these devices. However, the WDM video capture architecture provides optimal support for capture devices used primarily for TV viewing and video conferencing.

DirectShow supplies backward compatibility for Video for Windows applications without the shortcomings of Video for Windows. WDM video capture aims to provide additional support for the following: USB conferencing cameras, 1394 DV devices, desktop cameras, TV viewing, multiple video streams support and VPE capture support. This support is provided through kernel-based streaming.

WDM-based streaming extends the nonkernel streaming of DirectShow by providing a kernel connection. Streaming services are processed by the WDM Stream Class Driver and other cross-process system software components. The WDM Stream Class Driver is also responsible for calling a minidriver, which is a hardware-specific dynamic-link library (DLL) provided by IHVs to support device-specific controls. The minidriver and the Microsoft-provided WDM Stream Class Driver work together to provide low-level services for the lowest latency streaming, and DirectShow provides the higher-level features specific for your application. Because the Stream class supports a uniform streaming model for standard and custom data types, and supports data transfer between kernel drivers without requiring a transition to user mode, it is a highly efficient mode to use.

Previously, DirectShow filters transmitted data to and from the kernel whenever necessary to achieve things like decompression or rendering. Unfortunately, each of these transitions of the data stream from user mode to kernel mode was time-consuming because of the transition itself, and because of parameter validation, security validation, and possibly data copying, that must occur.

Through kernel streaming, a stream makes fewer transitions between user and the kernel mode. It can be either partially or entirely produced and consumed in kernel mode. When streams are processed in kernel mode, the DirectShow filters merely expose control mechanisms to direct the streams. This greatly reduces the overhead associated with numerous transitions between modes.

Kernel streams can pass data to the filter graph at appropriate points, depending on the application. The following diagram illustrates the transition to user mode.

During video capture, the Stream class passes uncompressed video data back to the video capture filter for writing or rendering. Also, because kernel streaming supports multiple streams, other types of data contained in the stream, such as timecode or closed captioning, could be passed up simultaneously.

WDM Video Capture Architecture

The following diagram shows the three basic components of the WDM capture architecture.

WDM capture architecture

Because the WDM capture architecture was designed to integrate smoothly with DirectShow, it is straightforward to build capture graphs in DirectShow by using WDM capture filters that send control messages from DirectShow into the streaming class. The Ksproxy.ax, Kstune.ax, and Ksxbar.ax filters, which shipped in the Windows 98 Device Driver Kit (DDK), enable WDM streaming data, such as data from Universal Serial Bus (USB) conferencing cameras, 1394 DV devices, TV viewing, and desktop cameras, to be easily controlled and sent by the Stream class to the DirectShow capture graph. The following diagram demonstrates how these components are integrated into the basic architecture.

Components of WDM capture architecture

In this diagram, the Ksproxy.ax, Kstune.ax, Ksxbar.ax, and other DirectShow filters communicate directly with the Stream class. The Microsoft WDM Stream class, through its participation in CSA, transports high-bandwidth, time-stamped, latency-sensitive data streams between kernel mode components or between kernel mode drivers and user-mode components. Through CSA, the Stream class works well with DirectShow in that it shares media types, has similar streaming states (Stop, Pause, and Run), and shares the same concept of pins and connections. This provides an easy transition of data from the Stream class to the filters in the filter graph.

The Ksproxy.ax, Kstune.ax, and Ksxbar.ax filters also have supporting minidrivers (or one minidriver that supports all three). Video capture minidrivers are clients of the Stream class and control hardware devices that produce streams of video images and related data. These minidrivers provide the following functionality:

  • Capture of compressed and uncompressed video streams, vertical blanking interval data, timecode, and ancillary data streams.
  • Control of devices associated with video streams such as TV tuners, video routing devices, TV audio control, and video compressors.
  • Compatibility with WDM-CSA.

Stream class video capture drivers can support multiple, simultaneous streams of compressed and uncompressed video, timecode, closed caption, raw and decoded VBI data, as well as custom data formats. For each data type that can be produced simultaneously with other data types, the driver should create a new stream. The Stream class exposes each stream as a separate WDM-CSA pin. Each stream can be connected to another WDM-CSA kernel filter, or it can make the transition to user mode and flow on an output pin of a DirectShow user-mode filter. Each stream (or pin) can support a variety of different formats. For example, a single pin can provide RGB16, RGB24, YVU9, and JPEG digital video. For more information on minidrivers, see the Windows 98 DDK.

Filter Graph Configuration

The association between DirectShow filters and CSA makes DirectShow filters a powerful and relatively safe method for manipulating data from a kernel mode Stream class driver. The flexibility of DirectShow makes numerous configurations of filters possible. The following diagram shows one possible configuration of user-mode DirectShow filters for simultaneous preview and capture of video to disk.

Configuration of user-mode DirectShow filters

In this diagram, an incoming TV signal can be tuned in with the Tuner filter and routed with the Crossbar filter. The filter graph passes data in various streams to the video or audio capture filters to be saved on disk. This includes audio streams, video streams, and any other ancillary data in various streams such as SMPTE timecode or closed captioning data.

WDM Capture Interfaces and Filters

The WDM capture interfaces exposed by the kernel streaming filters are IAMTVTuner, IAMCrossbar, IAMAnalogVideoDecoder, IAMVideoProcAmp, and IAMCameraControl.

Some of the Windows 98 video capture filters for WDM are Ksproxy.ax, Kstune.ax, Ksxbar.ax. See the Windows 98 DDK for more information on these filters.


Improving Capture Performance

Capturing is a hardware-intensive operation that requires saving a large amount of information to disk as quickly as possible. This information is typically in the form of video and audio data. Reducing bottlenecks that slow down the system is very important, because it can help improve the quality of the captured movie.

This article presents some general suggested practices and hints and tips that can help you, as the user of a capture application, set up the capture system for optimal capture performance.

Note Be sure to read your capture card manual for information specific to your capture card. Systems vary as well, so all the information presented in this article might not apply to your system configuration.

This article contains the following sections.

  • Calculating the Bytes of Capture Video Data
  • Optimizing the Hard Disk for Capture
  • Disk Settings in Windows 9x
  • Reducing Noncapture-Related Machine Activity
  • Additional Hints and Tips for Improving Capture Performance

Calculating the Bytes of Capture Video Data

Capturing involves transferring a large amount of data from a capture card to disk. To get an idea of the amount of data and the data throughput required for a particular capture scenario, consider the following:

Suppose you want to capture a movie with a height of 320 pixels, a width of 240 pixels, a capture rate of 30 frames per second (fps), and in 24-bit color format. The movie does not include any sound.

Use the following formula to determine the number of bytes of uncompressed data that must be transferred every second in order to capture all of the image data, and therefore to maintain the image quality.

bytes of transferred video data = height (in pixels) x width (in pixels) x rate (in fps) x color depth (in bytes)

Plugging in the numbers from the preceding scenario produces the following result.

320 x 240 x 30 x 3 = 6912000 bytes of transferred video data

Capturing one second of this movie at the desired size, frame rate, and color depth requires approximately 6.9 million bytes of disk space. Multiplying by 60 seconds produces the results for a minute; each minute of capture requires 414,720,000 bytes in this case. You can reduce the amount of data required by reducing any of the parameters in the above formula: capture a smaller image, at fewer frames per second, or with fewer colors. However, in cases where your image requirements push the system to its limits and you need to be able to capture at the highest possible number of megabytes per second, you'll want to optimize your system as much as possible. After all, the capture settings you use affect how the movie will look when someone plays it back.

The preceding numbers are for a silent movie. If you want to capture audio as well as video, you have to add the amount of required audio data. For example, CD-quality audio, recorded at 44 kilohertz (kHz), 16-bit, stereo, requires about 172 kilobytes (KB) per second. Audio capture is also very CPU-intensive, and synchronizing the audio and video data (to achieve proper lip synch, for example) can cause delays as well.

You might find that your system can't keep up with the required amount of data transfer for the settings you've chosen. When capturing, your system might pause, the video might be jerky or jitter (not smooth), and some of the frames might be dropped (not saved to disk). Playback quality of such an image is typically unsatisfactory. To avoid such problems, you can follow a number of practices to optimize your system for capturing.

The suggestions presented in this article can help you reach the goal of optimal capture performance. At the same time, bear in mind that each system is different and something that improves performance on one system might not be effective on another system.

Optimizing the Hard Disk for Capture

Because capturing is very hard-disk intensive, optimizing the files on the hard drive that you'll use for capturing (also called the data drive or data disk) is the most important task in optimizing capture performance. The following list contains goals in optimizing the data drive and techniques you might use to achieve those goals. The techniques discussed here are suggestions and might not be helpful given particular capture requirements. Your requirements and resources govern precisely which techniques you might want to try.

  • Ensure the capture file is in a contiguous (nonfragmented) location on the data drive.

    The heads of a hard drive can read from and write to a contiguous file more efficiently than if they have to seek to other, nonadjacent portions of the disk. Use a tool such as the Microsoft® Windows® Disk Defragmenter (Defrag.exe) to defragment your data disk. Defragment both the data drive and the operating system drive. The operating system drive comes into play when using drivers (such as audio and video drivers), writing to the system cache, writing to the registry, using overlays, and so forth. Run the Windows 9x Scandisk tool to ensure the integrity of the data drive and the operating system drive.

  • Preallocate a capture file that is larger than any movie clips you expect to save.

    Allocating file space is time-consuming, so you should allocate your file before you capture. If you capture more data than will fit in the capture file, the system has to allocate more space for the file as you capture, which, again, slows down capture. Avoid the reallocation of file space during capture, and the speed penalty, by allocating a file that is large enough to meet your needs. Saving the captured data can require as much space as the original capture file, so ensure you have enough free hard disk space to save your captured data to another file. Be sure to regularly defragment your capture file as well.

  • Devote an entire hard disk, or partition on the disk, for the capture file.

    This technique is particularly useful under Microsoft® Windows NT® 4.x and Windows 2000, because they do not include a Scandisk or Disk Defragmenter tool. Reserving an entire disk or partition on the disk for the capture file can make it easier to keep the capture file space clean and contiguous. You can format such a disk or partition, and then preallocate file space again, or defragment it without having to worry about other files on the disk or partition. When you format a dedicated capture drive, use the full format to initialize the disk rather than a quick format that leaves old data on the disk.

    Save your captured images to a directory that is not on your data drive or data partition to help keep your data drive clean. If you can't devote an entire drive to capture, allocate space for the capture file, defragment the file, and (in Windows 9x) run the Windows 9x Scandisk tool.

  • Place the capture file at the beginning (outer rim) of the data drive.

    If you allocate the capture file as the only file on the disk, or as the only file in the first partition on the disk, it will begin at the outer rim of the disk. Access to the outer portion of a hard disk is faster than access to the inner portion of the disk. If you don't have a hard drive to devote to capture, you can use disk utilities to move your capture file to the beginning of the disk.

Revisit these goals as necessary before each capture session to ensure your disk is configured for optimal performance. Defragment the data disk before each capture session and defragment the drive containing your saved images before you play back the saved files.

Disk Settings in Windows 9x

The System applet of the Windows 9x Control Panel contains several options you can disable for optimal capture performance. In high-bandwidth situations such as capture, it's important to make sure the drive is writing as much data as possible and not spending time with software optimizations or checking for system changes. The options to disable include the following:

  • Automatic detection that a CD-ROM disc has been inserted in the CD-ROM drive
  • Read-ahead optimization for the hard disk
  • Write-behind caching for all drives

To access these options in Windows 9x, click the Start menu. Under Settings, click Control Panel, and double-click the System applet. Select the appropriate tab and proceed as shown in the following list.

  • Device Manager tab: Click CD-ROM and click your CD-ROM drive. Click the Properties button, select the Settings tab and clear the Auto insert notification check box.
  • Performance tab: Click the File System button and drag the Read-ahead optimization slider to None. (The default is Full.) While still on the File System Properties dialog, select the Troubleshooting tab and check Disable write-behind caching for all drives.

You will have to restart your machine for the new settings to take effect.

Note For optimal performance for other applications, be sure to return these settings to their original values after your capture session is complete.

Reducing Noncapture-Related Machine Activity

Anything that interrupts the system or consumes CPU time for purposes other than capture can potentially decrease capture performance. Consider performing the following tasks to see if they affect performance on your system.

  • Close all applications except the capture application.
  • Turn off the clock that Windows 9x displays on the taskbar. To do so, right-click the taskbar, click Properties and clear the Show Clock check box on the Taskbar Options tab.
  • Turn off the screen saver. To do so, right-click the desktop, click Properties, select the Screen Saver tab, and choose "(None)" from the screen saver drop-down combo box.
  • Turn off your printer.
  • Disable your network card if you have one. Sending and receiving data over the network can interrupt the system, even if you aren't actively doing anything over the network.

Additional Hints and Tips for Improving Capture Performance

This section contains a collection of hints and tips for improving capture performance that you might want to try after experimenting with the other suggestions in this article. The suggestions are grouped according to hardware and software-related suggestions.

Software

  • Consider capturing on Windows 2000 or Windows NT 4.x, because the NT-based file system (NTFS) is typically faster than the traditional FAT file system, due to its use of threads. You might need to contact the manufacturer of your capture card for a driver that will work on Windows NT. Use a dedicated NTFS drive rather than a drive that is part NTFS and part FAT. The FAT-32 file system is typically faster than the FAT file system.
  • Using your capture software, experiment with different compression ratios (for example 2:1 or 1:1) to decrease the amount of data that has to be saved. Start with the default compression ratio and increase it until you drop frames. Try three passes and take the best results of the three. After you've saved the captured image to another drive, run Scandisk on the standard setting to quickly defragment the drive.
  • If you installed Windows 9x over your Windows 3.1 installation, put the line "verify=off" in your Autoexec.bat file. This line will prevent DOS from re-reading data after a write operation to make sure the correct data was written. Verification slows down the writing operation.

Hardware

  • Insert the capture card in PCI slot zero so it will be checked for activity before other cards on the system.
  • Make sure the hard drive cache is turned on for the data drive. Refer to your SCSI card manual for more information.
  • Heat buildup inside a system can wear down the system components and decrease capture performance. If you will be capturing continuously for hours at a time, make sure your system has three fans: one each for the power supply, CPU, and components (cards). If your captured images look fine at first, but become jittery after the system has been capturing for a while, the capture card might be overheating.
  • Some capture cards include a built-in audio card. Whether you use the on-board audio card or a separate audio card depends on your needs. You might find that a separate audio card provides features you need, or the on-board audio card might suit you just as well.
  • Some capture cards have an external connection for a monitor so you don't have to go through software to preview what you're capturing. That feature can help with performance, because the system isn't busy with the preview window.


Advanced Capture Topics

This article describes some advanced aspects of using Microsoft® DirectShow® in a capture application, although most capture applications do not require the information given here. Before reading this article, read How to Write a Capture Application.

Most capture applications can use the ICaptureGraphBuilder2 interface to build a capture graph. This interface correctly handles the majority of capture scenarios. However, if your application requires an unusually complicated graph, you might need to build the graph by hand, one filter at a time. If so, you must understand the details that ICaptureGraphBuilder2 would otherwise handle for you. Even if you construct your graph by hand, you might find some of the ICaptureGraphBuilder2 methods helpful, such as FindInterface and FindPin.

This article contains the following sections:

  • Repaint Events
  • Pin Categories
  • Using the Smart Tee Filter
  • Video Port Pins
  • Closed Captioning
  • VideoInfo2 Format Type
  • WDM Stream-Class Driver Filters

Repaint Events

If the user covers and uncovers the preview window, the video renderer receives a WM_PAINT message. By default, the video renderer requests a new frame so that it can repaint the window. If this occurs during file capture, it will corrupt your capture file and make it unusable. Therefore, if your capture graph writes data to a file, you must cancel the default handling for repaint events. Query the filter graph manager for the IMediaEvent interface, and call the IMediaEvent::CancelDefaultHandling method with the EC_REPAINT event code as the parameter.

For more information, see Event Notification in DirectShow.

Pin Categories

A capture filter can have multiple output pins, each with a different purpose. For example, some capture filters have separate pins for capture and preview. Others deliver closed-captioned data in addition to a primary video stream. The function of a pin is identified by a kernel-streaming property set. This article discusses the following pin categories:
Category GUID | Description
PIN_CATEGORY_CAPTURE | Capture pin
PIN_CATEGORY_PREVIEW | Preview pin
PIN_CATEGORY_VIDEOPORT | Video port (VP) pin
PIN_CATEGORY_CC | Closed-captioned pin
PIN_CATEGORY_VBI | Vertical blanking interval (VBI) pin
PIN_CATEGORY_VIDEOPORT_VBI | Video port pin for VBI

Every capture filter has at least one capture pin. It may also have a preview pin or a video port pin, but never both. Filters can have multiple capture pins and preview pins, each delivering a separate media type. Thus, a single filter might have video and audio capture pins, plus video and audio preview pins. Closed captioning and VBI are used in television and DVD.

To determine a pin's category, call the IKsPropertySet::Get method. The GUID of the property set is AMPROPSETID_Pin, and the property identifier is AMPROPERTY_PIN_CATEGORY. The following code example shows how to query the pin:

IPin *pPin; // Pointer to an output pin on a capture filter.
IKsPropertySet *pKs;
HRESULT hr;

hr = pPin->QueryInterface(IID_IKsPropertySet, (void **)&pKs);
if (SUCCEEDED(hr))
{
    GUID PinCategory;
    DWORD cbReturned;
    hr = pKs->Get(AMPROPSETID_Pin, AMPROPERTY_PIN_CATEGORY, NULL, 0,
                        &PinCategory, sizeof(GUID), &cbReturned);
    if (SUCCEEDED(hr))
    {
        // PinCategory now contains the category GUID.
    }
    pKs->Release();
}

For more information about property sets, refer to the Microsoft® Windows® Driver Development Kit (DDK) documentation.

Using the Smart Tee Filter

If a filter provides separate capture and preview pins, you can capture from one while previewing from the other. However, even if the filter lacks a preview pin, you can do the same thing using the Smart Tee filter. This filter splits data from a capture pin into two identical streams, one for capture and one for preview.

The following illustration shows a graph with a Smart Tee filter.

Using the Smart Tee Filter

To compensate for previewing and capturing from one pin, the Smart Tee filter performs two optimizations:

  • It delivers preview data only when doing so does not hurt capture performance.
  • It removes the time stamps from the preview stream.

The second feature requires some explanation: Live data always arrives slightly late at the renderer filter, because of latency in the graph. If preview data is time-stamped, the renderer might drop frames in order to catch up. However, no matter how many frames it drops, every frame is still late. Removing the time stamps prevents the renderer from dropping frames unnecessarily. For more information, see Time and Clocks in DirectShow.

Note You can treat a video port pin as a kind of preview pin, so a filter with a VP pin does not need a Smart Tee filter. However, VP pins have a few special requirements. The next section describes these requirements.

Video Port Pins

A capture device with a hardware video port might use the video port extensions (VPE) in Microsoft® DirectX®. If so, the capture filter will have a video port (VP) pin. A VP pin must connect to an Overlay Mixer filter, and the Overlay Mixer must connect to the Video Renderer filter.

No video data travels from the VP pin through the filter graph. Instead, video frames are produced in hardware and sent directly to video memory. The VP pin allows control messages to be sent to the hardware. It is very important to connect the VP pin, even if you're only interested in capture functionality, since if you leave the pin unconnected, your capture graph will not work. This is different from preview pins, which can remain unconnected. Always connect the VP pin to input pin 0 on the Overlay Mixer.

The Video Renderer filter does not receive any video data from the Overlay Mixer. It controls the video window, however, so the filter graph must include it. You can make the video window a child of your application window by querying the filter graph manager for the IVideoWindow interface. For more information, see Setting the Video Window.

The following illustration shows a capture graph with a video port pin.

Filter Graph with Video Port Pin

The following code example connects a video port pin to the Overlay Mixer. It uses the ICaptureGraphBuilder2::FindPin method to find the capture filter's video port pin and the Overlay Mixer's input pin 0. (You could use the IBaseFilter::EnumPins method instead.) For brevity, the example omits error checking.

IPin *pPinOut,  // Video port pin on capture filter.
     *pPinIn;   // Input pin on Overlay Mixer.
IBaseFilter *pOvMix = NULL;

// Find the video port pin.
pCGB->FindPin(
    pCaptureFilter,           // Pointer to capture filter.
    PINDIR_OUTPUT,            // Find an output pin.
    &PIN_CATEGORY_VIDEOPORT,  // Find a video port pin.
    NULL,                     // Any media type.
    TRUE,                     // Pin must be unconnected.
    0,                        // Retrieve first matching pin.
    &pPinOut                  // Address of pointer to pin.
);

// Create the overlay mixer.
CoCreateInstance(CLSID_OverlayMixer, NULL, CLSCTX_INPROC,
        IID_IBaseFilter, (void **)&pOvMix);

// Add it to the filter graph.
pGraph->AddFilter(pOvMix, L"Overlay Mixer");

// Retrieve input pin 0 on the overlay mixer.
pCGB->FindPin(pOvMix, PINDIR_INPUT, NULL, NULL, TRUE, 0, &pPinIn);

//Connect the two pins.
pGraph->Connect(pPinOut, pPinIn);

You can use similar code to connect the Overlay Mixer to the Video Renderer, or call IGraphBuilder::Render with the Overlay Mixer's output pin.

Closed Captioning

Closed-captioned pins come in several varieties:

  • Closed-captioned pin (PIN_CATEGORY_CC)
  • VBI pin (PIN_CATEGORY_VBI)
  • VBI video port pin (PIN_CATEGORY_VIDEOPORT_VBI)

The pin type determines the connection requirements:

Closed-Captioned Pin: For preview, connect this pin to the Line 21 Decoder filter and connect that filter to Pin 1 on the Overlay Mixer. (Pin 0 is reserved for the primary video stream.) If you call IGraphBuilder::Connect, the filter graph manager automatically adds the Line 21 Decoder. For file capture, connect to a mux filter, not the Overlay Mixer.

VBI Pin: Connect this pin to the Tee/Sink-to-Sink Converter filter (also called the VBI Infinite Tee). This filter splits the VBI data into separate streams. Connect this filter to the CC Decoder filter. For preview, connect the CC Decoder to the Overlay Mixer, as described previously. For file capture, connect it to a mux filter.

VBI Video Port Pin: Connect this pin to the VBI Surface Allocator filter (CLSID_VBISurfaces). This filter handles the Microsoft® DirectDraw® surfaces for the VBI data. If a filter has both a VBI pin and a VBI video port pin, connect both of them.

For preview, connect the capture filter's preview pin to Pin 0 on the Overlay Mixer. This applies to PIN_CATEGORY_PREVIEW pins as well as PIN_CATEGORY_VIDEOPORT pins. The Overlay Mixer overlays the closed captions onto the primary video.

The following diagram shows a preview graph with a VBI pin and a VBI video port pin.

Filter Graph with Closed Captioning

The Tee/Sink-to-Sink Converter and the CC Decoder filters are actually WDM mini-drivers, wrapped by the KSProxy filter. Therefore, you cannot create these filters by calling CoCreateInstance. Instead, use the system device enumerator to enumerate each filter's device category:

Filter | Category
Tee/Sink-to-Sink Converter | AM_KSCATEGORY_SPLITTER (WDM streaming tee/splitter)
CC Decoder | AM_KSCATEGORY_VBICODEC (WDM streaming VBI codecs)

Within the category, test each filter's friendly name until you find a matching string. Then call IMoniker::BindToObject to create an instance of the filter.

The following example code creates a Tee/Sink-to-Sink Converter filter. For brevity, it omits error checking.

IBaseFilter *pFilter = NULL; // Pointer to receive the filter instance.

// Create the system device enumerator.
ICreateDevEnum *pDevEnum;
CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
    IID_ICreateDevEnum, (void**)&pDevEnum);

// Create a class enumerator for the tee/splitter category.
IEnumMoniker *pEnum;
pDevEnum->CreateClassEnumerator(AM_KSCATEGORY_SPLITTER, &pEnum, 0);

// Enumerate devices within this category.
IMoniker *pMoniker;
ULONG cFetched;
while(pEnum->Next(1, &pMoniker, &cFetched) == S_OK)
{
    IPropertyBag *pBag;
    pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag);

    // Check the friendly name.
    VARIANT var;
    var.vt = VT_BSTR;
    pBag->Read(L"FriendlyName", &var, NULL);
    if (lstrcmpiW(var.bstrVal, L"Tee/Sink-to-Sink Converter") == 0)
    {
        // This is the right filter.
        pMoniker->BindToObject(0, 0, IID_IBaseFilter, (void**)&pFilter);
        SysFreeString(var.bstrVal);
        pBag->Release();
        pMoniker->Release();
        break;
    }
    SysFreeString(var.bstrVal);
    pBag->Release();
    pMoniker->Release();
}
pEnum->Release();
pDevEnum->Release();

VideoInfo2 Format Type

A preview pin might prefer a media type with a VIDEOINFOHEADER2 format. This format supports special features such as non-square pixels and interlaced video (field-based video, rather than frame-based video). The Overlay Mixer filter supports this format.

To take advantage of these features, do the following:

  1. Enumerate the pin's preferred media types, using the IPin::EnumMediaTypes method.
  2. Check the first media type in the enumeration sequence.
  3. If the formattype GUID is FORMAT_VideoInfo2, connect the pin to the Overlay Mixer. Then connect the Overlay Mixer to the video renderer. (See Video Port Pins.)

If you do not care about these features, you do not have to use the Overlay Mixer.

WDM Stream-Class Driver Filters

If a capture device uses a Windows Driver Model (WDM) driver, the graph might require certain filters upstream from the capture filter. These filters are called stream-class driver filters or WDM filters. They support additional functionality provided by the hardware. For example, a TV tuner card has functions for setting the channel. The corresponding filter is the TV Tuner filter, which exposes the IAMTVTuner interface. To make this functionality available to the application, you must connect the TV Tuner filter to the capture filter.

The ICaptureGraphBuilder2 interface provides the easiest way to add WDM filters to the graph. At some point while building the graph, call FindInterface or RenderStream. Either of these methods automatically locates the necessary WDM filters and connects them to the capture filter. The rest of this section describes how to add WDM filters manually. However, it is highly recommended that you call one of the ICaptureGraphBuilder2 methods instead.

The pins on a WDM filter support one or more mediums. A medium defines a method of communication, such as a bus. You must connect pins that support the same medium. Mediums are defined in DirectShow by the REGPINMEDIUM structure, which is equivalent to the KSPIN_MEDIUM structure used for kernel streaming drivers. To retrieve a pin's medium, call the IKsPin::KsQueryMediums method. This method returns a pointer to a block of memory that contains a KSMULTIPLE_ITEM structure, followed by zero or more REGPINMEDIUM structures. The clsMedium member of the REGPINMEDIUM structure specifies the class identifier (CLSID) for the medium.

The following helper function retrieves a pin's medium:

// Caller allocates pMedium.
HRESULT GetMedium(IPin *pPin, REGPINMEDIUM *pMedium)
{
    IKsPin *pKsPin = NULL;
    PKSMULTIPLE_ITEM pmi;

    HRESULT hr = pPin->QueryInterface(IID_IKsPin, (void **)&pKsPin);
    if (FAILED(hr))
        return hr;  // Pin does not support IKsPin.

    hr = pKsPin->KsQueryMediums(&pmi);
    pKsPin->Release();
    if (FAILED(hr))
        return hr;  // Pin does not support mediums.

    if (pmi->Count == 0) {
        CoTaskMemFree(pmi);
        return E_FAIL;  // Medium count is zero.
    }
    else {
        // Use pointer arithmetic to reference the medium structure.
        REGPINMEDIUM *pTemp = (REGPINMEDIUM*)(pmi + 1);
        memcpy(pMedium, pTemp, sizeof(REGPINMEDIUM));
        CoTaskMemFree(pmi);
        return S_OK;
    }
}

Do not connect a pin if the medium has a CLSID of GUID_NULL or KSMEDIUMSETID_Standard. These are default values indicating that the pin does not support mediums.

Also, do not connect a pin unless the filter requires exactly one connected instance of that pin. Otherwise, your application might try to connect various pins that shouldn't have connections, which can cause the program to stop responding. To find out the number of required instances, retrieve the KSPROPERTY_PIN_NECESSARYINSTANCES property set, as shown in the following code example. (For brevity, this example does not test any return codes or release any interfaces. Your application should do both, of course.)

// Obtain the pin factory identifier.
IKsPinFactory *pPinFactory;
hr = pPin->QueryInterface(IID_IKsPinFactory, (void **)&pPinFactory);

ULONG ulFactoryId;
hr = pPinFactory->KsPinFactory(&ulFactoryId);

// Get the "instance" property from the filter.
IKsControl *pKsControl;
hr = pFilter->QueryInterface(IID_IKsControl, (void **)&pKsControl);

KSP_PIN ksPin;
ksPin.Property.Set = KSPROPSETID_Pin;
ksPin.Property.Id = KSPROPERTY_PIN_NECESSARYINSTANCES;
ksPin.Property.Flags = KSPROPERTY_TYPE_GET;
ksPin.PinId = ulFactoryId;
ksPin.Reserved = 0;

KSPROPERTY ksProp;
ULONG ulInstances, bytes;
pKsControl->KsProperty((PKSPROPERTY)&ksPin, sizeof(ksPin),
    &ulInstances, sizeof(ULONG), &bytes);

if (hr == S_OK && bytes == sizeof(ULONG))
{
    if (ulInstances == 1)
    {
        // Filter requires one instance of this pin.
        // This pin is OK.
    }
}

The following pseudocode is an extremely brief outline, showing how to find and connect the WDM filters. It omits many details, and is only meant to show the general steps your application would need to take.

Add supporting filters:
{
    foreach input pin:
        skip if (pin is connected)

        Get pin medium
        skip if (medium is GUID_NULL or KSMEDIUMSETID_Standard)

        Query filter for KSPROPERTY_PIN_NECESSARYINSTANCES property
        skip if (necessary instances != 1)

        Match an existing pin || Find a matching filter
}

Match an existing pin:
{
    foreach filter in the graph
        foreach unconnected pin
            Get pin medium
            if (mediums match)
                connect the pins
}

Find a matching filter:
{
    Query the filter graph manager for IFilterMapper2.
    Find a filter with an output pin that matches the medium.
    Add the filter to the graph.
    Connect the pins.
    Add supporting filters. (Recursive call.)
}


DirectShow Editing Services

Microsoft® DirectShow® Editing Services (DES) is an application programming interface (API) that supports video editing. This section describes how to use DES. It contains the following topics:

  • Introduction to DirectShow Editing Services
  • Getting Started with DirectShow Editing Services
  • Using DirectShow Editing Services
  • DirectShow Editing Services Reference


Introduction to DirectShow Editing Services

Microsoft® DirectShow® Editing Services (DES) is an application programming interface (API) that greatly simplifies the tasks involved in video editing. DES is built on top of the core DirectShow architecture. It abstracts much of the complexity of DirectShow, and provides a set of interfaces designed specifically for manipulating video editing projects. As an application developer, you get the benefits of DirectShow inside a framework much better suited for creating video editing applications.

By itself, DirectShow is a powerful architecture for handling streaming media. With it, an application can play multimedia content authored in a wide variety of formats, without the developer needing to worry about file compression and other tedious details. Prior to DES, however, DirectShow lacked the flexibility needed for nonlinear editing.

For example, suppose you wanted to create a video sequence consisting of 4 seconds from source A, followed by 10 seconds from source B, and ending with 5 seconds from source C. You could accomplish that much fairly easily using only the core DirectShow API.

But what if you decided that source C should come before source B, not after; that the sequence should use 8 seconds from source A, not 4; and that the entire production needed a separate audio track playing in the background? Even minor changes such as these could be difficult to implement. But the scenario just described is a trivial editing project in DES—you can do it with a handful of method calls.

Here are some of the features that DES brings to DirectShow:

  • A timeline model that organizes video and audio tracks into nested layers, making it easy to manipulate the final production
  • The ability to preview a video project on the fly
  • Project persistence through an XML-based format
  • Support for video and audio effects, as well as transitions between video tracks (such as fades and wipes)
  • Almost 100 standard wipes, as defined by the Society of Motion Picture and Television Engineers (SMPTE)
  • Keying based on hue, luminance, RGB value, or alpha value
  • Automatic conversion of frame rates and audio sampling rates, enabling a production to use heterogeneous sources
  • Resizing or cropping of video

The quickest way to see DES in action is to run the sample application XtlTest. This utility parses DES project files (authored in XML) and renders them to the screen. You can experiment with XtlTest by manually editing sample project files and then rendering them to see the change.


Getting Started with DirectShow Editing Services

This section describes the basic concepts you need to get started with Microsoft® DirectShow® Editing Services (DES).

  • Basic Concepts in DirectShow Editing Services
  • The Timeline Model
  • Time in DirectShow Editing Services


Basic Concepts in DirectShow Editing Services

This article contains the following topics.

  • Architecture
  • DES and the DirectShow Core API
  • Structure of a Typical Application

Architecture

The following illustration shows the architecture of Microsoft® DirectShow® Editing Services (DES).

DirectShow Editing Services Architecture

  • Timeline: Represents a video production as a collection of source clips, transitions, and effects, organized into a set of nested tracks. For more information, see The Timeline Model.
  • XML Parser: Parses the timeline and generates an output file, or reads an input file and generates a timeline. DES supports an XML-based persistence format.
  • Render engine: Translates the timeline into a form that can be rendered as streaming media. By default, the render engine produces a DirectShow filter graph (see next section).
  • Media locator: Maintains a cache of locations of media elements. When an attempt to open a media element fails, DES uses the cache to locate the element, based on a history of successful opens.

DES and the DirectShow Core API

DirectShow controls streams of multimedia data through modular components called filters. A filter is a component that takes a media stream as input, does something to it, and passes the result as output. Filters can also combine multiple streams or split one stream into multiple output streams. A filter graph is a collection of filters chained together. Source filters take media data from a source file and introduce it into the filter graph. Rendering filters render the stream as video, audio, or some other type of finished output. The media stream travels from source filter to rendering filter, typically passing through other filters along the way.

A timeline in DES is an abstract description of a video editing project. It specifies the source clips used in the project, their start and stop times, the placement of any effects or transitions, and so forth. By itself, however, the timeline cannot render the video and audio that it represents. This is the function of the render engine. The render engine translates a timeline into a filter graph. The filter graph, when run, renders the project—either directly to the screen as a preview, or as output to a file. An application manipulates the timeline rather than directly manipulating the filter graph, which would be cumbersome and error prone.

Structure of a Typical Application

The following table lists the primary tasks that a typical video editing application performs, along with the DES interfaces that support each task. Later sections describe these tasks and the interfaces in more detail.

Task | Interface(s)
Construct or modify a timeline. | IAMTimeline and the other IAMTimelineXXXX interfaces
Save and load project files. | IXml2Dex
Preview a project or write it to a file. | IRenderEngine, ISmartRenderEngine

In addition to these primary tasks, an application might perform some or all of the following secondary tasks.

Task | Interface(s)
Obtain information about media files. (Number of streams; format and duration of each stream.) | IMediaDet
Set properties on transitions and effects. | IPropertySetter
Receive notification when errors occur during rendering. | IAMSetErrorLog, IAMErrorLog
Retrieve poster frames. | IMediaDet, ISampleGrabber


The Timeline Model

A timeline is an object that Microsoft® DirectShow® Editing Services (DES) uses to represent a video editing project. This article explains timelines in conceptual terms, describing the various objects that a timeline contains.

This article contains the following sections.

  • Structure of a Timeline
  • How a Timeline Is Rendered
  • Transitions
  • Compositions and Layering
  • Effects

Structure of a Timeline

A video production starts out as a collection of raw source files, such as video clips, sound files, and still images. The producer or video editor takes sections of those files—ten seconds from one clip, five seconds from another, thirty seconds from another. Then he or she arranges them in a particular sequence.

In the simplest case, the clips appear in a strictly linear order: Each clip is followed by the next. This basic arrangement forms a track. Thus, a simple production might contain just one video track and one audio track. More sophisticated productions use multiple tracks. For example, several audio tracks can be mixed together. The tracks might include audio effects, so that a track fades out while another fades in. With video, one track can transition to the next, using a fade or wipe. This is an example of compositing. Another example is a chroma key, in which the background of one track is keyed out and replaced by a different track. (An example of chroma keying is a weather forecaster placed in front of a satelite image.)

Thus, a video production contains source clips that are arranged in time (one clip followed by another) and in layers (one clip composited onto another). DES represents this organization using a tree:

  • The leaf nodes are individual streams of audio or video, taken from media files. Each node is a source.
  • A collection of sources with a uniform media type (audio or video) is a track.
  • A collection of tracks is a composition. A composition is rendered as the composite of all the tracks it contains. Using an earlier example, the weather forecaster and the satellite map would reside on two separate tracks, within the same composition. Compositions can contain other compositions, which allows for complex arrangements of tracks.
  • A top-level collection of compositions and tracks (all representing the same media type) is a group.
  • A set of one or more groups forms a timeline. The timeline is the root node in the tree.

A timeline must contain at least one group. Each group represents a single stream in the final production. A typical production includes one video group and one audio group. Compositions are optional; they exist to provide more structure if needed.

The following illustration shows the timeline structure. This illustration shows child-parent relations in the tree, but not the time sequence.

How a Timeline Is Rendered

The tree diagram shown in the previous section does not indicate how the overlapping tracks and compositions are rendered. For this purpose, it is helpful to consider the timeline as a time sequence, rather than as a node structure. The following illustration shows a simple project with two video tracks and two audio tracks. The arrow at the top represents the direction of the timeline, starting from time 0.

First, consider the video group. Track 1 has a higher priority than Track 0. Wherever Track 1 contains a video source, that source obscures anything in Track 0. Where Track 1 is empty, Track 0 "shows through." When the video is rendered, it begins with Source A. Then, it cuts to Source C, obscuring the last part of Source A and the beginning of Source B. Finally, when Source C ends, it cuts to Source B (already in progress).

The audio group behaves differently: All tracks are simply mixed together. The audio begins with Source D, switches to a mix of Source D and Source E, and finishes with Source D by itself again.

Transitions

A transition is a way to segue from one video track to another, using a visual effect such as a fade or a wipe. In the preceding example, the video cuts are instantaneous. Now consider the same video group with a transition added to it:

Timeline with Transition

The transition resides on Track 1. It represents a transition between that track and the layer above it (Track 0). At the start of the transition, the rendered output is entirely from Track 0 (source A). At the end, the output is entirely from Track 1 (source C). In between, the output transforms from Source A to Source C. In a fade transition, for example, one source progressively fades into another.

The rendered output is schematized along the bottom of the illustration. In the transition region, the video image transforms from Source A to Source C. There is still a jump cut from Source C to Source B, because the track does not contain a transition at that point.

Note that a transition has a particular direction. At the beginning of the transition, the video output is mostly from Source A. In the middle of the transition, the video is a mixture of the two sources. At the end, the output is mostly from Source B. By default, a transition goes from the track with lower priority to the one with higher priority, as shown. However, you can specify the opposite behavior. The following illustration shows an example of this situation. Track 0 fades to Track 1, and then Track 1 fades back to Track 0. Both transitions reside on Track 1.

Track with Two Transitions

Compositions and Layering

You can think of each video track as occupying its own layer. In a collection of tracks, the first track has the lowest priority (priority 0) and each subsequent track has a priority one level higher. At each layer, the source clips in that layer hide the source clips in the layers below it, unless that layer also contains a transition. Thus you can imagine DES making several passes when it renders:

First, it renders Track 0. There is nothing "under" Track 0, so empty regions are rendered as a solid black image. Transitions in this layer occur between the black image and Track 0 or vice versa. (For example, the video clip fades from black.) DES then lays Track 1 on top of Track 0, generating any transitions between the two tracks. The result is the composite of the two tracks. Next, it places Track 2 onto this composite. Transitions at this layer occur between the composite and Track 2. The process continues until the last (highest-priority) track is put down.

When several tracks are composited together, they behave like a single track (called a virtual track). In DES, the composition object encapsulates this behavior. You can insert multiple tracks into a composition, and then insert the composition into another composition (which might contain other tracks, or even other compositions). The first composition behaves as a single layer within the larger composition.

Complex results are possible with this model. For example, one video clip can wipe to a second clip, while at the same time the composite (the two clips plus the wipe) fades into a third clip.

Effects

Unlike transitions, effects apply to a single layer. Examples of video effects are blurring the video image, converting color video to monochrome, and rotating the image around an axis. Examples of audio effects are reverb and echo. You can apply an effect to an individual source, to a track, or to an entire composition.


Time in DirectShow Editing Services

To edit video, you must work with some important timing concepts. For example:

  • Each clip has a duration.
  • Clips, transitions, and effects appear at certain times in a project.
  • Video has a frame rate, expressed in frames per second (fps).

Microsoft® DirectShow® Editing Services (DES) contains numerous methods that deal with times or frame rates, and the meaning of these values depends on the context. This article describes the various time measurements used in DES. It contains the following sections.

  • Time Values
  • Frame Rates

Time Values

When a parameter expresses a time, three distinct meanings are possible:

  • Timeline time: The time relative to the beginning of the timeline. For example, a clip might start 2 seconds into the timeline, or a transition might occur 15 seconds into the timeline. The timeline determines the final rendered project, so you can also think of timeline time as "project time."
  • Media time: A point in a source file relative to the start of the file, as reached during normal playback. For example, if you have a 10-second video file, the point midway through the file occurs at 5 seconds, expressed as a media time.
  • Parent time: Time relative to an object in the timeline. For example, if an object starts at 8 seconds on the timeline and contains another object that starts at 10 seconds on the timeline, the child object starts at 2 seconds relative to the parent. Virtual tracks all start at time zero, relative to the timeline. So for any object in a virtual track, parent time equals timeline time.

Media time applies only to source objects. Each source object has a media start time and a media stop time. For example, suppose you have a 10-second video clip, and you want to use only 5 seconds from the middle of the clip, trimming the first 2 seconds and the last 3 seconds from the clip. If you want the clip to appear 20 seconds into the project (and assuming a normal playback rate) you would specify the following start and stop times.

  • Media start: 2 seconds
  • Media stop: 7 seconds
  • Timeline start: 20 seconds
  • Timeline stop: 25 seconds

Inserting a Source Clip on a Timeline

Frame Rates

Frame rate is the "speed" of a media stream, measured in frames per second. As with time values, the meaning of a frame rate depends on the context:

  • Output frame rate: The frame rate of the final rendered project, defined by the group. When you render the project, each group becomes a separate media stream with its own frame rate.
  • Source frame rate: The frame rate in which the source file was originally authored. The authored frame rate does not have to match the group's output frame rate. DES automatically upsamples or downsamples the file as needed. For most media formats, DES can determine the frame rate by examining the format. DIB sequences are an exception; you must specify the frame rate of a DIB sequence. (For more information, see Working with Sources.)
  • Playback rate: The apparent speed of a source clip when it appears in the project. For example, 10 seconds' of video can be fit into 5 seconds on the timeline. As a result, the speed of the clip increases by a factor of 2, as the following diagram illustrates.

    Making a Source Play Faster

    (With an audio source, the pitch would shift as well.) The following formula determines a source clip's playback rate:
    Playback rate = (Media Stop – Media Start) / (Timeline Stop – Timeline Start)

Note that each of these three rates is independent of the others:

  • You can speed up or slow down a clip by adjusting the media times; this does not affect the frame rate of the final output.
  • You can increase or decrease the output frame rate without affecting how fast a file plays.
  • Finally, within the same group you can mix source files that have different authored frame rates, and DES will upsample or downsample each clip to match the group's frame rate.

When you render a project, all times are rounded to the nearest frame boundary, as determined by the group frame rate. For example, suppose a video group has a frame rate of 30 fps. Each frame is roughly 33 milliseconds (ms). Suppose you add a 1.68-second source clip to the timeline, starting at time zero. The source does not end exactly on a frame boundary, so DES rounds the stop time to 1.6666 seconds (50 frames). If you seek to 1.68 seconds in the rendered project, you will actually seek past the end of the source, to the 51st frame.

However, DES does not overwrite the source's stop time. You might later change the group frame rate, or move the source to a new spot in the timeline where it rounds differently. Therefore, DES preserves the original stop time and rounds only when necessary. For more information, see IAMTimelineObj::FixTimes.


Using DirectShow Editing Services

This section describes in detail how to use Microsoft® DirectShow® Editing Services (DES) to develop a video editing application. It contains the following sections:

  • Overview of the Timeline Components
  • Loading and Previewing a Project
  • Constructing a Timeline
  • Working with Sources
  • Working with Effects and Transitions
  • Rendering a Project
  • Logging Errors
  • Managing Video Editing Projects
  • Alpha Blending
  • Converting Cutlists to Timelines


Overview of the Timeline Components

The timeline in Microsoft® DirectShow® Editing Services (DES) is a COM component. The objects inside the timeline are also COM components. This article provides an overview of the interfaces exposed by the various objects.

This article contains the following topics:

  • The Timeline
  • Timeline Objects
  • Subobjects

For more information about timelines, see The Timeline Model. For a list of components in DES, see DirectShow Editing Services Components.

The Timeline

The timeline exposes the IAMTimeline interface. This interface contains methods for setting properties on the timeline; for adding groups to the timeline; and for creating timeline objects, such as groups, tracks, and sources. To create a new timeline, call the standard CoCreateInstance function as follows:

IAMTimeline *pTL = NULL;
hr = CoCreateInstance(CLSID_AMTimeline, NULL, CLSCTX_INPROC_SERVER,
        IID_IAMTimeline, (void**)&pTL);

The new timeline is empty. At this point you can either load an existing project file (see Loading and Previewing a Project), or build up the timeline by creating and inserting new objects (see Constructing a Timeline).

Timeline Objects

Each type of object in the timeline—source, track, effect, and so forth—is a distinct COM object. However, an application does not create them using the CoCreateInstance function. Instead, it calls the IAMTimeline::CreateEmptyNode method. This method creates an object of the requested type, initializes it, and returns a pointer to the object. For details, see Constructing a Timeline.

Every timeline object exposes the IAMTimelineObj interface. In addition, the various object types support their own specialized interfaces:

  • Source: IAMTimelineSrc
  • Track: IAMTimelineTrack
  • Composition: IAMTimelineComp
  • Group: IAMTimelineComp, IAMTimelineGroup
  • Effect: IAMTimelineEffect
  • Transition: IAMTimelineTrans

Note that groups are a type of composition, so they support IAMTimelineComp, as well as their own IAMTimelineGroup interface.

In addition to the interfaces listed previously, timeline objects expose other, secondary interfaces. These interfaces determine the relationships between the object types.

Interface | Meaning | Exposed By
IAMTimelineVirtualTrack | The object is a virtual track. A virtual track is any object that can act like a track. Virtual tracks can reside inside compositions and hold other timeline objects. | Composition, Track
IAMTimelineEffectable | The object can have effects. | Composition, Track, Source
IAMTimelineTransable | The object can have transitions. | Composition, Track
IAMTimelineSplittable | The object can be split, using the IAMTimelineSplittable::SplitAt method. | Track, Source, Effect, Transition

Subobjects

Sources, effects, and transitions have internal pointers to other COM objects, called subobjects. The subobject performs the actual work of the object. The subobject of a source is the component that creates the video or audio data. The subobject of an effect or transition is the component that transforms the data; for example, in a video effect, it creates the visual effect in the video stream.

The type of subobject depends on the type of object:

  • Source: Any DirectShow source filter or parser filter that supports seeking and produces a format that DES supports. (It can be a compressed format if DirectShow filters exist to decode it.)
  • Effect: For video, any 2-D one-input Microsoft® DirectX® Transform object. For audio, any DirectShow audio effect filter.
  • Transition: For video, any 2-D two-input DirectX Transform object. Audio does not support transitions.

Groups, compositions, and tracks do not have subobjects.

The application does not directly set the subobject pointer. For effects and transitions, the application calls the IAMTimelineObj::SetSubObjectGUID method to specify the GUID of the subobject. For source objects, an application typically calls the IAMTimelineSrc::SetMediaName to specify the name of a source file. However, the SetSubObjectGUID method can also be used for source objects, to specify the class identifier (CLSID) of a filter.

For more information, see Working with Sources and Working with Effects and Transitions.


Loading and Previewing a Project

This article describes how to load and preview a project file with Microsoft® DirectShow® Editing Services (DES). It presents a sample application that loads an XML project file into an empty timeline and renders the timeline for preview. You can modify the sample application to work with any example XML project file that ships with this SDK.

This article contains the following topics.

  • Loading a Project File
  • Previewing the Project
  • Cleaning Up
  • Sample Code

Loading a Project File

To load a project file, you need two components: the XML parser and an empty timeline. The XML parser reads an XML project file and creates each object defined in the file. Then it inserts the objects into the timeline and sets any timeline attributes, such as the default frame rate. The following code example loads a file.

HRESULT         hr;
IAMTimeline     *pTL = NULL;
IXml2Dex        *pXML = NULL;

hr = CoCreateInstance(CLSID_AMTimeline, NULL, CLSCTX_INPROC_SERVER,
            IID_IAMTimeline, (void**)&pTL);

hr = CoCreateInstance(CLSID_Xml2Dex, NULL, CLSCTX_INPROC_SERVER,
            IID_IXml2Dex, (void**)&pXML);

hr = pXML->ReadXMLFile(pTL, L"C:\\example.xtl");
pXML->Release();

The parser exposes the IXml2Dex interface, which contains methods for loading and saving project files. The timeline exposes the IAMTimeline interface, which contains methods for manipulating the timeline and creating new timeline objects. Call the CoCreateInstance function to create each component, as shown. Remember that by creating a new instance, you are incrementing the reference count on the interface. To avoid memory leaks, always release an interface when you are through with it. In this example, the pointer to IXml2Dex is not needed for anything more, so you can release the interface. The pointer to IAMTimeline is still needed for previewing the timeline.

The IXml2Dex::ReadXMLFile method reads the specified file and populates the timeline with the objects defined in the file. The file name is specified using a BSTR value. To shorten the example, the file name in the example is given as a literal string. Normally, you obtain it from an Open File dialog or something similar.

If the ReadXML method is successful, it returns a success code. Otherwise, it returns an error code such as VFW_E_INVALID_FILE_FORMAT. Always check the return value, in order to handle error conditions gracefully. Again for brevity, the example code does not check for errors.

Previewing the Project

To preview the project, you need a component called a render engine, which builds a DirectShow filter graph from a timeline. The filter graph is what actually renders the project. You can use the render engine to preview a project or to write the final output file.

This article does not go into detail about the render engine. For preview, you only need a few method calls. You can find a more thorough discussion, including how to write output files, in Rendering a Project. The following code example shows how to construct a preview graph.

IRenderEngine *pRender = NULL;
hr = CoCreateInstance(CLSID_RenderEngine, NULL, CLSCTX_INPROC_SERVER,
            IID_IRenderEngine, (void**) &pRender);

hr = pRender->SetTimelineObject(pTL);
hr = pRender->ConnectFrontEnd( );
hr = pRender->RenderOutputPins( );

Create the render engine using the CoCreateInstance function. Then call the following methods on the render engine's IRenderEngine interface:

  • SetTimelineObject. Specifies the timeline to use.
  • ConnectFrontEnd. Builds a partial filter graph, with one output pin for each group in the timeline.
  • RenderOutputPins Completes the preview graph by connecting each output pin to a video or audio renderer.

Once the graph is built, you can preview the project by running the graph, as you would with any DirectShow filter graph. First, obtain a pointer to the filter graph by calling the IRenderEngine::GetFilterGraph method.

IGraphBuilder   *pGraph = NULL;
hr = pRender->GetFilterGraph(&pGraph);

Query the filter graph for the IMediaControl and IMediaEvent interfaces. Use these two interfaces to run the graph and wait for playback to complete. For an explanation of how to use these interfaces, see How to Play a File and Responding to Events. The following code shows one way to use these interfaces.

IMediaControl   *pControl = NULL;
IMediaEvent     *pEvent = NULL;
long evCode;

pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);
hr = pControl->Run();
hr = pEvent->WaitForCompletion(INFINITE, &evCode);
pControl->Stop();

The code in this example blocks program execution until playback completes, because of the INFINITE parameter in the IMediaEvent::WaitForCompletion method call. If something goes wrong during playback, however, it could cause the program to stop responding. In a real application, use a message loop to wait for playback to complete. It's also recommended that you provide the user with a way to interrupt playback.

Cleaning Up

When you finish using the render engine, always call the IRenderEngine::ScrapIt method. This method deletes the filter graph and releases any resources held by the render engine.

pRender->ScrapIt();

Sample Code

The following is the complete code for the sample application described in this article.

#include <dshow.h>
#include <qedit.h>

// Preview a timeline.
void PreviewTL(IAMTimeline *pTL, IRenderEngine *pRender)
{
    HRESULT hr;
    IGraphBuilder   *pGraph = NULL;
    IMediaControl   *pControl = NULL;
    IMediaEvent     *pEvent = NULL;

    // Build the graph.
    hr = pRender->SetTimelineObject(pTL);
    hr = pRender->ConnectFrontEnd( );
    hr = pRender->RenderOutputPins( );

    // Run the graph.
    hr = pRender->GetFilterGraph(&pGraph);
    pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
    pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);
    hr = pControl->Run();

    long evCode;
    hr = pEvent->WaitForCompletion(INFINITE, &evCode);
    pControl->Stop();

    // Clean up.
    pEvent->Release();
    pControl->Release();
    pGraph->Release();
}

void main( void )
{
    HRESULT         hr;
    IAMTimeline     *pTL = NULL;
    IRenderEngine   *pRender = NULL;
    IXml2Dex        *pXML = NULL;

    CoInitialize(NULL);
    hr = CoCreateInstance(CLSID_AMTimeline, NULL, CLSCTX_INPROC_SERVER,
                IID_IAMTimeline, (void**)&pTL);
    hr = CoCreateInstance(CLSID_Xml2Dex, NULL, CLSCTX_INPROC_SERVER,
                IID_IXml2Dex, (void**)&pXML);
    hr = CoCreateInstance(CLSID_RenderEngine, NULL, CLSCTX_INPROC_SERVER,
                IID_IRenderEngine, (void**)&pRender);

    // Load a project file.
    hr = pXML->ReadXMLFile(pTL, L"C:\\example.xtl");
    pXML->Release();

    PreviewTL(pTL, pRender);

    // Clean up.
    pRender->ScrapIt();
    pTL->Release();
    pRender->Release();
    CoUninitialize();
}


Constructing a Timeline

This article describes how to construct a timeline in Microsoft® DirectShow® Editing Services (DES). It presents an example console application that creates a timeline and renders it. The timeline is minimal, consisting of a single video group with one source clip, but it demonstrates most of the concepts needed to create more complex timelines.

This article contains the following topics.

  • Creating Timeline Objects
  • Creating Groups, Compositions, and Tracks
  • Setting the Group Media Type
  • Adding a Source
  • Sample Code

Creating Timeline Objects

The sample code presented in this article starts with an empty timeline, but the same steps apply if you load an existing project and want to add objects to it.

To create any type of object in the timeline, call the IAMTimeline::CreateEmptyNode method and specify the major type to create, such as composition, group, or track. For example, the following code creates a new group.

IAMTimelineObj *pGroupObj = NULL;
pTL->CreateEmptyNode(&pGroupObj, TIMELINE_MAJOR_TYPE_GROUP);

The CreateEmptyNode method creates the object and returns a pointer to the object's IAMTimelineObj interface. It also increments the reference count on the IAMTimelineObj interface, so you must release the interface when you finish using it. Do not call the CoCreateInstance function. Instead, always use CreateEmptyNode to create a timeline object, because it initializes the new object for use in a timeline.

The IAMTimelineObj interface is a generic interface. It provides methods that are common to all types of timeline object. Each type of object exposes other interfaces as well. For example, groups expose the IAMTimelineGroup interface, among others. You can obtain pointers to the other interfaces by calling QueryInterface.

After you create an object, it is not yet a part of the timeline. The method to add an object to the timeline depends on the object type. The following section describes how to add groups, compositions, and tracks to the timeline.

Creating Groups, Compositions, and Tracks

Groups, compositions, and tracks are the intermediate layers between the timeline and the source clips. They are distinguished by the type of object they can contain.

  • Tracks contain source objects.
  • Compositions contain tracks and other compositions, but not source objects.
  • Groups are top-level compositions. Groups contain compositions and tracks, but compositions cannot contain groups.
  • A virtual track is any object that can reside inside a composition or a group. This includes tracks and compositions.

The following interfaces are exposed by these objects:

Interface | Exposed By
IAMTimelineTrack | Tracks
IAMTimelineVirtualTrack | Tracks, Compositions
IAMTimelineComp | Compositions, Groups
IAMTimelineGroup | Groups

These interfaces contain the methods for adding objects to the timeline.

  • IAMTimeline::AddGroup: Inserts a group into the timeline.
  • IAMTimelineComp::VTrackInsBefore: Inserts a virtual track into a composition or group.
  • IAMTimelineTrack::SrcAdd: Inserts a source into a track.

For example, the following code inserts a new track into a group. As shown in the previous table, a group is considered a kind of composition, and a track is a kind of virtual track. Therefore, to insert the track into the group, you must query the group for its IAMTimelineComp interface and call the IAMTimelineComp::VTrackInsBefore method.

IAMTimelineGroup    *pGroup;
// Create a new group (not shown).

IAMTimelineComp     *pComp = NULL;
IAMTimelineObj      *pTrackObj = NULL;

pTL->CreateEmptyNode(&pTrackObj, TIMELINE_MAJOR_TYPE_TRACK);
pGroup->QueryInterface(IID_IAMTimelineComp, (void **)&pComp);
pComp->VTrackInsBefore(pTrackObj, 0);

The second parameter to VTrackInsBefore specifies the priority of the virtual track. Priority levels start at zero. If you specify the value –1, the virtual track is inserted at the end of the priority list. If you specify a value where there is already a virtual track, everything from that point on moves down the list by one priority level. Do not insert a virtual track at a priority greater than the number of virtual tracks, because it will cause undefined behavior.

To delete an object permanently from the timeline, call IAMTimelineObj::RemoveAll on the object. This method removes the object and all its children. To remove an object for the purpose of reinserting it elsewhere in the timeline, call IAMTimelineObj::Remove instead. Unlike RemoveAll, this method does not delete the object's children. To remove everything from the timeline, call IAMTimeline::ClearAllGroups.

Setting the Group Media Type

All groups must define an uncompressed media type, either audio or video. The uncompressed media type is the format that viewers see or hear during playback. Typically, the final output will be in a compressed format. For more information, see Rendering a Project.

To set the uncompressed format, create an AM_MEDIA_TYPE structure and fill it with the appropriate major type, subtype, and format header. For video, set the width, height, and bit depth in the format header. For audio, set the sample rate in the format header. If you set only the major type, DES provides reasonable defaults for the other values. In practice, you should set the values explicitly to control the output. The CMediaType base class provides a convenient way to manage the AM_MEDIA_TYPE structure. If you prefer, you can work directly with the AM_MEDIA_TYPE structure.

After initializing the media type structure, call the IAMTimelineGroup::SetMediaType method to set the media type for the group.

The following example specifies 16-bit RGB video, 320 pixels wide by 240 pixels high.

AM_MEDIA_TYPE mtGroup;
mtGroup.majortype = MEDIATYPE_Video;
mtGroup.subtype = MEDIASUBTYPE_RGB555;

// Set format headers.
mtGroup.pbFormat = (BYTE*)CoTaskMemAlloc(sizeof(VIDEOINFOHEADER));
VIDEOINFOHEADER *pVideoHeader = (VIDEOINFOHEADER*)mtGroup.pbFormat;
ZeroMemory(pVideoHeader, sizeof(VIDEOINFOHEADER));
pVideoHeader->bmiHeader.biBitCount = 16;
pVideoHeader->bmiHeader.biWidth = 320;
pVideoHeader->bmiHeader.biHeight = 240;
pVideoHeader->bmiHeader.biPlanes = 1;
pVideoHeader->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pVideoHeader->bmiHeader.biSizeImage = DIBSIZE(pVideoHeader->bmiHeader);

mtGroup.formattype = FORMAT_VideoInfo;
mtGroup.bFixedSizeSamples = TRUE;
mtGroup.lSampleSize = DIBSIZE(pVideoHeader->bmiHeader);

// Set the group media type.
pGroup->SetMediaType( &mtGroup );

Adding a Source

Create a source object the same way you create other timeline objects. Before inserting it into the timeline, however, you must specify at least the following properties on the source.

  • The start and stop times, relative to the timeline. Call the IAMTimelineObj::SetStartStop method.
  • The media file to use as a source. Call the IAMTimelineSrc::SetMediaName method with a wide-character string representing the name of the file.
  • The media start and stop times, which are relative to the original file. Call the IAMTimelineSrc::SetMediaTimes method. For more information about media times, see Time in DirectShow Editing Services.

In the following example, the source clip starts four seconds into the file. The media duration is 10 seconds, twice the length of the timeline duration, meaning the source will play at twice normal speed. The constant UNITS is defined as 10000000 (107) and equals one second.

pSourceObj->SetStartStop(0, 50000000)
pSource->SetMediaName(L"C:\\Example.avi");
pSource->SetMediaTimes(40000000, 140000000);

Note Currently, DES cannot simultaneously render more than 75 sources that were compressed with Video Compression Manager (VCM) codecs. Also, if the project as a whole contains more than 75 such sources, you must use dynamic reconnection or DES cannot preview the project. For more information, see IRenderEngine::SetDynamicReconnectLevel.

For more information about sources, see Working with Sources.

Sample Code

The following is the complete code for the sample application described in this article.

Note For the sake of brevity, the sample code performs no error checking. In a real application, you should check the return values of method calls to make sure none has failed.

#include <dshow.h>
#include <qedit.h>

// Preview a timeline.
void PreviewTL(IAMTimeline *pTL, IRenderEngine *pRender)
{
    IGraphBuilder   *pGraph = NULL;
    IMediaControl   *pControl = NULL;
    IMediaEvent     *pEvent = NULL;

    // Build the graph.
    pRender->SetTimelineObject(pTL);
    pRender->ConnectFrontEnd( );
    pRender->RenderOutputPins( );

    // Run the graph.
    pRender->GetFilterGraph(&pGraph);
    pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
    pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);
    pControl->Run();

    long evCode;
    pEvent->WaitForCompletion(INFINITE, &evCode);
    pControl->Stop();

    // Clean up.
    pEvent->Release();
    pControl->Release();
    pGraph->Release();
}

void main( void )
{
    // Start by making an empty timeline.

    IAMTimeline    *pTL = NULL;
    CoInitialize(NULL);
    CoCreateInstance(CLSID_AMTimeline, NULL, CLSCTX_INPROC_SERVER,
        IID_IAMTimeline, (void**)&pTL);

    // GROUP: Add a video group to the timeline.

    IAMTimelineGroup    *pGroup = NULL;
    IAMTimelineObj      *pGroupObj = NULL;
    pTL->CreateEmptyNode(&pGroupObj, TIMELINE_MAJOR_TYPE_GROUP);
    pGroupObj->QueryInterface(IID_IAMTimelineGroup, (void **)&pGroup);

    // Set the group media type.
    AM_MEDIA_TYPE mtGroup;
    ZeroMemory(&mtGroup, sizeof(AM_MEDIA_TYPE));
    mtGroup.majortype = MEDIATYPE_Video;
    pGroup->SetMediaType(&mtGroup);
    pTL->AddGroup(pGroupObj);
    pGroupObj->Release();

    // TRACK: Add a track to the group.

    IAMTimelineObj      *pTrackObj;
    IAMTimelineTrack    *pTrack;
    IAMTimelineComp     *pComp = NULL;

    pTL->CreateEmptyNode(&pTrackObj, TIMELINE_MAJOR_TYPE_TRACK);
    pGroup->QueryInterface(IID_IAMTimelineComp, (void **)&pComp);
    pComp->VTrackInsBefore(pTrackObj, 0);
    pTrackObj->QueryInterface(IID_IAMTimelineTrack, (void **)&pTrack);

    pTrackObj->Release();
    pComp->Release();
    pGroup->Release();

    // SOURCE: Add a source to the track.

    IAMTimelineSrc *pSource = NULL;
    IAMTimelineObj *pSourceObj;
    pTL->CreateEmptyNode(&pSourceObj, TIMELINE_MAJOR_TYPE_SOURCE);
    pSourceObj->QueryInterface(IID_IAMTimelineSrc, (void **)&pSource);

    // Set the times and the file name.
    pSourceObj->SetStartStop(0, 50000000);
    pSource->SetMediaName(L"C:\\Example.avi");
    pSource->SetMediaTimes(40000000, 140000000);
    pTrack->SrcAdd(pSourceObj);

    pSourceObj->Release();
    pSource->Release();
    pTrack->Release();

    // Preview the timeline.
    IRenderEngine       *pRenderEngine = NULL;
    CoCreateInstance(CLSID_RenderEngine, NULL, CLSCTX_INPROC_SERVER,
        IID_IRenderEngine, (void**) &pRenderEngine);
    PreviewTL(pTL, pRenderEngine);

    // Clean up.
    pRenderEngine->ScrapIt();
    pTL->ClearAllGroups();
    pRenderEngine->Release();
    pTL->Release();
    CoUninitialize();
}


Working with Sources

A source object represents a single media stream from a source file. Sources provide the raw material for a project. Everything else in the timeline exists either to provide structure (tracks, compositions, and groups) or to modify sources (effects and transitions).

This article describes various details relating to sources in Microsoft® DirectShow® Editing Services (DES). For information on the basic steps needed to add a source to the timeline, see Constructing a Timeline.

This article contains the following sections.

  • Setting Properties on Sources
  • Using the Media Detector
  • Using the Media Locator
  • Still Images
  • Video Color Source

Setting Properties on Sources

When you create a new source object, there are a few properties you are required to set and others you can optionally set. You must set the following properties.

  • The start and stop times, relative to the rest of the timeline. Call the IAMTimelineObj::SetStartStop method. Do not set overlapping times on source objects within the same track, or it will cause undefined behavior.
  • The media file to use as a source clip. Call the IAMTimelineSrc::SetMediaName.
  • The media start and stop times, relative to the original source file. Call the IAMTimelineSrc::SetMediaTimes method. Exception: If the source is a still image, do not specify the media times. For more information about media times, see Time in DirectShow Editing Services.

A source object inherits its media type from the parent group, so it is not necessary to specify a media type.

Optional properties include the following:

  • The stretch mode. The stretch mode specifies how Microsoft® DirectShow® Editing Services (DES) renders a source whose size does not match the output dimensions. By default, DES stretches an image without preserving the aspect ratio. Alternatively, DES can crop an image or create a letterbox. Call the IAMTimelineSrc::SetStretchMode method to specify the stretch mode.
  • The duration of the source file. If you set this property before setting the media times, DES validates the media stop time and truncates the stop time if it exceeds the file duration. This can help avoid rendering errors later. You can obtain the duration of the file using the media detector, as described in Using the Media Detector. Call the IAMTimelineSrc::SetMediaLength method to specify the file duration.
  • The stream number. By default, a source object uses the first stream in the file that matches the media type of the parent group. If a file contains two or more streams of the same media type, select which stream to use by calling IAMTimelineSrc::SetStreamNumber. You can use the media detector to find the number of streams.

Using the Media Detector

The media detector is a helper object that can retrieve information about a file, such as the number of streams, their type, and their duration. It also contains methods for retrieving poster frames from a video stream. It exposes the IMediaDet interface.

The media detector operates in one of two modes. When you create an instance of the media detector, it is not attached to a particular source file. In this mode, you can retrieve stream information from multiple source files. However, once you use the media detector to obtain a poster frame, it switches to bitmap grab mode. In bitmap grab mode, the media detector is attached to a specific video stream, and the stream information methods no longer work. Moreover, there is no way to switch the media detector back to its starting mode. Therefore, obtain any stream information you need before retrieving poster frames, or else create new instances of the media detector for each stream.

To obtain stream information, do the following:

  1. Call IMediaDet::put_Filename with the name of the source file.
  2. Call IMediaDet::get_OutputStreams to obtain the number of streams in the source.
  3. Specify a stream number with IMediaDet::put_CurrentStream. Then call one or more of the following methods:
    • IMediaDet::get_StreamType: Retrieves the stream's media type.
    • IMediaDet::get_StreamLength: Retrieves the duration of the stream.
    • IMediaDet::get_FrameRate: Retrieves a video stream's frame rate.

To obtain a poster frame, specify the stream number, as in the previous step. Then call either IMediaDet::GetBitmapBits, which copies a poster frame into a buffer, or IMediaDet::WriteBitmapBits, which saves a poster frame to a file.

Using the Media Locator

The media locator is a helper object that verifies file names and searches for missing files on local or network directories. The media detector keeps a cache of directory paths where it has successfully found files in past searches. To locate a file, it searches the directories in its cache. Failing that, the media detector can display an Open File dialog for the user to locate a file manually. Assuming the user locates the file, the media locator adds the new directory to its cache. The media locator exposes the IMediaLocator interface.

Typically, your application does not directly create an instance of the media locator. Instead, the timeline and the render engine provide the following methods for validating file names using the media detector.

  • To validate file names in the timeline, call IAMTimeline::ValidateSourceNames. Optionally, this method also updates the source objects with the correct file names.
  • To validate file names when the project is rendered, call IRenderEngine::SetSourceNameValidation.

Both methods take flags that control the behavior of the media locator. For example, you can restrict the search to local directories.

Still Images

DES supports the following file formats for still images:

  • Bitmap (.bmp)
  • GIF (Graphics Interchange Format)
  • JPEG (Joint Photographic Experts Group)
  • Targa or Truevision Graphics Adapter (.tga): Mode 2 (uncompressed RGB) in 16-bit, 24,-bit, or 32-bit format.

They can be used either as still images, or to create animations. For bitmap, JPEG, and Targa files, if you are using the file as a still image, call the IAMTimelineSrc::SetDefaultFPS method to set the frame rate to zero.

DIB Sequences

Given a series of bitmap, JPEG, or Targa files, the render engine can construct a device-independent bitmap (DIB) sequence. To create a DIB sequence, give the files numerically sequential names, such as Image001.bmp, Image002.bmp, Image003.bmp, and so on. Use the first file in the sequence as the source. Set the frame rate for the sequence by calling IAMTimelineSrc::SetDefaultFPS. The render engine cycles through the images in the sequence at the specified frame rate.

If the sequence is too short to fill the duration, given the frame rate, the rest of the duration is solid black. No error occurs during rendering.

GIF Sources

DES supports GIF sources, including animated and transparent GIFs, using the GIF89a specification. With an animated GIF, unlike the other file types, you do not need to set the frame rate. The GIF file specifies the delay between each image in the animation.

To support transparent GIFs, DES converts transparent regions in the image to the RGB triplet RGB(0,0,0). You can then use the Key Transition to key on RGB(0,0,0).

DES also converts any black regions that fall within the range RGB(0–7,0–7,0–7) to the value RGB(8,8,8)—except for the transparency index, if it falls in that range. This conversion is not detectable to the eye.

Video Color Source

The Video Color Source object creates a continuous video image of a solid color. One use for this object is to make it a layer in a transition. For example, you could use it to create a video fade-in or fade-out.


Working with Effects and Transitions

This article describes how to use effects and transitions in Microsoft® DirectShow® Editing Services (DES). It contains the following sections.

  • Adding Effect and Transition Objects
  • Previewing Effects and Transitions
  • Enumerating Effects and Transitions
  • Setting Properties on Effects and Transitions
  • Transition Direction

Adding Effect and Transition Objects

To add an effect or transition object, perform the following steps.

  1. Create the effect or transition object.

    Call the IAMTimeline::CreateEmptyNode method with a major type of TIMELINE_MAJOR_TYPE_EFFECT or TIMELINE_MAJOR_TYPE_TRANSITION. Effects expose the IAMTimelineEffect interface, and transitions expose the IAMTimelineTrans interface. For more information, see Creating Timeline Objects.

  2. Set the subobject.

    Effect and transition objects are wrappers for subobjects. The subobjects do the real work by implementing a data transform. The effect or transition object uses the subobject to transform the audio or video stream. You can use any one-input Microsoft® DirectX® Transform object as an effect, or any two-input DirectX Transform object as a transition. A DirectShow audio effect filter can serve as an effect in an audio group. DES also provides a special audio effect called the Volume Envelope, which sets the volume. Each object in a timeline can have at most one Volume Envelope effect. Other effects do not have this restriction.

    After you create an effect or transition object, call IAMTimelineObj::SetSubObjectGUID with the class identifier (CLSID) of the subobject. Enumerating Effects and Transitions describes how to enumerate the effects and transitions available on the user's system.

  3. Set the start and stop times.

    Call the IAMTimelineObj::SetStartStop method to set the start and stop times relative to the parent object.

  4. Set properties.

    Many effects and transitions support custom properties. Setting Properties on Effects and Transitions describes how to set these properties.

  5. Insert the effect or transition object into the timeline.

    Call one of the following methods on the parent object:

    • Effects: IAMTimelineEffectable::EffectInsBefore
    • Transitions: IAMTimelineTransable::TransAdd

    The parent object can have multiple effects and transitions. Effects can overlap on the same object; transitions cannot. For each object, its effects are rendered in the order of their priority, starting from priority zero. (Specify the priority level when you call EffectInsBefore.)

The following code example adds an SMPTE Wipe Transition to a track. It assumes the track is already created.

// IAMTimeline *pTL;
// IAMTimelineTrack *pTrack;

// Create the transition object.
IAMTimelineObj *pTransObj = NULL;
hr = pTL->CreateEmptyNode(&pTransObj, TIMELINE_MAJOR_TYPE_TRANSITION);

// Set the subobject.
hr = pTransObj->SetSubObjectGUID(CLSID_DxtJpeg);  // SMPTE Wipe

// Set the start and stop times.
hr = pTransObj->SetStartStop(50000000, 100000000);

// Insert the transition object into the timeline.
IAMTimelineTransable *pTransable = NULL;
hr = pTrack->QueryInterface(IID_IAMTimelineTransable, (void **)&pTransable);
hr = pTransable->TransAdd(pTransObj);
hr = pTransObj->Release();

Previewing Effects and Transitions

Some effects and transitions take a relatively long time to render. During preview this can cause the video to become choppy or out of sync with the audio. You can increase preview speed by disabling effects or transitions:

  • To disable all effects, call IAMTimeline::EnableEffects.
  • To disable all transitions, call IAMTimeline::EnableTransitions.
  • To disable a particular transition, call IAMTimelineTrans::SetCutsOnly.

When effects are disabled, they are not rendered during preview. When a transition is disabled, it is rendered as a jump cut. The segue between tracks still occurs, but the visual effect is not rendered.

If an effect or transition cannot be rendered, the render engine substitutes a default effect or transition. Call the IAMTimeline::SetDefaultEffect method to set the default effect, and the IAMTimeline::SetDefaultTransition method to set the default transition. If you do not specify a default, or if the one you specify also causes an error, DES uses its own default.

Note You can also improve preview quality by increasing the amount of frame buffering. See IAMTimelineGroup::SetOutputBuffering.

Enumerating Effects and Transitions

DirectShow provides a system device enumerator for enumerating devices. You can use it to retrieve monikers for effects or transitions installed on the user's system.

The system device enumerator exposes the ICreateDevEnum interface. It returns category enumerators for specified device categories. A category enumerator, in turn, exposes the IEnumMoniker interface and returns monikers for each device in the category. For a detailed discussion of using ICreateDevEnem, see Enumerating Devices and Filters. The following is a brief summary, specific to DirectShow Editing Services.

To enumerate effects or transitions, perform the following steps.

  1. Create an instance of the system device enumerator.
  2. Call the ICreateDevEnum::CreateClassEnumerator method to retrieve a category enumerator. Categories are defined by class identifiers (CLSIDs). Use CLSID_VideoEffects1Category for effects or CLSID_VideoEffects2Category for transitions.
  3. Call IEnumMoniker::Next to retrieve each moniker in the enumeration.
  4. For each moniker, call IMoniker::BindToStorage to retrieve its associated property bag.
  5. The property bag contains the friendly name and the globally unique identifier (GUID) for the effect or transition. An application can display a list of friendly names and then obtain the corresponding GUID.

The following code example illustrates these steps.

ICreateDevEnum *pCreateDevEnum;
IEnumMoniker *pEm;
CoCreateInstance(CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC_SERVER,
        IID_ICreateDevEnum, (void**)&pCreateDevEnum);

pCreateDevEnum->CreateClassEnumerator(
        CLSID_VideoEffects1Category,  // Effects category.
        &pEnumMoniker, 0);            // Use CLSID_VideoEffects2Category for transitions.

ULONG cFetched;
IMoniker *pMoniker;
while(S_OK == pEnumMoniker->Next(1, &pMoniker, &cFetched))
{
    HRESULT hr;
    IPropertyBag *pBag;
    hr = pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pBag);
    if(SUCCEEDED(hr))
    {
        VARIANT var;
        var.vt = VT_BSTR;
        hr = pBag->Read(L"FriendlyName", &var, NULL);
        if (SUCCEEDED(hr))
        {
            if ( ... )  // Check whether var.bstrVal is the name you want.
            {
                VARIANT var2;
                GUID guid;
                pBag->Read(L"guid", &var2, NULL);
                GuidFromString(var2.bstrVal, &guid);
                SysFreeString(var2.bstrVal);
                // GUID is now the CLSID for the effect.
                break;
            }
            SysFreeString(var.bstrVal);
        }
        pBag->Release();
    }
    pMoniker->Release();
}
pEnumMoniker->Release();
pCreateDevEnum->Release();

Setting Properties on Effects and Transitions

Many effects and transitions support properties that control their appearance. For example, the Volume Envelope effect has a property that specifies the volume level. Using the IPropertySetter interface, an application can set the value of a property across a range of times.

To set a property, perform the following steps.

  1. Create an instance of the property setter (CLSID_PropertySetter).
  2. Fill DEXTER_PARAM and DEXTER_VALUE structures with the property data. These structures are discussed below.
  3. Pass the DEXTER_PARAM and DEXTER_VALUE structures to the IPropertySetter::AddProp method.
  4. Repeat steps 2 and 3 for each property you want to set.
  5. Pass the IPropertySetter interface pointer to the IAMTimelineObj::SetPropertySetter method.

The DEXTER_PARAM structure specifies which property is being set. It contains the following members.

  • Name: Name of the property
  • dispID: Dispatch identifier (DISPID) of the property
  • nValues: Number of values

If you know the DISPID of the property, you can set the dispID member. Typically, you would set this member to zero and set the Name member to the name of the property.

The DEXTER_VALUE structure specifies the value of a property at a given time. It contains the following members.

  • v: VARIANT type that specifies a new value for the property. The vt member of this VARIANT defines the data type of the property. For more information on the VARIANT type, see the Platform SDK.
  • rt: Reference time when the property assumes this value, relative to the starting time of the effect or transition. The start time of the effect or transition is relative to the start time of its parent object.
  • dwInterp: Flag that specifies how the property changes from the previous value to the new value. With the DEXTERF_JUMP flag, the property jumps instantly to the new value at the specified time. With the DEXTERF_INTERPOLATE flag, the property is interpolated linearly from the previous value.

If you set the vt member to VT_BSTR, the property setter makes any necessary conversions. For floating-point values, include the leading zero before the decimal place. For example, 0.3, not .3.

The value of a property can change over time, so the IPropertySetter::AddProp method takes a single DEXTER_PARAM structure and a pointer to an array of DEXTER_VALUE structures. The array defines a set of time-based values for the property. The members of the array must be in ascending time order, and the nValues member of the DEXTER_PARAM structure must equal the length of the array.

The following code example creates property data for the SMPTE Wipe transition. It sets the wipe code to 120, which creates an oval wipe. It sets the reference time to zero, indicating the start of the transition.

IPropertySetter     *pProp;   // Property setter
IAMTimelineObj      *pTransObj;  // Transition object
// Create an SMPTE Wipe transition object. (Not shown)

CoCreateInstance(CLSID_PropertySetter,
    NULL, CLSCTX_INPROC_SERVER,
    IID_IPropertySetter, (void**) &pProp);

DEXTER_PARAM param;
DEXTER_VALUE *pValue = (DEXTER_VALUE *)CoTaskMemAlloc(sizeof(DEXTER_VALUE));

// Initialize the parameter.
param.Name = SysAllocString(L"MaskNum");
param.dispID = 0;
param.nValues = 1;

// Initialize the value.
pValue->v.vt = VT_BSTR;
pValue->v.bstrVal = SysAllocString(L"120"); // Oval
pValue->rt = 0;
pValue->dwInterp = DEXTERF_JUMP;

pProp->AddProp(param, pValue);

// Free allocated resources.
SysFreeString(param.Name);
VariantClear(&(pValue->v));
CoTaskMemFree(pValue);

// Set the property on the transition.
pTransObj->SetPropertySetter(pProp);
pProp->Release();

Transition Direction

A transition goes from input A to input B, and from time t0 to t1. Therefore, the direction of a transition can mean one of two things:

  • The mapping of timeline layers to inputs.
  • The progression over time.

The first is the input direction, and the second is the progress direction. You can control both directions.

  • Input direction: By default, a transition goes from the composite of the lower-priority layers to the layer that contains the transition. To reverse this direction, call the IAMTimelineTrans::SetSwapInputs method.
  • Progress direction: Most transitions support a standard Progress property, which specifies what percentage of the transition is reflected in the output at a given moment. By default, the value of the Progress property goes from 0.0 to 1.0 over the duration of the transition. To reverse the progress, set the Progress property to go from 1.0 to 0.0.

The following diagram illustrates the difference between input direction and progress direction. It shows four variations on a standard SMPTE Wipe transition.

The transition resides on track 1. By default, the wipe goes from left to right and from track 0 to track 1. Swapping inputs causes the wipe to go from track 1 to track 0, but still from left to right. Reversing the progress makes the transition go from right to left. You can combine both, as shown on the far left.

For more information about how DES renders transitions, see The Timeline Model.


Rendering a Project

This section describes how to render a video editing project in Microsoft® DirectShow® Editing Services (DES). It contains the following topics.

  • About the Render Engines
  • Previewing a Project
  • Writing a Project to a File


About the Render Engines

This article describes how Microsoft DirectShow Editing Services (DES) renders a video editing project.

In DES, a project is represented as a timeline. The timeline is useful because it simplifies the most common tasks in video editing, such as rearranging source clips and adding video effects. The DirectShow stream architecture, on the other hand, requires a filter graph. Thus, to render your project, you must translate a timeline into a filter graph. The component that does this is called a render engine. DirectShow provides two render engines:

  • Basic render engine: Builds a filter graph that delivers uncompressed output.
  • Smart render engine: Builds a filter graph that delivers compressed output.

The smart render engine uses smart recompression to improve performance. With smart recompression, source files are recompressed only when the original file format differs from the final output format. If the formats match, the source is never decompressed. Smart recompression is supported only for video compression, not for audio compression.

For preview, use the basic render engine. The smart render engine can also preview, but less efficiently because it has to decompress the compressed stream. For writing files, use the smart render engine if you want smart recompression. Otherwise, use the basic render engine. Smart recompression can greatly reduce the time it takes to write the file.

Important If your source files include ASF files, and your target file is an AVI file, do not use the smart render engine. The file might not play back correctly. Use the basic render engine, or consider writing an ASF file instead.

Constructing the Filter Graph

The filter graph is built in two stages. In the first stage, the render engine constructs a "front end," which is a partial filter graph. The following diagram illustrates a typical front end:

Filter Graph Front End

The subsystems contain various specialized filters, which the render engine assembles automatically. The front end contains one output pin for each group in the timeline. The output pins deliver uncompressed data if you use the basic render engine, or compressed data if you use the smart render engine.

In the second step, the output pins are connected to rendering filters. For preview, the rendering filters are video and audio renderers. For file writing, the rendering filters are multiplexer (mux) filters and file-writer filters.

Completing the Filter Graph

Further Reading

  • Previewing a Project
  • Writing a Project to a File


Previewing a Project

To preview a project, create an instance of the basic render engine by calling the CoCreateInstance function. The class identifier is CLSID_RenderEngine. Then call the following methods on the render engine's IRenderEngine interface:

  • SetTimelineObject. Specifies the timeline to use.
  • ConnectFrontEnd. Builds the front end of the graph.
  • RenderOutputPins. Completes the preview graph, by connecting each output pin to a video or audio renderer.

The following code example shows these steps.

IRenderEngine *pRender = NULL;
hr = CoCreateInstance(CLSID_RenderEngine, NULL,
    CLSCTX_INPROC_SERVER, IID_IRenderEngine, (void**) &pRender);

hr = pRender->SetTimelineObject(pTL);
hr = pRender->ConnectFrontEnd( );
hr = pRender->RenderOutputPins( );

Now you can run the filter graph. Obtain a pointer to the graph by calling the IRenderEngine::GetFilterGraph method. Query the graph for the IMediaControl interface and call IMediaControl::Run, as show in the following code example.

IGraphBuilder   *pGraph = NULL;
IMediaControl   *pControl = NULL;

hr = pRender->GetFilterGraph(&pGraph);
hr = pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
hr = pControl->Run();

For a complete example that loads and previews a project file, see Loading and Previewing a Project.


Writing a Project to a File

This article describes how to write a video editing project to a file. First it describes how to write a file with the basic render engine. Then it describes smart recompression with the smart render engine. It contains the following sections.

  • Using the Basic Render Engine
  • Using the Smart Render Engine

For an overview of how Microsoft® DirectShow® Editing Services renders projects, see About the Render Engines.

Using the Basic Render Engine

Start by building the front end of the graph, as follows:

  1. Create the render engine.
  2. Specify the timeline.
  3. Build the front end of the graph.

The following code example shows these steps.

IRenderEngine *pRender = NULL;
hr = CoCreateInstance(CLSID_RenderEngine, NULL, CLSCTX_INPROC,
    IID_IRenderEngine, (void**) &pRender);

hr = pRender->SetTimelineObject(pTL);
hr = pRender->ConnectFrontEnd( );

Next, add multiplexer and file-writing filters to the filter graph. The easiest way to do this is with the capture graph builder, a DirectShow component for building capture graphs. The capture graph builder exposes the ICaptureGraphBuilder2 interface. Perform the following steps:

  1. Create an instance of the capture graph builder.
  2. Obtain a pointer to the graph and pass it to the graph builder.
  3. Specify the name and media type of the output file. This step also obtains a pointer to the mux filter, which is required later.

The following code example shows these steps.

CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC,
    IID_ICaptureGraphBuilder2, (void **)&pBuilder);

// Get a pointer to the graph front end.
IGraphBuilder *pGraph;
pRender->GetFilterGraph(&pGraph);
pBuilder->SetFiltergraph(pGraph);

// Create the file-writing section.
IBaseFilter *pMux;
pBuilder->SetOutputFileName(&MEDIASUBTYPE_Avi, L"Output.avi", &pMux, NULL);

Finally, connect the output pins on the front end to the mux filter.

  1. Retrieve the number of groups.
  2. For each pin, obtain a pointer to the pin.
  3. Optionally, create an instance of a compression filter to compress the stream. The type of compressor will depend on the media type of the group. You can use the system device enumerator to enumerate the available compression filters. For more information, see Enumerating Devices and Filters.
  4. Optionally, set compression parameters such as the key-frame rate. This step is discussed in detail later in the article.
  5. Call ICaptureGraphBuilder2::RenderStream. This method takes pointers to the pin, the compression filter (if any), and the multiplexer.

The following code example shows how to connect the output pins.

long NumGroups;
pTimeline->GetGroupCount(&NumGroups);

// Loop through the groups and get the output pins.
for (i = 0; i < NumGroups; i++)
{
    IPin *pPin;
    if (pRender->GetGroupOutputPin(i, &pPin) == S_OK)
    {
        IBaseFilter *pCompressor;
        // Create a compressor filter. (Not shown.)
        // Set compression parameters. (Not shown.)

        // Connect the pin.
        pBuilder->RenderStream(NULL, NULL, pPin, pCompressor, pMux);
        pCompressor->Release();
        pPin->Release();
    }
}

To set compression parameters (step 4, previously), use the IAMVideoCompression interface. This interface is exposed on the output pins of compression filters. Enumerate the compression filter's pins, and query each output pin for IAMVideoCompression. (For information about enumerating pins, see Enumerating Pins.) Be sure to release all the interface pointers that you obtained during this step.

After you build the filter graph, call the IMediaControl::Run method on the filter graph manager. As the filter graph runs, it writes the data to a file. Use event notification to wait for playback to complete. (See Responding to Events.) When playback finishes, you must explicitly call IMediaControl::Stop to stop the filter graph. Otherwise, the file is not written correctly.

Using the Smart Render Engine

To get the benefits of smart recompression, use the smart render engine in place of the basic render engine. The steps in building the graph are almost the same. The major difference is that compression is handled in the front end of the graph, not in the file-writing section.

Each video group has a property that specifies the compression format for that group. The compression format must exactly match the group's uncompressed format in height, width, bit depth, and frame rate. The smart render engine uses the compression format when it constructs the graph. Before you set the compression format, make sure to set the uncompressed format for that group by calling IAMTimelineGroup::SetMediaType.

To set a group's compression format, call the IAMTimelineGroup::SetSmartRecompressFormat method. This method takes a pointer to an SCompFmt0 structure. This structure has two members: nFormatId, which must be zero, and MediaType, which is an AM_MEDIA_TYPE structure. Initialize the AM_MEDIA_TYPE structure with the format information.

Note If you want the final project to have the same format as one of your source files, you can get the AM_MEDIA_TYPE structure directly from the source file, using the media detector. See IMediaDet::get_StreamMediaType.

Cast the SCompFmt0 variable to a pointer of type long, as shown in the following example.

SCompFmt0 *pFormat = new SCompFmt0;
memset(pFormat, 0, sizeof(SCompFmt0));
pFormat->nFormatId = 0;

// Initialize pFormat->MediaType. (Not shown.)

pGroup->SetSmartRecompressFormat( (long*) pFormat );

The smart render engine automatically searches for a compatible compression filter. You can also specify a compression filter for a group by calling ISmartRenderEngine::SetGroupCompressor.

Building the Graph

To build the graph, use the same steps that were described in Using the Basic Render Engine. The only differences are the following:

  • Use the smart render engine, not the basic render engine. The class identifier is CLSID_SmartRenderEngine.
  • Set compression parameters after you build the front end but before you render the output pins. Call the ISmartRenderEngine::GetGroupCompressor method to obtain a pointer to a group's compression filter. Then query for the IAMVideoCompression interface, as described previously.
  • When you render the output pins, there is no need to insert a compression filter. The stream is already compressed.


Logging Errors

Microsoft® DirectShow® Editing Services (DES) provides a built-in mechanism for logging errors that occur when loading, constructing, or rendering a DES project. This article presents a sample console application that loads an XML project file and attempts to render it. If an error occurs, the application prints an error message in the console window. The sample code presented in this article builds on the example given in Loading and Previewing a Project.

Note Your application is not required to implement error logging. DES does not log errors unless you explicitly request it.

This article assumes that you understand COM client programming and the DES timeline model. In addition, you need to understand the basics of COM object programming. For information about timelines in DES, see The Timeline Model.

This article contains the following sections.

  • Overview of Error Logging
  • Creating an Error Logging Class
  • Implementing IAMErrorLog
  • Setting the Error Log
  • Sample Code

Overview of Error Logging

To give applications maximum flexibility in handling errors, DES uses a callback mechanism. Your application implements a method for logging an error. At run time, if an error occurs, DES calls the method you have provided. The method takes parameters that describe the error. What the method does with this information is up to you. (It should return as quickly as possible, however, or it might interfere with the execution of the program.)

The error logging callback method is contained in a COM interface, IAMErrorLog. Your application must implement this interface. Like all COM interfaces, IAMErrorLog inherits the IUnknown interface, so your application must implement that as well.

You have several choices for implementing these COM interfaces. You can use the Active Template Library (ATL), which provides stock implementations of the IUnknown methods. DirectShow also provides a C++ base class, CUnknown, that makes it easy to implement a COM interface. For information on using CUnknown, see How to Implement IUnknown.

The sample code in this article defines a self-contained C++ class, which implements both IUnknown and IAMErrorLog. The result is not a true COM object, because it does not support CoCreateInstance. However, this approach is adequate for the purpose of the example.

Creating an Error Logging Class

First, declare a class that will implement error logging. The class inherits the IAMErrorLog interface. It contains declarations for the three IUnknown methods, and for the single method in IAMErrorLog. The class declaration is as follows:

class CErrReporter : public IAMErrorLog
{
protected:
    long    m_lRef; // Reference count.

public:
    CErrReporter() { m_lRef = 0; }

    // IUnknown
    STDMETHOD(QueryInterface(REFIID, void**));
    STDMETHOD_(ULONG, AddRef());
    STDMETHOD_(ULONG, Release());

    // IAMErrorLog
    STDMETHOD(LogError(LONG, BSTR, LONG, HRESULT, VARIANT*));
};

The only member variable in the class is m_lRef, which holds the object's reference count.

Next, define the methods in IUnknown. For details, refer to the sample code at the end of this article. With the COM framework in place, you can now implement the IAMErrorLog interface. The next section describes how to do this.

Implementing IAMErrorLog

The IAMErrorLog interface contains a single method, LogError. The parameters to the method contain information about the error that occurred.

STDMETHODIMP LogError(
    LONG Severity,          // Reserved. Do not use.
    BSTR ErrorString,       // Description.
    LONG ErrorCode,         // Error code.
    HRESULT hresult,        // HRESULT that caused the error.
    VARIANT *pExtraInfo);   // Extra information about the error.

The error code and the error string are defined by DirectShow Editing Services. For a list of errors, see Rendering Errors.

The pExtraInfo parameter contains a pointer to a VARIANT type that holds additional information about the error. The data type and contents of the VARIANT depend on the specific error that occurred. For example, if the error was caused by an incorrect file name, the VARIANT is a string with the bad file name. Some errors do not have extra information, so pExtraInfo might be NULL. The following code shows how to test the vt member of the VARIANT, which indicates the data type, and format a message accordingly.

if( pExtraInfo )    // Report extra information, if any.
{
    printf("\tExtra info: ");
    if( pExtraInfo->vt == VT_BSTR )      // Extra info is a BSTR.
    {
        char szExtra[256];
        WideCharToMultiByte(CP_ACP, 0, pExtraInfo->bstrVal, -1, szExtra, 256, 0, 0);
        printf("%s\n", szExtra);
    }
    else if( pExtraInfo->vt == VT_I4 )   // Extra info is an integer.
        printf("%d\n", pExtraInfo->lVal);

    else if( pExtraInfo->vt == VT_R8 )   // Extra info is floating-point.
        printf("%f\n", pExtraInfo->dblVal);
}

Note Do not free the VARIANT pointed to by pExtraInfo. Also, the VARIANT becomes invalid after the method returns, so do not reference it later.

Setting the Error Log

After you implement the error logging class, create a new instance of the class. Then, give DES a pointer to it by calling the IAMSetErrorLog::put_ErrorLog method on the timeline. Query the timeline for the IAMSetErrorLog interface. To ensure that all errors are logged, you should call this method before you load, save, or render the timeline.

IAMSetErrorLog  *pSetLog = NULL;
IAMErrorLog     *pLog = new CErrReporter();

pTL->QueryInterface(IID_IAMSetErrorLog, (void **)&pSetLog);
pSetLog->put_ErrorLog(pLog);
pSetLog->Release();

Error logging has no effect on the return values that you receive when you call methods in your application. Error logging complements but does not replace the usual error handling techniques. To create a robust application, always check HRESULT values.

Sample Code

The following sample code presents a complete console application that loads and previews an XML project file, using the error logging class described in this article. The name of the project file is hard-coded into the application.

To make the code shorter, the console application uses ATL smart pointers, which removes the need to call QueryInterface and Release. If you prefer, you can modify the sample application in Loading and Previewing a Project. Simply add the code shown in the previous section.

#include <atlbase.h>
#include <dshow.h>
#include <qedit.h>
#include <stdio.h>

// Error logging class
class CErrReporter : public IAMErrorLog
{
protected:
    long    m_lRef; // Reference count.

public:
    CErrReporter() { m_lRef = 0; }

    // IUnknown
    STDMETHOD(QueryInterface(REFIID, void**));
    STDMETHOD_(ULONG, AddRef());
    STDMETHOD_(ULONG, Release());

    // IAMErrorLog
    STDMETHOD(LogError(LONG, BSTR, LONG, HRESULT, VARIANT*));
};

STDMETHODIMP CErrReporter::QueryInterface(REFIID riid, void **ppv)
{
    if (ppv == NULL)
        return E_POINTER;
    *ppv = NULL;

    if (riid == IID_IUnknown)
        *ppv = (IUnknown*)this;
    else if (riid == IID_IAMErrorLog)
        *ppv = (IAMErrorLog*)this;

    if (*ppv)
    {
        AddRef();
        return S_OK;
    }
    return E_NOINTERFACE;
}

STDMETHODIMP_(ULONG) CErrReporter::AddRef()
{
    return InterlockedIncrement(&m_lRef);
}

STDMETHODIMP_(ULONG) CErrReporter::Release()
{
    if (InterlockedDecrement(&m_lRef) == 0)
    {
        delete this;
        return 0;
    }
    return m_lRef;
}

STDMETHODIMP CErrReporter::LogError(
        LONG Severity,
        BSTR ErrorString,
        LONG ErrorCode,
        HRESULT hresult,
        VARIANT *pExtraInfo)
{
    char szError[256];
    WideCharToMultiByte(CP_ACP, 0, ErrorString, -1, szError, 256, 0, 0);
    printf("Error %d: %s\n", ErrorCode, szError);

    if( pExtraInfo )    // Report extra information, if any.
    {
        printf("\tExtra info: ");
        if( pExtraInfo->vt == VT_BSTR )      // Extra info is a BSTR.
        {
            char szExtra[256];
            WideCharToMultiByte(CP_ACP, 0, pExtraInfo->bstrVal, -1, szExtra, 256, 0, 0);
            printf("%s\n", szExtra);
        }
        else if( pExtraInfo->vt == VT_I4 )   // Extra info is an integer.
            printf("%d\n", pExtraInfo->lVal);

        else if( pExtraInfo->vt == VT_R8 )   // Extra info is floating-point.
            printf("%f\n", pExtraInfo->dblVal);
    }
    return hresult;
};

void __cdecl main(void)
{
    CoInitialize(NULL);
    {
    HRESULT hr;
    CComPtr< IAMTimeline >   pTL;
    CComPtr< IRenderEngine > pRenderEngine;
    CComPtr< IXml2Dex >      pXML;
    CComPtr< IGraphBuilder > pGraph;

    hr = CoCreateInstance(CLSID_AMTimeline, NULL, CLSCTX_INPROC_SERVER,
                IID_IAMTimeline, (void**) &pTL);

    hr = CoCreateInstance(CLSID_Xml2Dex, NULL, CLSCTX_INPROC_SERVER,
                IID_IXml2Dex, (void**) &pXML);

    hr = CoCreateInstance(CLSID_RenderEngine, NULL, CLSCTX_INPROC_SERVER,
                IID_IRenderEngine, (void**) &pRenderEngine);

    // Set the error log.
    CComQIPtr<IAMSetErrorLog, &IID_IAMSetErrorLog> pSetLog(pTL);
    if (pSetLog)
    {
        IAMErrorLog *pLog = new CErrReporter;
        pSetLog->put_ErrorLog(pLog);
    }

    // Load and preview the project.
    hr = pXML->ReadXMLFile(pTL, L"C:\\Example.xtl");
    if (SUCCEEDED(hr))
    {
        hr = pRenderEngine->SetTimelineObject(pTL);
        hr = pRenderEngine->ConnectFrontEnd( );
        hr = pRenderEngine->RenderOutputPins( );
        hr = pRenderEngine->GetFilterGraph(&pGraph);

        CComQIPtr<IMediaControl, &IID_IMediaControl> pControl(pGraph);
        CComQIPtr<IMediaEvent, &IID_IMediaEvent> pEvent(pGraph);
        pControl->Run();

        long evCode;
        hr = pEvent->WaitForCompletion(INFINITE, &evCode);
        pControl->Stop();
    }
    // Clean up.
    pRenderEngine->ScrapIt();
    }
    CoUninitialize();
}


Rendering a Project

Microsoft DirectX 8.0

Managing Video Editing Projects

The following tips will help you to manage projects in Microsoft® DirectShow® Editing Services.

Changes to the Timeline

  • If you change the timeline after you build the filter graph, call IRenderEngine::ConnectFrontEnd again to rebuild the front end. Usually, the rest of the graph is not affected. Occasionally, the render engine needs to delete the entire graph before it can rebuild the front end. (For example, this happens if you add or remove a group.) The ConnectFrontEnd method returns S_WARN_OUTPUTRESET to signal that it deleted the graph. If this happens, your application must rebuild the rendering section of the graph.
  • To remove all objects completely from the timeline, call the IAMTimeline::ClearAllGroups method.

Cleaning Up

  • When you are finished using a render engine, call the IRenderEngine::ScrapIt method. As with any COM object, be sure to release every interface pointer when you are finished using it.
  • The render engine does not keep a reference count on the timeline. Do not release the timeline before you are done using it, and always call ScrapIt on the render engine first.
  • If you release all references to a timeline, do not use any of the objects in that timeline, even if you are holding reference counts on them.

Multiple Instances

  • Do not move timeline objects between timelines. Every object in a timeline must be created by that timeline. The timeline holds an internal cache with information about the objects that it creates; moving timeline objects can disrupt the cache.
  • Never use the same instance of a render engine with more than one timeline. The render engine holds a cache with information about the timeline. Multiple timelines will disrupt the cache and cause unpredictable results. If you need two active timelines, make separate instances of render engines for each timeline.
  • A timeline can use more than one render engine, but not at the same time. Delete the old render engine before using another render engine. (You would typically do this when you switch from using the basic render engine for preview to the smart render engine for file writing.)

Persistence

  • The filter graph is not persistent when you save the project to an XML file. Therefore, you lose any information relating to smart recompression, compression format, or compression parameters. It is up to the application to restore these parameters after it loads a project.


Alpha Blending

This article describes how to perform alpha blending in Microsoft® DirectShow® Editing Services (DES).

Alpha measures the transparency of a pixel or image. In 32-bit uncompressed RGB video, four components define each pixel: an alpha channel (A) and three color components (RGB). A pixel with an alpha value of zero is completely transparent. A pixel with an alpha value of 255 is opaque. Between these values, the pixel has various degrees of transparency.

DirectShow defines two media types for 32-bit RGB video:

  • MEDIASUBTYPE_ARGB32: The video is 32-bit RGB with a valid alpha channel.
  • MEDIASUBTYPE_RGB32: Pixels are 32 bits, but the alpha channel is not necessarily valid.

To use alpha blending in DES, first set the group's uncompressed media type to MEDIASUBTYPE_ARGB32. In C++, call the IAMTimelineGroup::SetMediaType method. In the XTL format, setting the BITDEPTH attribute of the GROUP element to 32 accomplishes this as well. For more information, see XML Reference.

Next, you need video data that contains an alpha channel. There are several options:

  • You can use an AVI file that already has 32-bit RGB video with alpha data. Currently, alpha is not supported for MPEG or Microsoft® Windows Media™ Format (WMF) source files.
  • DES supports 32-bit bitmap (.bmp) and Targa (.tga) files with alpha data.
  • You can write a custom source filter that creates 32-bit RGB data with alpha. The output media type must be MEDIASUBTYPE_ARGB32. Use the filter as the subobject in a timeline source object (see Subobjects).

If your video source does not have alpha, you can use an effect that creates alpha data. The Alpha Setter effect can set the alpha channel for the entire image to a constant value. To vary the alpha over time, use the IPropertySetter interface. The original source does not have to be 32 bits, as long as the group's uncompressed media type is MEDIASUBTYPE_ARGB32. You can also create your own custom Microsoft® DirectX® Transform effect that creates alpha data.

Note If your video source already contains alpha data, you can use the Alpha Setter effect to change the alpha value of each pixel by a specified percentage. For more information, see Alpha Setter.

Finally, pass the video to an effect or transition that performs alpha blending. The Compositor and SMPTE Wipe transitions both perform alpha blending. The Key transition can key by alpha value. Some third-party DirectX Transform objects also support alpha blending.

The following sample XTL project performs alpha blending:

<TIMELINE>
<GROUP TYPE="video" BITDEPTH="32" WIDTH="320" HEIGHT="240">

<TRACK>
  <CLIP START="0" STOP="6" SRC="c:\Example.avi" />
</TRACK>

<TRACK>
  <CLIP START="0" STOP="6" SRC="c:\Example2.avi">

    <!-- Alpha Setter effect. -->
    <EFFECT CLSID="{506D89AE-909A-44f7-9444-ABD575896E35}" START="0" STOP="6">
      <PARAM NAME="alpha" VALUE="255">
        <LINEAR TIME="6" VALUE="0" />
      </PARAM>
    </EFFECT>

  </CLIP>

  <!-- Key transition, with alpha keying. -->
  <TRANSITION CLSID="{C5B19592-145E-11d3-9F04-006008039E37}" START="0" STOP="6">
    <PARAM NAME="KeyType" VALUE="3" />
  </TRANSITION>
</TRACK>


Converting Cutlists to Timelines

This article describes how to convert an existing cutlist application to Microsoft® DirectShow® Editing Services (DES).

Cutlists were a feature in earlier versions of DirectShow that provided limited support for non-linear editing. As of Microsoft® DirectX® 8.0, cutlists are no longer supported. A straight feature-for-feature conversion to DES should be straightforward to implement. At the very least, you will see the following benefits:

  • Support for heterogeneous sources.
  • Support for compressed sources.
  • Automatic conversion of frame rates.
  • Support for stretching video to fill the frame, or to create a letterbox.
  • Support for slow- and fast-motion audio and video.
  • Better support for audio gaps (silence).

Moving beyond cutlists, you can add features such as project persistence, compositing of multiple tracks, effects, transitions, and poster frames.

A typical cutlist application performs the following steps:

  1. Create separate cutlists (IStandardCutList) for the video and audio streams.
  2. For each source file, create a video file clip, audio file clip, or both (IFileClip).
  3. From each file clip, create one or more cuts (IAMCutListElement). Add them to the cutlists.
  4. Create a cutlist graph builder (ICutListGraphBuilder).
  5. Add each cutlist to the cutlist graph builder.
  6. Optionally, set the output file name.
  7. Render and play the graph.

The equivalent steps in DES are:

  1. Create a timeline (IAMTimeline).
  2. For each video and audio stream in the final production, create one group (IAMTimelineGroup).
  3. Add one or more tracks (IAMTimelineTrack) to each group.
  4. Create source objects (IAMTimelineSrc) and add them to the tracks.
  5. Create a render engine (IRenderEngine).
  6. Add the timeline to the render engine.
  7. Render and play the graph.

To highlight some of the differences:

File clips: In DES, there is no object equivalent to the file clip. A source object is roughly equivalent to a cut. As with cuts, more than one source object can refer to the same source file.

Media type: With cutlists, there are two distinct file-clip objects for audio and video. Each has its own class identifier. In DES, the group's media type determines a source object's media type.

File output: There is no direct equivalent in DES to the ICutListGraphBuilder::SetOutputFileName method. File output is somewhat more complicated in DES. However, you gain a great deal of control over the format and compression type. For more information, see Writing a Project to a File.

Modifying projects: With cutlists, you can add new cuts, but you cannot modify or remove cuts. With DES, you can add, remove, rearrange, or modify source objects. For more information, see Managing Video Editing Projects.


DirectShow Editing Services Reference

This section contains all the Microsoft® DirectShow® Editing Services reference information. This material is presented in the following articles.

  • Interfaces
  • Structures
  • Enumerated Types
  • Constants
  • Transitions and Effects
  • DirectShow Editing Services Components
  • XML Reference
  • Rendering Errors


Interfaces

This section contains reference entries for all the Microsoft® DirectShow® Editing Services (DES) COM interfaces and their methods.

  • IAMErrorLog
  • IAMSetErrorLog
  • IAMTimeline
  • IAMTimelineComp
  • IAMTimelineEffect
  • IAMTimelineEffectable
  • IAMTimelineGroup
  • IAMTimelineObj
  • IAMTimelineSplittable
  • IAMTimelineSrc
  • IAMTimelineTrack
  • IAMTimelineTrans
  • IAMTimelineTransable
  • IAMTimelineVirtualTrack
  • IFindCompressorCB
  • IMediaDet
  • IMediaLocator
  • IPropertySetter
  • IRenderEngine
  • ISmartRenderEngine
  • IXml2Dex


IAMErrorLog Interface

Provides a callback method for error logging in Microsoft® DirectShow® Editing Services (DES).

DES does not implement this interface. To perform error logging, implement this interface in your application and call IAMSetErrorLog::put_ErrorLog on the timeline. If an error occurs when you render the project, DES will call the IAMErrorLog::LogError method implemented by your application.

DES logs errors only when you render a project using the IRenderEngine interface. For example, if you save a project as a DirectShow filter graph (.grf format) and play the graph file, there is no error logging.

For more information on using this interface, see Logging Errors.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMErrorLog Methods | Description
LogError | Logs an error.

IAMErrorLog::LogError

IAMErrorLog Interface

Logs an error. Applications do not need to call this method. It is called internally in response to rendering errors.

Syntax

HRESULT LogError(
    LONG Severity,
    BSTR ErrorString,
    LONG ErrorCode,
    HRESULT hresult,
    VARIANT *pExtraInfo
);

Parameters

Severity
Reserved. Do not use.
ErrorString
String value containing the text of the error.
ErrorCode
Error code.
hresult
The HRESULT value that was returned by the method call that caused the error.
pExtraInfo
[in] Pointer to a VARIANT that contains any additional information about the error.

Return Value

Returns an HRESULT value. Return the value of the hresult parameter.

Remarks

Within this method, do not free the VARIANT pointed to by pExtraInfo. Also, the VARIANT becomes invalid after the method returns, so do not try to reference it later.

Implement this method to return as quickly as possible. Do not make function calls from inside this method that might block program execution. For example, do not call Microsoft® Win32® functions that send messages, block on events, or otherwise might block execution. Doing so could cause the computer to stop responding, or "hang."

For a list of errors defined by DES, along with the meaning and data type of the VARIANT pointed to by pExtraInfo, see Rendering Errors.


IAMSetErrorLog Interface

Sets or retrieves an error log in Microsoft® DirectShow® Editing Services (DES). The timeline object implements this interface. Applications can use this interface to log rendering errors at run time. Implement the IAMErrorLog interface in your application, and then call the IAMSetErrorLog::put_ErrorLog method on the timeline.

For more information on using this interface, see Logging Errors.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMSetErrorLog Methods | Description
get_ErrorLog | Retrieves the error log set on this object.
put_ErrorLog | Specifies an error log for the object.

IAMSetErrorLog::get_ErrorLog

IAMSetErrorLog Interface

Retrieves the error log set on this object.

Syntax

HRESULT get_ErrorLog(
    IAMErrorLog **pVal
);

Parameters

pVal
[out, retval] Address of a pointer that receives the error log's IAMErrorLog interface. If the timeline does not have an error log, the value is set to NULL.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If the value returned in pVal is not NULL, the IAMErrorLog interface has an outstanding reference count. Be sure to release the interface when you are done using it.

IAMSetErrorLog::put_ErrorLog

IAMSetErrorLog Interface

Specifies an error log for the object.

Syntax

HRESULT put_ErrorLog(
    IAMErrorLog *newVal
);

Parameters

newVal
[in] Pointer to the error log's IAMErrorLog interface.

Return Value

Returns S_OK.


IAMTimeline Interface

Provides methods for manipulating the timeline, the central object in Microsoft® DirectShow® Editing Services (DES). A timeline is a collection of time-ordered elements, such as video clips, audio clips, effects, and transitions between clips. The render engine uses the timeline to create a filter graph, from which the application can generate the rendered output.

IAMTimeline performs three basic services. It

  • Creates the objects in the timeline.
  • Acts as a container for those objects.
  • Sets and retrieves general parameters of the timeline.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimeline Methods | Description
CreateEmptyNode | Creates a new timeline object.
AddGroup | Adds a group to the timeline.
RemGroupFromList | Not supported.
GetGroup | Retrieves a specified group.
GetGroupCount | Retrieves the number of groups that are contained in the timeline.
ClearAllGroups | Removes all groups from the timeline, along with all objects contained in those groups.
GetInsertMode | Not supported.
SetInsertMode | Not implemented.
EnableTransitions | Enables or disables all transitions in the timeline.
TransitionsEnabled | Determines whether transitions are enabled.
EnableEffects | Enables or disables all effects in the timeline.
EffectsEnabled | Determines whether effects are enabled.
SetInterestRange | Not implemented.
GetDuration | Retrieves the duration of the timeline.
GetDuration2 | Equivalent to GetDuration, but takes a parameter of type double.
SetDefaultFPS | Sets the default output frame rate, in frames per second.
GetDefaultFPS | Retrieves the default output frame rate, in frames per second.
IsDirty | Not supported.
GetDirtyRange | Not supported.
GetCountOfType | Retrieves the number of objects of the specified type that are contained in a specified group and all of its children.
ValidateSourceNames | Validates source names in the timeline.
SetDefaultTransition | Sets the default transition.
GetDefaultTransition | Retrieves the default transition.
SetDefaultEffect | Sets the default effect.
GetDefaultEffect | Retrieves the default effect.
SetDefaultTransitionB | Equivalent to SetDefaultTransition, but takes a BSTR value.
GetDefaultTransitionB | Equivalent to GetDefaultTransition, but receives a BSTR value.
SetDefaultEffectB | Equivalent to SetDefaultEffect, but takes a BSTR value.
GetDefaultEffectB | Equivalent to GetDefaultEffect, but receives a BSTR value.

IAMTimeline::AddGroup

IAMTimeline Interface

Adds a group to the timeline.

Syntax

HRESULT AddGroup(
    IAMTimelineObj *pGroup
);

Parameters

pGroup
Pointer to the IAMTimelineObj interface of the group.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | Maximum number of groups exceeded.
E_NOINTERFACE | The object is not a group.

Remarks

Currently, timelines support a maximum of 32 groups.

IAMTimeline::ClearAllGroups

IAMTimeline Interface

Removes all groups from the timeline, along with all objects contained in those groups.

Syntax

HRESULT ClearAllGroups( void );

Return Value

Returns S_OK.

IAMTimeline::CreateEmptyNode

IAMTimeline Interface

Creates a new timeline object.

Use this method to create timeline objects, rather than the CoCreateInstance function, because this method performs important initialization routines. Every object created by this method supports at least the IAMTimelineObj interface, along with other interfaces specific to that type of object.

Syntax

HRESULT CreateEmptyNode(
    IAMTimelineObj **ppObj,
    TIMELINE_MAJOR_TYPE Type
);

Parameters

ppObj
[out] Address of a pointer that receives the new object's IAMTimelineObj interface.
Type
Member of the TIMELINE_MAJOR_TYPE enumerated type, specifying the type of object to create.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | Object type is not valid.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

Do not add the new object to another timeline instance. Every object in a timeline must be created by that timeline.

If the method succeeds, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimeline::EffectsEnabled

IAMTimeline Interface

Determines whether effects are enabled. If effects are disabled, they remain in the timeline but are not rendered.

Syntax

HRESULT EffectsEnabled(
    BOOL *pfEnabled
);

Parameters

pfEnabled
Pointer to a variable that receives a Boolean value indicating whether effects are enabled. If TRUE, effects are enabled. If FALSE, effects are disabled.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimeline::EnableEffects

IAMTimeline Interface

Enables or disables all effects in the timeline. If effects are disabled, they remain in the timeline but are not rendered.

Syntax

HRESULT EnableEffects(
    BOOL fEnabled
);

Parameters

fEnabled
Boolean value that specifies whether to enable or disable effects. If TRUE, effects are enabled. If FALSE, effects are disabled.

Return Value

Returns S_OK.

IAMTimeline::EnableTransitions

IAMTimeline Interface

Enables or disables all transitions in the timeline. If transitions are disabled, the render engines treats them as cuts; that is, the rendered output jumps instantly from one track to the next. The default cut point is halfway through the duration of the transition. You can change the cut point by calling the IAMTimelineTrans::SetCutPoint method on the transition. Disabled transitions are not removed from the timeline.

Syntax

HRESULT EnableTransitions(
    BOOL fEnabled
);

Parameters

fEnabled
Boolean value that specifies whether to enable or disable transitions. If TRUE, transitions are enabled. If FALSE, transitions are disabled.

Return Value

Returns S_OK.

IAMTimeline::GetCountOfType

IAMTimeline Interface

Retrieves the number of objects of the specified type that are contained in a specified group and all of its children.

Syntax

HRESULT GetCountOfType(
    long Group,
    long *pVal,
    long *pValWithComps,
    TIMELINE_MAJOR_TYPE MajorType
);

Parameters

Group
Index number of the group for which to retrieve the count.
pVal
Pointer to a variable that receives the number of objects of the specified type contained in the group and all of its virtual tracks, recursively.
pValWithComps
Pointer to a variable that receives the count returned in pVal plus the number of compositions searched, including this one.
MajorType
Member of the TIMELINE_MAJOR_TYPE enumerated type, specifying the type of object to count.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | Invalid group number.
E_POINTER | NULL pointer argument.

Remarks

Calling this method is equivalent to calling IAMTimelineComp::GetCountOfType on the specified group. See the Remarks section of that method for more information.

Typically, an application will not call this method. It is called internally by the render engine.

IAMTimeline::GetDefaultEffect

IAMTimeline Interface

Retrieves the default effect. If the render engine cannot render an effect, it substitutes the default effect.

Syntax

HRESULT GetDefaultEffect(
    GUID *pGuid
);

Parameters

pGuid
Pointer to a variable that receives the globally unique identifier (GUID) of the default effect.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimeline::GetDefaultEffectB

IAMTimeline Interface

Retrieves the default effect. This method is equivalent to GetDefaultEffect, but receives a BSTR value rather than a GUID.

Syntax

HRESULT GetDefaultEffectB(
    BSTR *pGuid
);

Parameters

pGuid
[out, retval] Pointer to a variable that receives a BSTR value representing the GUID of the default effect.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

IAMTimeline::GetDefaultFPS

IAMTimeline Interface

Retrieves the default output frame rate, in frames per second (FPS). Groups use this value as their default frame rate. To set a group's frame rate, call the IAMTimelineGroup::SetOutputFPS method on the group.

Syntax

HRESULT GetDefaultFPS(
    double *pFPS
);

Parameters

pFPS
Pointer to a variable that receives the default frame rate, in frames per second.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimeline::GetDefaultTransition

IAMTimeline Interface

Retrieves the default transition. If the render engine cannot render a transition, it substitutes the default transition.

Syntax

HRESULT GetDefaultTransition(
    GUID *pGuid
);

Parameters

pGuid
Pointer to a variable that receives the GUID of the default transition.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimeline::GetDefaultTransitionB

IAMTimeline Interface

Retrieves the default transition. This method is equivalent to GetDefaultTransition, but receives a BSTR value, rather than a GUID.

Syntax

HRESULT GetDefaultTransitionB(
    BSTR *pGuid
);

Parameters

pGuid
[out, retval] Pointer to a variable that receives a BSTR value representing the GUID of the default transition.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

IAMTimeline::GetDirtyRange

IAMTimeline Interface

Not supported.

Syntax

HRESULT GetDirtyRange(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

IAMTimeline::GetDuration

IAMTimeline Interface

Retrieves the duration of the timeline.

Syntax

HRESULT GetDuration(
    REFERENCE_TIME *pDuration
);

Parameters

pDuration
Pointer to a variable that receives the duration of the timeline, in 100-nanosecond units.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimeline::GetDuration2

IAMTimeline Interface

Retrieves the duration of the timeline. This method is equivalent to GetDuration, but takes a parameter of type double.

Syntax

HRESULT GetDuration2(
    double *pDuration
);

Parameters

pDuration
Pointer to a variable that receives the duration of the timeline, in fractional seconds.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimeline::GetGroup

IAMTimeline Interface

Retrieves a specified group.

Syntax

HRESULT GetGroup(
    IAMTimelineObj **ppGroup,
    long WhichGroup
);

Parameters

ppGroup
[out] Address of a pointer that receives the group's IAMTimelineObj interface.
WhichGroup
Index of the group to retrieve, based on the order in which the groups were added to the timeline. The first group added to the timeline has an index of 0.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

If the method succeeds, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimeline::GetGroupCount

IAMTimeline Interface

Retrieves the number of groups that are contained in the timeline.

Syntax

HRESULT GetGroupCount(
    long *pCount
);

Parameters

pCount
Pointer to a variable that receives the number of groups in the timeline.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimeline::GetInsertMode

IAMTimeline Interface

Not supported.

Syntax

HRESULT GetInsertMode(
    long *pMode
);

IAMTimeline::IsDirty

IAMTimeline Interface

Not supported.

Syntax

HRESULT IsDirty(
    BOOL *pDirty
);

IAMTimeline::RemGroupFromList

IAMTimeline Interface

Not supported.

Syntax

HRESULT RemGroupFromList(
    IAMTimelineObj *pGroup
);

IAMTimeline::SetDefaultEffect

IAMTimeline Interface

Sets the default effect. If the render engine cannot render an effect, it substitutes the default effect.

Syntax

HRESULT SetDefaultEffect(
    GUID *pGuid
);

Parameters

pGuid
Pointer to a variable that contains the GUID of the default effect.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If you do not set a default effect, or if the effect that you specify as a default causes an error, DES uses its own default effect.

IAMTimeline::SetDefaultEffectB

IAMTimeline Interface

Sets the default effect. This method is equivalent to SetDefaultEffect, but takes a BSTR value, rather than a pointer to a GUID.

Syntax

HRESULT SetDefaultEffectB(
    BSTR pGuid
);

Parameters

pGuid
BSTR value representing the GUID of the default effect.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

IAMTimeline::SetDefaultFPS

IAMTimeline Interface

Sets the default output frame rate, in frames per second. Groups use this value as their default frame rate. To set a group's frame rate, call the IAMTimelineGroup::SetOutputFPS method on the group.

Syntax

HRESULT SetDefaultFPS(
    double FPS
);

Parameters

FPS
Default frame rate, in frames per second.

Return Value

Returns S_OK.

IAMTimeline::SetDefaultTransition

IAMTimeline Interface

Sets the default transition. If the render engine cannot render a transition, it substitutes the default transition.

Syntax

HRESULT SetDefaultTransition(
    GUID *pGuid
);

Parameters

pGuid
Pointer to a variable that contains the GUID of the default transition.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If you do not set a default transition, or if the transition that you specify as a default causes an error, DES uses its own default transition.

IAMTimeline::SetDefaultTransitionB

IAMTimeline Interface

Sets the default transition. This method is equivalent to SetDefaultTransition, but takes a BSTR value, rather than a pointer to a GUID.

Syntax

HRESULT SetDefaultTransitionB(
    BSTR pGuid
);

Parameters

pGuid
BSTR value representing the GUID of the default transition.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

IAMTimeline::SetInsertMode

IAMTimeline Interface

Not implemented.

Syntax

HRESULT SetInsertMode(
    long Mode
);

IAMTimeline::SetInterestRange

IAMTimeline Interface

Not implemented.

Syntax

HRESULT SetInterestRange(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

IAMTimeline::TransitionsEnabled

IAMTimeline Interface

Determines whether transitions are enabled.

Syntax

HRESULT TransitionsEnabled(
    BOOL *pfEnabled
);

Parameters

pfEnabled
Pointer to a variable that receives a Boolean value. If TRUE, transitions are enabled. Otherwise, transitions are disabled.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

See Also

EnableTransitions

IAMTimeline::ValidateSourceNames

IAMTimeline Interface

Validates source names in the timeline, using the media locator. Optionally, this method also updates any source object for which it locates a file.

Syntax

HRESULT ValidateSourceNames(
    long ValidateFlags,
    IMediaLocator *pOverride,
    long NotifyEventHandle
);

Parameters

ValidateFlags
Bitwise combination of flags specifying the behavior of the media locator. The SFN_VALIDATEF_REPLACE and SFN_VALIDATEF_CHECK flags must be present, or the method returns E_INVALIDARG.
pOverride
Optional pointer to the IMediaLocator interface of a media locator to use in place of the default. To use the default media locator, set the value of this parameter to NULL. See Remarks for more information.
NotifyEventHandle
Handle to an event. The method signals the event after it has completed the validation.

Return Value

Returns S_OK if successful. Otherwise, returns E_INVALIDARG or another error code.

Remarks

Using the pOverride parameter, you can supply your own custom implementation of the IMediaLocator interface. For example, the default media locator will not notify your application about the files that it finds (or cannot find). To get around this limitation, you could implement a custom media locator, making it a wrapper for the default version. In your custom version, pass FindMediaFile calls directly to the default version, and examine the return value.


IAMTimelineComp Interface

Inserts or retrieves virtual tracks on a composition in Microsoft® DirectShow® Editing Services (DES).

A composition is a collection of layers that acts as a single, composited track. For example, a composition that contains two tracks with a transition between them acts as a single track with the transition precomposited. A composition should contain media of only one type (such as audio or video), but this limitation is not enforced. A virtual track is any object that can reside in a composition, including tracks and other compositions.

The topmost nodes in the timeline are groups. Groups implement both the IAMTimelineComp interface and the IAMTimelineGroup interface.

For more information, see The Timeline Model and Groups, Compositions, and Tracks.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimelineComp Methods | Description
VTrackInsBefore | Inserts a virtual track into the composition at the specified priority.
VTrackSwapPriorities | Switches the priority levels of two tracks.
VTrackGetCount | Retrieves the number of virtual tracks contained in the composition.
GetVTrack | Retrieves the virtual track at the specified priority.
GetCountOfType | Retrieves the number of objects of a given type contained in this composition and all of its virtual tracks, recursively.
GetRecursiveLayerOfType | Performs a depth-first ordering of the virtual tracks contained in this composition, and retrieves the nth virtual track from that ordering.
GetRecursiveLayerOfTypeI | Not supported.
GetNextVTrack | Retrieves the next virtual track after a specified virtual track.

IAMTimelineComp::GetCountOfType

IAMTimelineComp Interface

Retrieves the number of objects of a given type contained in this composition and all its virtual tracks, recursively.

Syntax

HRESULT GetCountOfType(
    long *pVal,
    long *pValWithComps,
    TIMELINE_MAJOR_TYPE MajorType
);

Parameters

pVal
Pointer to a variable that receives the number of objects of the specified type contained in this composition and all its virtual tracks, recursively.
pValWithComps
Pointer to a variable that receives the count returned in pVal plus the number of compositions searched, including this one.
MajorType
Member of the TIMELINE_MAJOR_TYPE enumerated type, specifying the type of object to count.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

Typically, an application will not call this method. It is called by the render engine.

If you count compositions, the value returned in pVal is zero and the value returned in pValWithComps is the number of compositions. The value of *pValWithComps includes the composition on which you call the method. For example, if you call this method on an empty composition, *pValWithComps equals 1.

Groups cannot reside inside compositions, so you cannot use this method to count groups. (The returned count will always be zero.) To count groups, call the IAMTimeline::GetGroupCount method.

IAMTimelineComp::GetNextVTrack

IAMTimelineComp Interface

Retrieves the next virtual track after a specified virtual track.

Syntax

HRESULT GetNextVTrack(
    IAMTimelineObj *pVirtualTrack,
    IAMTimelineObj **ppNextVirtualTrack
);

Parameters

pVirtualTrack
Pointer to the previous virtual track, or NULL to retrieve the first virtual track in the composition.
ppNextVirtualTrack
[out] Address of a pointer that receives the IAMTimelineObj interface of the next virtual track, in order of priority.

Return Value

Returns S_OK if the method retrieves a virtual track, or S_FALSE otherwise.

Remarks

If the method succeeds, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimelineComp::GetRecursiveLayerOfType

IAMTimelineComp Interface

Performs a depth-first ordering of the virtual tracks contained in this composition, and retrieves the nth virtual track from that ordering.

Syntax

HRESULT GetRecursiveLayerOfType(
    IAMTimelineObj **ppVirtualTrack,
    long WhichLayer,
    TIMELINE_MAJOR_TYPE Type
);

Parameters

ppVirtualTrack
[out] Address of a pointer that receives the virtual track's IAMTimelineObj interface.
WhichLayer
Value that specifies which virtual track to retrieve, indexed from zero.
Type
Member of the TIMELINE_MAJOR_TYPE enumerated type that specifies whether to include tracks in the search.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | No object of the specified type.
E_POINTER | NULL pointer argument.

Remarks

Typically, an application will not need to call this method.

If the Type parameter is TIMELINE_MAJOR_TYPE_TRACK, the depth-first ordering includes tracks. If not, it includes only compositions and groups. The object itself is included in the ordering.

For example, in the following arrangement, starting from Composition A, the ordering would be B, C, F, D, E, A.

If the method succeeds, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimelineComp::GetRecursiveLayerOfTypeI

IAMTimelineComp Interface

Not supported. Call the GetRecursiveLayerOfType method instead.

Syntax

HRESULT GetRecursiveLayerOfTypeI(
    IAMTimelineObj **ppVirtualTrack,
    long *pWhichLayer,
    TIMELINE_MAJOR_TYPE Type
);

IAMTimelineComp::GetVTrack

IAMTimelineComp Interface

Retrieves the virtual track at the specified priority.

Syntax

HRESULT GetVTrack(
    IAMTimelineObj **ppVirtualTrack,
    long Which
);

Parameters

ppVirtualTrack
[out] Address of a pointer that receives the virtual track's IAMTimelineObj interface.
Which
Priority of the virtual track to retrieve.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | No virtual track with the specified priority.
E_POINTER | NULL pointer argument.

Remarks

If the method succeeds, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimelineComp::VTrackGetCount

IAMTimelineComp Interface

Retrieves the number of virtual tracks contained in the composition.

Syntax

HRESULT VTrackGetCount(
    long *pVal
);

Parameters

pVal
Pointer to a variable that receives the number of virtual tracks.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineComp::VTrackInsBefore

IAMTimelineComp Interface

Inserts a virtual track into the composition at the specified priority.

Syntax

HRESULT VTrackInsBefore(
    IAMTimelineObj *pVirtualTrack,
    long Priority
);

Parameters

pVirtualTrack
Pointer to the IAMTimelineObj interface of the virtual track.
Priority
Priority at which to insert the virtual track, or –1 to insert the virtual track at the end of the priority list.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOINTERFACE | Object is not a virtual track.

Remarks

Priority levels start at zero. If the timeline already contains a virtual track at the specified priority level, everything from that point on moves down the priority list to make room for the inserted track. This method fails if the specified priority is greater than the current number of tracks.

IAMTimelineComp::VTrackSwapPriorities

IAMTimelineComp Interface

Switches the priority levels of two tracks.

Given two priority levels, this method switches the virtual tracks at those priorities. When the method returns, the track that was at the first priority level is now at the second priority level, and vice versa.

Syntax

HRESULT VTrackSwapPriorities(
    long VirtualTrackA,
    long VirtualTrackB
);

Parameters

VirtualTrackA
First priority level at which to swap virtual tracks.
VirtualTrackB
Second priority level at which to swap virtual tracks.

Return Value

Returns S_OK if successful, or E_INVALIDARG otherwise.


IAMTimelineEffect Interface

Provides methods for manipulating effects in Microsoft® DirectShow® Editing Services (DES). Effect objects implement this interface.

An effect object is a wrapper object for any type of one-input effect that DES supports. To specify which effect to use, call the IAMTimelineObj::SetSubObjectGUID method on the effect. To set properties on an effect, use the IPropertySetter interface. For more information, see Working with Effects and Transitions.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimelineEffect Methods | Description
EffectGetPriority | Retrieves the effect's priority level.

IAMTimelineEffect::EffectGetPriority

IAMTimelineEffect Interface

Retrieves the effect's priority level. For a given object, the render engine applies effects in order of priority, starting with priority level zero.

Syntax

HRESULT EffectGetPriority(
    long *pVal
);

Parameters

pVal
Pointer to a variable that receives the priority level.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.


IAMTimelineEffectable Interface

Provides methods for adding effects to a timeline object in Microsoft® DirectShow® Editing Services (DES), and for manipulating the effects on an object. All objects that can have effects applied to them implement this interface; this includes sources, tracks, and compositions.

An object that implements this interface can have any number of effects. For each object, the render engine applies its effects in order of priority, starting with priority level 0.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimelineEffectable Methods | Description
EffectInsBefore | Inserts an effect into the object at the specified priority level.
EffectSwapPriorities | Switches the priority levels of two effects.
EffectGetCount | Retrieves the number of effects applied to this object.
GetEffect | Retrieves the effect at the specified priority level.

IAMTimelineEffectable::EffectGetCount

IAMTimelineEffectable Interface

Retrieves the number of effects applied to this object.

Syntax

HRESULT EffectGetCount(
    long *pCount
);

Parameters

pCount
Pointer to a variable that receives the number of effects.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineEffectable::EffectInsBefore

IAMTimelineEffectable Interface

Inserts an effect into the object at the specified priority level.

Syntax

HRESULT EffectInsBefore(
    IAMTimelineObj *pFX,
    long Priority
);

Parameters

pFX
Pointer to the IAMTimelineObj interface of the effect.
Priority
Priority level at which to insert the effect. Use the value –1 to insert the effect at the end of the priority list.

Return Value

Returns S_OK if successful or E_NOTIMPL if the object is not an effect. Otherwise, returns another HRESULT value indicating the cause of the error.

Remarks

The start and stop times of the effect are clipped within the bounds of the object's time range, if necessary.

If there is already an effect at the specified priority level, all the effects from that point on move down the priority list to make room for the new effect.

IAMTimelineEffectable::EffectSwapPriorities

IAMTimelineEffectable Interface

Switches the priority levels of two effects.

Given two priority values, this method swaps the effects at those priorities. When the method returns, the effect that was at the first priority level is at the second priority level, and vice versa.

Syntax

HRESULT EffectSwapPriorities(
    long PriorityA,
    long PriorityB
);

Parameters

PriorityA
First priority level at which to swap effects.
PriorityB
Second priority level at which to swap effects.

Return Value

Returns S_OK if successful, or E_INVALIDARG otherwise.

IAMTimelineEffectable::GetEffect

IAMTimelineEffectable Interface

Retrieves the effect at the specified priority level.

Syntax

HRESULT GetEffect(
    IAMTimelineObj **ppFx,
    long Which
);

Parameters

ppFX
[out] Address of a pointer that receives the effect's IAMTimelineObj interface.
Which
Priority level of the effect to retrieve.

Return Value

Returns an HRESULT value. Possible values include the following:

S_FALSE | No effect at the specified priority,
S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.


IAMTimelineGroup Interface

Sets and retrieves properties on groups in Microsoft® DirectShow® Editing Services (DES).

A group contains one or more tracks, and possibly one or more compositions, which in turn contain source clips of a uniform type, such as video or audio. Groups are the topmost compositions in a timeline, and also expose the IAMTimelineComp interface. A timeline can contain multiple groups.

Each group has the following attributes.

  • An associated media type.
  • The frame rate at which the group renders, in frames per second (FPS). All edits occur at a time rounded to the nearest frame boundary, as defined by the group's FPS setting.
  • A priority level, for writing files with multiple streams of the same media type (for example, a two-video-stream AVI file).

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimelineGroup Methods | Description
SetTimeline | Not supported.
GetTimeline | Retrieves the timeline to which this group belongs.
GetPriority | Retrieves the group's priority.
GetMediaType | Retrieves the uncompressed media type for the group.
SetMediaType | Sets the uncompressed media type for the group.
SetOutputFPS | Sets the uncompressed output frame rate for this group.
GetOutputFPS | Retrieves the output frame rate of this group.
SetGroupName | Sets the application-defined name of the group.
GetGroupName | Retrieves the application-defined name of the group.
SetPreviewMode | Sets the preview mode for the group.
GetPreviewMode | Retrieves the preview mode for the group.
SetMediaTypeForVB | Specifies the group media type, for Automation clients.
GetOutputBuffering | Retrieves the number of frames rendered in advance during preview.
SetOutputBuffering | Specifies the number of frames rendered in advance during preview.
SetSmartRecompressFormat | Specifies a compression format to use for smart recompression.
GetSmartRecompressFormat | Retrieves the current compression format for smart recompression.
IsSmartRecompressFormatSet | Determines whether a smart compression format was set for the group.
IsRecompressFormatDirty | Not supported.
ClearRecompressFormatDirty | Not supported.
SetRecompFormatFromSource | Sets the video recompression format using the compression format from a source file.

IAMTimelineGroup::ClearRecompressFormatDirty

IAMTimelineGroup Interface

Not supported.

Syntax

HRESULT ClearRecompressFormatDirty(void);

IAMTimelineGroup::GetGroupName

IAMTimelineGroup Interface

Retrieves the application-defined name of the group.

Syntax

HRESULT GetGroupName(
    BSTR *pGroupName
);

Parameters

pGroupName
[out, retval] Pointer to a variable of type BSTR that receives the name of the group.

Return Value

Returns S_OK if successful. Otherwise, returns E_POINTER or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

IAMTimelineGroup::GetMediaType

IAMTimelineGroup Interface

Retrieves the uncompressed media type for the group.

Syntax

HRESULT GetMediaType(
    AM_MEDIA_TYPE *pmt
);

Parameters

pmt
[out] Pointer to an AM_MEDIA_TYPE structure that is filled with the media type.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineGroup::GetOutputBuffering

IAMTimelineGroup Interface

Retrieves the number of frames rendered in advance during preview.

Syntax

HRESULT GetOutputBuffering(
    int *pnBuffer
);

Parameters

pnBuffer
[out] Pointer to a variable that receives the number of buffered frames.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineGroup::GetOutputFPS

IAMTimelineGroup Interface

Retrieves the output frame rate of this group.

Syntax

HRESULT GetOutputFPS(
    double *pFPS
);

Parameters

pFPS
Pointer to a variable that receives the output frame rate, in frames per second.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineGroup::GetPreviewMode

IAMTimelineGroup Interface

Retrieves the preview mode for the group.

Syntax

HRESULT GetPreviewMode(
    BOOL *pfPreview
);

Parameters

pfPreview
Pointer to a variable that receives a Boolean value indicating the preview mode. If TRUE, the group is in preview mode. If FALSE, the group is in authoring mode.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

In preview mode, frames are dropped during slow effects or transitions to keep the video synchronized with the audio. The video might look choppy as a result. In authoring mode, every frame is rendered. Authoring mode is appropriate for writing files; for on-screen preview, the video might become out of sync with the audio.

IAMTimelineGroup::GetPriority

IAMTimelineGroup Interface

Retrieves the group's priority.

Syntax

HRESULT GetPriority(
    long *pPriority
);

Parameters

pPriority
Pointer to a variable that receives the group's priority.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineGroup::GetSmartRecompressFormat

IAMTimelineGroup Interface

Retrieves the current compression format for smart recompression.

Syntax

HRESULT GetSmartRecompressFormat(
   long **ppFormat
);

Parameters

ppFormat
Address of a variable that receives a pointer to an SCompFmt0 structure, cast as a pointer to a long. If the method fails, the value is set to NULL.

Return Value

Returns an HRESULT value. Possible values include the following.
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
if successful, or E_POINTER otherwise.

Remarks

If the application has not set a smart compression format (by calling SetSmartRecompressFormat), the format returned by this method will be invalid. Call the IsSmartRecompressFormatSet method to determine whether a compression format was set.

If the method succeeds, the caller must free the returned media type and delete the SCompFmt0 structure:

if (pFormat) {
    FreeMediaType(pFormat->MediaType);
    delete pFormat;
}

IAMTimelineGroup::GetTimeline

IAMTimelineGroup Interface

Retrieves the timeline to which this group belongs.

Syntax

HRESULT GetTimeline(
    IAMTimeline **ppTimeline
);

Parameters

ppTimeline
[out] Address of a pointer that receives the timeline's IAMTimeline interface. If the group is not part of a timeline, the value is set to NULL.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If the value returned in ppTimeline is not NULL, the IAMTimeline interface has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimelineGroup::IsRecompressFormatDirty

IAMTimelineGroup Interface

Not supported.

Syntax

HRESULT IsRecompressFormatDirty(
    BOOL *pVal
);

IAMTimelineGroup::IsSmartRecompressFormatSet

IAMTimelineGroup Interface

Determines whether a smart recompression format was set for the group.

Syntax

HRESULT IsSmartRecompressFormatSet(
    BOOL *pVal
);

Parameters

pVal
Pointer to a variable that receives a Boolean value indicating whether a compression format was set. If TRUE, a compression format was set.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineGroup::SetGroupName

IAMTimelineGroup Interface

Sets the application-defined name of the group.

Syntax

HRESULT SetGroupName(
    BSTR pGroupName
);

Parameters

pGroupName
BSTR that specifies the name of the group.

Return Value

Returns S_OK.

IAMTimelineGroup::SetMediaType

IAMTimelineGroup Interface

Sets the uncompressed media type for the group.

Syntax

HRESULT SetMediaType(
    AM_MEDIA_TYPE *pmt
);

Parameters

pmt
[in] Pointer to an AM_MEDIA_TYPE structure describing the format.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | The specified media type is invalid.

Remarks

Currently, the following media types are supported:

  • Uncompressed RGB video
    • 16 bits per pixel, 555 format
    • 24 bits per pixel
    • 32 bits per pixel
  • 16-bit stereo PCM audio

To specify a compression format for the group, call the SetSmartRecompressFormat method.

IAMTimelineGroup::SetMediaTypeForVB

IAMTimelineGroup Interface

Specifies the group media type, for Automation clients.

Syntax

HRESULT SetMediaTypeForVB(
    long Val
);

Parameters

Val
[in] Value that specifies the media type. Set the value to 0 for video, or 1 for audio.

Return Value

Returns S_OK.

Remarks

This method is intended for Automation clients. For C++ applications, use the SetMediaType method.

IAMTimelineGroup::SetOutputBuffering

IAMTimelineGroup Interface

Specifies the number of frames rendered in advance during preview.

Syntax

HRESULT SetOutputBuffering(
    int nBuffer
);

Parameters

nBuffer
[in] Number of frames to buffer during preview. Must be two or greater.

Return Value

Returns S_OK if successful, or E_INVALIDARG otherwise.

Remarks

A larger buffer requires more memory but can result in smoother previewing, especially during effects or transitions that require more time to render. The default buffer is 30 frames.

IAMTimelineGroup::SetOutputFPS

IAMTimelineGroup Interface

Sets the uncompressed output frame rate for this group.

Syntax

HRESULT SetOutputFPS(
    double FPS
);

Parameters

FPS
Output frame rate for this group, in frames per second. The value cannot equal zero, and cannot have more than seven digits after the decimal place.

Return Value

Returns S_OK if successful, or E_INVALIDARG otherwise.

Remarks

Rendered output from this group runs at the specified frame rate, and all edits on the source material are rounded to the nearest frame boundary, as defined by the frame rate.

The SetSmartRecompressFormat method overwrites the frame rate.

IAMTimelineGroup::SetPreviewMode

IAMTimelineGroup Interface

Sets the preview mode for the group.

Syntax

HRESULT SetPreviewMode(
    BOOL fPreview
);

Parameters

fPreview
Boolean value that specifies the preview mode. If TRUE, the group is in preview mode. If FALSE, the group is in authoring mode.

Return Value

Returns S_OK.

Remarks

In preview mode, frames are dropped during slow effects or transitions to keep the video synchronized with the audio. The video might look choppy as a result. In authoring mode, every frame is rendered. Authoring mode is appropriate for writing files; for on-screen preview, the video might be out of sync with the audio.

IAMTimelineGroup::SetRecompFormatFromSource

IAMTimelineGroup Interface

Sets the video recompression format using the compression format from a source file.

Syntax

HRESULT SetRecompFormatFromSource(
    IAMTimelineSrc *pSource
);

Parameters

pSource
Pointer to the IAMTimelineSrc interface of the source object.

Return Value

Returns an HRESULT values. Possible values include the following.

S_OK | Success.
E_NO_TIMELINE | The group is not within a timeline.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type. The group is not a video group, or the source file has no video stream.

Remarks

This method finds the source file associated with pSource, retrieves the media type of the first video stream in the file, and sets the group compression format using that type. For more information about compression formats, see SetSmartRecompressFormat.

IAMTimelineGroup::SetSmartRecompressFormat

IAMTimelineGroup Interface

Specifies a compression format to use for smart recompression.

Smart recompression is not supported for audio groups.

Syntax

HRESULT SetSmartRecompressFormat(
    long *pFormat
);

Parameters

pFormat
Pointer to a structure describing the compression format. Currently, only the SCompFmt0 structure is valid. You must cast this parameter to a pointer of type long.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_POINTER | NULL pointer argument.
E_INVALIDARG | Invalid argument.

Remarks

Before calling this method, call the SetMediaType method on the same group, to specify an uncompressed format. The compressed and uncompressed formats must have the same width, height, and frame rate. If these values do not match, the group output pin produces uncompressed output instead of compressed output.

This method overwrites any frame rate value that was set using the SetOutputFPS method.

The smart recompression format is not persistent. If an application uses smart recompression, it must set the recompression format whenever it loads a project file.

IAMTimelineGroup::SetTimeline

IAMTimelineGroup Interface

Not supported. Call the IAMTimeline::AddGroup method instead.

Syntax

HRESULT SetTimeline(
    IAMTimeline *pTimeline
);


IAMTimelineObj Interface

Provides methods for manipulating timeline objects in Microsoft® DirectShow® Editing Services (DES). All timeline objects implement this method, including source, effect, transition, track, group, and composition objects. Create a timeline object by calling the IAMTimeline::CreateEmptyNode method.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimelineObj Methods | Description
GetStartStop | Retrieves the object's start and stop times, relative to the object's parent.
GetStartStop2 | Equivalent to GetStartStop, but takes REFTIME values.
FixTimes | Rounds the specified start and stop times to the nearest frame boundaries, as defined by the parent group's frame rate setting.
FixTimes2 | Equivalent to FixTimes, but takes REFTIME values.
SetStartStop | Sets the object's start and stop times, relative to the timeline.
SetStartStop2 | Equivalent to SetStartStop, but takes REFTIME values.
GetPropertySetter | Retrieves the object's property setter.
SetPropertySetter | Sets the object's property setter.
GetSubObject | Retrieves the subobject associated with this object.
SetSubObject | Not supported.
SetSubObjectGUID | Specifies the globally unique identifier (GUID) of the subobject associated with this object.
SetSubObjectGUIDB | Equivalent to SetSubObjectGUID, but takes a BSTR value.
GetSubObjectGUID | Retrieves the GUID of the subobject associated with this timeline object.
GetSubObjectGUIDB | Equivalent to GetSubObjectGUID, but receives a BSTR value.
GetSubObjectLoaded | Determines whether the object's subobject pointer has been set.
GetTimelineType | Retrieves the object's type.
SetTimelineType | Not supported.
SetUserID | Sets an application-defined identifier for the object.
GetUserID | Retrieves the object's application-defined identifier.
GetGenID | Retrieves the object's generated identifier.
SetUserName | Sets an application-defined name for the object.
GetUserName | Retrieves the object's application-defined name.
SetUserData | Sets application-defined persistent data.
GetUserData | Retrieves the application-defined persistent data.
SetMuted | Sets the object's muted state.
GetMuted | Retrieves the object's muted state.
SetLocked | Sets the object's editing state to locked or unlocked.
GetLocked | Retrieves the object's editing state (locked or unlocked).
GetDirtyRange | Not supported.
GetDirtyRange2 | Not supported.
SetDirtyRange | Not implemented.
SetDirtyRange2 | Not implemented.
ClearDirty | Not supported.
Remove | Removes this object from the timeline, for reinsertion elsewhere.
RemoveAll | Permanently removes this object from the timeline, including subobjects and children.
GetTimelineNoRef | Not supported.
GetGroupIBelongTo | Not supported.
GetEmbedDepth | Not supported.

IAMTimelineObj::ClearDirty

IAMTimelineObj Interface

Not supported.

Syntax

HRESULT ClearDirty( void );

IAMTimelineObj::FixTimes

IAMTimelineObj Interface

Rounds the specified start and stop times to the nearest frame boundaries, as defined by the parent group's frame rate setting.

Syntax

HRESULT FixTimes(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

Parameters

pStart
Pointer to a variable that contains the start time, in 100-nanosecond units. If the call succeeds, this variable is set to the rounded time.
pStop
Pointer to a variable that contains the stop time, in 100-nanosecond units. If the call succeeds, this variable is set to the rounded time.

Return Value

Returns S_OK if successful, or E_NOTINTREE if the object is not part of a group.

Remarks

During rendering, DES rounds the object's start and stop times to the nearest frame boundary. However, DES does not overwrite the object's times. If you change the group frame rate, the rounded times are always calculated from the original times. For more information, see Frame Rates.

Use this method to determine accurate start and stop times in the rendered project. For example, you should seek to the rounded times, rather than the object's original start and stop times. Call GetStartStop to obtain the original times, and pass those values to FixTimes.

IAMTimelineObj::FixTimes2

IAMTimelineObj Interface

Rounds the specified start and stop times to the nearest frame boundaries, as defined by the parent group's frame rate setting. This method is equivalent to FixTimes, but takes REFTIME values.

Syntax

HRESULT FixTimes2(
    REFTIME *pStart,
    REFTIME *pStop
);

Parameters

pStart
Pointer to a variable that contains the start time, in seconds. If the call succeeds, this variable is set to the rounded time.
pStop
Pointer to a variable that contains the stop time, in seconds. If the call succeeds, this variable is set to the rounded time.

Return Value

Returns S_OK if successful, or E_NOTINTREE if the object is not part of a group.

IAMTimelineObj::GetDirtyRange

IAMTimelineObj Interface

Not supported.

Syntax

HRESULT GetDirtyRange(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

IAMTimelineObj::GetDirtyRange2

IAMTimelineObj Interface

Not supported.

Syntax

HRESULT GetDirtyRange2(
    REFTIME *pStart,
    REFTIME *pStop
);

IAMTimelineObj::GetEmbedDepth

IAMTimelineObj Interface

Not supported.

Syntax

HRESULT GetEmbedDepth(
    long *pVal
);

IAMTimelineObj::GetGenID

IAMTimelineObj Interface

Retrieves the object's generated identifier. The identifier is a reserved number; applications should not use it.

Syntax

HRESULT GetGenID(
    long *pVal
);

Parameters

pVal
Pointer to a variable that receives the generated identifier.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineObj::GetGroupIBelongTo

IAMTimelineObj Interface

Not supported.

Syntax

HRESULT GetGroupIBelongTo(
    IAMTimelineGroup **ppGroup
);

IAMTimelineObj::GetLocked

IAMTimelineObj Interface

Retrieves the object's editing state (locked or unlocked). A locked state indicates that the object should not be edited; an unlocked state indicates that the object can be edited. The timeline does not enforce the lock. The locked setting exists only for the convenience of the application.

Syntax

GetLocked(
    BOOL *pVal
);

Parameters

pVal
Pointer to a Boolean variable that receives the object's editing state. If the value is TRUE, the object is locked and should not be edited. If FALSE, the object is unlocked and can be edited.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineObj::GetMuted

IAMTimelineObj Interface

Retrieves the object's muted state.

Syntax

HRESULT GetMuted(
    BOOL *pVal
);

Parameters

pVal
Pointer to a Boolean variable that receives a value indicating the muted state. If the value is TRUE, the object and its children are muted.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If an object's parent is muted, the object is muted regardless of its muted state. When the parent is no longer muted, the object's previous muted state is restored.

IAMTimelineObj::GetPropertySetter

IAMTimelineObj Interface

Retrieves the object's property setter. When the object is rendered, the property information contained in the property setter is applied to the object.

Syntax

HRESULT GetPropertySetter(
    IPropertySetter **pVal
);

Parameters

pVal
[out, retval] Address of a pointer that receives the property setter's IPropertySetter interface. If the object does not have a property setter, the value is set to NULL.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

If the value returned in pVal is not NULL, the IPropertySetter interface has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimelineObj::GetStartStop

IAMTimelineObj Interface

Retrieves the object's start and stop times, relative to the object's parent.

Syntax

HRESULT GetStartStop(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

Parameters

pStart
Pointer to a variable that receives the start time, in 100-nanosecond units.
pStop
Pointer to a variable that receives the stop time, in 100-nanosecond units.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

Compositions, groups, and tracks always have a start time of 0.

During rendering, DES rounds an object's start and stop times to the nearest frame boundary. However, DES does not overwrite the object's times. If you change the group frame rate, the rounded times are always calculated from the original times. For more information, see Frame Rates.

To determine the start and stop times in the rendered project, pass the values returned by GetStartStop to the FixTimes method.

IAMTimelineObj::GetStartStop2

IAMTimelineObj Interface

Retrieves the object's start and stop times, relative to the object's parent. This method is equivalent to GetStartStop, but takes REFTIME values.

Syntax

HRESULT GetStartStop2(
    REFTIME *pStart,
    REFTIME *pStop
);

Parameters

pStart
Pointer to a variable that receives the start time, in seconds.
pStop
Pointer to a variable that receives the stop time, in seconds.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineObj::GetSubObject

IAMTimelineObj Interface

Retrieves the subobject associated with this object.

Syntax

HRESULT GetSubObject(
    IUnknown **pVal
);

Parameters

pVal
[out, retval] Address of a pointer that receives the subobject's IUnknown interface. If the object does not have a subobject, the value is set to NULL.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

Every timeline object can hold a pointer to an associated subobject. For example, the subobject of an effect is typically a Microsoft® DirectX® Transform object that generates the effect.

If the value returned in pVal is not NULL, the IUnknown interface has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimelineObj::GetSubObjectGUID

IAMTimelineObj Interface

Retrieves the GUID of the subobject associated with this timeline object.

Syntax

HRESULT GetSubObjectGUID(
    GUID *pVal
);

Parameters

pVal
Pointer to a variable that receives the GUID of the subobject, or GUID_NULL if the object does not have a subobject.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineObj::GetSubObjectGUIDB

IAMTimelineObj Interface

Retrieves the GUID of the subobject associated with this timeline object. This method is equivalent to GetSubObjectGUID, but receives a BSTR value.

Syntax

HRESULT GetSubObjectGUIDB(
    BSTR *pVal
);

Parameters

pVal
[out, retval] Pointer to a BSTR that receives a string representing the subobject GUID.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

IAMTimelineObj::GetSubObjectLoaded

IAMTimelineObj Interface

Determines whether the object's subobject pointer has been set.

Syntax

HRESULT GetSubObjectLoaded(
    BOOL *pVal
);

Parameters

pVal
Pointer to a variable that receives a Boolean value. If the value is TRUE, the subobject pointer has been set. If FALSE, the pointer has not been set.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineObj::GetTimelineNoRef

IAMTimelineObj Interface

Not supported.

Syntax

HRESULT GetTimelineNoRef(
    IAMTimeline **ppResult
);

IAMTimelineObj::GetTimelineType

IAMTimelineObj Interface

Retrieves the object's type.

Syntax

HRESULT GetTimelineType(
    TIMELINE_MAJOR_TYPE *pVal
);

Parameters

pVal
Pointer to a variable that receives a member of the TIMELINE_MAJOR_TYPE enumerated type, indicating the type of object.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineObj::GetUserData

IAMTimelineObj Interface

Retrieves the application-defined persistent data.

Syntax

HRESULT GetUserData(
    BYTE *pData,
    long *pSize
);

Parameters

pData
Pointer to a buffer that receives the data. To determine the size of buffer to allocate, set this parameter to NULL. The required size is returned in pSize.
pSize
Pointer to a variable that receives the size of the data, in bytes.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineObj::GetUserID

IAMTimelineObj Interface

Retrieves the object's application-defined identifier.

Syntax

HRESULT GetUserID(
    long *pVal
);

Parameters

pVal
Pointer to a variable that receives the application-defined identifier.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineObj::GetUserName

IAMTimelineObj Interface

Retrieves the object's application-defined name.

Syntax

HRESULT GetUserName(
    BSTR *pVal
);

Parameters

pVal
[out, retval] Pointer to a BSTR that receives the name of the object.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

IAMTimelineObj::Remove

IAMTimelineObj Interface

Removes this object from the timeline (including subobjects but not children), for reinsertion elsewhere.

Syntax

HRESULT Remove( void );

Return Value

Returns S_OK.

Remarks

Call this method only if the application will immediately insert the object back into the timeline. It is an invalid operation to call this method without then reinserting the object. To remove an object permanently, call RemoveAll.

IAMTimelineObj::RemoveAll

IAMTimelineObj Interface

Permanently removes this object from the timeline, including subobjects and children.

Syntax

HRESULT RemoveAll( void );

Return Value

Returns S_OK.

Remarks

To remove an object for the purpose of reinserting it elsewhere in the timeline, call Remove.

IAMTimelineObj::SetDirtyRange

IAMTimelineObj Interface

Not implemented.

Syntax

HRESULT SetDirtyRange(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

IAMTimelineObj::SetDirtyRange2

IAMTimelineObj Interface

Not implemented.

Syntax

HRESULT SetDirtyRange2(
    REFTIME Start,
    REFTIME Stop
);

IAMTimelineObj::SetLocked

IAMTimelineObj Interface

Sets the object's editing state to locked or unlocked. A locked state indicates that the object should not be edited; an unlocked state indicates that the object can be edited. The timeline does not enforce the lock. The locked setting exists only for the convenience of the application.

Syntax

HRESULT SetLocked(
    BOOL newVal
);

Parameters

newVal
Boolean value that specifies the object's editing state. If TRUE, the object is locked and should not be edited. If FALSE, the object is unlocked and can be edited.

Return Value

Returns S_OK.

IAMTimelineObj::SetMuted

IAMTimelineObj Interface

Sets the object's muted state. A muted object is not rendered, but it remains in the timeline.

Syntax

HRESULT SetMuted(
    BOOL newVal
);

Parameters

newVal
Flag that specifies the muted state. If TRUE, the object and all of its children are muted.

Return Value

Returns S_OK.

Remarks

Muting an object also mutes any children contained in the object. For example, if you mute a track, the transitions, sources, and effects in that track are also muted. Once the object is no longer muted, its children revert to their previous state, which might be muted or unmuted.

IAMTimelineObj::SetPropertySetter

IAMTimelineObj Interface

Sets the object's property setter. When the object is rendered, the property information contained in the property setter is applied to the object. Call this method on transition and effect objects.

Syntax

HRESULT SetPropertySetter(
    IPropertySetter *newVal
);

Parameters

newVal
Pointer to the property setter's IPropertySetter interface.

Return Value

Returns S_OK.

IAMTimelineObj::SetStartStop

IAMTimelineObj Interface

Sets the object's start and stop times, relative to the object's parent.

Syntax

HRESULT SetStartStop(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

Parameters

Start
New start time, in 100-nanosecond units, or –1 to keep the existing start time.
Stop
New stop time, in 100-nanosecond units, or –1 to keep the existing stop time.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

Remarks

Tracks, compositions, and groups do not implement this method. For these objects, the start time is always zero, and the stop time is the maximum stop time of the objects they contain.

Do not set overlapping times on source objects within the same track. Doing so can cause undefined behaviors.

For source objects, the start and stop times are independent of the media start and media stop times. Changing one pair of values does not change the other. To set the media start and stop times, call the IAMTimelineSrc::SetMediaTimes method. For more information, see Time in DirectShow Editing Services.

IAMTimelineObj::SetStartStop2

IAMTimelineObj Interface

Sets the object's start and stop times, relative to the object's parent. This method is equivalent to SetStartStop, but takes REFTIME values.

Syntax

HRESULT SetStartStop2(
    REFTIME Start,
    REFTIME Stop
);

Parameters

Start
New start time, in seconds, or –1 to keep the existing start time.
Stop
New stop time, in seconds, or –1 to keep the existing stop time.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

IAMTimelineObj::SetSubObject

IAMTimelineObj Interface

Not supported.

Syntax

HRESULT SetSubObject(
    IUnknown *newVal
);

IAMTimelineObj::SetSubObjectGUID

IAMTimelineObj Interface

Specifies the GUID of the subobject associated with this object.

Syntax

HRESULT SetSubObjectGUID(
    GUID newVal
);

Parameters

newVal
GUID of the subobject.

Return Value

Returns S_OK.

Remarks

The render engine creates an instance of the subobject as needed.

IAMTimelineObj::SetSubObjectGUIDB

IAMTimelineObj Interface

Specifies the GUID of the subobject associated with this object. This method is equivalent to SetSubObjectGUID but takes a BSTR value.

Syntax

HRESULT SetSubObjectGUIDB(
    BSTR newVal
);

Parameters

newVal
BSTR representing the GUID of the subobject.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

IAMTimelineObj::SetTimelineType

IAMTimelineObj Interface

Not supported. Call the IAMTimeline::CreateEmptyNode method to create a new timeline object. Once an object is created, you cannot change its type.

Syntax

HRESULT SetTimelineType(
    TIMELINE_MAJOR_TYPE newVal
);

IAMTimelineObj::SetUserData

IAMTimelineObj Interface

Sets application-defined persistent data.

Syntax

HRESULT SetUserData(
    BYTE *pData,
    long Size
)

Parameters

pData
Pointer to a buffer containing the data.
Size
Size of the data, in bytes.

Return Value

Returns S_OK if successful, or E_OUTOFMEMORY if there is insufficient memory.

IAMTimelineObj::SetUserID

IAMTimelineObj Interface

Sets an application-defined identifier for the object.

Syntax

HRESULT SetUserID(
    long newVal
);

Parameters

newVal
Value that specifies the identifier. This identifier is used only by the application and can be any value.

Return Value

Returns S_OK.

IAMTimelineObj::SetUserName

IAMTimelineObj Interface

Sets an application-defined name for the object.

Syntax

HRESULT SetUserName(
    BSTR newVal
);

Parameters

newVal
Wide-character string that contains the name. Strings longer than 256 characters might be truncated.

Return Value

Returns S_OK.


IAMTimelineSplittable Interface

Splits a timeline object in Microsoft® DirectShow® Editing Services (DES). Sources, effects, transitions, and tracks implement this interface.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimelineSplittable Methods | Description
SplitAt | Splits the object at the specified time.
SplitAt2 | Equivalent to SplitAt, but takes a REFTIME value.

IAMTimelineSplittable::SplitAt

IAMTimelineSplittable Interface

Splits the object at the specified time.

Syntax

HRESULT SplitAt(
    REFERENCE_TIME Time
);

Parameters

Time
Time at which to split the object, relative to the start of the object, in 100-nanosecond units.

Return Value

Returns an HRESULT value. Possible values include the following:

S_FALSE | Nothing to split.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.

Remarks

If you split a source, effect, or transition, this method creates a second object of the same type. The original object is truncated at the specified split time, and the new object replaces the truncated portion. The new object inherits all of the same properties. In a source object, the method also splits any effects that fall on the split time.

Calling this method on a track splits all the sources, effects, and transitions that are contained in the track at the specified split time. It does not create a second track. (A track begins at time zero and extends to infinity.) If the split time is later than everything in the track, the method returns S_FALSE.

IAMTimelineSplittable::SplitAt2

IAMTimelineSplittable Interface

Splits the object at the specified time. This method is equivalent to SplitAt, but takes a REFTIME value.

Syntax

HRESULT SplitAt2(
    REFTIME Time
);

Parameters

Time
Time at which to split the object, relative to the start of the object, in seconds.

Return Value

Returns an HRESULT value. Possible values include the following:

S_FALSE | Nothing to split.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.


IAMTimelineSrc Interface

Provides methods for manipulating and setting properties on source objects in Microsoft® DirectShow® Editing Services (DES). A source object represents one stream from a media source.

You can use a portion of the data within a source file by setting the media start and media stop times. These values specify the beginning and end of the source object, relative to the original media source. The media times can differ from the object's start and stop times on the timeline, allowing for fast- or slow-motion playback. (With audio sources, pitch shifting occurs.)

For more information, see Constructing a Timeline and Working with Sources.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimelineSrc Methods | Description
GetMediaTimes | Retrieves the media start and stop times.
GetMediaTimes2 | Equivalent to GetMediaTimes, but takes REFTIME values.
ModifyStopTime | Sets the stop time, relative to the timeline.
ModifyStopTime2 | Equivalent to ModifyStopTime, but takes REFTIME values.
FixMediaTimes | Rounds the specified time values to the nearest frame boundary, as defined by the output frame rate.
FixMediaTimes2 | Equivalent to FixMediaTimes, but takes REFTIME values.
SetMediaTimes | Sets the media stop and start times.
SetMediaTimes2 | Equivalent to SetMediaTimes, but takes REFTIME values.
SetMediaLength | Specifies the duration of the source file.
SetMediaLength2 | Equivalent to SetMediaLength, but takes REFTIME values.
GetMediaLength | Retrieves the media length of this source object.
GetMediaLength2 | Equivalent to GetMediaLength, but takes REFTIME values.
GetMediaName | Retrieves the name of the source file represented by this source object.
SetMediaName | Specifies the name of the source file represented by this source object.
SpliceWithNext | Joins this source object to another source object.
GetStreamNumber | Retrieves the current stream number for the source object.
SetStreamNumber | Specifies which stream to read from the source file associated with this source object.
IsNormalRate | Indicates whether the clip will play at the normal playback rate.
GetDefaultFPS | Retrieves the source object's default frame rate.
SetDefaultFPS | Sets the source object's default frame rate.
GetStretchMode | Retrieves the stretch mode of a video source.
SetStretchMode | Sets the stretch mode of a video source.

IAMTimelineSrc::FixMediaTimes

IAMTimelineSrc Interface

Rounds the specified time values to the nearest frame boundary, as defined by the output frame rate. In general, applications do not need to call this method.

Syntax

HRESULT FixMediaTimes(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

Parameters

pStart
Pointer to a variable that contains the start time, in 100-nanosecond units. If the call succeeds, this variable is set to the rounded time.
pStop
Pointer to a variable that contains the stop time, in 100-nanosecond units. If the call succeeds, this variable is set to the rounded time.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

This method is similar to the IAMTimelineObj::FixTimes method, but it preserves the original ratio of media times and timeline times. Just rounding the times to the nearest frame boundary could distort this ratio.

IAMTimelineSrc::FixMediaTimes2

IAMTimelineSrc Interface

Rounds the specified time values to the nearest frame boundary, as defined by the output frame rate. This method is equivalent to FixMediaTimes, but takes REFTIME values.

Syntax

HRESULT FixMediaTimes2(
    REFTIME *pStart,
    REFTIME *pStop
);

Parameters

pStart
Pointer to a variable that contains the start time, in seconds. If the call succeeds, this variable is set to the rounded time.
pStop
Pointer to a variable that contains the stop time, in seconds. If the call succeeds, this variable is set to the rounded time.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineSrc::GetDefaultFPS

IAMTimelineSrc Interface

Retrieves the source object's default frame rate. The render engine uses this value if it cannot determine the frame rate from the original source.

Syntax

HRESULT GetDefaultFPS(
    double *pFPS
);

Parameters

pFPS
Pointer to a variable that receives the default frame rate, in frames per second.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

The default frame rate is not required if the file format specifies the frame rate. This is the case for audio and video formats.

If the source is a bitmap or JPEG image, the render engine uses it as the first image in a device-independent bitmap (DIB) sequence, with a frame rate equal to the default frame rate. To render a static image, rather than a DIB sequence, set the default frame rate to 0.

If the source is a GIF, do not set the frame rate. For animated GIFs, the GIF file specifies the delay between each image.

IAMTimelineSrc::GetMediaLength

IAMTimelineSrc Interface

Retrieves the media length of this source object.

Syntax

HRESULT GetMediaLength(
    REFERENCE_TIME *pLength
);

Parameters

pLength
Pointer to a variable that receives the media length in 100-nanosecond units.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_NOTDETERMINED | Media times are not set on this object.
E_POINTER | NULL pointer argument.

See Also

SetMediaLength

IAMTimelineSrc::GetMediaLength2

IAMTimelineSrc Interface

Retrieves the media length of this source object. This method is equivalent to GetMediaLength, but takes REFTIME values.

Syntax

HRESULT GetMediaLength2(
    REFTIME *pLength
);

Parameters

pLength
Pointer to a variable that receives the media length in seconds.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_NOTDETERMINED | Media times are not set on this object.
E_POINTER | NULL pointer argument.

IAMTimelineSrc::GetMediaName

IAMTimelineSrc Interface

Retrieves the name of the source file represented by this source object.

Syntax

HRESULT GetMediaName(
    BSTR *pVal
);

Parameters

pVal
[out, retval] Pointer to a string that receives the name of the file.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

IAMTimelineSrc::GetMediaTimes

IAMTimelineSrc Interface

Retrieves the media start and stop times.

Syntax

HRESULT GetMediaTimes(
    REFERENCE_TIME *pStart,
    REFERENCE_TIME *pStop
);

Parameters

pStart
Pointer to a variable that receives the media start time, in 100-nanosecond units.
pStop
Pointer to a variable that receives the media stop time, in 100-nanosecond units.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

The media times are relative to the original media file. For more information, see Time in DirectShow Editing Services.

IAMTimelineSrc::GetMediaTimes2

IAMTimelineSrc Interface

Retrieves the media start and stop times. This method is equivalent to GetMediaTimes, but takes REFTIME values.

Syntax

HRESULT GetMediaTimes2(
    REFTIME *pStart,
    REFTIME *pStop
);

Parameters

pStart
Pointer to a variable that receives the media start time, in seconds.
pStop
Pointer to a variable that receives the media stop time, in seconds.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineSrc::GetStreamNumber

IAMTimelineSrc Interface

Retrieves the current stream number for the source object.

Syntax

HRESULT GetStreamNumber(
    long *pVal
);

Parameters

pVal
Pointer to a variable that receives the stream number.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineSrc::GetStretchMode

IAMTimelineSrc Interface

Retrieves the stretch mode. The stretch mode determines how a video source is rendered if its size does not match the output dimensions.

Syntax

HRESULT GetStretchMode(
    int *pnStretchMode
);

Parameters

pnStretchMode
Pointer to a variable that receives a flag indicating the current stretch mode. Possible values include the following:
  • RESIZEF_STRETCH
  • RESIZEF_CROP
  • RESIZEF_PRESERVEASPECTRATIO
  • RESIZEF_PRESERVEASPECTRATIO_NOLETTERBOX

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineSrc::IsNormalRate

IAMTimelineSrc Interface

Indicates whether the clip will play at the normal playback rate; that is, the playback rate of the original file.

Syntax

HRESULT IsNormalRate(
    BOOL *pVal
);

Parameters

pVal
Pointer to a variable that receives a Boolean value indicating how the clip will render. If the value is TRUE, the clip will play at the normal rate. Otherwise, it will play faster or slower than normal.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

Remarks

A clip's playback rate is determined by its media start and stop times, relative to its timeline times:

Playback rate = (Media Stop — Media Start) / (Timeline Stop — Timeline Start)

If this ratio is equal to 1, the clip plays at the authored speed. Otherwise, it plays faster or slower. For more information, see Time in DirectShow Editing Services.

IAMTimelineSrc::ModifyStopTime

IAMTimelineSrc Interface

Sets the stop time, relative to the timeline.

Syntax

HRESULT ModifyStopTime(
    REFERENCE_TIME Stop
);

Parameters

Stop
New stop time, in 100-nanosecond units.

Return Value

Returns S_OK, or E_INVALIDARG if the specified time is not valid.

Remarks

This method is equivalent to calling IAMTimelineObj::SetStartStop with the original start time and a new stop time.

IAMTimelineSrc::ModifyStopTime2

IAMTimelineSrc Interface

Sets the stop time. This method is equivalent to ModifyStopTime, but takes a REFTIME value.

Syntax

HRESULT ModifyStopTime2(
    REFTIME Stop
);

Parameters

Stop
New stop time, in seconds.

Return Value

Returns S_OK if successful, or E_INVALIDARG if the specified time is not valid.

IAMTimelineSrc::SetDefaultFPS

IAMTimelineSrc Interface

Sets the source object's default frame rate.

Syntax

HRESULT SetDefaultFPS(
    double FPS
);

Parameters

FPS
Default frame rate, in frames per second.

Return Value

Returns S_OK if successful, or E_INVALIDARG if the specified frame rate is less than zero.

Remarks

The render engine uses this value if it cannot determine the frame rate from the original source file.

Call this method only for source files without a predefined frame rate. For bitmap and JPEG files, the default frame rate is zero, which causes the source to be rendered as a still image. To use the image as the first frame in a DIB sequence, set the frame rate to a value greater than zero. For more information, see Working with Sources.

IAMTimelineSrc::SetMediaLength

IAMTimelineSrc Interface

Specifies the duration of the source file.

Syntax

HRESULT SetMediaLength(
    REFERENCE_TIME Length
);

Parameters

Length
Media length, in 100-nanosecond units.

Return Value

Returns S_OK.

Remarks

You can avoid potential rendering errors by setting the media length before you set the media stop time. When you set the media stop time, DES checks it against the media length.

This method does not validate the Length parameter, but the value must equal the actual duration of the source file. Obtain the source file duration by calling IMediaDet::get_StreamLength.

IAMTimelineSrc::SetMediaLength2

IAMTimelineSrc Interface

Specifies the duration of the source file. This method is equivalent to SetMediaLength, but takes a REFTIME value.

Syntax

HRESULT SetMediaLength2(
    REFTIME Length
);

Parameters

Length
Media length, in seconds.

Return Value

Returns S_OK.

IAMTimelineSrc::SetMediaName

IAMTimelineSrc Interface

Specifies the name of the source file represented by this source object.

Syntax

HRESULT SetMediaName(
    BSTR newVal
);

Parameters

newVal
String that specifies the name of the media file.

Return Value

Returns S_OK.

IAMTimelineSrc::SetMediaTimes

IAMTimelineSrc Interface

Sets the media stop and start times.

Syntax

HRESULT SetMediaTimes(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

Parameters

Start
Media start time, in 100-nanosecond units.
Stop
Media stop time, in 100-nanosecond units.

Return Value

Returns S_OK.

Remarks

The media times are the stop and start times relative to the original media file. Always set the media times when you add a video or audio source to the timeline. Otherwise, rendering problems might occur. The stop time must be greater than the start time.

To use a still frame from a video source, set the stop time to a fractional amount more than the start time, such as 100 nanoseconds. Setting them to the same value causes a rendering error.

If the timeline duration does not match the media duration, the source stretches or shrinks accordingly. This causes the clip to play slower or faster than the authored rate. (Pitch shifting will occur in an audio source.) For more information, see Time in DirectShow Editing Services.

You can specify the duration of the source file by calling the SetMediaLength method. If you set a media stop time that exceeds the duration, DES truncates the stop time.

IAMTimelineSrc::SetMediaTimes2

IAMTimelineSrc Interface

Sets the media stop and start times. This method is equivalent to SetMediaTimes, but takes REFTIME values.

Syntax

HRESULT SetMediaTimes2(
    REFTIME Start,
    REFTIME Stop
);

Parameters

Start
Media start time, in seconds.
Stop
Media stop time, in seconds.

Return Value

Returns S_OK.

IAMTimelineSrc::SetStreamNumber

IAMTimelineSrc Interface

Specifies which stream to read from the source file associated with this source object.

Syntax

HRESULT SetStreamNumber(
    long Val
);

Parameters

Val
The stream number, from the set of streams matching the media type of the parent group.

Return Value

Returns S_OK if successful, or E_INVALIDARG if Val is less than zero.

Remarks

The Val parameter specifies a stream number from the set of streams that matches the parent group's media type, not from the entire set of streams in the source file. For example, For example, suppose that a file contains two video streams and two audio streams. If the source object is inside a video group, setting Val to 0 selects the first video stream. The caller is responsible for specifying a valid stream number.

The stream number defaults to zero.

IAMTimelineSrc::SetStretchMode

IAMTimelineSrc Interface

Sets the stretch mode. The stretch mode determines how a video source is rendered if its size does not match the output dimensions.

Syntax

HRESULT SetStretchMode(
    int nStretchMode
);

Parameters

nStretchMode
Flag indicating the current stretch mode. Possible values include the following:
  • RESIZEF_STRETCH
  • RESIZEF_CROP
  • RESIZEF_PRESERVEASPECTRATIO
  • RESIZEF_PRESERVEASPECTRATIO_NOLETTERBOX

Return Value

Returns S_OK.

IAMTimelineSrc::SpliceWithNext

IAMTimelineSrc Interface

Joins the source object to another source object.

Syntax

HRESULT SpliceWithNext(
    IAMTimelineObj *pNext
);

Parameters

pNext
Pointer to the IAMTimelineObj interface of the source object to join to the current source.

Return Value

Returns an HRESULT value. Possible return values include the following:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOINTERFACE | Object specified by pNext parameter is not a source object.
E_POINTER | NULL pointer argument.

Remarks

As currently implemented, this method discards any effects on pNext.

For this method to succeed, pNext must be a match frame of the current source object:

  • It must share the same source file.
  • The media start time must equal the media stop time of the current source.
  • The playback rate must be the same. Playback rate is media duration divided by timeline duration.


IAMTimelineTrack Interface

Provides methods for manipulating track objects in Microsoft® DirectShow® Editing Services (DES).

A track contains a list of sources that are rendered in the final output. Sources within the same track may not overlap. Video tracks can have both effects and transitions. The render engine applies effects before it applies transitions. Audio tracks can have effects, but not transitions.

For more information, see The Timeline Model.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimelineTrack Methods | Description
SrcAdd | Adds a source to the track.
GetNextSrc | Searches the track for the next source that appears at the specified time or later.
GetNextSrc2 | Equivalent to GetNextSrc, but takes a REFTIME value.
MoveEverythingBy | Moves all objects that start at a specified time or later, moving them a specified distance along the timeline.
MoveEverythingBy2 | Equivalent to MoveEverythingBy, but takes REFTIME values.
GetSourcesCount | Retrieves the number of sources in the track.
AreYouBlank | Determines whether the track is blank (contains no source objects).
GetSrcAtTime | Retrieves the source object nearest to the specified time, according to the specified boundary conditions.
GetSrcAtTime2 | Equivalent to GetSrcAtTime, but takes REFTIME values.
InsertSpace | Splits any objects that exist at the specified time and inserts space between them.
InsertSpace2 | Equivalent to InsertSpace, but takes REFTIME values.
ZeroBetween | Removes everything from the track between the specified times.
ZeroBetween2 | Equivalent to ZeroBetween, but takes REFTIME values.
GetNextSrcEx | Retrieves the next source after the specified source.

IAMTimelineTrack::AreYouBlank

IAMTimelineTrack Interface

Determines whether the track is blank (contains no source objects).

Syntax

HRESULT AreYouBlank(
    long *pVal
);

Parameters

pVal
Pointer to a variable that receives a Boolean value specifying whether the track is blank. If the value is TRUE, the track is blank and contains no source objects. If FALSE, the track is not blank.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineTrack::GetNextSrc

IAMTimelineTrack Interface

Searches the track for the next source that appears at the specified time or later.

Syntax

HRESULT GetNextSrc(
    IAMTimelineObj **ppSrc,
    REFERENCE_TIME *pInOut
);

Parameters

ppSrc
[out] Address of a pointer that receives the source object's IAMTimelineObj interface.
pInOut
Pointer to a variable that contains the start time for the search, in 100-nanosecond units. If the method retrieves a source, it sets the value to the stop time of the source. If the method does not retrieve a source, the value becomes invalid and the application should not use it.

Return Value

Returns S_OK if the method retrieves a source, or S_FALSE otherwise.

Remarks

If the time specified by pInOut falls between the start and stop times of a source, the method retrieves that source.

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimelineTrack::GetNextSrc2

IAMTimelineTrack Interface

Searches the track for the next source that appears at the specified time or later. This method is equivalent to GetNextSrc, but takes a REFTIME value.

Syntax

HRESULT GetNextSrc2(
    IAMTimelineObj **ppSrc,
    REFTIME *pInOut
);

Parameters

ppSrc
[out] Address of a pointer that receives the source object's IAMTimelineObj interface.
pInOut
Pointer to a variable that contains the start time for the search, in seconds. If the method retrieves a source, it sets the value to the stop time of the source. If the method does not retrieve a source, the value becomes invalid and the application should not use it.

Return Value

Returns S_OK if the method retrieves a source, or S_FALSE otherwise.

IAMTimelineTrack::GetNextSrcEx

IAMTimelineTrack Interface

Retrieves the next source after the specified source.

Syntax

HRESULT GetNextSrcEx(
    IAMTimelineObj *pLast,
    IAMTimelineObj **ppNext
);

Parameters

pLast
Pointer to the previous source object, or NULL to retrieve the first source in the track.
ppNext
[out] Address of a pointer that receives the next source object's IAMTimelineObj interface.

Return Value

Returns S_OK if the method retrieves a source, or S_FALSE otherwise.

Remarks

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimelineTrack::GetSourcesCount

IAMTimelineTrack Interface

Retrieves the number of sources in the track.

Syntax

HRESULT GetSourcesCount(
    long *pVal
);

Parameters

pVal
Pointer to a variable that receives the number of sources in the track.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineTrack::GetSrcAtTime

IAMTimelineTrack Interface

Retrieves the source object nearest to the specified time, according to the specified boundary conditions.

Syntax

HRESULT GetSrcAtTime(
    IAMTimelineObj **ppSrc,
    REFERENCE_TIME Time,
    long SearchDirection
);

Parameters

ppSrc
[out] Address of a pointer that receives the IAMTimelineObj interface of the source object.
Time
Start time for the search, in 100-nanosecond units.
SearchDirection
Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Return Value

Returns one of the following HRESULT values:

S_FALSE | Did not locate a source object.
S_OK | Located a source object.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimelineTrack::GetSrcAtTime2

IAMTimelineTrack Interface

Retrieves the source object nearest to the specified time, according to the specified boundary conditions. This method is equivalent to GetSrcAtTime, but takes a REFTIME value.

Syntax

HRESULT GetSrcAtTime2(
    IAMTimelineObj **ppSrc,
    REFTIME Time,
    long SearchDirection
);

Parameters

ppSrc
[out] Address of a pointer that receives the IAMTimelineObj interface of the source object.
Time
Start time for the search, in seconds.
SearchDirection
Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Return Value

Returns one of the following HRESULT values:

S_FALSE | Did not locate a source object.
S_OK | Located a source object.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

IAMTimelineTrack::InsertSpace

IAMTimelineTrack Interface

Splits any objects that exist at the specified time and inserts space between them.

Syntax

HRESULT InsertSpace(
    REFERENCE_TIME rtStart,
    REFERENCE_TIME rtEnd
);

Parameters

rtStart
Time at which to create the split, and the starting point of the inserted space, in 100-nanosecond units.
rtEnd
End point of the inserted space, in 100-nanosecond units.

Return Value

Returns an HRESULT value. Possible return values include the following:

S_FALSE | There are no objects at the specified time.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.

IAMTimelineTrack::InsertSpace2

IAMTimelineTrack Interface

Splits any objects that exist at the specified time and inserts space between them. This method is equivalent to InsertSpace, but takes REFTIME values.

Syntax

HRESULT InsertSpace2(
    REFTIME rtStart,
    REFTIME rtEnd
);

Parameters

rtStart
Time at which to create the split, and the starting point of the inserted space, in seconds.
rtEnd
End point of the inserted space, in seconds.

Return Value

Returns an HRESULT value. Possible return values include the following:

S_FALSE | There are no objects at the specified time.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.

IAMTimelineTrack::MoveEverythingBy

IAMTimelineTrack Interface

Moves all objects that start at a specified time or later, moving them a specified distance along the timeline.

Syntax

HRESULT MoveEverythingBy(
    REFERENCE_TIME Start,
    REFERENCE_TIME MoveBy
);

Parameters

Start
Starting time of the move, in 100-nanosecond units. Only objects that begin at this time or later are moved.
MoveBy
Amount of time along the timeline to move the objects, in 100-nanosecond units.

Return Value

Returns S_OK if any objects were moved, or S_FALSE if no objects were moved.

IAMTimelineTrack::MoveEverythingBy2

IAMTimelineTrack Interface

Moves all objects that start at a specified time or later, moving them a specified distance along the timeline. This method is equivalent to MoveEverythingBy, but takes REFTIME values.

Syntax

HRESULT MoveEverythingBy2(
    REFTIME Start,
    REFTIME MoveBy
);

Parameters

Start
Starting time of the move, in seconds. Only objects that begin at this time or later are moved.
MoveBy
Amount of time along the timeline to move the objects, in seconds.

Return Value

Returns S_OK if any objects were moved, or S_FALSE if no objects were moved.

IAMTimelineTrack::SrcAdd

IAMTimelineTrack Interface

Adds a source to the track.

Syntax

HRESULT SrcAdd(
    IAMTimelineObj *pSrc
);

Parameters

pSrc
Pointer to the source object's IAMTimelineObj interface.

Return Value

Returns S_OK if successful. Returns E_NOINTERFACE if the object is not a source object. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

Set the source's start and stop times before calling this method. (Call IAMTimelineObj::SetStartStop.)

Currently, DES cannot simultaneously render more than 75 sources that were compressed with Video Compression Manager (VCM) codecs. Also, if the project as a whole contains more than 75 such sources, you must use dynamic reconnection or DES cannot preview the project. For more information, see IRenderEngine::SetDynamicReconnectLevel.

IAMTimelineTrack::ZeroBetween

IAMTimelineTrack Interface

Removes everything from the track between the specified times. This method splits any objects that span the specified time range and removes the pieces that fall within the range.

Syntax

HRESULT ZeroBetween(
    REFERENCE_TIME rtStart,
    REFERENCE_TIME rtEnd
);

Parameters

rtStart
Beginning of the range to clear, in 100-nanosecond units.
rtEnd
End of the range to clear, in 100-nanosecond units.

Return Value

Returns an HRESULT value. Possible values include the following.

S_FALSE | The time range falls beyond everything in the track.
S_OK | Success.

IAMTimelineTrack::ZeroBetween2

IAMTimelineTrack Interface

Removes everything from the track between the specified times. This method is equivalent to ZeroBetween, but takes REFTIME values.

Syntax

HRESULT ZeroBetween2(
    REFTIME rtStart,
    REFTIME rtEnd
);

Parameters

rtStart
Beginning of the range to clear, in seconds.
rtEnd
End of the range to clear, in seconds.

Return Value

Returns an HRESULT value. Possible values include the following.

S_FALSE | The time range falls beyond everything in the track.
S_OK | Success.


IAMTimelineTrans Interface

Provides methods for manipulating transition objects in Microsoft® DirectShow® Editing Services (DES).

A transition is a progression between one layer and the rendered composite of all the layers with a lower priority. Objects that can have transitions implement the IAMTimelineTransable interface. To set properties on a transition, use the IPropertySetter interface. For more information about using transition, see Working with Effects and Transitions.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimelineTrans Methods | Description
GetCutPoint | Retrieves the cut point.
GetCutPoint2 | Equivalent to GetCutPoint, but takes a REFTIME value.
SetCutPoint | Sets the time at which the transition cuts from one source to the next, if the transition is rendered as a cut.
SetCutPoint2 | Equivalent to SetCutPoint, but takes a REFTIME value.
GetSwapInputs | Retrieves a value that indicates whether the transition inputs are swapped.
SetSwapInputs | Specifies whether the transition inputs are swapped.
GetCutsOnly | Determines whether the transition is rendered as a cut.
SetCutsOnly | Specifies whether the transition is rendered as a cut.

IAMTimelineTrans::GetCutPoint

IAMTimelineTrans Interface

Retrieves the cut point. If you render a transition as a cut, the cut point is the time when the transition cuts from one source to the next. By default, this value is the middle of the transition. For example, in a transition that spans one second, the default cut point is 0.5 seconds into the transition.

Syntax

HRESULT GetCutPoint(
    REFERENCE_TIME *pTLTime
);

Parameters

pTLTime
Pointer to a variable that receives the cut point, relative to the start time of the transition, in 100-nanosecond units.

Return Value

Returns one of the following HRESULT values:

S_FALSE | The cut point was not set. The value returned is the default value.
S_OK | The cut point was set to a value other than the default.
E_POINTER | NULL pointer argument.

See Also

SetCutPoint, GetCutsOnly, IAMTimeline::TransitionsEnabled

IAMTimelineTrans::GetCutPoint2

IAMTimelineTrans Interface

Retrieves the cut point. This method is equivalent to GetCutPoint, but takes a REFTIME value.

Syntax

HRESULT GetCutPoint2(
    REFTIME *pTLTime
);

Parameters

pTLTime
Pointer to a variable that receives the cut point, relative to the start time of the transition, in seconds.

Return Value

Returns one of the following HRESULT values:

S_FALSE | The cut point was not set. The value returned is the default value.
S_OK | The cut point was set to a value other than the default.
E_POINTER | NULL pointer argument.

IAMTimelineTrans::GetCutsOnly

IAMTimelineTrans Interface

Determines whether the transition is rendered as a cut. If so, the transition occurs instantaneously at the cut point.

Syntax

HRESULT GetCutsOnly(
    BOOL *pVal
);

Parameters

pVal
Pointer to a variable that receives a Boolean value specifying whether the transition is rendered as a cut. If TRUE, the transition is an instantaneous cut. If FALSE, the transition occurs over its normal duration.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

See Also

SetCutsOnly, GetCutPoint, IAMTimeline::TransitionsEnabled

IAMTimelineTrans::GetSwapInputs

IAMTimelineTrans Interface

Retrieves a value that indicates whether the transition inputs are swapped.

By default, a transition goes from the composite of all lower-priority layers to the layer where the transition resides. You can reverse this progression, so the transition goes from the layer where it resides back to the composite of lower-priority layers.

Syntax

HRESULT GetSwapInputs(
    BOOL *pVal
);

Parameters

pVal
Pointer to a variable that receives a Boolean value. If the value is FALSE, the transition goes from the composite of all lower-priority layers to the transition layer. If the value is TRUE, the transition goes in the opposite direction. The default value is FALSE.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IAMTimelineTrans::SetCutPoint

IAMTimelineTrans Interface

Sets the time at which the transition cuts from one source to the next, if the transition is rendered as a cut.

Syntax

HRESULT SetCutPoint(
    REFERENCE_TIME TLTime
)

Parameters

TLTime
Cut point relative to the start of the transition, in 100-nanosecond units. If the value falls outside the bounds of the transition, it is truncated to the nearest valid time.

Return Value

Returns S_OK.

Remarks

By default, the cut-point is the middle of the transition. For example, in a transition that spans one second, the default cut point is 0.5 seconds into the transition.

IAMTimelineTrans::SetCutPoint2

IAMTimelineTrans Interface

Sets the time at which the transition cuts from one source to the next, if the transition is rendered as a cut. This method is equivalent to SetCutPoint, but takes a REFTIME value.

Syntax

HRESULT SetCutPoint2(
    REFTIME TLTime
)

Parameters

TLTime
Cut point relative to the start of the transition, in seconds.

Return Value

Returns S_OK.

IAMTimelineTrans::SetCutsOnly

IAMTimelineTrans Interface

Specifies whether the transition is rendered as a cut. If so, the transition occurs instantly at the cut point. If a transition takes a long time to render, you might want to preview it as a cut to speed preview.

Syntax

HRESULT SetCutsOnly(
    BOOL Val
);

Parameters

Val
Boolean value that specifies whether to render the transition as a cut. If TRUE, the transition is rendered as an instantaneous cut. If FALSE, the transition renders over its normal duration.

Return Value

Returns S_OK.

Remarks

Rendering a transition as a cut is not compatible with swapping the inputs. (See SetSwapInputs.) If you call SetCutsOnly with a value of TRUE, it temporarily overrides the SetSwapInputs setting. The cuts-only setting is intended for preview, however, so this limitation does not affect file output—just remember to call SetCutsOnly with the value FALSE before writing the file.

IAMTimelineTrans::SetSwapInputs

IAMTimelineTrans Interface

Specifies whether the transition inputs are swapped.

By default, a transition goes from the composite of all lower-priority layers to the layer where the transition resides. You can reverse this progression, so the transition goes from the layer where it resides back to the composite of lower-priority layers. For more information, see Transition Direction.

Syntax

HRESULT SetSwapInputs(
    BOOL Val
);

Parameters

Val
Boolean value that specifies whether the inputs are swapped. If the value is FALSE, the transition goes from the composite of all lower-priority layers to the transition layer. If the value is TRUE, the transition goes in the opposite direction.

Return Value

Returns S_OK.

Remarks

This method does not change the direction of the visual effect. For example, a left-to-right wipe will still go from left to right. To change the direction, set the Progress property using the IPropertySetter interface.


IAMTimelineTransable Interface

Adds transitions to an object in Microsoft® DirectShow® Editing Services (DES). This interface is exposed by any object that can have transitions applied to it, including tracks, compositions, and groups. An object that implements this interface can have any number of transitions, but the transitions must not overlap in time.

Note Audio does not support transitions. Objects within audio groups can expose the IAMTimelineTransable interface, but the application should not add transitions to them.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimelineTransable Method | Description
TransAdd | Adds a transition to the object.
TransGetCount | Retrieves the number of transitions on this object.
GetNextTrans | Retrieves the first transition that appears at the specified time or later.
GetNextTrans2 | Equivalent to GetNextTrans, but takes REFTIME values.
GetTransAtTime | Retrieves the transition nearest to the specified time, according to the specified boundary conditions.
GetTransAtTime2 | Equivalent to GetTransAtTime, but takes a REFTIME value.

IAMTimelineTransable::GetNextTrans

IAMTimelineTransable Interface

Retrieves the first transition that appears at the specified time or later.

Syntax

HRESULT GetNextTrans(
    IAMTimelineObj **ppTrans,
    REFERENCE_TIME *pInOut
);

Parameters

ppTrans
[out] Address of a pointer to receive the transition object's IAMTimelineObj interface.
pInOut
Pointer to a variable that specifies the time in 100-nanosecond units. On input, this value specifies the time from which to find the transition. On output, if a transition is retrieved, this value is set to the stop time of the transition.

Return Value

Returns S_OK if the method retrieves a transition, or S_FALSE if it does not find a transition. Otherwise, returns an HRESULT value indicating the cause of the failure.

Remarks

The start time of the transition might be less than the time that you specify in pInOut, if the transition spans the specified time.

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimelineTransable::GetNextTrans2

IAMTimelineTransable Interface

Retrieves the first transition that appears at the specified time or later. This method is equivalent to GetNextTrans, but takes a REFTIME value.

Syntax

HRESULT GetNextTrans2(
    IAMTimelineObj **ppTrans,
    REFTIME *pInOut
);

Parameters

ppTrans
[out] Address of a pointer to receive the transition object's IAMTimelineObj interface.
pInOut
Pointer to a variable that specifies the time in seconds. On input, this value specifies the time from which to find the transition. On output, if a transition is retrieved, this value is set to the stop time of the transition.

Return Value

Returns S_OK if the method retrieves a transition, or S_FALSE if it does not find a transition. Otherwise, returns an HRESULT value indicating the cause of the failure.

IAMTimelineTransable::GetTransAtTime

IAMTimelineTransable Interface

Retrieves the transition nearest to the specified time, according to the specified boundary conditions.

Syntax

HRESULT GetTransAtTime(
    IAMTimelineObj **ppObj,
    REFERENCE_TIME Time,
    long SearchDirection
);

Parameters

ppObj
[out] Address of a pointer to receive the transition's IAMTimelineObj interface.
Time
Time from which to begin the search, in 100-nanosecond units.
SearchDirection
Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Return Value

Returns one of the following HRESULT values:

S_FALSE | No transition was found.
S_OK | Transition was found.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

If the method returns S_OK, the IAMTimelineObj interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IAMTimelineTransable::GetTransAtTime2

IAMTimelineTransable Interface

Retrieves the transition nearest to the specified time, according to the specified boundary conditions. This method is equivalent to GetTransAtTime, but takes a REFTIME parameter.

Syntax

HRESULT GetTransAtTime2(
    IAMTimelineObj **ppObj,
    REFTIME Time,
    long SearchDirection
);

Parameters

ppObj
[out] Address of a pointer to receive the transition's IAMTimelineObj interface.
Time
Time from which to begin the search, in seconds.
SearchDirection
Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Return Value

Returns one of the following HRESULT values:

S_FALSE | No transition was found.
S_OK | Transition was found.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

IAMTimelineTransable::TransAdd

IAMTimelineTransable Interface

Adds a transition to the object. An object can have multiple transitions, but they must not overlap in time. Transitions must fall within the time boundaries of the object.

Syntax

HRESULT TransAdd(
    IAMTimelineObj *pTrans
);

Parameters

pTrans
Address of the IAMTimelineObj interface of the transition to add.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | Cannot insert the transition.
E_NOINTERFACE | pTrans is not a pointer to a transition.

Remarks

If the transition overlaps an existing transition, the method returns E_INVALIDARG.

IAMTimelineTransable::TransGetCount

IAMTimelineTransable Interface

Retrieves the number of transitions on this object.

Syntax

HRESULT TransGetCount(
    long *pCount
);

Parameters

pCount
Pointer to a variable that receives the number of transitions.

Return Value

Returns S_OK if successful or E_POINTER otherwise.


IAMTimelineVirtualTrack Interface

Provides methods for working with virtual tracks in Microsoft® DirectShow® Editing Services (DES). Compositions and tracks support this interface.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimelineVirtualTrack Methods | Description
TrackGetPriority | Retrieves the object's priority level.
SetTrackDirty | Not supported.

IAMTimelineVirtualTrack::SetTrackDirty

IAMTimelineVirtualTrack Interface

Not supported.

Syntax

HRESULT SetTrackDirty( void );

IAMTimelineVirtualTrack::TrackGetPriority

IAMTimelineVirtualTrack Interface

Retrieves the object's priority level.

Syntax

HRESULT TrackGetPriority(
    long *pPriority
);

Parameters

pPriority
Pointer to a variable that receives the priority level. If the object is not part of a timeline, the value is set to –1.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.


IFindCompressorCB Interface

This interface provides a callback method that enables an application to specify a compressor for a particular media type.

Note The component designed to use this interface (the smart render engine) is currently not implemented to do so.

To do smart recompression, the render engine must be able to find the right compression filters. The IFindCompressorCB interface is a way for the application to choose the compressor. To use this interface, first implement it in your application. Then, give the render engine a pointer to the interface by calling the ISmartRenderEngine::SetFindCompressorCB method.

Note If you know beforehand what compressor a timeline group should use, a more straightforward approach is to call the ISmartRenderEngine::SetGroupCompressor method with a pointer to the compressor. Also, the render engine will search for an appropriate compressor if the application does not specify one.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IFindCompressorCB methods | Description
GetCompressor | Retrieves a compression filter for the specified media type.

IFindCompressorCB::GetCompressor

IFindCompressorCB Interface

Retrieves a compression filter for the specified media type.

Syntax

HRESULT GetCompressor(
    AM_MEDIA_TYPE *pType,
    AM_MEDIA_TYPE *pCompType,
    IBaseFilter **ppFilter
);

Parameters

pType
Pointer to an AM_MEDIA_TYPE structure that describes the uncompressed media type.
pCompType
Pointer to an AM_MEDIA_TYPE structure that describes the compression format.
ppFilter
[out] Address of variable that receives a pointer to the compression filter's IBaseFilter interface. If the method fails, it sets this pointer to NULL.

Return Value

Returns S_OK if successful. Otherwise, returns an error code that depends on the implementation.


IMediaDet Interface

Retrieves information about a media file, such as the number of streams and the type, duration, and frame rate of each stream. This interface also contains methods for retrieving poster frames from a video stream. The media detector exposes this interface. Use this interface in Microsoft® DirectShow® Editing Services (DES) applications.

To obtain information about a file, perform the following steps:

  1. Create an instance of the media detector by calling CoCreateInstance. The class ID is CLSID_MediaDet.
  2. Call put_Filename to specify the name of the source file. (Alternatively, call put_Filter.)
  3. Call get_OutputStreams to obtain the number of output streams in the source.
  4. Call put_CurrentStream to specify a particular stream.
  5. Call any of the following methods: get_StreamType, get_StreamMediaType, get_StreamLength, or get_FrameRate.

To retrieve poster frames, call GetBitmapBits or WriteBitmapBits. Alternatively, call EnterBitmapGrabMode and then GetSampleGrabber to obtain a pointer to the ISampleGrabber interface. All three of these methods put the media detector into a new mode, called bitmap grab mode. The informational methods described previously do not work in this mode. Therefore, obtain any information you need before retrieving poster frames, or else create new instances of the media detector for each stream.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaDet Methods | Description
get_Filter | Retrieves a pointer to the source filter currently used by the media detector.
put_Filter | Specifies a source filter for the media detector to use.
get_OutputStreams | Retrieves the number of output streams contained in the media source.
get_CurrentStream | Retrieves the stream number currently used by the media detector.
put_CurrentStream | Specifies the stream number for the media detector to use.
get_StreamType | Retrieves the globally unique identifier (GUID) for the media type of the current stream.
get_StreamTypeB | Retrieves a string representing the GUID of the media type for the current stream.
get_StreamLength | Retrieves the duration of the current stream.
get_Filename | Retrieves the name of the source file currently used by the media detector.
put_Filename | Specifies the name of the source file for the media detector to use.
GetBitmapBits | Retrieves a poster frame at the specified media time.
WriteBitmapBits | Retrieves a poster frame at the specified media time and writes it to a file.
get_StreamMediaType | Retrieves the media type of the current stream.
GetSampleGrabber | Retrieves a pointer to the ISampleGrabber interface.
get_FrameRate | Retrieves the frame rate of the current stream.
EnterBitmapGrabMode | Switches the media detector to bitmap grab mode and seeks the filter graph to a specified time.

IMediaDet::EnterBitmapGrabMode

IMediaDet Interface

Switches the media detector to bitmap grab mode and seeks the filter graph to a specified time.

Syntax

HRESULT EnterBitmapGrabMode(
    double StreamTime
);

Parameters

StreamTime
Time, in seconds, to which the graph seeks.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_INVALIDMEDIATYPE | File does not have a video stream.
VFW_E_TIME_EXPIRED | Could not seek.

Remarks

Before calling this method, set the file name and stream by calling put_Filename and put_CurrentStream.

This method inserts the Sample Grabber filter into the filter graph. You can then call GetSampleGrabber to obtain a pointer to the ISampleGrabber interface. Once the media detector enters bitmap grab mode, the various informational methods in IMediaDet do not work.

The GetBitmapBits or WriteBitmapBits methods also put the media detector into bitmap grab mode.

IMediaDet::GetBitmapBits

IMediaDet Interface

Retrieves a poster frame at the specified media time.

Syntax

HRESULT GetBitmapBits(
    double StreamTime,
    long *pBufferSize,
    char *pBuffer,
    long Width,
    long Height
);

Parameters

StreamTime
Time at which to retrieve the poster frame.
pBufferSize
Pointer to a variable that receives the required buffer size. If pBuffer is NULL, the variable receives the size of the buffer needed to retrieve the poster frame. If pBuffer is not NULL, this parameter is ignored.
pBuffer
Pointer to a buffer that receives the poster frame.
Width
Width of the poster frame image, in pixels.
Height
Height of the poster frame image, in pixels.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_NOINTERFACE | Could not add the Sample Grabber filter to the graph.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer error.
E_UNEXPECTED | Unexpected error.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

Before calling this method, set the file name and stream by calling put_Filename and put_CurrentStream.

To determine the size of the buffer that is required, call this method with pBuffer equal to NULL. The size is returned in the variable pointed to by pBufferSize. Then create the buffer and call the method again, as shown in the following code.

long BufferSize = 0;
GetBitmapBits(StreamTime, &BufferSize, NULL, Width, Height);
char *pBuffer = new char[BufferSize];
GetBitmapBits(StreamTime, 0, pBuffer, Width, Height);

This method puts the media detector into bitmap grab mode. Once this method has been called, the various stream information methods in IMediaDet do not work, unless you create a new instance of the media detector.

IMediaDet::get_CurrentStream

IMediaDet Interface

Retrieves the stream number currently used by the media detector.

Syntax

HRESULT get_CurrentStream(
    long *pVal
);

Parameters

pVal
[out, retval] Pointer to a variable that receives the current stream number.

Return Value

Returns S_OK if successful, or E_POINTER otherwise.

IMediaDet::get_Filename

IMediaDet Interface

Retrieves the name of the source file currently used by the media detector.

Syntax

HRESULT get_Filename(
    BSTR *pVal
);

Parameters

pVal
[out, retval] Pointer to a variable that receives the file name.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

IMediaDet::get_Filter

IMediaDet Interface

Retrieves a pointer to the source filter currently used by the media detector.

Syntax

HRESULT get_Filter(
    IUnknown **ppVal
);

Parameters

ppVal
[out, retval] Address of a pointer to receive the filter's IUnknown interface. If no source filter is in use, the value is set to NULL.

Return Value

Returns an HRESULT value.

Remarks

When the method returns, if *ppVal is not NULL, the IUnknown interface has an outstanding reference count. Be sure to release the interface when you are finished using it.

IMediaDet::get_FrameRate

IMediaDet Interface

Retrieves the frame rate of the current stream. The stream must be a video stream.

Syntax

HRESULT get_FrameRate(
    double *pVal
);

Parameters

pVal
[out, retval] Pointer to a variable that receives the frame rate, in frames per second.

Return Value

Returns an HRESULT value. Possible values include the following:

S_FALSE | Video format header does not specify a frame rate.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

This method cannot retrieve the frame rate from an ASF file.

Before calling this method, set the file name and stream by calling put_Filename and put_CurrentStream.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see EnterBitmapGrabMode.

IMediaDet::get_OutputStreams

IMediaDet Interface

Retrieves the number of output streams contained in the media source.

Syntax

HRESULT get_OutputStreams(
    long *pVal
);

Parameters

pVal
[out, retval] Pointer to a variable that receives the number of output streams.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

Before calling this method, call put_Filename to set the file name.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see EnterBitmapGrabMode.

IMediaDet::GetSampleGrabber

IMediaDet Interface

Retrieves a pointer to the ISampleGrabber interface, which enables an application to retrieve individual samples from a media stream.

Syntax

HRESULT GetSampleGrabber(
    ISampleGrabber **ppVal
);

Parameters

ppVal
[out] Address of a pointer to receive the ISampleGrabber interface.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_NOINTERFACE | Cannot retrieve the interface because the media detector is not in bitmap grab mode.
E_POINTER | NULL pointer argument.

Remarks

Call EnterBitmapGrabMode before calling this method. The ISampleGrabber interface enables you to retrieve individual media samples from the stream. If you just need a bitmap for a poster frame, call the IMediaDet::GetBitmapBits method instead. The ISampleGrabber interface is more flexible, but requires more work by the application.

If this method succeeds, the ISampleGrabber interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IMediaDet::get_StreamLength

IMediaDet Interface

Retrieves the duration of the current stream.

Syntax

HRESULT get_StreamLength(
    double *pVal
);

Parameters

pVal
[out, retval] Pointer to a variable that receives the duration of the stream, in seconds.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

Before calling this method, set the file name and stream by calling put_Filename and put_CurrentStream.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see EnterBitmapGrabMode.

IMediaDet::get_StreamMediaType

IMediaDet Interface

Retrieves the media type of the current stream.

Syntax

HRESULT get_StreamMediaType(
    AM_MEDIA_TYPE *pVal
);

Parameters

pVal
[out, retval] Pointer to an AM_MEDIA_TYPE structure that is filled with the media type.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

Before calling this method, set the file name and stream by calling put_Filename and put_CurrentStream.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see EnterBitmapGrabMode.

IMediaDet::get_StreamType

IMediaDet Interface

Retrieves the globally unique identifier (GUID) for the media type of the current stream.

Syntax

HRESULT get_StreamType(
    GUID *pVal
);

Parameters

pVal
[out, retval] Pointer to a variable that receives the major type GUID for the media type.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

This method retrieves the majortype member of the AM_MEDIA_TYPE structure. The AM_MEDIA_TYPE structure describes the format of the stream, and the majortype member is a GUID that indicates the general category, such as audio or video. For a video stream, the GUID is MEDIATYPE_Video. For audio, it is MEDIATYPE_Audio. To retrieve the entire AM_MEDIA_TYPE structure, call the get_StreamMediaType method.

Before calling this method, set the file name and stream by calling put_Filename and put_CurrentStream.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see EnterBitmapGrabMode.

IMediaDet::get_StreamTypeB

IMediaDet Interface

Retrieves a string representing the GUID of the media type for the current stream.

Syntax

HRESULT get_StreamTypeB(
    BSTR *pVal
);

Parameters

pVal
[out, retval] Pointer to a BSTR that receives a string representation of the media type GUID.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

The returned BSTR is formatted like the following: {73647561-0000-0010-8000-00AA00389B71}

The method allocates memory for the string. The application must call SysFreeString to free the memory.

Before calling this method, set the file name and stream by calling put_Filename and put_CurrentStream.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see EnterBitmapGrabMode.

IMediaDet::put_CurrentStream

IMediaDet Interface

Specifies the stream number for the media detector to use.

Syntax

HRESULT put_CurrentStream(
    long newVal
);

Parameters

newVal
[in] Stream number.

Return Value

Returns S_OK if successful, or E_INVALIDARG otherwise.

Remarks

Before calling this method, call put_Filename to set the file name. Call get_OutputStreams to determine the number of streams contained in the source file.

If the media detector is in bitmap grab mode, this method returns E_INVALIDARG. For more information, see EnterBitmapGrabMode.

IMediaDet::put_Filename

IMediaDet Interface

Specifies the name of the source file for the media detector to use.

Syntax

HRESULT put_Filename(
    BSTR newVal
);

Parameters

newVal
[in] File name of the source.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

IMediaDet::put_Filter

IMediaDet Interface

Specifies a source filter for the media detector to use.

Syntax

HRESULT put_Filter(
    IUnknown *newVal
);

Parameters

newVal
[in] Pointer to the source filter's IUnknown interface.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_NOINTERFACE | newVal does not point to a filter.
E_POINTER | NULL pointer argument.

Remarks

Instead of calling put_Filename, an application can call this method with a pointer to a source filter's IUnknown interface. Do not use a filter already connected to the filter graph.

IMediaDet::WriteBitmapBits

IMediaDet Interface

Retrieves a poster frame at the specified media time and writes it to a file.

Syntax

HRESULT WriteBitmapBits(
    double StreamTime,
    long Width,
    long Height,
    BSTR Filename
);

Parameters

StreamTime
Time at which to retrieve the poster frame.
Width
Width of the poster frame image, in pixels.
Height
Height of the poster frame image, in pixels.
Filename
Path of the file in which to save the poster frame. If the file already exists, this method overwrites it.

Return Value

Returns S_OK it successful. Otherwise, returns an HRESULT value that indicates the cause of the error. Possible error codes include the following:

E_NOINTERFACE | Could not add the Sample Grabber filter to the graph.
E_FAIL | Failure.
E_OUTOFMEMORY | Insufficient memory.
E_UNEXPECTED | Unexpected error.
STG_E_ACCESSDENIED | Cannot overwrite file.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

Before calling this method, set the file name and stream by calling put_Filename and put_CurrentStream.

This method puts the media detector into bitmap grab mode. Once this method has been called, the various stream information methods in IMediaDet do not work, unless you create a new instance of the media detector.


IMediaLocator Interface

Provides methods for validating file names in Microsoft® DirectShow® Editing Services (DES). Use this interface to ensure that a given file name and path correspond to an existing file. This interface also provides a way to search for the file at other locations, and to display an Open dialog box so that the user can locate the file.

The media locator implements this interface. The timeline and the render engine also support file name validation through the following methods:

  • IAMTimeline::ValidateSourceNames: Validates and updates file names in the timeline.
  • IRenderEngine::SetSourceNameValidation: Specifies how the render engine validates file names at rendering time.

Typically, a DES application will call these methods rather than directly create an instance of the media locator. For more information, see Using the Media Locator.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaLocator methods | Description
FindMediaFile | Searches for a file and, if successful, retrieves the path to the file.
AddFoundLocation | Adds a directory to the directory cache.

IMediaLocator::AddFoundLocation

IMediaLocator Interface

Adds a directory to the directory cache.

Syntax

HRESULT AddFoundLocation(
    BSTR DirectoryName
);

Parameters

DirectoryName
Directory path to add to the cache.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

The media locator keeps a cache of directory paths where it has successfully found files in past searches. When it successfully locates a file, it adds the directory to the cache.

IMediaLocator::FindMediaFile

IMediaLocator Interface

Searches for a file and, if successful, retrieves the path to the file.

Syntax

HRESULT FindMediaFile(
    BSTR Input,
    BSTR FilterString,
    BSTR *pOutput,
    long Flags
);

Parameters

Input
File name, including path, where the file was last known to reside. For source objects in the timeline, use the current media name.
FilterString
BSTR containing pairs of filter strings, formatted as required by the lpstrFilter member of the Microsoft® Win32® OPENFILENAME structure. The media locator uses this filter if it displays an Open dialog box. The value can be NULL if the Flags parameter does not include the SFN_VALIDATEF_POPUP flag.
pOutput
Pointer to a variable that receives the actual path to the file, if it differs from the value contained in Input and if the method successfully locates the file.
Flags
Bitwise combination of zero or more of the following flags:
  • SFN_VALIDATEF_NOFIND
  • SFN_VALIDATEF_POPUP
  • SFN_VALIDATEF_TELLME
  • SFN_VALIDATEF_USELOCAL

Return Value

Returns an HRESULT value. Possible values include the following.

S_FALSE | File was found in another location.
S_OK | File was found in the specified location.
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_POINTER | NULL pointer argument.

Remarks

The filter string for the Open dialog, which is specified by the FilterString parameter, contains internal Null characters. For example, Video\0*.avi\0\0 is a valid filter string. You cannot use the SysAllocStr function to allocate the BSTR, because that function expects a Null-terminated string and will truncate the string at the first Null character. Therefore, use a function such as SysAllocStringLen, which includes an explicit parameter for the length:

BSTR filter = SysAllocStringLen(L"Video\0*.avi\0\0", 13);

If the user cancels the Open dialog, the method returns E_FAIL.

The method allocates memory for the BSTR in pOutput. The application must call SysFreeString to free the memory.


IPropertySetter Interface

Sets properties on an effect or transition in Microsoft® DirectShow® Editing Services (DES).

To use this interface, create an instance of a property setter object (CLSID_PropertySetter), and associate it with an effect or transition by calling the IAMTimelineObj::SetPropertySetter method. For more information, see Working with Effects and Transitions.

Usually an application needs to call only the ClearProps method to clear existing properties, and the AddProp method to add new properties. The other methods on this interface are called by other DES components.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IPropertySetter Methods | Description
LoadXML | Loads property data expressed in Extensible Markup Language (XML).
PrintXML | Converts property data into an XML string.
CloneProps | Clones a set of properties from this property setter and adds them to a new property setter.
AddProp | Adds a property to the property setter, with an array of time-value pairs defining the value of the property over a range of time.
GetProps | Retrieves the properties set on this object, with their corresponding values.
FreeProps | Frees resources allocated by the GetProps method.
ClearProps | Clears all property data from the property setter.
SaveToBlob | Saves the property data to a persistence format.
LoadFromBlob | Loads property data from a persistence format.
SetProps | Sets the properties of the target object to the appropriate state for the specified time.

IPropertySetter::AddProp

IPropertySetter Interface

Adds a property to the property setter, with an array of time-value pairs defining the value of the property over a range of time.

Syntax

HRESULT AddProp(
    DEXTER_PARAM Param,
    DEXTER_VALUE *paValue
);

Parameters

Param
[in] DEXTER_PARAM structure that specifies the property. The nValues member of the structure must equal the size of the array given in the paValue parameter.
paValue
[in] Pointer to an array of DEXTER_VALUE structures that contain time-value pairs. The array must be in ascending time order. The times are relative to the starting time of the effect or transition.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

The first DEXTER_VALUE structure must specify a reference time of zero and an interpolation flag (dwInterp) of DEXTERF_JUMP, or the method returns an error.

IPropertySetter::ClearProps

IPropertySetter Interface

Clears all property data from the property setter. The application can set new property data after calling this function.

Syntax

HRESULT ClearProps( void );

Return Value

Returns S_OK.

IPropertySetter::CloneProps

IPropertySetter Interface

Clones a set of properties from this property setter and adds them to a new property setter.

Syntax

HRESULT CloneProps(
    IPropertySetter **ppSetter,
    REFERENCE_TIME rtStart,
    REFERENCE_TIME rtStop
);

Parameters

ppSetter
[out] Address of a pointer to receive the IPropertySetter interface of the new property setter.
rtStart
[in] Start time of the range of values to clone, in 100-nanosecond units.
rtStop
[in] Reserved.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error. Possible error codes include the following:

E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

Only values that fall after the specified start time are cloned. The times on the cloned values are then adjusted relative to the start time. For example, if rtStart is 20000000 (2 seconds), then a value at time 30000000 (3 seconds) is cloned with time 10000000 (1 second). Finally, each cloned property is given an initial value equal to the value of the original property at the start time (correctly interpolated if necessary). In effect, the property data is split at the specified start time.

If the method succeeds, the IPropertySetter interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IPropertySetter::FreeProps

IPropertySetter Interface

Frees resources allocated by the GetProps method. Call this method after calling GetProps, passing it the structures returned by GetProps.

Syntax

HRESULT FreeProps(
    LONG cParams,
    DEXTER_PARAM *paParam,
    DEXTER_VALUE *paValue
);

Parameters

cParams
[in] Value that specifies the size of the array given in the paParam parameter.
paParam
[in] Pointer to an array of DEXTER_PARAM structures.
paValue
[in] Pointer to an array of DEXTER_VALUE structures.

Return Value

Returns S_OK.

IPropertySetter::GetProps

IPropertySetter Interface

Retrieves the properties set on this object, with their corresponding values.

Syntax

HRESULT GetProps(
    LONG *pcParams,
    DEXTER_PARAM **paParam,
    DEXTER_VALUE **paValue
);

Parameters

pcParams
[out] Pointer to a variable that receives the number of structures returned in paParam.
paParam
[out] Address of a pointer to an array of DEXTER_PARAM structures.
paValue
[out] Address of a pointer to an array of DEXTER_VALUE structures.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

For each property returned in paParam, the nValues member indicates the number of DEXTER_VALUE structures associated with the property. The pairs are returned in ascending time order for each property.

For example, the following code fragment shows how to iterate through all the values:

DEXTER_PARAM *pParam;
DEXTER_VALUE *pValue;
LONG count;

hr = pSetter->GetProps(&count, &pParam, &pValue);

LONG num = 0;
for (LONG i = 0; i < count; i++)
{
    for (LONG j = 0; j < pParam[i].nValues; j++)
    {
        // pValue[num] is the next value in the sequence for pParam[i]
    }
    num += pParam[i].nValues;
}

When you are finished using the returned structures, call FreeProps to free the resources allocated by this method.

IPropertySetter::LoadFromBlob

IPropertySetter Interface

Loads property data from a persistence format.

Syntax

HRESULT LoadFromBlob(
    LONG cSize,
    BYTE *pb
);

Parameters

cSize
[in] Size of the data, in bytes.
pb
[in] Pointer to an array of bytes that contains the data.

Return Value

Returns S_OK if successful. Otherwise, returns E_OUTOFMEMORY or another error code.

IPropertySetter::LoadXML

IPropertySetter Interface

Loads property data expressed in Extensible Markup Language (XML).

Syntax

HRESULT LoadXML(
    IUnknown *pxml
);

Parameters

pxml
[in] Pointer to the IUnknown interface of an XML element created by the Microsoft XML parser.

Return Value

Returns an HRESULT value. Possible values include the following.

S_FALSE | No property data.
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_INVALID_FILE_FORMAT | Invalid format.

Remarks

Typically, applications will not need to use this method. DES uses it internally to load properties from XTL files.

To use this method, create an IXMLDocument object and use it to parse an XML file. Then use the IXMLDocument object to retrieve IXMLElement objects. If the object has properties, you can pass the IXMLElement pointer to the LoadXML method. The method loads the properties into the property setter.

IPropertySetter::PrintXML

IPropertySetter Interface

Converts property data into an Extensible Markup Language (XML) string.

Syntax

HRESULT PrintXML(
    char *pszXML,
    int cbXML,
    int *pcbPrinted,
    int indent
);

Parameters

pszXML
[out] Pointer to a buffer that receives the XML string.
cbXML
[in] Size of the buffer pointed to by pszXML, in bytes.
pcbPrinted
[out] Pointer to a variable that receives the length of the XML string. Can be NULL.
indent
[in] Number of indent levels for the outermost tag.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error. If the XML string is longer than the buffer, the method returns E_OUTOFMEMORY.

IPropertySetter::SaveToBlob

IPropertySetter Interface

Saves the property data to a persistence format.

Syntax

HRESULT SaveToBlob(
    LONG *pcSize,
    BYTE **ppb
);

Parameters

pcSize
[out] Pointer to a variable that receives the size of the data, in bytes.
ppb
[out] Address of a pointer to an array of bytes that receives the data.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

The method allocates memory for the byte array. The caller must free it, using the CoTaskMemFree function.

IPropertySetter::SetProps

IPropertySetter Interface

Sets the properties of the target object to the appropriate state for the specified time.

Syntax

HRESULT SetProps(
    IUnknown *pTarget,
    REFERENCE_TIME rtNow
);

Parameters

pTarget
[in] Pointer to the target object for which to set the properties.
rtNow
[in] Time at which to set the properties, in 100-nanosecond units, or –1 to set static properties (those that do not vary over time).

Return Value

Returns an HRESULT value.

Remarks

This method is called by DES to set the properties on a transition or effect. An application will not normally call this method.

The object specified by pTarget must implement the IDispatch interface.


IRenderEngine Interface

Renders a Microsoft® DirectShow® Editing Services (DES) project by constructing a filter graph from a timeline.

DES provides two components that implement this interface:

  • The basic render engine creates uncompressed output. You can use the output for preview, or route it through compression filters and write it to a file.
  • The smart render engine creates compressed output, using smart recompression. With smart recompression, a source file is recompressed only if its format differs from the output format. A source with a matching format is written directly to the output file. Depending on the scenario, smart recompression can greatly improve rendering time.

The smart render engine also supports the ISmartRenderEngine interface.

Although an application can create a filter graph and pass it to a render engine, the typical scenario is for the render engine to create the filter graph. Building the graph is a two-stage process. First, build the front end by calling the ConnectFrontEnd method. Then connect the output pins on the front end to the desired rendering filters:

  • Video and audio renderers for preview, or
  • Compressors, multiplexers, and file writers to generate the final output.

For more information, see Rendering a Project.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IRenderEngine Methods | Description
SetTimelineObject | Sets the timeline for the render engine to use.
GetTimelineObject | Retrieves the timeline that the render engine is currently using.
GetFilterGraph | Retrieves the filter graph that the render engine has constructed, if any.
SetFilterGraph | Specifies a filter graph for the render engine to use.
SetInterestRange | Not supported.
SetInterestRange2 | Not supported.
SetRenderRange | Sets the range of time on the timeline to be rendered.
SetRenderRange2 | Equivalent to SetRenderRange, but takes values of type double.
GetGroupOutputPin | Retrieves the output pin for the specified group.
ScrapIt | Discards the render engine's filter graph and all associated objects.
RenderOutputPins | Creates the previewing portion of the filter graph.
GetVendorString | Retrieves the vendor string.
ConnectFrontEnd | Builds the front end of the filter graph from the current timeline.
SetSourceConnectCallback | Not supported.
SetDynamicReconnectLevel | Sets the level of dynamic reconnection during rendering.
DoSmartRecompression | Not supported.
UseInSmartRecompressionGraph | Not supported.
SetSourceNameValidation | Specifies how the render engine validates file names.
Commit | Not implemented.
Decommit | Not implemented.
GetCaps | Not implemented.

IRenderEngine::Commit

IRenderEngine Interface

Not implemented.

Syntax

HRESULT Commit( void );

IRenderEngine::ConnectFrontEnd

IRenderEngine Interface

Builds the front end of the filter graph from the current timeline.

Syntax

HRESULT ConnectFrontEnd( void );

Return Value

Returns an HRESULT value. Possible return values include the following:

S_OK | Success.
S_WARN_OUTPUTRESET | Rendering portion of the graph was deleted.
E_INVALIDARG | No timeline set for this render engine.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because the project was not rendered successfully.
E_UNEXPECTED | Unexpected error.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

This method does not build the rendering portion of the filter graph. The application must connect the output pins on the front end to the desired rendering filters:

  • To preview, call the RenderOutputPins method.
  • To output a file, call GetGroupOutputPin to retrieve the output pin for each group, then connect the pins to a multiplexer filter.

If you are using the basic render engine, the output pins on the front end produce uncompressed data. If you are using the smart render engine, the output pins produce compressed data.

If you change the timeline after you build the filter graph, you must call ConnectFrontEnd again to rebuild the front end. The method preserves the rendering portion of the graph whenever possible. However, if you add or delete a group, or change the order of the groups, ConnectFrontEnd deletes the rendering portion and your application must rebuild it. If the method deletes the rendering portion, it returns S_WARN_OUTPUTRESET.

IRenderEngine::Decommit

IRenderEngine Interface

Not implemented.

Syntax

HRESULT Decommit( void );

IRenderEngine::DoSmartRecompression

IRenderEngine Interface

Not supported.

Syntax

HRESULT DoSmartRecompression( void );

IRenderEngine::GetCaps

IRenderEngine Interface

Not implemented.

Syntax

HRESULT GetCaps(
    long Index,
    long *pReturn
);

IRenderEngine::GetFilterGraph

IRenderEngine Interface

Retrieves the filter graph that the render engine has constructed, if any.

Syntax

HRESULT GetFilterGraph(
    IGraphBuilder **ppFG
);

Parameters

ppFG
[out] Address of a pointer to receive the filter graph's IGraphBuilder interface. It receives the value NULL if there is no filter graph.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_POINTER | Invalid pointer.

Remarks

On return, if the value of *ppFG is non-NULL, the IGraphBuilder interface has an outstanding reference count. Be sure to release the interface when you are finished using it.

IRenderEngine::GetGroupOutputPin

IRenderEngine Interface

Retrieves the output pin for the specified group.

Syntax

HRESULT GetGroupOutputPin(
    long Group,
    IPin **ppRenderPin
);

Parameters

Group
Zero-based index that specifies the group.
ppRenderPin
[out] Address of a pointer to receive the output pin's IPin interface.

Return Value

Returns an HRESULT value. Possible values include the following:

S_FALSE | Group does not have an output pin.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_POINTER | Invalid pointer.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because project was not rendered successfully.
E_UNEXPECTED | Unexpected error.

Remarks

Before calling this method, call ConnectFrontEnd to build the front end of the graph. Each group represents a single media stream, and the front end has a corresponding output pin.

You can use this method to create the rendering portion of a file-writing graph. Connect the output pins to multiplexer filters and file writer filters. For more information, see Rendering a Project.

For preview, you don't need to call this method. Just call ConnectFrontEnd followed by RenderOutputPins.

If the method returns S_OK, the IPin interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IRenderEngine::GetTimelineObject

IRenderEngine Interface

Retrieves the timeline that the render engine is currently using.

Syntax

HRESULT GetTimelineObject(
    IAMTimeline **ppTimeline
);

Parameters

ppTimeline
[out] Address of a pointer to receive the timeline's IAMTimeline interface. It receives the value NULL if there is no timeline.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_POINTER | Invalid pointer.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Remarks

On return, if the value of *ppTimeline is non-NULL, the IAMTimeline interface has an outstanding reference count. Be sure to release the interface when you are finished using it.

IRenderEngine::GetVendorString

IRenderEngine Interface

Retrieves the vendor string.

Syntax

HRESULT GetVendorString(
    BSTR *pVendorID
);

Parameters

pVendorID
[out, retval] Pointer to a variable that receives a BSTR containing the vendor string.

Return Value

Returns S_OK if the method succeeds. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

IRenderEngine::RenderOutputPins

IRenderEngine Interface

Creates the previewing portion of the filter graph.

Syntax

HRESULT RenderOutputPins( void );

Return Value

Returns an HRESULT values. The following are possible values:

S_OK | Success.
VFW_S_AUDIO_NOT_RENDERED | Cannot play back the audio stream.
E_INVALIDARG | Invalid argument.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because project was not rendered successfully.
E_UNEXPECTED | Unexpected error.

Remarks

Before calling this method, call ConnectFrontEnd to build the front end of the graph. To perform an operation other than preview, do not call this method. Instead, call GetGroupOutputPin to obtain pointers to the output pins.

If there is no sound card on the user's computer, this method returns VFW_S_AUDIO_NOT_RENDERED. There will not be audio preview in this case, but video preview is unaffected.

If the pin is from a video group, this method creates a video window. The calling thread must dispatch messages—for example, to move the window, or respond to mouse clicks in the window's client area.

IRenderEngine::ScrapIt

IRenderEngine Interface

Discards the render engine's filter graph and all associated objects.

Syntax

HRESULT ScrapIt( void );

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

IRenderEngine::SetDynamicReconnectLevel

IRenderEngine Interface

Sets the level of dynamic reconnection during rendering.

Syntax

HRESULT SetDynamicReconnectLevel(
    DWORD Level
);

Parameters

Level
Combination of Dynamic Reconnection Flags, specifying the level of dynamic reconnection.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_NOTIMPL | Not implemented.

Remarks

By default, the basic render engine loads every source before rendering a project. This can result in a long start-up time. With dynamic reconnection, sources are loaded only when needed. This can shorten the start-up time, but possibly interfere with smooth playback. Generally, the more source clips that a project uses, the more you might benefit from dynamic reconnection.

The smart render engine does not implement this method.

IRenderEngine::SetFilterGraph

IRenderEngine Interface

Specifies a filter graph for the render engine to use.

Syntax

HRESULT SetFilterGraph(
    IGraphBuilder *pFG
);

Parameters

pFG
Pointer to the IGraphBuilder interface of the filter graph.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Remarks

Most applications do not need to call this method. It is more typical to let the render engine build the graph for you, by calling the ConnectFrontEnd method.

This method fails if the render engine already has a filter graph.

Never retrieve a pointer to a filter graph created by one render engine and then use it as the parameter to this method on another render engine. Doing so will cause unpredictable results.

IRenderEngine::SetInterestRange

IRenderEngine Interface

Not supported.

Syntax

HRESULT SetInterestRange(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

IRenderEngine::SetInterestRange2

IRenderEngine Interface

Not supported.

Syntax

HRESULT SetInterestRange2(
    double Start,
    double Stop
);

IRenderEngine::SetRenderRange

IRenderEngine Interface

Sets the range of time on the timeline to be rendered. Objects that lie outside the specified range are not rendered, and resources are not allocated for them.

Syntax

HRESULT SetRenderRange(
    REFERENCE_TIME Start,
    REFERENCE_TIME Stop
);

Parameters

Start
Start time, in 100-nanosecond units.
Stop
Stop time, in 100-nanosecond units.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

IRenderEngine::SetRenderRange2

IRenderEngine Interface

Sets the range of time on the timeline to be rendered. This method is equivalent to SetRenderRange, but takes values of type double.

Syntax

HRESULT SetRenderRange2(
    double Start,
    double Stop
);

Parameters

Start
Start time, in seconds.
Stop
Stop time, in seconds.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

IRenderEngine::SetSourceConnectCallback

IRenderEngine Interface

Not supported.

Syntax

HRESULT SetSourceConnectCallback(
    IGrfCache *pCallback
);

IRenderEngine::SetSourceNameValidation

IRenderEngine Interface

Specifies how the render engine validates file names.

Syntax

HRESULT SetSourceNameValidation(
    BSTR FilterString,
    IMediaLocator *pOverride,
    LONG Flags
);

Parameters

FilterString
BSTR value containing pairs of filter strings, formatted as required by the lpstrFilter member of the Microsoft® Win32® OPENFILENAME structure. The media locator uses this filter if it presents an Open File dialog box to the end user.
pOverride
Optional pointer to the IMediaLocator interface of a media locator to use in place of the default. To use the default media locator, set the value of this parameter to NULL. See Remarks for more information.
Flags
Bitwise combination of flags specifying the behavior of the media locator. The SFN_VALIDATEF_CHECK flag must be present. The SFN_VALIDATEF_IGNOREMUTED flag has no effect with this method.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Remarks

Using the pOverride parameter, you can supply your own custom implementation of the IMediaLocator interface. For example, the default media locator does not notify an application about the files that it finds (or cannot find). To get around this limitation, you could implement a custom media locator, making it a wrapper for the default version. Then pass IMediaLocator::FindMediaFile calls directly to the default version and examine the return value.

Currently, this method does not validate dynamically loaded sources. See SetDynamicReconnectLevel.

IRenderEngine::SetTimelineObject

IRenderEngine Interface

Sets the timeline for the render engine to use.

Syntax

HRESULT SetTimelineObject(
    IAMTimeline *pTimeline
);

Parameters

pTimeline
Pointer to the timeline object's IAMTimeline interface.

Return Value

Returns one of the following HRESULT values:

S_OK | Success.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | Invalid pointer.

IRenderEngine::UseInSmartRecompressionGraph

IRenderEngine Interface

Not supported.

Syntax

HRESULT UseInSmartRecompressionGraph( void );


ISmartRenderEngine Interface

Provides methods that support smart recompression in Microsoft® DirectShow® Editing Services (DES). The smart render engine exposes this interface. For more information on using ISmartRenderEngine, see Rendering a Project.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
ISmartRenderEngine Methods | Description
SetGroupCompressor | Specifies a compression filter to use when rendering the specified group.
GetGroupCompressor | Retrieves the compression filter for the specified group.
SetFindCompressorCB | Not implemented.

ISmartRenderEngine::GetGroupCompressor

ISmartRenderEngine Interface

Retrieves the compression filter for the specified group.

Syntax

HRESULT GetGroupCompressor(
    long Group,
    IBaseFilter **pCompressor
);

Parameters

Group
Zero-based index of the group.
pCompressor
Address of a pointer to receive the IBaseFilter interface of the compression filter. It receives the value NULL if there is no compression filter.

Return Value

Returns one of the following values.

E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer error.
S_OK | Success.

Remarks

Use this method to set properties on the compression filter, such as the key-frame rate. Call this method after calling IRenderEngine::ConnectFrontEnd, but before rendering the project. Then query the compression filter's output pin for the IAMVideoCompression interface, which contains methods for setting compression parameters. Release the interface when you are done. If you make any subsequent changes to the timeline, call ConnectFrontEnd, and then call GetGroupCompressor again to reset the compression parameters.

On return, if the value of *pCompressor is non-NULL, the IBaseFilter interface has an outstanding reference count. Be sure to release the interface when you are done using it.

ISmartRenderEngine::SetFindCompressorCB

ISmartRenderEngine Interface

Not implemented.

Syntax

HRESULT SetFindCompressorCB(
    IFindCompressorCB *pCallback
);

ISmartRenderEngine::SetGroupCompressor

ISmartRenderEngine Interface

Specifies a compression filter to use when rendering the specified group.

Syntax

HRESULT SetGroupCompressor(
    long Group,
    IBaseFilter *pCompressor
);

Parameters

Group
Zero-based index of the group.
pCompressor
Pointer to the IBaseFilter interface of the compression filter.

Return Value

Returns S_OK if successful. Otherwise, returns E_INVALIDARG.


IXml2Dex Interface

Saves and loads Microsoft® DirectShow® Editing Services (DES) project files in Extensible Markup Language (XML). This interface also provides methods for reading and writing DirectShow graph (.grf) files.

Requirements

Requires Qedit.h.

Requires Internet Explorer 4.0 or later.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IXml2Dex Methods | Description
CreateGraphFromFile | Not implemented.
WriteGrfFile | Writes a filter graph to a file in .grf format.
WriteXMLFile | Translates a timeline to XML and writes the XML data to a file.
ReadXMLFile | Loads an XML project file.
Delete | Not implemented.
WriteXMLPart | Not implemented.
PasteXMLFile | Not implemented.
CopyXML | Not implemented.
PasteXML | Not implemented.
Reset | Not implemented.
ReadXML | Not implemented.
WriteXML | Translates a timeline to an XML string.

IXml2Dex::CopyXML

IXml2Dex Interface

Not implemented.

Syntax

HRESULT CopyXML(
    IUnknown *pTimeline,
    double dStart,
    double dEnd
);

IXml2Dex::CreateGraphFromFile

IXml2Dex Interface

Not implemented.

Syntax

HRESULT CreateGraphFromFile(
    IUnknown **ppGraph,
    IUnknown *pTimeline,
    BSTR FileName
);

IXml2Dex::Delete

IXml2Dex Interface

Not implemented.

Syntax

HRESULT Delete(
    IUnknown *pTimeline,
    double dStart,
    double dEnd
);

IXml2Dex::PasteXML

IXml2Dex Interface

Not implemented.

Syntax

HRESULT PasteXML(
    IUnknown *pTimeline,
    double dStart
);

IXml2Dex::PasteXMLFile

IXml2Dex Interface

Not implemented.

Syntax

HRESULT PasteXMLFile(
    IUnknown *pTimeline,
    double dStart,
    BSTR FileName
);

IXml2Dex::ReadXML

IXml2Dex Interface

Not implemented.

Syntax

HRESULT ReadXML(
    IUnknown *pTimeline,
    IUnknown *pXML
);

IXml2Dex::ReadXMLFile

IXml2Dex Interface

Loads an XML project file. This method creates instances of all the objects expressed in the XML file and inserts them into the timeline, as well as applying any attributes given for the timeline, such as frame rate or default effect.

Syntax

HRESULT ReadXMLFile(
    IUnknown *pTimeline,
    BSTR XMLName
);

Parameters

pTimeline
Pointer to a timeline object's IUnknown interface.
XMLName
String that specifies the name of the file to load.

Return Value

Returns S_OK if successful. Otherwise, returns VFW_E_INVALID_FILE_FORMAT or another error code.

Remarks

This method does not clear existing objects from the timeline before it inserts the new objects defined in the XML file. If you need to refresh an existing timeline, call IAMTimeline::ClearAllGroups first.

IXml2Dex::Reset

IXml2Dex Interface

Not implemented.

Syntax

HRESULT Reset(void);

IXml2Dex::WriteGrfFile

IXml2Dex Interface

Writes a filter graph to a file in .grf format.

Syntax

HRESULT WriteGrfFile(
    IUnknown *pGraph,
    BSTR FileName
);

Parameters

pGraph
Pointer to the filter graph's IUnknown interface.
FileName
String that specifies the name of the file to write.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
S_OK | Success.

This method can also return error codes generated by internal calls to the IStorage::CreateStream and IPersist::Save methods. For more information, see the Platform SDK.

IXml2Dex::WriteXML

IXml2Dex Interface

Translates a timeline to an XML string.

Syntax

HRESULT WriteXML(
    IUnknown *pTimeline,
    BSTR *pbstrXML
);

Parameters

pTimeline
Pointer to the timeline object's IUnknown interface.
pbstrXML
Pointer to a variable of type BSTR that receives the XML string describing the timeline.

Return Value

Returns S_OK if successful. If there is insufficient memory for the conversion, returns E_OUTOFMEMORY. Otherwise, returns another error code.

Remarks

The method allocates memory for the string. The application must call SysFreeString to free the memory.

IXml2Dex::WriteXMLFile

IXml2Dex Interface

Translates a timeline to XML and writes the XML data to a file.

Syntax

HRESULT WriteXMLFile(
    IUnknown *pTimeline,
    BSTR FileName
);

Parameters

pTimeline
Pointer to the timeline object's IUnknown interface.
FileName
String that specifies the name of the file to write.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_INVALIDARG | Argument is invalid.
E_OUTOFMEMORY | Insufficient memory.
S_OK | Success.

Remarks

This method generates an XML file that represents all the components in the timeline.

IXml2Dex::WriteXMLPart

IXml2Dex Interface

Not implemented.

Syntax

HRESULT WriteXMLPart(
    IUnknown *pTimeline,
    double dStart,
    double dEnd,
    BSTR FileName
);


Structures

Microsoft® DirectShow® Editing Services defines the following structures.

Structure | Description
DEXTER_PARAM | Specifies a property on a transition or effect.
DEXTER_VALUE | Specifies the value of a property.
SCompFmt0 | Contains format information for smart recompression.


DEXTER_PARAM Structure

Specifies the value that a property assumes at a given time.

Syntax

typedef struct {
    BSTR      Name;
    DISPID    dispID;
    LONG      nValues;
} DEXTER_PARAM;

Members

Name
Name of the property.
dispID
Dispatch ID (DISPID) of the property, or zero if the Name member is specified.
nValues
Number of values that the property assumes.

Remarks

The object must support the IDispatch interface.

If you know the DISPID of the property, you can set the dispID member. Typically, however, you would set the Name member equal to the text name of the property and set dispID to 0. The property setter calls IDispatch::GetIDsOfNames to retrieve the DISPID.

See Also

IPropertySetter, DEXTER_VALUE,


DEXTER_VALUE Structure

Identifies a property that is to be set on a transition or effect, along with the number of distinct values that the property assumes over the duration of the transition or effect.

Syntax

typedef struct {
    VARIANT           v;
    REFERENCE_TIME    rt;
    DWORD             dwInterp;
} DEXTER_VALUE;

Members

v
Value of the property.
rt
Time at which the property assumes the value, relative to the start of the transition or effect.
dwInterp
Flag indicating how the property progresses from the previous value to this value. Must be one of the following:
DEXTERF_JUMP | The property jumps instantly to the new value at the specified time.
DEXTERF_INTERPOLATE | The property is interpolated linearly over time from the previous value.

See Also

IPropertySetter, DEXTER_PARAM


SCompFmt0 Structure

Contains format information for smart recompression.

Syntax

typedef struct _SCompFmt0
{
    long nFormatId;
    AM_MEDIA_TYPE MediaType;
} SCompFmt0;

Members

nFormatId
Reserved; must be zero.
MediaType
AM_MEDIA_TYPE structure that describes the compression format.

See Also

IAMTimelineGroup::GetSmartRecompressFormat, IAMTimelineGroup::SetSmartRecompressFormat


Enumerated Types

Microsoft® DirectShow® Editing Services defines the following enumerated types.

Enumerated Types

DEXTERF_TRACK_SEARCH_FLAGS | Specifies the boundary conditions on a search for an object in the timeline.
TIMELINE_MAJOR_TYPE | Specifies the major type of a timeline object.


DEXTERF_TRACK_SEARCH_FLAGS Enumerated Type

Specifies the boundary conditions on a search for an object in the timeline.

Syntax

typedef enum
{
    DEXTERF_BOUNDING = -1,
    DEXTERF_EXACTLY_AT = 0,
    DEXTERF_FORWARDS = 1
} DEXTERF_TRACK_SEARCH_FLAGS;

Elements

DEXTERF_BOUNDING
Search for an object that spans the specified time.
DEXTERF_EXACTLY_AT
Search for an object that starts exactly at the specified time.
DEXTERF_FORWARDS
Search for an object that starts at the specified time or later.

Remarks

These boundary conditions are summarized in the following table.

Enumeration value | Boundary condition
DEXTERF_BOUNDING Start <= Time
Stop > Time
DEXTERF_EXACTLY_AT | Start == Time
DEXTERF_FORWARDS | Start >= Time
  • Start: start time of the retrieved object.
  • Stop: stop time of the retrieved object.
  • Time: specified search time.

See Also

IAMTimelineTrack::GetSrcAtTime


TIMELINE_MAJOR_TYPE Enumerated Type

Specifies the major type of an object.

Syntax

typedef enum
{
    TIMELINE_MAJOR_TYPE_COMPOSITE = 1,
    TIMELINE_MAJOR_TYPE_TRACK = 2,
    TIMELINE_MAJOR_TYPE_SOURCE = 4,
    TIMELINE_MAJOR_TYPE_TRANSITION = 8,
    TIMELINE_MAJOR_TYPE_EFFECT = 16,
    TIMELINE_MAJOR_TYPE_GROUP = 128
} TIMELINE_MAJOR_TYPE;

Elements

TIMELINE_MAJOR_TYPE_COMPOSITE
Composite object. Holds one or more tracks.
TIMELINE_MAJOR_TYPE_TRACK
Track object. Holds one or more sources.
TIMELINE_MAJOR_TYPE_SOURCE
Source object. Contains a reference to a media source.
TIMELINE_MAJOR_TYPE_TRANSITION
Transition object. Defines a transition between composites, tracks, or sources.
TIMELINE_MAJOR_TYPE_EFFECT
Effect object. Defines a single-input effect to be applied to a composite, track, or source object.
TIMELINE_MAJOR_TYPE_GROUP
Group object. Contains one or more tracks of a given type.

See Also

IAMTimeline, IAMTimelineComp::GetCountOfType, IAMTimelineObj::GetTimelineType


Constants

Microsoft® DirectShow® Editing Services defines the following constants.

  • Dynamic Reconnection Flags
  • File Name Validation Flags
  • Resize Flags

Dynamic Reconnection Flags

These flags specify the level of dynamic reconnection to use during rendering.

Constant | Value | Description
CONNECTF_DYNAMIC_NONE | 0x00 | No dynamic reconnection. Load everything before rendering the project.
CONNECTF_DYNAMIC_SOURCES | 0x01 | Load sources only as needed.
CONNECTF_DYNAMIC_EFFECTS | 0x02 | Reserved. Do not use.

See Also

IRenderEngine::SetDynamicReconnectLevel

File Name Validation Flags

These flags specify the behavior of the media locator.

Constant | Value | Description
SFN_VALIDATEF_CHECK | 0x01 | Check the validity of file names. You must set this flag to validate file names. If not, the other flags have no effect.
SFN_VALIDATEF_POPUP | 0x02 | If a file is not located, display an Open File dialog box for the end user.
SFN_VALIDATEF_TELLME | 0x04 | If a missing file is located, briefly display a message box with the name and location of the file. This flag is mostly useful for testing purposes; the message box is probably not suitable for a retail product.
SFN_VALIDATEF_REPLACE | 0x08 | If a missing file is located, update the name of the source object. (Only valid in the IAMTimeline::ValidateSourceNames method.)
SFN_VALIDATEF_USELOCAL | 0x10 | Search local directories only, not directories on the network.
SFN_VALIDATEF_NOFIND | 0x20 | Do not search for missing files. File names are still validated if you set the SFN_VALIDATEF_CHECK flag.
SFN_VALIDATEF_IGNOREMUTED | 0x40 | Ignore muted source objects. (Only valid in the IAMTimeline::ValidateSourceNames method.)

See Also

IMediaLocator::FindMediaFile, IRenderEngine::SetSourceNameValidation

Resize Flags

These flags specify how a video source is rendered if its size does not match the output dimensions.

Constant | Value | Description
RESIZEF_STRETCH | 0 | The image is stretched to fit the target frame size in both dimensions, without preserving the aspect ratio.
RESIZEF_CROP | 1 | The image is not resized. If the image is smaller than the target frame, the surrounding area is black. If the image is larger than the target frame, the image is cropped.
RESIZEF_PRESERVEASPECTRATIO | 2 | The image is resized to fit the target frame along one dimension, while preserving the aspect ratio. If the ratio of width to height in the image does not match the ratio in the target frame, it creates a letterbox.
RESIZEF_PRESERVEASPECTRATIO_NOLETTERBOX | 3 | The image is resized to fill the entire target frame while preserving the aspect ratio. Rather than create a letterbox, this mode crops the image, either along the sides or across the top and bottom.

The following images show the effects of these flags.

See Also

IAMTimelineSrc::GetStretchMode, IAMTimelineSrc::SetStretchMode


Transitions and Effects

This section describes the effects and transitions provided with Microsoft® DirectShow® Editing Services.

Transitions

Compositor | Stretches the foreground into a designated rectangle, without altering the background.
Key | Performs keying based on chroma, alpha, hue, or luminance.
SMPTE Wipe | Performs the standard SMPTE wipes.

Effects

Alpha Setter | Sets the alpha bits on a video image.
Volume Envelope | Sets the volume on an audio stream.

Source Objects

Video Color Source Creates a continuous video image of a solid color.


Alpha Setter Effect

Sets the alpha bits on a video image.

Class ID (CLSID): 506D89AE-909A-44f7-9444-ABD575896E35

CLSID Variable Name: CLSID_DxtAlphaSetter

Properties

Property | Type | Default | Description
Alpha | BYTE | -1 | Sets the alpha for the entire image.
AlphaRamp | double | -1.0 | Sets the alpha as a percentage of the original alpha value.

Remarks

A property with a negative value is ignored. Only one property can have a non-negative value. The Alpha property specifies a constant alpha value for every pixel in the image. This property overwrites the alpha values from the original image. The AlphaRamp property specifies each pixel's alpha value as a percentage of the pixel's original value, from 0.0 to 1.0.

See Also

Alpha Blending


Compositor Transition

Composites a subrectangle from the foreground into a designated rectangle on the background, without altering the rest of the background. Use this transition to create split-screen or picture-in-picture effects.

The following image shows the compositor transition:

Class ID (CLSID): BB44391D-6ABD-422f-9E2E-385C9DFF51FC

CLSID Variable Name: CLSID_DxtCompositor

Properties

Property | Type | Default | Description
Height | long | 0 | Height of the target rectangle, in pixels.
OffsetX | long | 0 | Horizontal offset of the target rectangle, in pixels.
OffsetY | long | 0 | Vertical offset of the target rectangle, in pixels.
SrcHeight | long | 0 | The height of the subrectangle on the source, in pixels.
SrcOffsetX | long | 0 | The x-coordinate of the subrectangle on the source, in pixels.
SrcOffsetY | long | 0 | The y-coordinate of the subrectangle on the source, in pixels.
SrcWidth | long | 0 | The width of the subrectangle on the source, in pixels.
Width | long | 0 | Width of the target rectangle, in pixels.

The following diagram illustrates these properties:


Key Transition

Performs keying based on RGB value, alpha value, hue, or luminance.

The following image shows the key transition:

Class ID (CLSID): C5B19592-145E-11D3-9F04-006008039E37

CLSID Variable Name: CLSID_DxtKey

Properties

Property | Type | Valid range | Description | Applies To
Hue | int | 0–360 | The hue value on which to key. | Hue
Invert | BOOL | FALSE or TRUE | Boolean value indicating whether to invert the default operation of the key. If FALSE, pixels in the overlying image are made transparent in the default manner. If TRUE, the operation inverts. | Chroma, Hue, Luminance, Nonred
KeyType | int | See Remarks | Specifies the type of key. For more information, see Remarks. | All
Luminance | int | 0–100 | The luminance value on which to key. | Luminance
RGB | DWORD | 0x0 – 0xFFFFFF | The color on which to key. The value is a hexadecimal number with the format 0xRRGGBB, where RR is the red value, GG is the green value, and BB is the blue value. (Pure red, green, and blue are 0xFF0000, 0x00FF00, and 0x0000FF, respectively.) | Chroma, Hue
Similarity | int | 0–100 | The range of color data that becomes transparent. At higher values, a wider range of similar colors is transparent. | Chroma, Nonred

Remarks

The type of key that is performed depends on the value of the KeyType property, which must be one of the following:

Value | Enumeration | Description
0 | DXTKEY_RGB | Chroma key (key by RGB value).
1 | DXTKEY_NONRED | Nonred key. (Makes blue and green areas transparent.)
2 | DXTKEY_LUMINANCE | Luminance key.
3 | DXTKEY_ALPHA | Key by alpha value.
4 | DXTKEY_HUE | Key by hue.

The key type defaults to DXTKEY_ALPHA.


SMPTE Wipe Transition

Produces any of the standard wipes defined by the Society of Motion Picture and Television Engineers (SMPTE) in SMPTE document 258M-1993, with the exception of the quad split.

The following image shows a wipe transition in progress:

Class ID (CLSID): DE75D012-7A65-11D2-8CEA-00A0C9441E20

CLSID Variable Name: CLSID_DxtJpeg

Properties

Property | Type | Default | Description
BorderColor | long | 0x000000 | Color of the border around the edges of the wipe pattern. The value of this attribute is a hexadecimal number with the format 0xRRGGBB, where RR is the red hexadecimal value, GG is the green hexadecimal value, and BB is the blue hexadecimal value. (Thus, pure red, green, and blue are 0xFF000, 0x00FF00, and 0x0000FF, respectively.)
BorderSoftness | long | 0 | Width of the blurry region around the edges of the wipe pattern. Specify zero for no blurry region.
BorderWidth | long | 0 | Width of the solid border around the edges of the wipe pattern. Specify zero for no border.
MaskName | BSTR | NULL | If not NULL, specifies the name of a JPEG file to use as the wipe mask instead of a standard, built-in wipe. The file must contain a monochrome, 8-bits-per-pixel gradient. The gradient is used as a mask to define the wipe's progression.
MaskNum | long | 1 | Standard SMPTE wipe code specifying the style of wipe to use. For a list of wipe codes and their associated schematics, see SMPTE document 258M-1993.
OffsetX | long | 0 | Offset of the wipe origin from the center of the image, in the horizontal direction.
OffsetY | long | 0 | Offset of the wipe origin from the center of the image, in the vertical direction.
ReplicateX | long | 0 | Number of times to replicate the wipe pattern in the horizontal direction.
ReplicateY | long | 0 | Number of times to replicate the wipe pattern in the vertical direction.
ScaleX | double | 1.0 | Amount by which to stretch the wipe in the horizontal direction, as a percentage of the original wipe definition.
ScaleY | double | 1.0 | Amount by which to stretch the wipe in the vertical direction, as a percentage of the original wipe definition.


Video Color Source

Creates a continuous video image of a solid color.

Class ID (CLSID): 1c621200-67b2-11d2-9eeb-006008039e37

CLSID Variable Name: CLSID_ColorSource

Properties

Property | Type | Default | Description
Color | DWORD | 0 | Color to generate. The value of this attribute is a hexadecimal number with the format 0xAARRGGBB, where AA is the alpha value, RR is the red value, GG is the green value, and BB is the blue value. Alpha values range from 0x00 (transparent) to 0xFF (opaque). The property is static and must be applied at time zero.

Remarks

The Video Color Source is used with source objects. First, create a new source object. Then set the source object's subobject GUID to CLSID_ColorSource, by calling the IAMTimelineObj::SetSubobjectGUID method.

To set the color, create a property setter object and apply the Color property at time zero. The Video Color Source does not support dynamic changes to this property; the value cannot change over time.

The following code example shows how to use this object. For more information about using IPropertySetter, see Setting Properties on Effects and Transitions:

DWORD           dwYellow = 0xFFFF00;
IAMTimelineObj  *pSource = NULL;
IPropertySetter *pProp = NULL;

pTimeline->CreateEmptyNode(&pSourceObj, TIMELINE_MAJOR_TYPE_SOURCE);
pSource->SetStartStop(0, 50000000);
pSource->SetSubObjectGUID(CLSID_ColorSource);

// Create a property setter.
CoCreateInstance(CLSID_PropertySetter, NULL, CLSCTX_INPROC_SERVER,
    IID_IPropertySetter, (void**) &pProp);

// Set the color.
DEXTER_PARAM param;
DEXTER_VALUE val;

param.Name = SysAllocString(L"Color");
param.dispID = 0;
param.nValues = 1;

val.v.vt = VT_I4;
val.v.lVal = dwYellow;
val.rt = 0;  // Time must be zero.
val.dwInterp = DEXTERF_JUMP;

pProp->AddProp(param, &val);
pSource->SetPropertySetter(pProp);

// Clean up.
SysFreeString(param.Name);
VariantClear(&val.v));
pProp->Release();

The following example shows the XML representation of the object created in the previous example. In this case the PARAM tag does not support AT or LINEAR tags, because the object does not support dynamic properties:

<clip start="0" stop="5" clsid="{0CFDD070-581A-11D2-9EE6-006008039E37}">
<param name="Color" value="16776960"/>
</clip>


Volume Envelope Effect

Sets the volume on an audio stream.

Class ID (CLSID): 036A9790-C153-11D2-9EF7-006008039E37

CLSID Variable Name: CLSID_AudMixer

Properties

Property | Type | Default | Description
Vol | double | 1.0 | Volume, as a percentage of the authored volume. You can produce audio fades by varying this property value over time.

Remarks

Each object in a timeline can have at most one volume envelope effect. On a track, composition, or group, the volume envelope is always applied last, after any other audio effects. (On a clip, the volume effect is applied according to its priority, like any other effect.)


DirectShow Editing Services Components

Microsoft® DirectShow® Editing Services (DES) includes the following COM components. (See also: Transitions and Effects.)

  • Composition
  • Effect
  • Group
  • Media Detector
  • Media Locator
  • Property Setter
  • Render Engine (Basic)
  • Render Engine (Smart)
  • Source
  • Timeline
  • Track
  • Transition
  • XML Parser

    • Composition

    Description | Contains tracks and other compositions.
    Class Identifier | Not applicable. Use IAMTimeline::CreateEmptyNode to create.
    Interfaces
    • IAMTimelineComp
    • IAMTimelineEffectable
    • IAMTimelineObj
    • IAMTimelineTransable
    • IAMTimelineVirtualTrack
    See Also | The Timeline Model, Constructing a Timeline

    Effect

    Description | Produces a video or audio effect.
    Class Identifier | Not applicable. Use IAMTimeline::CreateEmptyNode to create.
    Interfaces
    • IAMTimelineEffect
    • IAMTimelineObj
    • IAMTimelineSplittable
    • IPropertyBag
    See Also | The Timeline Model, Working with Effects and Transitions

    Group

    Description | Top-level composition.
    Class Identifier | Not applicable. Use IAMTimeline::CreateEmptyNode to create.
    Interfaces
    • IAMTimelineComp
    • IAMTimelineGroup
    • IAMTimelineObj
    See Also | The Timeline Model, Constructing a Timeline

    Media Detector

    Description | Retrieves information and still frames from file sources.
    Class Identifier | CLSID_MediaDet
    Interfaces
    • IMediaDet
    See Also | Working with Sources

    Media Locator

    Description | Locates the files associated with source objects.
    Class Identifier | CLSID_MediaLocator
    Interfaces
    • IMediaLocator
    See Also | Working with Sources

    Property Setter

    Description | Sets IDispatch properties on a timeline object.
    Class Identifier | CLSID_PropertySetter
    Interfaces
    • IAMSetErrorLog
    • IPropertySetter
    See Also | The Timeline Model, Working with Effects and Transitions

    Render Engine (Basic)

    Description | Renders uncompressed output from a timeline.
    Class Identifier | CLSID_RenderEngine
    Interfaces
    • IAMSetErrorLog
    • IRenderEngine
    See Also | Rendering a Project

    Render Engine (Smart)

    Description | Renders compressed output from a timeline.
    Class Identifier | CLSID_SmartRenderEngine
    Interfaces
    • IAMSetErrorLog
    • IRenderEngine
    • ISmartRenderEngine
    See Also | Rendering a Project

    Source

    Description | Represents a source clip in timeline.
    Class Identifier | Not applicable. Use IAMTimeline::CreateEmptyNode to create.
    Interfaces
    • IAMTimelineEffectable
    • IAMTimelineObj
    • IAMTimelineSrc
    • IAMTimelineSplittable
    See Also | The Timeline Model, Working with Sources

    Timeline

    Description | Contains all of the objects in a video editing project.
    Class Identifier | CLSID_AMTimeline
    Interfaces
    • IAMTimeline
    • IAMSetErrorLog
    • IPersistStream
    See Also | The Timeline Model, Constructing a Timeline

    Track

    Description | Contains source objects.
    Class Identifier | Not applicable. Use IAMTimeline::CreateEmptyNode to create.
    Interfaces
    • IAMTimelineEffectable
    • IAMTimelineObj
    • IAMTimelineSplittable
    • IAMTimelineTrack
    • IAMTimelineTransable
    • IAMTimelineVirtualTrack
    See Also | The Timeline Model, Constructing a Timeline

    Transition

    Description | Creates a transition between tracks or compositions.
    Class Identifier | Not applicable. Use IAMTimeline::CreateEmptyNode to create.
    Interfaces
    • IAMTimelineObj
    • IAMTimelineSplittable
    • IAMTimelineTrans
    See Also | The Timeline Model, Working with Effects and Transitions

    XML Parser

    Description | Converts an XML project file into a timeline.
    Class Identifier | CLSID_Xml2Dex
    Interfaces
    • IXml2Dex
    See Also | Loading and Previewing a Project


XML Format Reference

Microsoft DirectX 8.0

XML Reference

Microsoft® DirectShow® Editing Services uses an Extensible Markup Language (XML) persistence format. The format defines the following elements.

Element | Description
AT | Specifies a time-based setting for a PARAM element.
CLIP | Specifies a source file.
COMPOSITE | Defines a composition.
EFFECT | Defines an effect.
GROUP | Defines a group (audio or video).
LINEAR | Specifies a time-based setting for a PARAM element.
PARAM | Specifies the value of a property on a transition, effect, or other subobject.
TIMELINE | Defines the timeline.
TRACK | Defines a track.
TRANSITION | Defines a transition.

Attribute Data Types

The following attribute types require special formatting:

Boolean: The following values are defined as TRUE: y, Y, t, T, 1. The following values are defined as FALSE: n, N, f, F, 0 (zero).

CLSID: Class identifiers are specified as strings, with the format {00000000-0000-0000-0000-000000000000}.

Float: All floating-point values must include the leading zero before the decimal place. For example, 0.3, not .3.

Time: Time values use hh:mm:ss.ff format, where hh = hours, mm = minutes, ss = seconds, and ff = fractions of seconds. Example: 1:04:30.512. Leading units can be omitted. For example, 3:00 (three minutes) and 45 (45 seconds) are both valid.


AT Element

XML Reference

Defines the value of a PARAM element at a particular time, relative to the start of the transition or effect that contains the parameter. The AT element causes the parameter to jump abruptly to the new value at the given time. For a smooth progression to a new value, use the LINEAR element.

Example

<AT TIME="1" VALUE="0.5" />

Attributes

Name | Description | Type
TIME | Time at which the parameter assumes the new value, relative to the start of the transition or effect. | Time
VALUE | Value the parameter has at the specified time. | See Remarks.

Parent/Child Information

Parent | PARAM
Children | None

Remarks

The data type for the VALUE attribute depends on the propery being set. For more information, see Transitions and Effects.


CLIP Element

XML Reference

Specifies a media source.

Example

<CLIP SRC="sample.avi" START="1:05" STOP="1:42.5" MSTART="30" />

Attributes

Name | Description | Type | C/C++ Equivalent
CLSID | CLSID of a source filter to use as the source. Do not specify this attribute if the SRC attribute is specified. | CLSID | IAMTimelineObj::SetSubObjectGUID
FRAMERATE | Default frame rate, in frames per second. Applies to still images and DIB sequences. For a still image, set the value to zero. For a DIB sequence, use a nonzero value. The default value is zero. Do not use a value with more than seven decimal digits. | Float | IAMTimelineSrc::SetDefaultFPS
LOCK Specifies whether the clip is locked (should not be edited).
  • TRUE: The clip is locked.
  • FALSE: The clip is not locked. (Default)
Boolean IAMTimelineObj::SetLocked
MLENGTH | Duration of the original file. This value must be the actual duration, or rendering errors may occur. | Time | IAMTimelineSrc::SetMediaLength
MSTART | Start time of the clip, relative to the original media file. | Time | IAMTimelineSrc::SetMediaTimes
MSTOP | Stop time of the clip, relative to the original media file. | Time | IAMTimelineSrc::SetMediaTimes
MUTE Specifies the source's mute state.
  • TRUE: The source is not rendered.
  • FALSE: The source is rendered. (Default)
Boolean IAMTimelineObj::SetMuted
SRC | Path name of the media file. The file can be any type supported by DirectShow or a still image. The supported formats for still images are bitmap, device-independent bitmap, GIF, and JPEG. For more details, see Remarks. Do not specify this attribute if the CLSID attribute is specified. | String | IAMTimelineSrc::SetMediaName
START | Start time of the clip, relative to the timeline. | Time | IAMTimelineObj::SetStartStop
STOP | Stop time of the clip, relative to the timeline. | Time | IAMTimelineObj::SetStartStop
STREAM | Specifies which stream to use in a multistream file, such as an AVI file. | Integer | IAMTimelineSrc::SetStreamNumber
STRETCHMODE Specifies how an image that does not match the output dimensions is stretched. Can have one of the following values.
  • Stretch: The image is stretched to fit the output frame size without preserving aspect ratio. (Default)
  • Crop: The image is cropped to fit the output frame size.
  • PreserveAspectRatio: The original aspect ratio is preserved, with a black letterbox along the shorter dimension.
  • PreserveAspectRatioNoLetterBox: The image is resized to fill the entire target frame while preserving the aspect ratio.
 String IAMTimelineSrc::SetStretchMode
USERDATA | Application-defined persistent data. Must be an even number of digits. The values A–F must be capitalized. Do not use a prefix such as 0x. Example: 123ABC. | Hexadecimal | IAMTimelineObj::SetUserData
USERID | Application-defined identifier for the object. | Integer | IAMTimelineObj::SetUserID
USERNAME | Application-defined name for the object. | String | IAMTimelineObj::SetUserName

Parent/Child Information

Parent | TRACK
Children | EFFECT

Remarks

Specify at least one start-time attribute (START or MSTART) and one stop-time attribute (STOP or MSTOP). If one of the start-time attributes is unspecified, it defaults to 0 (the beginning of the timeline for START, or the beginning of the clip for MSTART). If one of the stop-time attributes is unspecified, DES assumes a normal playback rate and calculates the unspecified stop time accordingly. If both stop times are specified, playback is faster or slower than normal, if necessary.

In the following example, the timeline duration is seven seconds (STOP minus START). Normal playback rate is assumed, so the media stop time defaults to 10 seconds (the duration plus MSTART).

<CLIP START="2" STOP="9" MSTART="3" />

In the second example, the media start time defaults to 0, forcing the media duration to be 10 seconds. The timeline duration is five seconds, so the clip plays back at twice the normal rate.

<CLIP START="5" STOP="10" MSTOP="10" />

If a still image is specified for the SRC attribute, DES attempts to load a series of still images to create an animation. For example, if the SRC attribute is IMAGE001.BMP, DES looks for IMAGE002.BMP, IMAGE003.BMP, IMAGE004.BMP, and so on. Assuming that they exist, they are displayed in sequential numerical order at the rate specified by the FRAMERATE attribute.


COMPOSITE Element

XML Reference

Defines a composition, a container object for tracks and other nested compositions.

Example

<COMPOSITE> </COMPOSITE>

Attributes

Name | Description | Type | C/C++ Equivalent
LOCK Specifies whether the composition is locked (should not be edited).
  • TRUE: The composition is locked.
  • FALSE: The composition is not locked. (Default)
Boolean IAMTimelineObj::SetLocked
MUTE Specifies the mute state of the composition and all children.
  • TRUE: The composition and all of its children are not rendered.
  • FALSE: The composition is rendered; children are rendered according to their own mute state. (Default)
Boolean IAMTimelineObj::SetMuted
USERDATA | Application-defined persistent data. Must be an even number of digits. The values A–F must be capitalized. Do not use a prefix such as 0x. Example: 123ABC. | Hexadecimal | IAMTimelineObj::SetUserData
USERID | Application-defined identifier for the object. | Integer | IAMTimelineObj::SetUserID
USERNAME | Application-defined name for the object. | String | IAMTimelineObj::SetUserName

Parent/Child Information

Parent | COMPOSITE, GROUP
Children | COMPOSITE, EFFECT, TRACK, TRANSITION

Remarks

Within a COMPOSITE element, the priority of nested layers is determined implicitly by the order in which they appear inside the tag. The first layer has priority 0, and subsequent layers have increasing priority values.


EFFECT Element

XML Reference

Defines an effect object. An effect is a one-input transform applied to a single stream (such as a composition, track, or source).

Example

<EFFECT CLSID="{B05A941C-3CE1-11D2-952A-00C04FA34F05}" START="0" STOP="32.0" />

Attributes

Name | Description | Type | C/C++ Equivalent
CLSID | The class identifier (CLSID) of the subobject that creates the effect. | CLSID | IAMTimelineObj::SetSubObjectGUID
LOCK Specifies whether the effect is locked (should not be edited).
  • TRUE: The effect is locked.
  • FALSE: The effect is not locked. (Default)
Boolean IAMTimelineObj::SetLocked
MUTE Specifies the effect's mute state.
  • TRUE: The effect is not rendered.
  • FALSE: The effect is rendered. (Default)
Boolean IAMTimelineObj::SetMuted
START | Start time of the effect, relative to the parent object. | Time | IAMTimelineObj::SetStartStop
STOP | Stop time of the effect, relative to the parent object. | Time | IAMTimelineObj::SetStartStop
USERDATA | Application-defined persistent data. Must be an even number of digits. The values A–F must be capitalized. Do not use a prefix such as 0x. Example: 123ABC. | Hexadecimal | IAMTimelineObj::SetUserData
USERID | Application-defined identifier for the object. | Integer | IAMTimelineObj::SetUserID
USERNAME | Application-defined name for the object. | String | IAMTimelineObj::SetUserName

Parent/Child Information

Parent | COMPOSITE, GROUP, CLIP, TRACK
Children | PARAM


GROUP Element

XML Reference

Defines a group, the top-level object in a timeline.

Example

<GROUP TYPE="video" WIDTH="640" HEIGHT="480" FRAMERATE="30"> </GROUP>

Attributes

Name | Description | Type | C/C++ Equivalent
BITDEPTH | Bit depth of the output video, in bits per pixel. Must be 16, 24, or 32. Set this attribute only if the TYPE attribute is video. The default value is 16. | Integer
BUFFERING | Number of frames to render in advance during preview. Must be a number greater than 1. The default value is 30. | Integer | IAMTimelineGroup::SetOutputBuffering
FRAMERATE | Output frame rate, in frames per second. Do not use values with more than seven decimal digits. | Float | IAMTimelineGroup::SetOutputFPS
HEIGHT | Height of the output video, in pixels. Set this attribute only if the TYPE attribute is video. | Integer
LOCK Specifies whether the group is locked (should not be edited).
  • TRUE: The group is locked.
  • FALSE: The group is not locked. (Default)
Boolean IAMTimelineObj::SetLocked
MUTE Specifies the group's mute state.
  • TRUE: The group and all of its children are not rendered.
  • FALSE: The group is rendered; children are rendered according to their own mute state. (Default)
Boolean IAMTimelineObj::SetMuted
PREVIEWMODE Preview mode for the group.
  • TRUE: Frames might be dropped during preview. (Default)
  • FALSE: No frames are dropped.
Under the default setting, frames are dropped while previewing slow effects or transitions, to keep the video synchronized with the audio. The video might look choppy as a result. Setting this attribute to FALSE forces every frame to render during preview, possibly resulting in the video becoming out of sync with the audio. (Frames are never dropped when writing to a file.) 		Boolean IAMTimelineGroup::SetPreviewMode
SAMPLINGRATE | Sampling rate of the output audio, in Hz. Must be 8000, 11025, 22050, 32000, 44100, or 48000. Set this attribute only if the TYPE attribute is audio. The default value is 44100. | Integer
TYPE | Group media type. Must be either video or audio. | String | IAMTimelineGroup::SetMediaType
USERDATA | Application-defined persistent data. Must be an even number of digits. The values A–F must be capitalized. Do not use a prefix such as 0x. Example: 123ABC. | Hexadecimal | IAMTimelineObj::SetUserData
USERID | Application-defined identifier for the object. | Integer | IAMTimelineObj::SetUserID
USERNAME | Application-defined name for the object. | String | IAMTimelineObj::SetUserName
WIDTH | Width of the output video, in pixels. Set this attribute only if the TYPE attribute is video. | Integer

Parent/Child Information

Parent | TIMELINE
Children | COMPOSITE, EFFECT, TRACK

Remarks

Within a GROUP element, the priority of nested layers is determined implicitly by the order in which they appear inside the tag. The first layer has priority 0, and subsequent layers have increasing priority values.


LINEAR Element

XML Reference

Defines the value of a PARAM element at a particular time, relative to the start of the transition or effect that contains the PARAM element. The LINEAR element causes the parameter to make a smooth transition from its previous value to the new value. For an instantaneous jump to a new value, use the AT element.

Example

<LINEAR TIME="6" VALUE="0.0" />

Attributes

Name | Description | Type
TIME | Time at which the parameter assumes the new value, relative to the start of the transition or effect. | Time
VALUE | Value the parameter has at the specified time. | See Remarks.

Parent/Child Information

Parent | PARAM
Children | None

Remarks

The data type for the VALUE attribute depends on the propery being set. For more information, see Transitions and Effects.


PARAM Element

XML Reference

Specifies the value of a property on a transition, effect, or other subobject.

Example

<PARAM NAME="progress" VALUE="1.0" />

Attributes

Name | Description | Type
NAME | Name of the property to set. | String
VALUE | Value the property has at time 0, relative to the start of the transition or effect. Use the AT or LINEAR element to specify the value after time 0. If the PARAM element contains no AT or LINEAR elements, the value specified by this attribute remains constant over the entire effect or transition. | Depends on the property.

Parent/Child Information

Parent | CLIP, EFFECT, TRANSITION
Children | AT, LINEAR

Remarks

Many effects and transitions support properties that control various aspects of their behavior.

Most transitions support a standard Progress property that ranges from 0 to 1.0, indicating what percentage of the transition is reflected in the output. At Progress = 0.0, the transition is at the beginning of its sequence (entirely the first video image). At Progress = 0.5, the transition is half complete. (For example, in a wipe, at Progress = 0.5 the transition boundary is in the center of the image) At Progress = 1.0, the transition is complete (entirely the second image). By default, transitions go from Progress = 0.0 at the start of the transition to Progress = 1.0 at the end.

Other properties are usually specific to one particular transition or effect. For example, the wipe transition supports a GradientSize property that controls the width of the transition area. For more information about properties, see Transform Properties in the Microsoft® DirectX® Transform documentation.

You can set a property on a transition or effect by including a PARAM element. The VALUE attribute specifies the value of the property at time 0 (relative to the start of the transition or effect). If the PARAM element contains no children, the specified value remains constant over the duration of the transition or effect. To change the value over time, nest AT or LINEAR elements within the PARAM element. The AT element causes the property to jump directly from the old value to a new value at a specified time. The LINEAR element creates a smooth transition to a new value; DES interpolates the intermediate values.

In the following example, the Progress property starts at 0.0, jumps to 1.0 at time 2, and then makes a smooth progression back to 0.5 from time 2 to time 6.

<TRANSITION CLSID="{AF279B30-86EB-11D1-81BF-0000F87557DB}" START="0" STOP="6">
    <PARAM NAME="Progress" VALUE="0.0">
        <AT TIME="2" VALUE="1.0" />
        <LINEAR TIME="6" VALUE="0.5" />
    </PARAM>
</TRANSITION>

To run a transition backward, reverse the default behavior of the Progress property:

<TRANSITION CLSID="{AF279B30-86EB-11D1-81BF-0000F87557DB}" START="0" STOP="6">
    <PARAM NAME="Progress" VALUE="1.0">
        <LINEAR TIME="6" VALUE="0.0" />
    </PARAM>
</TRANSITION>


TIMELINE Element

XML Reference

Defines the timeline. This element is the root node in the XML file.

Example

<TIMELINE> </TIMELINE>

Attributes

Name | Description | Type | C/C++ Equivalent
DEFAULTFX | CLSID of the default effect. | CLSID | IAMTimeline::SetDefaultEffect
DEFAULTRANS | CLSID of the default transition. | CLSID | IAMTimeline::SetDefaultTransition
ENABLEFX Specifies whether effects are enabled.
  • TRUE: Effects are rendered. (Default)
  • FALSE: Effects are not rendered.
Boolean IAMTimeline::EnableEffects
ENABLETRANS Specifies whether transitions are enabled.
  • TRUE: Transitions are rendered normally. (Default)
  • FALSE: Transitions are rendered as cuts.
Boolean IAMTimeline::EnableTransitions
FRAMERATE | Default frame rate, in frames per second. Do not use values with more than 7 decimal digits. If a group's FRAMERATE attribute is specified, it overrides this value. | Float | IAMTimeline::SetDefaultFPS

Parent/Child Information

Parent | None. This element must be the root node in the file.
Children | GROUP


TRACK Element

XML Reference

Defines a track object.

Example

<TRACK> </TRACK>

Attributes

Name | Description | Type | C/C++ Equivalent
LOCK Specifies whether the track is locked (should not be edited).
  • TRUE: The track is locked.
  • FALSE: The track is not locked. (Default)
Boolean IAMTimelineObj::SetLocked
MUTE Specifies the mute state of the track.
  • TRUE: The track and all of its children are not rendered.
  • FALSE: The track is rendered; children are rendered according to their own mute state. (Default)
Boolean IAMTimelineObj::SetMuted
USERDATA | Application-defined persistent data. Must be an even number of digits. The values A–F must be capitalized. Do not use a prefix such as 0x. Example: 123ABC. | Hexadecimal | IAMTimelineObj::SetUserData
USERID | Application-defined identifier for the object. | Integer | IAMTimelineObj::SetUserID
USERNAME | Application-defined name for the object. | String | IAMTimelineObj::SetUserName

Parent/Child Information

Parent | COMPOSITE, GROUP
Children | CLIP, EFFECT, TRANSITION


TRANSITION Element

XML Reference

Defines a transition object. A transition is a two-input transform that results in a transition from one stream (such as a composite or track) to another.

Example

<TRANSITION
    CLSID="{2A54C913-07AA-11D2-8D6D-00C04F8EF8E0}"
    START="7"
    STOP="10"
/>

Attributes

Name | Description | Type | C/C++ Equivalent
CLSID | The class identifier (CLSID) of the subobject that creates the transition. | CLSID | IAMTimelineObj::SetSubObjectGUID
CUTPOINT | Time at which the transition cuts from one source to the next, if rendered as a cut. The value is relative to the start of the transition. | Time | IAMTimelineTrans::SetCutPoint
CUTSONLY Specifies whether the transition is rendered as a cut.
  • TRUE: The transition is an instantaneous cut.
  • FALSE: The transition is rendered normally. (Default)
Boolean IAMTimelineTrans::SetCutsOnly
LOCK Specifies whether the transition is locked (should not be edited). Must be one of the following values.
  • TRUE: The transition is locked.
  • FALSE: The transition is not locked. (Default)
Boolean IAMTimelineObj::SetLocked
MUTE Specifies the mute state of the transition. Must be one of the following values.
  • TRUE: The transition is not applied.
  • FALSE: The transition is applied. (Default)
Boolean IAMTimelineObj::SetMuted
START | Start time of the transition, relative to the parent object. | Time | IAMTimelineObj::SetStartStop
STOP | Stop time of the transition, relative to the parent object. | Time | IAMTimelineObj::SetStartStop
SWAPINPUTS Determines whether to swap the transition inputs.
  • TRUE: The inputs are swapped.
  • FALSE: The inputs are not swapped. (Default)
Boolean IAMTimelineTrans::SetSwapInputs
USERDATA | Application-defined persistent data. Must be an even number of digits. The values A–F must be capitalized. Do not use a prefix such as 0x. Example: 123ABC. | Hexadecimal | IAMTimelineObj::SetUserData
USERID | Application-defined identifier for the object. | Integer | IAMTimelineObj::SetUserID
USERNAME | Application-defined name for the object. | String | IAMTimelineObj::SetUserName

Parent/Child Information

Parent | COMPOSITE, TRACK
Children | PARAM

Remarks

By default, a transition proceeds from the composite of all lower-priority layers to the layer on which the transition resides. If the SWAPINPUTS attribute is 1, this direction is reversed. For more information about the layering model used by DES, see The Timeline Model.


Rendering Errors

Microsoft® DirectShow® Editing Services (DES) defines various error codes used to log rendering errors. If a project does not render correctly, the render engine calls the IAMErrorLog::LogError method. The following table summarizes the parameters given to LogError:

  • The error code is contained in the ErrorCode parameter
  • The description is contained in the ErrorString parameter.
  • The extra information, if any, is contained in the VARIANT pointed to by pExtraInfo.
  • If there is extra information, the VARIANT type is contained in the vt member of the VARIANT pointed to by pExtraInfo.

Note: The error codes described here are not HRESULT values. For a list of HRESULT return values specific to DES, see Error and Success Codes.

Error code | Description | Extra information | Variant type
DEX_IDS_BAD_SOURCE_NAME | File name doesn't exist, or DirectShow doesn't recognize the file extension. | File name | BSTR
DEX_IDS_BAD_SOURCE_NAME2 | File type does not match the file extension or the file is corrupt. | File name | BSTR
DEX_IDS_MISSING_SOURCE_NAME | File name was required, but wasn't given. | None | Not applicable
DEX_IDS_UNKNOWN_SOURCE | Cannot parse data source provided by this source. | None | Not applicable
DEX_IDS_INSTALL_PROBLEM | Unexpected error. Some DirectShow component is not installed properly. | None | Not applicable
DEX_IDS_NO_SOURCE_NAMES | Source filter does not accept file names. | None | Not applicable
DEX_IDS_BAD_MEDIATYPE | Group's media type is not supported. | Group number | int
DEX_IDS_STREAM_NUMBER | Invalid stream number for this source. | Stream number | int
DEX_IDS_OUTOFMEMORY | Out of memory. | None | Not applicable
DEX_IDS_DIBSEQ_NOTALLSAME | One bitmap in the sequence was not the same type as the others. | Bitmap name | BSTR
DEX_IDS_CLIPTOOSHORT | Clip's media times are invalid, or the device-independent bitmap (DIB) sequence is too short. Note If other rendering errors occur, this error might occur even though the media times are valid. | None | Not applicable
DEX_IDS_INVALID_DXT | Class identifier (CLSID) of the effect or transition is not a valid Microsoft® DirectX® Transform effect. | CLSID | BSTR
DEX_IDS_INVALID_DEFAULT_DXT | Default effect or transition is not a valid DirectX Transform effect. | CLSID | BSTR
DEX_IDS_NO_3D | Your version of DirectX does not support three-dimensional transforms. | CLSID | BSTR
DEX_IDS_BROKEN_DXT | This DirectX Transform effect is not the right kind, or is broken. | CLSID | BSTR
DEX_IDS_NO_SUCH_PROPERTY | No such property exists on the object. | Property name | BSTR
DEX_IDS_ILLEGAL_PROPERTY_VAL | Illegal value for this property. | Value specified | VARIANT
DEX_IDS_INVALID_XML | Syntax error in XML file. | Line number | VT_I4 (4-byte integer)
DEX_IDS_CANT_FIND_FILTER | Cannot find filter specified in XML by category and instance. | Friendly name (instance) | BSTR
DEX_IDS_DISK_WRITE_ERROR | Error writing XML file to disk. | None | Not applicable
DEX_IDS_INVALID_AUDIO_FX | CLSID not a valid DirectShow audio effect filter. | CLSID | BSTR
DEX_IDS_CANT_FIND_COMPRESSOR | Cannot find a compressor to produce the specified compression format. | None | Not applicable

The following errors should never occur. If you encounter one of these errors, please send a bug report to dxmbug.microsoft.com.

Error code | Description
DEX_IDS_TIMELINE_PARSE | Unexpected error parsing the timeline.
DEX_IDS_GRAPH_ERROR | Unexpected error building the filter graph.
DEX_IDS_GRID_ERROR | Unexpected error with the internal grid.
DEX_IDS_INTERFACE_ERROR | Unexpected error getting an interface.


DVD Applications

Microsoft® DirectShow® provides a component called the DVD Navigator source filter which simplifies DVD navigation tasks. The DVD Navigator has all the capabilities that you find on a full-featured stand-alone DVD player, plus additional capabilities specific to playing DVDs on personal computers. Using the DVD Navigator, C++ and scripting developers can create full-featured DVD applications without referring to the DVD specification. The DVD Navigator, in coordination with the decoder filters, also handles regional management and copyright protection (CSS and Macrovision), isolating application developers from these details.

The DVD Navigator filter works across an entire DVD-Video "volume," which consists of the files in the VIDEO_TS directory. Unlike most DirectShow source filters that work with individual streams or files, the DVD Navigator uses the DVD-Video structure of titles, chapters, and time codes. Developers wishing to play individual MPEG-2 files in DirectShow should use the MPEG-2 Splitter filter instead of the DVD Navigator filter. See MPEG-2 Support for more information.

C++ developers control the DVD Navigator directly through the Component Object Model (COM) interfaces it exposes. Developers using a scripting language or Microsoft® Visual Basic® control the DVD Navigator indirectly through the MSWebDVD ActiveX® control.

Most DVD applications, including as players with customized interfaces, Web pages that control DVD playback, PowerPoint presentations with embedded DVD video, can be created in HTML or Visual Basic using the MSWebDVD ActiveX control. This is simpler and faster than using C++, which is only required for more specialized applications, such as games, programs that overlay graphics on video, custom ActiveX controls or DLLs, and so on.

Note DirectShow provides all the filters necessary to navigate and play DVD-Video except the MPEG-2 decoder. To play DVDs using an application based on DirectShow, users must have installed on their system a third-party hardware or software decoder that is DirectShow-compatible.

This section contains the following topics.

  • New DVD Support Features in DirectShow 8.0
  • What Background Do I Need to Write a DVD Application?
  • DVD Basics
  • Writing a DVD Application in C++
  • Shortcuts to C++ DVD Reference Pages
  • Writing a Script-Based DVD Application
  • MSWebDVD ActiveX Control

For references on DVD/MPEG2 decoder development, see Decoder Development.

DVD-ROM content developers: The DVD-ROM Boilerplate video is located in the DXF > Extras folder of the DirectX® 8 Software Development Kit. (Click on "Explore this CD" to navigate to the folder. This folder does not install to your local drive.) The boilerplate video is provided for developers producing DVD-ROM titles that contain no DVD-Video formatted data. A disc without a proper DVD-Video zone may behave unpredictably when placed in a standalone DVD-Video player, possibly ejecting the disc or locking up. This confusing situation can be avoided by adding the DVD-ROM boilerplate video to the disc. When the disc is inserted into a DVD-Video player it will display a message informing the user that the disc is designed to work in a DVD-ROM PC with Microsoft® Windows®.


New DVD Support Features in DirectShow 8.0

The expanded functionality of the DVD Navigator filter is exposed through two new interfaces, IDvdControl2, which provides the "set" methods for the DVD Navigator, and IDvdInfo2, which provides the "get" methods. Scripting support for the DVD Navigator, including most new features, is provided through the MSWebDVD Microsoft® ActiveX® control.

The DVD Navigator incorporates a variety of new features requested by developers, including:

  • Karaoke support: You can now write a DVD-karaoke application using the DVD Navigator. (This requires a compatible decoder.)
  • Simplified access to DVD text information strings: The DVD Navigator now parses these strings and enables applications to easily enumerate, identify, and retrieve them.
  • Audio volume control through IBasicAudio
  • Support for customizing the DVD Navigator's behavior when the Stop command is issued: Applications can now instruct the DVD Navigator to either resume from the current location when restarting the filter graph, or start play from the beginning of the disc.
  • Digital Theater Systems (DTS) and Sony Dynamic Digital Sound (SDDS) audio support: Now DTS and SDDS audio streams are recognized by the DVD Navigator and passed to the audio decoder. (A third-party DTS-compatible or SDDS-compatible decoder is required to decode and play the audio.)
  • Improved support for parental level changes: The DVD Navigator now allows an application to accept, reject, or ignore parental level change commands from the disc.
  • Advanced options for managing the state of the DVD Navigator and synchronizing commands
  • Support for frame stepping, frame-accurate seeking, and reverse play: These new features require an updated video decoder that supports them.
  • The ability to save the current location in a title and return to it at any time.
  • Simplified support for time events in non-sequential PGC titles: For non-sequential PGC titles, the DVD Navigator now relays the raw timecode information to the application.
  • A new, more convenient data structure for handling timecode information: The DVD_HMSF_TIMECODE structure can be used in place of the binary coded decimal (BCD) format. DVD_HMSF_TIMECODE contains easily accessed members for hours, minutes, seconds, and frames, and can be cast to/from a ULONG.
  • The ability to control whether the filter graph flushes after a seek operation: The graph buffers can contain up to a few seconds of video at any given time. You can now instruct the graph to either finish playing the buffered video after a seek, or begin playing immediately at the new location.
  • The ability to set values in general parameter registers: An advanced feature for those familiar with the DVD specification who wish to implement advanced functionality.
  • The ability to generate numeric disc identifiers that are for all practical purposes unique: This is helpful in MSWebDVD applications where a disc needs to be associated with particular Web-based enhancements.


What Background Do I Need to Write a DVD Application?

All application developers should have a basic familiarity with the features provided by DVD technology such as parental management levels, multiple audio and subpicture streams, and angle blocks. DVD Basics briefly describes each of these features; more complete descriptions are available in third-party publications. You don't need to refer to the DVD specification unless you intend to implement advanced features beyond the Annex J command set.

C/C++ developers using the Microsoft® DirectShow® Component Object Model (COM) application programming interface (API) should be familiar with COM client programming techniques such as creating COM objects and obtaining and releasing COM interface pointers. You might also need a general knowledge of filter graph operations, because you might need to access and manipulate the graph directly.

If you are using Microsoft® Visual Basic®, Microsoft® JScript®, or Visual Basic Scripting Edition (VBScript), you should be familiar with the basics of hosting Microsoft® ActiveX® controls within an application. Writing a Script-Based DVD Application shows how to embed the control in a Web page and receive event notifications from it.


DVD Basics

The features that make DVD attractive to consumers—seamless branching, multiple languages, parental control, karaoke support, and multiple angles—also make the developer's job a little more complex. A DVD player must not only play back audio, video, and subpicture streams, but also must keep track of the navigation options that the disc is currently permitting, and correctly handle many types of user commands. The DVD Navigator shields you from much of this complexity while enabling you to create a fully-functional DVD application. You do not need to refer to the DVD specification to use the DVD Navigator API effectively, but you do need to know basic DVD navigation concepts. The following sections provide some necessary background information. You can find further information on DVD in third-party publications or on the World Wide Web.

  • Navigation Control Data
  • Audio, Video and Subpicture Data
  • Titles and Chapters
  • Menus
  • Parental Management Levels
  • Domains
  • User Operation Controls

Navigation Control Data

The audio and video data on a DVD-Video disc is interleaved at regular intervals with various kinds of navigation control data. This data may be an instruction that tells the player to do something, for example move to some particular place on the disc, or it may be an informational-only marker informing the player for example that the content that follows has a higher parental management level than the previous content, or that the chapter skip operation is disabled. The player relays this information to an application, and it is the responsibility of the application to act on it. These navigation markers are part of what give DVD its higher level of user-interactivity compared to Video CDs. A DVD-player application must handle events that originate with the disc as well as events that originate with the user.

Audio, Video and Subpicture Data

A DVD-Video disc contains three primary types of streams: video, audio and subpicture.

  • The video stream can contain up to nine "angles," which can be thought of as substreams. DVD authors can include multiple angles wherever they wish to offer the viewer a choice of camera angles from which to view the same scene. Only one angle can be active at a time. The video stream also contains line 21 Closed Caption data, if any exists.
  • There can be up to eight separate audio streams, or tracks, providing up to eight multichannel soundtracks and allowing DVD karaoke discs to make use of multichannel audio.
  • There can be up to 32 subpicture stream containing bitmap graphics used for menu buttons and subtitles. The subpicture data streams are independent of the Closed Caption data in the video stream, although they may look similar when they appear in the video rectangle. If a disc contains both subpicture and Closed Caption data, you cannot display both at the same time.

Titles and Chapters

The main logical division on a DVD-Video disc is a title. A title can represent an entire movie or a 30-second video clip. There may be up to 99 titles on a disc and disc authors may divide the title into as many as 999 logical chapters. In most feature films on DVD, movie content is formatted as a series of chapters which automatically play one after another. On such discs, the end-of-chapter marker contains a branching instruction that tells the player to continue playing the next chapter in the sequence. These titles are referred to as One Sequential PGC Titles. (PGC stands for program chain, another name for a group of chapters that belong together. This term is not used in the DVD Navigator documentation.) On discs with other types of content, such as karaoke discs, an end-of-chapter marker might instruct the player to show a menu, or it might simply instruct the player to stop.

DVD application developers use title and chapter numbers to jump to specific points on a disc. For finer access, a title number and timecode can be used. Timecodes can only be used with One Sequential PGC Titles, since other types do not contain timecode maps.

Menus

Menus are the principle means by which users interact with the content on a DVD when played in a traditional player. Menus enable users to choose which video title to show, which audio soundtrack to play, which subtitles to display, which camera angle to view, and what other special features to enable. DirectShow DVD application developers have the choice of enabling menus as in a traditional player or creating a new computer-based interface that replaces or supplements the menus authored on the disc. The application can also simulate user interaction by programmatically selecting and activating menu buttons.

The Video Manager Menu
The top level menu is the Video Manager Menu (VMGM), also called the Top Menu or Title Menu. This menu usually has buttons that enable the user to go to the main titles or groups of titles on the disc. A group of titles is called a title set. For example, on a disc that has a feature film, a title set called "Interviews With the Director and Cast," and a title set called "Coming Attractions," the VMGM would probably have three buttons. Clicking the "Coming Attractions" button would take the user to a Video Title Set Menu (VTSM) with buttons for each separate title in the title set.

Because a disc can contain soundtracks in up to eight languages. It can also contain multiple VMGMs in languages that correspond to those on the soundtracks.

The VMGM appears when the user starts playing the disc unless the first title on the disc is authored as an autoplay title. In this case there may not be a VMGM. Most feature films on DVD are authored as autoplay titles.

Video Title Set Menus and Submenus
A Video Title Set Menu, also called a Root Menu (even though it's not at the root!), is a submenu of the VMGM. There can be from 1 to 99 titles in a title set. The VTSM has buttons enabling the user to go to any of the titles in the title set. In addition, the VTSM can also have submenus which enable the user to go to choose options for the audio stream, camera angle, subpicture stream, or chapter. These submenus are always valid for all the titles in the title set. VTSM submenus are not used on most DVDs. The root menu and all other submenus are optional, so never assume that all submenus in a VTSM have a common root menu.

Parental Management Levels

All or part of a DVD disc can be encoded with a Parental Management Level (PML) numbered from one to eight. Eight is the most restrictive level (adults only) and one is the least restrictive (all ages). The idea is to prevent children from watching adult content without parental consent, while allowing adults to watch child-safe content. In the United States and Canada, the levels map to the rating system of the MPAA (G, PG, PG-13, NC-17), but this is not the case in other countries.

Because chapters can exist logically within a parental block, there may be two versions of the same chapter in a title, each assigned a different PML and in a different parental block. For example, a child who logs in and plays the disc would see one version of Chapter 3, and an adult who logs in would see a different version, assuming that the application supports PMLs.

A title or chapter can also contain temporary PMLs, whose content is rated higher than the PML for the title or chapter as a whole. This means that a title may have more than one parental level. Temporary PMLs are generally authored as angle blocks, so that a scene in a film may have two versions, one rated for younger viewers and one for adults.

It is the responsibility of the player application to enforce the parental levels.

Domains

The concept of the domain is very important to DVD navigation, but domains are not physically marked on the disc in the same way that titles, menus, and angle blocks are, and so DVD authors have no control over them. A DVD domain can be thought of as a type of state variable, with five possible values, that a DVD player monitors in order to keep track of the type of content that the player is currently reading from the disc. DVD players use domains to keep from issuing meaningless commands to the DVD drive. For example, a "SelectButton" command is only meaningful if a menu is displayed, and a "FastForward" command makes no sense if the player is currently stopped or is showing a menu, which is a still image. The following table summarizes the domains and their meaning from the perspective of an application.
Domain | What the DVD Navigator is reading
First Play | The initial section of the disc, for example, the FBI warning.
Video Manager Menu | The main menu for the entire disc or disc side. Any menu-related methods are valid.
Video Title Set Menu | The menu for a title or group of titles, or one of its submenus—subpicture, language, audio, or angle. Any menu-related methods are valid.
Title | The video content in a title. The menu-related methods are not valid.
Stop | Nothing. The head is retracted from the disc. From here you can call Play.

User Operation Controls

User Operation Controls (UOPs) are markers on a disc that DVD authors can insert anywhere to restrict a user's navigation options. Most discs follow standard UOP restrictions. For example, most discs do not allow the viewer to fast forward or show a menu while in First Play domain. In principle, each disc can insert any UOP command at any point on the disc, even if the command would otherwise be valid within the current domain. For example, a disc may be authored to disallow fast forwarding in a certain title or to prevent a particular menu from being shown after the user enters the title domain. The DVD Navigator complies with all such commands from the disc and will not allow an application to override the disc's UOP controls.


Writing a DVD Application in C++

This article describes the main steps in creating a DVD application in C++. Most of the code examples presented here are from the DirectShow 8.0 DVD sample application, located in the sample directory in the DirectShow SDK. This article contains the following sections. For background information on basic general concepts in DVD, see DVD Basics.

  • Writing a DVD Application: The Basics
  • DVD Filter Graph Configuration
  • Building the DVD Filter Graph
  • Handling DVD Event Notifications
  • Working with DVD Menus
  • Audio and Subpicture Streams
  • Enforcing Parental Management Levels
  • Working with DVD Text Strings
  • Saving and Restoring DvdState Objects
  • Playing Karaoke Audio Streams
  • Synchronizing DVD Commands
  • DVD Command Flags
  • Handling Disc Ejections

Writing a DVD Application: The Basics

When writing a DVD application, you supply the code for the user interface, and call into the Microsoft® DirectShow® application programming interface (API) to issue all DVD playback and navigation commands. This involves calling the Component Object Model (COM) CoCreateInstance method on the DVDGraphBuilder object, which does the actual work of creating the DVD filter graph. After the filter graph is created, you can obtain pointers to the IDvdControl2 and IDvdInfo2 interfaces exposed by the DVD Navigator source filter. After you have the interface pointers, you can connect your user interface to the DVD navigation commands such as PlayTitle, Pause, and so on. This basic process is quite simple and is similar to the creation of other types of DirectShow applications.

DVD Filter Graph Configuration

Generally, application developers don't need to be concerned with the details of the DVD filter graph because it is created automatically. This section is provided for those who want an idea of what is going on behind the scenes. (See the Filter Reference section if you require more detail on the individual filters referred to in this article.)

The following illustration shows a typical DVD filter graph.

DVD Filter Graph

The DVD Navigator is the first filter in a DVD playback filter graph; it performs several tasks:

  • Reads the navigation and video data from the disc.
  • Demultiplexes the video, audio, and subpicture data into separate streams.
  • Pumps the streams into the graph for further processing and eventual rendering.
  • Informs your application of DVD-related events.

On the audio stream, the DVD Navigator connects downstream to an audio decoder, which connects to the Default DirectShow Device filter, the default audio renderer. On the video and subpicture streams, the downstream filters are the third-party video decoder, the Overlay Mixer, and the Video Renderer. If your application will handle line 21 closed-captioned data, you must add the DirectShow Line 21 Decoder filter to the graph. This involves a single method call; the filter will be connected automatically between the video decoder and the Overlay Mixer.

Your application communicates with and controls the DVD Navigator through the custom interfaces that the DVD Navigator exposes: IDvdControl2—the "set" methods—and IDvdInfo2—the "get" methods. It also must communicate with the filter graph manager (through IMediaControl) to stop, start, and otherwise control the graph. You might also need to control other individual filters, such as the Overlay Mixer filter for switching between windowed and full-screen display. For more information, see IMixerPinConfig2. The exact configuration of the graph will vary depending on what type of MPEG-2 decoder you have installed, whether you need to handle line 21 closed-captioned data, and other factors.

Building the DVD Filter Graph

The recommended way to build the DVD playback filter graph is to have a DvdGraphBuilder object do it for you automatically. This approach is demonstrated below and in the DVD sample application. If you need to build your DVD filter graph manually, you can do so by following the basic rules of graph building discussed elsewhere in the DirectShow documentation. Generally, you should not manually add, remove, connect, or disconnect individual filters in the graph created by the DvdGraphBuilder, because doing so might confuse the cleanup code.

After creating an instance of the DvdGraphBuilder object, an application can simply call its IDvdGraphBuilder::RenderDvdVideoVolume member function, which builds the filter graph from the available DirectShow filters and MPEG-2 decoders on the local system. For more information, see Building the Filter Graph.

After the filter graph is built, your application can obtain the pointers it needs to control the DVD Navigator, the Filter Graph Manager, and the video window. The basic steps, with error-checking and other code left out for simplicity, are illustrated in the following code example. The complete code is found in the DirectShow DVDSample application in the DirectX8 SDK DXF\samples\multimedia\dshow\dvd directory in the CDvdCore::BuildGraph() method.

    // Create an instance of the DVD Graph Builder object.
   HRESULT hr;
   hr = CoCreateInstance(CLSID_DvdGraphBuilder,
                          NULL,
                          CLSCTX_INPROC_SERVER,
                          IID_IDvdGraphBuilder,
                          reinterpret_cast<void**>(&m_pIDvdGB));

   // Build the DVD filter graph.
   AM_DVD_RENDERSTATUS	buildStatus;
   hr = m_pIDvdGB->RenderDvdVideoVolume(pszwDiscPath, m_dwRenderFlags, &buildStatus);

   // Get the pointers to the DVD Navigator interfaces.
   hr = m_pIDvdGB->GetDvdInterface(IID_IDvdInfo2, reinterpret_cast<void**>(&m_pIDvdI2));
   hr = m_pIDvdGB->GetDvdInterface(IID_IDvdControl2, reinterpret_cast<void**>(&m_pIDvdC2));
   ...
   // Get a pointer to the filter graph manager.
   hr = m_pDvdGB->GetFiltergraph(&m_pGraph) ;
   ...
   // Use the graph pointer to get a pointer to IMediaControl,
   // used for controlling the filter graph as a whole.
   hr = m_pGraph->QueryInterface(IID_IMediaControl, reinterpret_cast<void**>(&m_pIMC));
   ...
   // Get a pointer to IMediaEventEx,
   // used for handling DVD and other filter graph events.
   hr = m_pGraph->QueryInterface(IID_IMediaEventEx, (LPVOID *)&m_pME) ;
   ...
   // Use the graph builder pointer again to get the IVideoWindow interface,
   // used to set the window style and message-handling behavior of the video renderer filter.
   hr = m_pIDvdGB->GetDvdInterface(IID_IVideoWindow, reinterpret_cast<void**>(&m_pIVW));

   hr = m_pDvdGB->GetDvdInterface(IID_IAMLine21Decoder, (LPVOID *)&pL21Dec) ;

Handling DVD Event Notifications

The DVD Navigator sends notifications to an application-specified window when certain events take place, such as when the DVD domain changes, when a new parental management level is encountered, and when the DVD Navigator is about to enter an angle block. The event parameters can contain additional information related to the event. Error messages and warnings are also sent in this way. The application specifies the window that will handle the event notifications by using the IMediaEventEx pointer to call SetNotifyWindow, as follows:

    hr = m_pIME->SetNotifyWindow(reinterpret_cast<OAHWND>(m_hWnd), WM_DVD_EVENT, 0);

In the preceding example, m_hWnd is the HWND of the window to receive the messages and WM_DVD_EVENT is the application-defined message (greater than WM_USER) that will signal that a DVD event has taken place. The event itself is retrieved by the application through a call to IMediaEvent::GetEvent. Because more than one event might be in the event queue at any given time, the application must call GetEvent within a loop that repeats until all queued events have been retrieved, as shown in the following code example.

while (SUCCEEDED(m_pIME->GetEvent(&lEvent, &lParam1, &lParam2, lTimeOut)))
    {
        HRESULT hr;
        switch(lEvent)
        {

        case EC_DVD_CURRENT_HMSF_TIME:
        {
            DVD_HMSF_TIMECODE * pTC = reinterpret_cast<DVD_HMSF_TIMECODE *>(&lParam1);
            m_CurTime = *pTC;
            ...
        }
        break;
        ...
    }

DVD events might contain additional information in the lParam1 or lParam2 parameters, as illustrated above where the current time is contained in lParam1. The preceding code example is from the DVD sample application in Dvdcore.cpp. For a complete list of all DVD events and their parameters, see DVD Event Notification Codes.

Working With DVD Menus

The logical structure of DVD menus is discussed in DVD Navigation Basics. An application can display a menu from the disc by calling IDvdControl2::ShowMenu and passing the index of the desired menu.

Keep in mind that selecting a button merely highlights its borders. To cause the associated command to be fired, the button must be activated. Some IDvdControl2 methods select a specified button, some activate a button, and SelectAndActivateButton does both. The selection and activation of menu buttons using the mouse is demonstrated in the DVD sample application in CDvdCore::OnMouseEvent.

The IDvdControl2 menu-related methods enable an application to control menus programmatically. An application can highlight or select a button based on a mouse movement or any other user action or some other program logic. An application can also implement and control a custom menu or bitmap representing the buttons on a DVD remote control. In the DVD sample application, the relative button menu commands are connected to the keyboard arrow keys (see CDvdCore::OnKeyEvent). Activating a button programmatically can be done in various ways, but the button must always be selected before it can be activated.

Audio and Subpicture Streams

A DVD-Video disc can have up to eight audio streams, numbered zero through seven, each with up to six discrete channels. (Note that audio and subpicture streams are numbered from zero, whereas titles, angles, and parental levels are numbered from one.) Only one of these streams can be selected at any given time. For subpictures, up to 32 streams are available, although only one stream can be activated at any given time. Discs are generally authored with default audio and subpicture streams, but an application can enable users to view a list of all the available streams, and select the one in the language they prefer. The basic steps in this process are the same for both audio and subpicture streams.

  1. Determine the number of streams available for a title.
  2. Iterate through the streams and retrieve the stream attributes for each.
  3. Retrieve the language code from the returned locale identifier (LCID) and create a human-readable string.
  4. Populate a list box or other user interface (UI) control to enable the user to select a preferred stream.

In the DVD sample application, the CAudioLangDlg::MakeAudioStreamList method in Dialogs.cpp demonstrates the basic steps.

Enforcing Parental Management Levels

Any title or portion of a title on a DVD-Video disc can be assigned a generic parental management level (PML) from 1 through 8. When the DVD Navigator is reading content that has a PML, it is said to be in a parental block. A parental block may consist of part of a chapter, multiple chapters, or multiple titles. A DVD application intended for an international market should not hard code a particular rating system into its parental management logic.

The DVD Navigator itself does not enforce the PMLs; it merely informs your application when it encounters PML information on the disc. By default, it ignores this information on the disc and plays the highest level content. To enforce the PMLs, your application must implement some form of password control logic that associates users with levels, instruct the DVD Navigator to send it PML event notifications (by calling the IDvdControl2::SetOption method on startup, with the parameters DVD_NotifyParentalLevelChange and TRUE), and respond to those events to allow or disallow access as appropriate.

A DVD title can have one overall PML, but disc authors can give certain sections of that title higher or more restrictive PMLs. These are called temporary PML commands; these commands always contain two branching instructions: one to follow if the temporary PML command is accepted by the player application, and the other to follow if the command is rejected. The sequence of events is as follows. The DVD Navigator is reading video content (DVD Title Domain) when it encounters a temporary PML command on the disc. It checks its internal flag to see whether the application has requested to be notified of this event. If the flag is not set, the DVD continues playing, following the "parental level change rejected" branch specified on the disc. If the flag is set, the DVD sends an EC_DVD_PARENTAL_LEVEL_CHANGE event to the application and waits in a paused state until it gets a response. When your application receives the event, it uses its own logic to determine whether to accept the command. It then calls IDvdControl2::AcceptParentalLevelChange with an argument of TRUE or FALSE. If TRUE, the DVD Navigator resumes playing, following the "parental level change accepted" branch specified on the disc. Otherwise it resumes playing and follow the "parental level change rejected" branch.

Saving and Restoring DvdState Objects

DvdState objects enable applications to save a snapshot of the user session, including information such as the current location on the disc, the parental level of the person who is viewing, the selected audio and subpicture streams, and so on. This means that users can save their place on a DVD-Video disc and watch it at a later time.

Applications can't create DvdState objects. These objects are created internally by the DVD Navigator when an application calls IDvdInfo2::GetState. DvdState objects expose the IDvdState interface to allow applications to query for certain information.

In the DVD sample application, the CDvdCore::RestoreBookmark and CDvdCore::SaveBookmark functions show how to save and retrieve DvdState objects.

Working with DVD Text Strings

DVD discs, especially karaoke discs, might contain a database of text information to supplement the video or audio content. Such text on karaoke discs can include song titles, artist names, record labels, and so on. Versions of this text can be present in more than one language. These strings are optional; discs are not required to have them. If present, they are organized in a way that closely mirrors the logical hierarchy of the DVD volume. Each string is preceded by a number that identifies what part of the disc structure the string belongs to or gives some clue as to the content of the string. A subset of the string types is defined in the DVD_TextStringType enumeration.

There are two basic types of text strings: structure identifiers and content strings. Types with a value of 0x01 through 0x20 are structure identifiers. They are empty strings; the numerical code is used to identify the logical structure to which any following content strings belong. This structure corresponds very closely to the logical structure of a DVD disc contents: volume, title, chapter, and so on. The remaining types identify content strings that hold information that may be displayed to the viewer in a user interface. The exact way in which content strings are used is not closely defined, so DVD authors can use them in various ways.

Historically, DVD text strings have been used almost exclusively on karaoke discs, and these discs mostly use the 0x01 and 0x02 structure identifiers and the 0x30 type content string. But it is reasonable to assume that, as time goes by, more types of DVD-Video discs will contain text strings and these strings will be organized in more complex ways to provide fuller descriptions of disc contents.

For information on DVD text strings, see the DVD Forum at www.dvdforum.org.

The CDvdCore::GetDvdText method in the DVDSample application demonstrates the basic steps in enumerating and displaying DVD text strings.

Playing Karaoke Audio Streams

The DVD Navigator can play DVD-Video discs with karaoke audio streams, but karaoke playback also requires a decoder that supports multichannel karaoke mixing. Specifically, the decoder must support the DVD Karaoke Property Set (AM_PROPERTY_DVDKARAOKE).

Karaoke discs are a type of DVD-Video disc and have the same navigation structure. Songs are generally formatted as titles, and titles can be grouped into title sets based on performer, musical style, or other criteria. The main difference between karaoke and other types of DVD-Videos is the audio stream. Karaoke discs all contain multichannel audio, usually Dolby AC-3. Channels 0 and 1 always contain the background instrumental music, while channels 2 through 5 can each contain any combination of guide vocals, guide melodies, and sound effects. A karaoke application can control the volume and destination speaker for each auxiliary channel.

When the DVD Navigator detects karaoke content on a disc and goes into karaoke mode, it informs the decoder, which then should mute the upper three channels (the auxiliary channels) until any or all of them are explicitly turned on by an application. The basic tasks of a karaoke application are to:

  1. Determine the number of auxiliary channels and their contents using IDvdInfo2 methods.
  2. Provide a user interface that displays the channel contents and enables users to turn any auxiliary channel on or off at any time, using IDvdControl2::SelectKaraokeAudioPresentationMode.

These steps are illustrated in the DVD Sample application in DVDCore.cpp in the GetAudioAttributes method.

Synchronizing DVD Commands

This section contains the following subtopics.

  • About Command Synchronization
  • Approach 1: No Synchronization
  • Approach 2: Simple Blocking Without Synchronization
  • Approach 3: Using Only the Synchronization Object
  • Approach 4: Synchronization of One Command at a Time Using Events
  • Approach 5: Synchronization Using Events and IDvdCmd Objects

About Command Synchronization

Command synchronization is an advanced topic for developers who are familiar with the DVD Navigator and DVD navigation issues in general, and whose application requires the sophisticated functionality that command synchronization provides. If you are just starting out with the DVD Navigator, or if your application does not require command synchronization, simply use the various play commands as illustrated in Approach #1. You can always incorporate command synchronization later.

The various playback methods in IDvdControl2—for example, PlayTitle—are asynchronous in nature. When the method is called, it immediately returns a result before it has carried out all the necessary steps. During the period between the successful return of the method call and the ultimate completion of the operation, other commands might be issued that put the DVD Navigator into a new DVD domain or new filter state that prevents the method from successfully completing all the necessary steps. For example, assume your application calls PlayTitle, and immediately afterward, the user clicks the Stop button. If the commands are not synchronized, the DVD Navigator can enter the DVD Stop domain before the disc begins playing at the specified location. This is because PlayTitle returns successfully before the entire operation is carried out. When the disc finally begins to play, the DVD Navigator is no longer in the correct state, and an error will result.

Because many method calls depend on the DVD Navigator being in a particular state, applications need a way to synchronize commands. This involves the following two basic capabilities.

  • Knowing when an asynchronous operation is actually finished and what the final result is, as distinct from the return value of the method call, which only indicates whether an operation successfully started.
  • Being able to block the DVD Navigator from processing subsequent commands until an operation is completed.

The DVD Navigator gives applications these capabilities, along with several options for synchronizing commands. Each playback method in IDvdControl2 has two parameters used for synchronization: an interface pointer to a synchronization object, and a set of DVD command flags. An application can use these parameters to implement command synchronization in various ways depending on its needs.

Approach 1: No Synchronization

To maintain the asynchronous nature of the method call, use the following syntax, where pDVDControl2 is an IDvdControl2 pointer.

HRESULT hres = pDVDControl2->PlayTitle( uTitle,
                                        DVD_CMD_FLAG_None, // = 0
                                        NULL);

Approach 2: Simple Blocking Without Synchronization

This approach uses the DVD command flags to implement simple blocking without managing command synchronization objects. This is the simplest way to synchronize commands, because you do not have to manage synchronization objects or handle event notifications, but it does not enable you to determine the return status of any particular command.

HRESULT hres = pDVDControl2->PlayTitle( uTitle,
                                        EC_DVD_CMD_FLAG_Block,
                                        NULL);

Approach 3: Using Only the Synchronization Object

This approach is functionally equivalent to Approach 2. It provides another way to block the DVD Navigator directly without processing event notifications. When an application passes the address of an IDvdCmd pointer, it receives a command synchronization object that is associated with this specific command. Calling the object's WaitToEnd function will block the DVD Navigator until the method successfully completes. In the meantime, new commands might be added to the queue. Be sure to release the object when you are done with it.

IDvdCmd* pObj;
HRESULT hr = pDVDControl2->PlayTitle( uTitle,  0, &pObj);
if(SUCCEEDED(hr))
{
    pObj->WaitToEnd();
    pObj->Release();
}

Approach 4: Synchronization of One Command at a Time Using Events

By specifying the EC_DVD_CMD_FLAG_SendEvents flag through a call to IDvdControl2::SetOption, the DVD Navigator will not block on the "play" method calls. Instead, it sends your application EC_DVD_CMD_START and EC_DVD_CMD_END event notifications when the command begins and then when its entire asynchronous operation completes. This enables you to synchronize single events without managing IDvdCmd objects. But by not using IDvdCmd objects, you cannot know for sure which command the event is associated with. For many situations, such information is probably not needed anyway, so this approach is sufficient in those cases.

// Call PlayChapterInTitle using "SendEvents".
HRESULT hres = pDVDControl2->PlayChapterInTitle( uTitle, 0x2,
                    DVD_CMD_FLAG_SendEvents, NULL);
…
// In the event notification handler function
switch (lEvent)
{
   case EC_DVD_CMD_END:
     DoSomethingGeneric();
     break;
}

Approach 5: Synchronization Using Events and IDvdCmd Objects

This approach provides the greatest control over command synchronization, but it is also the most complex to implement. It enables applications to know which command an event is associated with, so that the application can tailor its responses to the EC_DVD_CMD_END events. The first example shows a single-threaded solution, and the second example shows a multithreaded solution.

// In global code
IDvdCmd* pGlobalObj=0;
…
// pGlobalObj is assigned by the Navigator BEFORE the event
// is issued; otherwise the event can occur at (*1) before
// pGlobalObj is assigned.
HRESULT hres = pDVDControl2->PlayTitle( uTitle,
DVD_CMD_FLAG_SendEvents, &pGlobalObj );
// (*1)
If( FAILED( hres)) {
pGlobalObj = NULL;
}
…
switch (lEvent)
{
case EC_DVD_CMD_END:
   IDvdCmd* pObj = GetDvdCmd( lParam1 );
   HRESULT hres = HRESULT( lParam2 );
If( NULL != pObj ) {
    If(pGlobalObj == pObj ) {
…
pGlobalObj->Release();
pGlobalObj = NULL;
}
pObj->Release();
   }
break;

Use this approach when your event loop is on a separate thread.

// In global code
IDvdCmd* pGlobalObj=0;
CcritSect globalCritSect;
…
{
CautoLock(globalCritSect );
HRESULT hres = pDVDControl2->PlayTitle( uTitle,
DVD_CMD_FLAG_SendEvents, &pGlobalObj );
If( FAILED( hres)) {
pGlobalObj = NULL;
}
}
…
switch (lEvent)
{
case EC_DVD_CMD_COMPLETE:
case EC_DVD_CMD_CANCEL:
{
CautoLock(globalCritSect );

IDvdCmd* pObj = GetDvdCmd( lParam1 );
HRESULT hres = HRESULT( lParam2 );
If( NULL != pObj ) {
If(pGlobalObj == obj ) {
…
pGlobalObj->Release();
pGlobalObj = NULL;
}
pObj->Release();
}
break;
}

DVD Command Flags

The DVD command flags passed in the dwFlags parameter of SetOption are used either in addition to or in place of the synchronization object, depending on which approach you are using for the particular method call. The use of DVD_CMD_FLAG_Block was shown in Approach 2 and DVD_CMD_FLAG_SendEvents was illustrated in Approaches 4 through 6. Either of these flags can also be combined in a bitwise OR with another flag, DVD_CMD_FLAG_Flush. This flag causes the method to be executed immediately, without waiting for the one or two seconds of video in the filter graph's buffers to play. Specifying this flag results in a faster response time to user input. Do not use this flag if you need to ensure that a particular video segment finishes completely before the next command is issued. The four flags and their meanings are summarized in the following table.

Name | Numeric value | Meaning
DVD_CMD_FLAG_None | 0x00000000 | No flags, meaning the buffer is not flushed before the new command, no events are fired when the operation completes, and the DVD Navigator is not blocked after the method returns.
DVD_CMD_FLAG_Flush | 0x00000001 | Empty the buffers and immediately start play at the new location.
DVD_CMD_FLAG_SendEvents | 0x00000002 | Tells the DVD navigator to signal the completion of asynchronous operations and their return value by sending events back to the application.
DVD_CMD_FLAG_Block | 0x00000004 | Blocks the DVD Navigator until the asynchronous operation completes or is canceled.

Handling Disc Ejections

When the user ejects a DVD from the drive, the DVD Navigator sends your application an EC_DVD_DISC_EJECTED message. The application can safely ignore this message and let the DVD Navigator manage the graph's state. An application can also handle the EC_DVD_DISC_EJECTED method to implement custom behavior when a disc is ejected. If you handle the message, you must set the DVD_ResetOnStop flag to TRUE with the SetOption method and then call IMediaControl::Stop before closing the application or playing another disc.


Shortcuts to C++ DVD Reference Pages

The following interfaces are those typically used when writing a DVD application in C++.
Interface | Purpose
IAMLine21Decoder | Controls closed captioning display.
IDvdCmd | Used in advanced command synchronization techniques to control a command object.
IDvdControl2 | Issues commands to the DVD Navigator filter (the "set" methods).
IDvdGraphBuilder | Creates the DVD filter graph.
IDvdInfo2 | Queries the DVD Navigator for state information and information on the disc (the "get" methods).
IDvdState | Saves information, such as bookmarks, to disc.
IVideoFrameStep | Controls "frame stepping" if the decoder supports it.


Writing a Script-Based DVD Application

This article describes the basic tasks involved in writing a script-based DVD application using the MSWebDVD ActiveX® Control. For background information on the DVD navigation concepts discussed here, see DVD Basics.

  • Embedding the MSWebDVD Object
  • Enabling Users to Issue DVD Commands
  • Working with DVD Menus
  • Audio and Subpicture Streams
  • Enforcing Parental Management Levels
  • Saving and Restoring Bookmarks
  • Handling DVD Event Notifications
  • Handling UOP Event Notifications
  • Synchronizing HTML Content with the Video
  • Working with LCIDs
  • Playing Karaoke Discs
  • Working with DVD Text Strings

Embedding the MSWebDVD Object

The MSWebDVD object handles all the DVD navigation commands as well as the display of the video rectangle. It will appear on your Web page as the video display rectangle. Therefore, you must embed it within the HTML document's BODY element. Set the rectangle width and height, and the default values for any properties as required by your application.

<OBJECT CLASSID=clsid:38EE5CEE-4B62-11D3-854F-00A0C9C898E7 ID=DVD
    STYLE="height:369px; width:740px">
<PARAM NAME="BackColor" VALUE="1048592">
<PARAM NAME="EnableResetOnStop" VALUE="-1">
<PARAM NAME="ColorKey" VALUE="1048592">
</OBJECT>

Enabling Users to Issue DVD Commands

To enable users to control the DVD player, you need to provide a UI with buttons for issuing DVD commands such as "Stop" and "Play." The following code example shows how to hook up basic HTML buttons to the MSWebDVD object methods.

<INPUT ID=button1 NAME="button1" TYPE=button VALUE="Play" onClick='Play();'>
<INPUT ID=button2 NAME="button2" TYPE=button VALUE="Pause" onClick='Pause();'>

<SCRIPT LANGUAGE="JScript">
function Play(){
     DVD.Play();
}

function Pause(){
  DVD.Pause();
}

</SCRIPT>

Working With DVD Menus

MSWebDVD automatically handles menu commands when the user clicks on the on-screen buttons with the mouse. An application does not need to do anything to implement basic mouse support. But an application can override this automatic mouse handling at any time in order to cause additional actions to take place when a user clicks on a menu button. For example, you could cause certain text or images to be displayed on the web page depending on which button the user clicks. To implement custom mouse handling, use the MSWebDVD menu-related methods such as SelectAndActivateButton, GetButtonAtPosition, and so on. To completely disable automatic mouse handling, set the DisableAutoMouseProcessing property to true.

MSWebDVD also offers a set of methods (for example, SelectUpperButton) which allow you to display an image map on your web page representing a DVD remote control, with buttons that move the current menu selection up, down, right and left. These buttons are referred to as "directional" or "relative" buttons in the documentation. Unlike the buttons that appear within the DVD menus, the directional buttons are supplied by an application.

Audio and Subpicture Streams

A DVD-Video disc can have up to eight audio streams, numbered zero through seven, each with up to six discrete channels. Only one of these streams can be active at any given time. For subpictures, up to 32 streams are available, numbered 0 through 31, although for audio only one stream can be active at any given time. Discs are generally authored with default audio and subpicture streams, but an application can enable the user to see all the streams that are available for a given title, and select the one in the language they prefer. The basic steps in this process are the same for both audio and subpicture streams:

  1. Determine the number of streams available for a specified title.
  2. Iterate through the streams and retrieve the stream attributes for each.
  3. Retrieve the language code from the returned locale identifier (LCID) and create a human-readable string.
  4. Populate a "Select" box or other user interface control to enable the user to select the preferred stream.

(Note that audio and subpicture streams are numbered from zero, whereas titles, angles, and parental levels are numbered from one.)

Enforcing Parental Management Levels

Any title or portion of a title on a DVD-Video disc can be assigned a generic parental management level (PML) from 1 through 8. Eight is the most restrictive level and one is the least restrictive. The idea is to provide a mechanism to prevent children from watching adult content without parental consent, but the specific meaning of each level varies from country to country. In the United States and Canada, the levels map to the rating system of the Motion Picture Association of America (G, PG, PG-13, NC-17), but this is not the case in other countries. A DVD application intended for an international market should not hard code any particular rating system into its parental management logic.

The MSWebDVD object by default ignores PMLs on the disc. For an application to be notified of PML markers on the disc, it must call NotifyParentalLevels(true). MSWebDVD will then inform your application when it encounters PML information on the disc. To enforce PMLs, your application must implement some form of password control logic that associates users with levels, and respond to EC_DVD_PARENTAL_LEVEL_CHANGE events to allow or disallow access as appropriate.

Saving and Restoring Bookmarks

Bookmarks are an internal data structure that the MSWebDVD object uses to create a snapshot of the current user session, including information such as the current location on the disc, the parental level of the person who was viewing at the time, the selected audio and subpicture streams, and so on. This means that users can save their place on a DVD-Video disc and come back to watch it at a later time.

The SaveBookmark method enables a user to save their place on a disc and the RestoreBookmark method enables the same user to begin viewing again from the stored location.

Only one bookmark can be stored at a time. Calling SaveBookmark twice will cause the first bookmark to be overwritten. Bookmarks are specific to a computer. Running the same HTML page on a different computer and calling RestoreBookmark will restore the last-saved bookmark on that computer or will return an error if no bookmark was previously saved.

Handling DVD Event Notifications

The MSWebDVD object sends notifications to an application-specified method when certain events take place, such as when the DVD domain changes, when a new parental management level is encountered, when it is about to enter an angle block, and so on. The event parameters can contain additional information related to the event. Error messages and warnings are also sent in this way. To capture the various DVD event notifications, enter the following HTML SCRIPT tag below the OBJECT tag for the MSWebDVD object.

<SCRIPT LANGUAGE="JScript" FOR=DVD EVENT="DVDNotify(EventCode, Param1, Param2)">
    ProcessDVDEvent(EventCode, Param1, Param2)
</SCRIPT>

Then, in script, define the event codes and the ProcessDVDEvent function, as shown in the next code example. (You may give your event handling function any name; it isn't required to be "ProcessEvents." For more information about the event codes, see DVD Event Notification Codes.

<SCRIPT LANGUAGE="JScript">

// DVD event codes are valued 257 through 283
var EC_DVDBASE = 256;

var EC_DVD_DOMAIN_CHANGE = (EC_DVDBASE + 1);
var EC_DVD_TITLE_CHANGE = (EC_DVDBASE + 2);
var EC_DVD_CHAPTER_START = (EC_DVDBASE + 3);
var EC_DVD_AUDIO_STREAM_CHANGE = (EC_DVDBASE + 4);
var EC_DVD_SUBPICTURE_STREAM_CHANGE = (EC_DVDBASE + 5);
var EC_DVD_ANGLE_CHANGE  = (EC_DVDBASE + 6);
var EC_DVD_BUTTON_CHANGE = (EC_DVDBASE + 7);
var EC_DVD_VALID_UOPS_CHANGE = (EC_DVDBASE + 8);
var EC_DVD_STILL_ON  = (EC_DVDBASE + 9);
var EC_DVD_STILL_OFF  = (EC_DVDBASE + 10);
var EC_DVD_CURRENT_TIME  = (EC_DVDBASE + 11); // not used by MSWebDVD
var EC_DVD_ERROR  = (EC_DVDBASE + 12);
var EC_DVD_WARNING  = (EC_DVDBASE + 13);
var EC_DVD_CHAPTER_AUTOSTOP  = (EC_DVDBASE + 14);
var EC_DVD_NO_FP_PGC  = (EC_DVDBASE + 15);
var EC_DVD_PLAYBACK_RATE_CHANGE  = (EC_DVDBASE + 16);
var EC_DVD_PARENTAL_LEVEL_CHANGE  = (EC_DVDBASE + 17);
var EC_DVD_PLAYBACK_STOPPED  = (EC_DVDBASE + 18);
var EC_DVD_ANGLES_AVAILABLE  = (EC_DVDBASE + 19);
var EC_DVD_PLAYPERIOD_AUTOSTOP  = (EC_DVDBASE + 20);
var EC_DVD_BUTTON_AUTO_ACTIVATED  = (EC_DVDBASE + 21);
var EC_DVD_CMD_START  = (EC_DVDBASE + 22);            // not used by MSWebDVD
var EC_DVD_CMD_END = (EC_DVDBASE + 23);               // not used by MSWebDVD
var EC_DVD_DISC_EJECTED  = (EC_DVDBASE + 24);
var EC_DVD_DISC_INSERTED  = (EC_DVDBASE + 25);
var EC_DVD_CURRENT_HMSF_TIME  = (EC_DVDBASE + 26);
var EC_DVD_KARAOKE_MODE  = (EC_DVDBASE + 27);

var nCurDomain;
var nCurParentalLevel;

function ProcessDVDEvent(EventCode, Param1, Param2)
{
    switch (EventCode)
    {
    case EC_DVD_DOMAIN_CHANGE:
        nCurDomain = Param1;
        // do something
        break;
    case EC_DVD_PARENTAL_LEVEL_CHANGE:
        nCurParentalLevel = Param1;
        // do something
        break;

    // handle any other events you are interested in

    default:
        break;
    }
}
</SCRIPT>

Handling UOP Event Notifications

The MSWebDVD object sends UOP event notifications to inform an application when a specific user operation (UOP) has been enabled or disabled by the disc. Each user operation has its own event, with a single Boolean parameter indicating whether that operation is now enabled or disabled. See MSWebDVD Events for more information on specific events.

For each event that you wish to handle, specify an event handler as shown in the following example. (You can call your handler method anything you like.)

<SCRIPT LANGUAGE="JScript" FOR=DVD EVENT="PlayForwards(bEnabled)">
    PlayForwardsEventHandler(bEnabled)
</SCRIPT>
Now define your handler method to respond appropriately to the event. Assume that the "button_Play" variable here is the id attribute of the "Play" button in your application.
function PlayForwardsEventHander(bEnabled)
{
  if(bEnabled == true)
    button_Play.disabled = false;
  else
    button_Play.disabled = true;
}

Synchronizing HTML Content with the Video

By handling timecode events from the disc, a web application can synchronize HTML content to the video. For example, you can cause images or text on the page to change at specified points in the video. The following code snippet shows one way to synchronize JScript function calls to timecode events:
//DVDTriggerPoints array holds frame count for each trigger. Must be in ascending order.
//Use timecode2frames() to convert timecodes (hh:mm:ss:ff) to total number of frames.

var DVDTriggerPoints = new Array(
  timecode2frames("01:15:24:00"),
  timecode2frames("01:23:02:00"));

//DVDTriggerProcs array holds functions to be called at each trigger point defined in DVDTimePoints.
var DVDTriggerProcs = new Array(
  "showDogPic();",
  "showCatPic();");

//DVDTriggerIndex keeps track of current trigger (it indexes DVDTriggerPoints and DVDTriggerProcs).
var DVDTriggerIndex = 0;

//Handle DVD Events
function ProcessDVDEvent(EventCode, Param1, Param2) {
  switch (EventCode) {
     case EC_DVD_CURRENT_HMSF_TIME:
          if(MSWebDVD.CurrentDomain == 4) {  //Don’t bother checking unless disc is playing.
             if (DVDTriggerIndex < DVDTimePoints.length) {  //Are there trigger points left to check?
                currentDVDTime = (MSWebDVD.DVDTimeCode2bstr(Param1));
                 if (timecode2frames(currentDVDTime)>= DVDTriggerPoints[DVDTimeIndex]) {
                     // if trigger point has passed, execute the associated function
                    eval(DVDTriggerProcs[DVDTimeIndex++]);
                 }
             }
          }
       break;

       // handle other events
   }
}

function timecode2frames(timeCode) {

   if (timeCode != "undefined") {
       return timeCode.substring(0,2)*108000
       + timeCode.substring(3,5)*1800
       + timeCode.substring(6,8)*30
       + timeCode.substring(9,11);
   } else {
       return 0;
   }
}

Working with LCIDs

The LCID, or "locale identifer," is a 32-bit data type into which are packed several different values that help to identify a particular geographical region. One of these internal values is the "primary language ID" which identifies the basic language of the region or locale, such as English, Spanish, or Russian.

MSWebDVD requires a complete valid LCID as an input parameter for two methods: SelectDefaultAudioLanguage and SelectDefaultSubpictureLanguage. This can be any valid LCID recognized by Windows®, and even some that are not recognized by Windows. (It is not necessary that the host system actually support the locale with fonts, keyboard mappings, and so on.) The following table lists some common LCIDs as well as well as some less common ones that are valid for MSWebDVD even through Windows does not recognize them by default. This is not a complete list of all possible LCIDs. For more information on LCIDs, including a complete list of LCIDs recognized by Windows, consult the MSDN online documentation at http://msdn.microsoft.com.
Some Valid LCIDs
Afrikaans | 0x0436 | Albanian | 0x041c | Arabic (Algeria) | 0x1401
Arabic (Bahrain) | 0x3c01 | Arabic (Egypt) | 0x0c01 | Arabic (Iraq) | 0x0801
Arabic (Jordan) | 0x2c01 | Arabic (Kuwait) | 0x3401 | Arabic (Lebanon) | 0x3001
Arabic (Libya) | 0x1001 | Arabic (Morocco) | 0x1801 | Arabic (Oman) | 0x2001
Arabic (Qatar) | 0x4001 | Arabic (Saudi Arabia) | 0x0401 | Arabic (Syria) | 0x2801
Arabic (Tunisia) | 0x1c01 | Arabic (U.A.E.) | 0x3801 | Arabic (Yemen) | 0x2401
Basque | 0x042d | Belarusian | 0x0423 | Bulgarian | 0x0402
Catalan | 0x0403 | Chinese (Hong Kong) | 0x0c04 | Chinese (PRC) | 0x0804
Chinese (Singapore) | 0x1004 | Chinese (Taiwan) | 0x0404 | Croatian | 0x041a
Czech | 0x0405 | Danish | 0x0406 | Dutch (Belgian) | 0x0813
Dutch (Standard) | 0x0413 | English (Australian) | 0x0c09 | English (Belize) | 0x2809
English (Canadian) | 0x1009 | English (Caribbean) | 0x2409 | English (Ireland) | 0x1809
English (Jamaica) | 0x2009 | English (New Zealand) | 0x1409 | English (South Africa) | 0x1c09
English (Trinidad) | 0x2c09 | English (United Kingdom) | 0x0809 | English (United States) | 0x0409
Estonian | 0x0425 | Faeroese | 0x0438 | Farsi | 0x0429
Finnish | 0x040b | French (Belgian) | 0x080c | French (Canadian) | 0x0c0c
French (Luxembourg) | 0x140c | French (Standard) | 0x040c | French (Swiss) | 0x100c
German (Austrian) | 0x0c07 | German (Liechtenstein) | 0x1407 | German (Luxembourg) | 0x1007
German (Standard) | 0x0407 | German (Swiss) | 0x0807 | Greek | 0x0408
Hebrew | 0x040d | Hungarian | 0x040e | Icelandic | 0x040f
Indonesian | 0x0421 | Italian (Standard) | 0x0410 | Italian (Swiss) | 0x0810
Japanese | 0x0411 | Korean | 0x0412 | Korean (Johab) | 0x0812
Latvian | 0x0426 | Lithuanian | 0x0427 | Malay (Malaysian) | 0x043e
Malay (Brunei) | 0x083e | Norwegian (Bokmal) | 0x0414 | Norwegian (Nynorsk) | 0x0814
Polish | 0x0415 | Portuguese (Brazilian) | 0x0416 | Portuguese (Standard) | 0x0816
Romanian | 0x0418 | Russian | 0x0419 | Serbian (Cyrillic) | 0x0c1a
Serbian (Latin) | 0x081a | Slovak | 0x041b | Slovenian | 0x0424
Spanish (Argentina) | 0x2c0a | Spanish (Bolivia) | 0x400a | Spanish (Chile) | 0x340a
Spanish (Colombia) | 0x240a | Spanish (Costa Rica) | 0x140a | Spanish (Dominican Republic) | 0x1c0a
Spanish (Ecuador) | 0x300a | Spanish (El Salvador) | 0x440a | Spanish (Guatemala) | 0x100a
Spanish (Honduras) | 0x480a | Spanish (Mexican) | 0x080a | Spanish (Modern Sort) | 0x0c0a
Spanish (Nicaragua) | 0x4c0a | Spanish (Panama) | 0x180a | Spanish (Paraguay) | 0x3c0a
Spanish (Peru) | 0x280a | Spanish (Puerto Rico) | 0x500a | Spanish (Traditional Sort) | 0x040a
Spanish (Uruguay) | 0x380a | Spanish (Venezuela) | 0x200a | Swahili | 0x0441
Swedish | 0x041d | Swedish (Finland) | 0x081d | Thai | 0x041e
Turkish | 0x041f | Ukrainian | 0x0422 |  |

Several MSWebDVD methods and properties return locale identifier (LCID) values that identify which languages are available on the soundtracks or subtitles. To make use of this information, your application will need to extract the primary language ID from the returned LCID. To do this, perform a bitwise AND operation on the value of iLCID and 0x3FF. (The primary language ID is contained in the least significant 10 bits of the LCID.) The following code snippet shows how to do this.

iPrimaryLang = iLCID & 0x3FF;

To obtain a human-readable string from the primary language ID, call GetLangFromLangID as shown in this example:

sLanguage = DVD.GetLangFromLangID(iPrimaryLang);

See the Microsoft® Platform SDK for more information on LCIDs and language identifiers.

The following table lists the primary language IDs for the LCIDs in the table above.

Some Valid Primary Language IDs
Afrikaans | 0x36 | Albanian | 0x1c | Arabic | 0x01 | Basque | 0x2d
Belarusian | 0x23 | Bulgarian | 0x02 | Catalan | 0x03 | Chinese | 0x04
Croatian | 0x1a | Czech | 0x05 | Danish | 0x06 | Dutch | 0x13
English | 0x09 | Estonian | 0x25 | Faeroese | 0x38 | Farsi | 0x29
Finnish | 0x0b | French | 0x0c | German | 0x07 | Greek | 0x08
Hebrew | 0x0d | Hungarian | 0x0e | Icelandic | 0x0f | Indonesian | 0x21
Italian | 0x10 | Japanese | 0x11 | Korean | 0x12 | Latvian | 0x26
Lithuanian | 0x27 | Malay | 0x3e | Norwegian | 0x14 | Polish | 0x15
Portuguese | 0x16 | Romanian | 0x18 | Russian | 0x19 | Serbian | 0x1a
Slovak | 0x1b | Slovenian | 0x24 | Spanish | 0x0a | Swahili | 0x41
Swedish | 0x1d | Thai | 0x1e | Turkish | 0x1f | Ukrainian | 0x22

Playing Karaoke Discs

Karaoke discs are a type of DVD-Video disc and have the same navigation structure. Songs are generally formatted as titles, and titles can be grouped together into title sets based on performer, musical style, or other criteria. The main difference between karaoke and other types of DVD-Videos is the audio stream. Karaoke discs all contain multichannel audio, usually Dolby AC-3. Channels 0 and 1 always contain the background instrumental music, while channels 2 through 5 contain guide vocals or guide melodies or sound effects. A karaoke application can control the volume and destination speaker for each auxiliary channel.

Karaoke playback also requires an audio decoder that supports the multichannel karaoke mixing information sent by the DVD Navigator. Specifically, the decoder must support the DVD Karaoke Property Set (AM_PROPERTY_DVDKARAOKE).

When the DVD Navigator detects karaoke content on a disc and goes into karaoke mode, it informs the decoder, which then should mute the upper three channels (the auxiliary channels) until any or all of them are explicitly turned on by an application. The basic tasks of a karaoke application will therefore be to

  1. determine the number of auxiliary channels and their contents
  2. provide a user interface that displays the channel contents and allows users to turn any auxiliary channel on or off at any time.

Working with DVD Text Strings

DVD discs, especially karaoke discs, might contain a database of text information to supplement the video or audio content. Such text on karaoke discs might include song titles, artist names, record labels, and so on. Versions of this text can be present in more than one language. These strings are optional; discs are not required to have them. If present they are organized in a way that closely mirrors the logical hierarchy of the DVD volume. Each string is preceded by a number that identifies what part of the disc structure it belongs to or gives some clue as to the content of the string.

There are two basic types of text strings: structure identifiers and content strings. Types with a value of 0x01 through 0x20 are structure identifiers. They are empty strings; the numerical code is used to identify the logical structure to which any following content strings belong. This structure corresponds very closely to the logical structure of a DVD disc contents: volume, title, chapter, and so on. The remaining types identify content strings that hold information that may be displayed to the viewer in a user interface. The exact way in which content strings are used is not closely defined, so DVD authors might use them in various ways.

Historically, DVD text strings have been used almost exclusively on karaoke discs, and these discs mostly use the 0x01 and 0x02 structure identifiers and the 0x30 type content string. But it is reasonable to assume that as time goes by, (1) more types of DVD-Video discs will contain text strings and (2) these strings will be organized in more complex ways in order to provide fuller descriptions of disc contents.

The following code shows how to determine the number of text string language blocks on the disc, and retrieve the human-readable string(s) that could be shown to the user to allow them to choose the language they are interested in. In this code the strings are added to an HTML SELECT element called "TextLanguageList." For more information on LCIDs and primary language IDs, see GetLangFromLangID

  function GetTextLanguages()
  {
    //get the number of text blocks
    var numLangs = DVD.GetDVDTextNumberOfLanguages();
      var iLCID;
      var iPrimaryLang;
      var sLanguage;
      var oOption;

    for (j = 0; j < numLangs; j++)
    {
    //get the locale identifier for the language block
        iLCID = DVD.GetDVDTextLanguageLCID(j);

    //get the primary language ID from the LCID
        iPrimaryLang = iLCID & 0x3FF;

    //get the human-readable string from the primary language ID
        sLanguage = DVD.GetLangFromLangID(iPrimaryLang);

    //add it to the SELECT element on the HTML page
        oOption = document.createElement("OPTION");
        oOption.text = sLanguage;
        document.all.TextLanguageList.add(oOption);
    }

  } //end function GetTextStrings

The following test code demonstrates how to enumerate the strings and examine the text string type. It just dumps the results into an HTML TEXTAREA element called "myTextArea" so you can see how the numeric string types are used to organize the content strings. A real application would probably create its own data structure to hold the strings, or else would display them in a more useful way for the viewer.

  // iLanguage is the 0-based index for the language block
   function GetTextStrings(iLanguage)
   {

      var numStrings, stringType, j;

      numStrings = DVD.GetDVDTextNumberOfStrings(iLanguage);

      for( j = 0; j < numStrings; j++)
      {
        stringType = DVD.GetDVDTextStringType(iLanguage, j);

        if(stringType > 0x20) //there is actually some text to read here
        {
          myTextArea.value += (stringType + ": " + DVD.GetDVDTextString(iLanguage, j) + "\n");
        }
        else // It's a node indicating what level of the volume structure
            // the following strings will apply to
        {
          myTextArea.value += (stringType + "\n");
        }

      }
    } //end function GetTextStrings

DVD Text String Types

This table lists a subset of the DVD text string types. All types with a value 0x20 and below are empty strings that merely indicate the node level in the disc's content data structure. The other strings are content strings. Most title and song names are type 0x30. The types in the Title, SubTitle and Original categories help to further identify the particular genre. The exact meaning and intended use of these categories is defined in a public document that can be downloaded from the DVD Forum's web site at www.dvdforum.org.

Structure Identifiers
Volume | 0x01 | Indicates that the strings that follow pertain to the DVD volume.
Title | 0x02 | Indicates that the strings that follow pertain to a title.
ParentalID | 0x03 | Indicates that the strings that follow pertain to a particular parental ID.
Chapter | 0x04 | Indicates that the strings that follow pertain to a chapter.
Cell | 0x05 | Indicates that the strings that follow pertain to a cell (typically consisting of one scene from a movie).
Stream Identifiers
Audio | 0x10 | Indicates that the strings that follow pertain to an audio stream.
Subpicture | 0x11 | Indicates that the strings that follow pertain to a subpicture stream.
Angle | 0x12 | Indicates that the strings that follow pertain to an angle block.
Audio Channel Identifiers
Channel | 0x20 | Indicates that the strings that follow pertain to one channel in an audio stream.
General Content Strings
Name | 0x30 | The most common identifer for title names, chapter names, song names, etc.
Comments | 0x31 | General comments about the title, chapter, song, etc.
Title Content Strings
Series | 0x38 | Additional information about the title, chapter, song, etc.
Movie | 0x39 | Additional information about the title or chapter if this is a movie.
Video | 0x3a | Additional information about the title or chapter if this is a video.
Album | 0x3b | Additional information about the title or chapter if this is an album.
Song | 0x3c | Additional information about the title or chapter if this is a song.
Other | 0x3f | Additional information about the title or chapter if this belongs to some other genre or category.
Secondary Title Content Strings
Series | 0x40 | Additional information about the title, chapter, song, etc.
Movie | 0x41 | Additional information about the title or chapter if this is a movie.
Video | 0x42 | Additional information about the title or chapter if this is a video.
Album | 0x43 | Additional information about the title or chapter if this is an album.
Song | 0x44 | Additional information about the title or chapter if this is a song.
Other | 0x45 | Additional information about the title or chapter if this is this belongs to some other genre or category.
Original Content Strings
Series | 0x48 | Additional information about the title, chapter, song, etc.
Movie | 0x49 | Additional information about the title or chapter if this is a movie.
Video | 0x4a | Additional information about the title or chapter if this is a video.
Album | 0x4b | Additional information about the title or chapter if this is an album.
Song | 0x4c | Additional information about the title or chapter if this is a song.
Other | 0x4f | Additional information about the title or chapter if this is this belongs to some other genre or category.
Other Info Content Strings
Other Scene | 0x50 | Additional information about an alternate scene in a movie title or chapter.
Other Cut | 0x51 | Additional information about an alternate cut in a movie title or chapter.
Other Take | 0x52 | Additional information about an alternate take in a movie title or chapter.


MSWebDVD ActiveX Control

These pages document the methods and properties of objects exposed by the Microsoft® MSWebDVD ActiveX® control.

Object | Purpose
MSWebDVD | Controls all DVD commands and queries.
MSDVDAdm | Controls default settings in the Windows Registry.
DVDRect | Defines rectangles for use in various MSWebDVD methods.

MSWebDVD Events documents the event notifications sent to applications by the MSWebDVD Active X control.


MPEG-2 Support in DirectShow

This section describes the interfaces and components that you can use to play back MPEG-2 content using Microsoft® DirectShow®. MPEG-2 allows simple file playback, supports a variety of storage formats (disk or removable media), and requires no authoring. MPEG-2 is supported by all software decoders, but is not supported by some older hardware decoders. For information on playing back DVD-based content with DirectShow using the DVD Navigator and IDVDGraphBuilder components and their interfaces, see DVD Application Development in DirectShow. Note that MPEG-2 playback uses the IGraphBuilder and IMediaControl interfaces, not DVD-specific interfaces such as IDVDGraphBuilder and IDvdControl2.

The main component provided with DirectShow for MPEG-2 playback is the MPEG-2 Splitter filter (similar to the MPEG-1 Stream Splitter component provided with previous versions of DirectShow). DirectShow does not provide any MPEG-2 decoders. DirectShow-compatible MPEG-2 audio and video decoders that accept MPEG-2 Packetized Elementary Streams (PES) are required for use with the MPEG-2 Splitter filter. The user can activate file playback using the MPEG-2 Splitter filter by double-clicking a file recognized by DirectShow (preferably .mpg) that contains MPEG-2 program stream content.

See the following related topics for more information.

  • Using the MPEG-2 Splitter Filter
  • Time Stamps
  • MPEG Sample Properties
  • MPEG-2 Kernel Media Types


Using the MPEG-2 Splitter Filter

The MPEG-2 Splitter filter currently supports pull-mode playback of MPEG-2 program streams that contain at least one of the following stream types.

  • MPEG-2 video
  • MPEG-2 audio
  • Dolby AC-3 audio encoded as defined for DVD-Video
  • LPCM (Linear Pulse Code Modulated) audio encoded as defined for DVD-Video

Note The MPEG-2 Splitter does not handle transport streams. For transport streams delivered in push-mode only, use the MPEG-2 Demultiplexer.

For more information on MPEG audio specs, visit external link http://www.mpeg.org/MPEG/DVD/Book_B/Audio.html.

The MPEG-2 Splitter filter supports playback of these types when there are Microsoft® DirectShow®-compatible decoders that can handle the particular streams found in the program stream installed. For a list of the supported MPEG-2 Splitter filter media types, see MPEG-2 Splitter Filter Media Types.

See the following topics for more information about using the MPEG-2 Splitter filter.

  • MPEG Time Stamps
  • Stream Selection
  • Supported Interfaces

MPEG Time Stamps

When playing back MPEG-2 program streams, the MPEG-2 Splitter filter treats the first system clock reference it encounters as the time origin of any stream. This differs from the MPEG-1 Stream Splitter filter, which uses presentation time stamps. The IAMParse::GetParseTime method returns the (possibly estimated) stream system clock time for the data it has processed.

If the MPEG-2 splitter filter encounters an input sample with the discontinuity property set (the discontinuity property can be set by using IMediaSample::SetDiscontinuity or IMediaSample2::SetProperties), it skips data until it finds the first pack in the data and adjusts its time stamps so that the system clock reference (SCR) for that pack is considered identical to the SCR time before the discontinuity. If the SCR clock appears either to jump backward or to jump forward by more than a second, then (in line with the MPEG-2 program stream specification), this is also treated as a clock discontinuity and the apparent clock discrepancy is subtracted from the time stamps passed to downstream filters.

Stream Selection

When playing back the MPEG-2 program stream, the first video stream and first audio stream found traversing the program stream are chosen. Up to one audio and one video output pin are supported. Through the IAMStreamSelect interface, different streams of the same type can be selected up to the number specified by the audio limit in the system header. For MPEG-2 audio, it is currently assumed the streams form a contiguous range starting at stream 0xC0.

Supported Interfaces

The MPEG-2 splitter filter supports the following interfaces.

  • IAMParse—MPEG-2 program stream only
  • IAMStreamSelect—MPEG-2 program stream only, audio streams only
  • IMediaSeeking—includes byte mode seeking


Time Stamps

For more information about time stamps, see section 2.4.1 of ISO1-11172: "The packet header may contain decoding and/or presentation time stamps (DTS and PTS) that refer to the first access unit in the packet."

For MPEG_Stream major types, the start time is the byte position of the first byte, rated at 1 byte per second. The stop time is the byte position of the last byte. Thus, consecutive samples should have the stop time of the first packet equal to the start time of the next packet. For Video CD data, the origin of the medium must match the format of a video-CD file exposed by CDFS with the standard RIFF chunk at the start.

For MPEG video packet and payload types, the time stamp is the presentation time for the first video frame whose picture start code begins in the sample.

For MPEG audio packet and payload types, the time stamp is the presentation time for the first audio frame whose sync code starts in the sample.

It is assumed that packet and payload data without time stamps can be successfully prerolled by the handling filters.


MPEG Sample Properties

MPEG samples have the following properties or notifications.

Time stamp | Not all samples have start and stop times. The sample stop time for packet and payload data is not useful; it is usually set to the start time plus one. MPEG packet or payload data samples will have a start and stop time set if the system layer packet they are generated from had a valid PTS.
Discontinuity | If there is a break in the stream (for example, a gap in the real-time data, or an error in the data or after a seek), the Discontinuity property is set. This property is propagated from the MPEG-1 splitter to the stream handlers in the first sample sent after this property is set in a sample received. This also allows for a time-stamp discontinuity.
End Of Stream | This is not a sample property but a separate notification. When this is received, any buffered data must be forced through the decoder. Logically, any new data must then start with the Discontinuity property.


Kernel Media Types

Microsoft DirectX 8.0

MPEG-2 Kernel Media Types

MPEG-2 kernel media type GUIDs have names that differ from the Microsoft® DirectShow® names. The following table shows the DirectShow GUID and the kernel GUID for the types relevant to MPEG-2.

Name in Ksuuids.h | Name in Ksmedia.h
MEDIATYPE_MPEG2_PES | KSDATAFORMAT_TYPE_MPEG2_PES
MEDIASUBTYPE_MPEG2_VIDEO | KSDATAFORMAT_SUBTYPE_MPEG2_VIDEO
FORMAT_MPEG2Video | KSDATAFORMAT_SPECIFIER_MPEG2_VIDEO
MEDIASUBTYPE_DOLBY_AC3 | KSDATAFORMAT_SUBTYPE_AC3_AUDIO
MEDIATYPE_Video | KSDATAFORMAT_TYPE_VIDEO
MEDIATYPE_Audio | KSDATAFORMAT_TYPE_AUDIO
FORMAT_WaveFormatEx | KSDATAFORMAT_SPECIFIER_WAVEFORMATEX
FORMAT_MPEG2Video | KSDATAFORMAT_SPECIFIER_MPEG2_VIDEO
MEDIASUBTYPE_MPEG2_AUDIO | KSDATAFORMAT_SUBTYPE_MPEG2_AUDIO
MEDIASUBTYPE_DVD_LPCM_AUDIO | KSDATAFORMAT_SUBTYPE_LPCM_AUDIO


Windows Media Applications

With Microsoft® DirectShow® you can create applications that play and write Microsoft® Windows Media™ Format files. The Windows Media Format is optimized for streaming data over networks and rendering the data on a client computer. For more information on the Windows Media Format, see the Windows Media Format SDK.

The Windows Media Software Development Kit provides alternate solutions for creating Windows Media Format files. For a discussion that compares the Windows Media SDK to the DirectShow SDK, see Windows Media and DirectShow: Choices for Windows-based Media Applications

Advanced Streaming Format (ASF) is the file container for Windows Media Format. The DirectShow ASF Writer filter can write Windows Media Format files as well as ASF files that contain non-WMF streams. See Creating ASF Files in DirectShow


Creating ASF Files in DirectShow

The ASF File Format and the Windows Media Format

This section describes how to use the Microsoft® DirectShow® ASF Writer filter to create files in Advanced Streaming Format (ASF). ASF is a file format that can contain any type of compressed or uncompressed data. One advantage of ASF over formats such as AVI and WAV is that data in ASF files is time-stamped. Microsoft® Windows Media™ Format files are ASF files that use certain codecs as specified in the Windows Media Format Software Development Kit (SDK). These files use the extensions "wma" for Windows Media Audio files and "wmv" for Windows Media Video files. For more information about Windows Media Format, see the Windows Media Technologies home page.

The DirectShow SDK and the Windows Media Format SDK

DirectShow and the Windows Media Format SDK offer complementary solutions for writing applications that create and play back Windows Media Format streams. For more information, read the white paper at http://www.microsoft.com/hwdev/vidcap/WM_DS.htm.

The ASF Writer filter accepts any number of input streams and creates an ASF file. The filter uses the Windows Media Format SDK to convert uncompressed audio or video files to Windows Media Format for storage in an ASF file, as the Windows Media Format specification requires. You can bypass the filter's compression mechanism when you wish to use other codecs or save uncompressed data in ASF format.

You can use the ASF Writer in various scenarios including digital video (DV) capture, audio recompression, and conversion of Audio-Video Interleaved (AVI) or MPEG multimedia files for network streaming. This filter provides the only way to create Microsoft® Windows Media™ Audio (WMA) and Windows Media Video (WMV) files in DirectShow®. The filter can also create Windows Media Format files that are secured by Digital Rights Management (DRM).

The ASF Writer filter can be used only in conjunction with the Windows Media Format SDK. To develop applications that use this filter, you must have the Windows Media Format SDK installed on your development machine. When you download the SDK, Microsoft will send you a software certificate by e-mail. This certificate will enable your application to unlock that SDK, and to read or write any Windows Media Audio or Windows Media Video file that does not have Digital Rights Management (DRM) (without this certificate, an application cannot add the ASF Writer to a filter graph). To read or write DRM-enabled files, you need to obtain a different certificate from Microsoft, as described on the Windows Media Technologies Web site.

This topic contains the following sections:

  • Configuring the ASF Writer
  • Building a Graph
  • Unlocking the Windows Media Format SDK

Configuring the ASF Writer

When the ASF Writer filter is created, it is configured automatically with a default system profile. System profiles are discussed in detail in the Windows Media Format SDK; basically, they describe various attributes of a Windows Media Format file such as bit rate, number and type of streams, compression quality, and so on. If the default profile is not suitable, an application can modify it using the filter's IConfigAsfWriter interface methods. The filter uses the profile to determine what kind of Windows Media Format file to write, how many input pins it must set up, and what media types they can accept. The filter must be added to the graph before it can be configured, and it must be configured before it can be connected to upstream filters.

There are various ways to specify a profile to the ASF Writer. The ASF Writer has a property page that lists the profiles available on the system. This list shows what kinds of streams the filter can create based on the specified input streams. The profile descriptions appear as human-readable strings such as "250 Video—Creates video content for clients with 250 Kbps network connections, such as cable modems, DSL, and LAN connections" or "128 CD Quality Audio—creates CD transparency quality audio content for clients with high-speed Internet and LAN connections. Also suited for local playback." An application can expose this property page to the end user to enable the user to select a profile. For information on how to display a filter's property page, see Displaying a Filter's Property Pages. If you don't want to use the property page, you can get the list of profiles directly by using the Windows Media Format SDK and present these to the end user in your user interface. You can also create a custom profile and pass it directly to the filter, or pass the filter a globally unique identifier (GUID) for a profile from the Wmsysprf.h header file in the Windows Media Format SDK.

The filter allows profiles to be reset while its input pins are connected, but if the profile is changed—for example, from a one-input audio stream profile to a two-input audio and video profile—only the previously connected audio stream is reconnected.

By default, the ASF Writer expects uncompressed audio and video streams on its input pins, and handles the compression by using the Windows Media Format SDK. Because any data format can be converted to ASF, there might be occasions when you want to convert a data format for which the Windows Media Format SDK does not have an appropriate codec. (The resulting file will be a perfectly valid ASF file but it will not qualify as a WMA or WMV file.) In such cases, you need to compress the stream in the filter graph upstream of the ASF Writer and bypass the ASF Writer compression mechanism. To do this, ensure that the media type of the upstream output pin that connects to the ASF Writer exactly matches the output stream format used in the current ASF Writer profile. When the ASF Writer detects that the input streams are identical to the profile it was configured with, it converts the data to ASF without attempting to compress it further.

The ASF Writer always does the compression internally whenever filters are inserted automatically between the source filter and the ASF Writer (that is, by calling the IGraphBuilder::Connect) method. Therefore, to bypass the ASF Writer compression mechanism, you must create the entire graph manually, as described in the following section.

Because the Windows Media Format SDK requires an audio stream to work, the ASF Writer must always have an input audio pin, even if it is for a dummy stream—that is, a muted, low-bit-rate audio stream. All input data must be time-stamped, and all input pins must be connected before the filter can be run or paused.

Building a Graph

You can build a filter graph using the ASF Writer in two ways. The first way is to manually add each filter to the graph and connect the pins. After adding the ASF Writer, configure it through the IConfigAsfWriter methods, if the default profile is not suitable, and connect the ASF Writer input pins to the corresponding output pins on the upstream filters.

The second way is to call the IGraphBuilder::RenderFile method with the name of the file to convert to ASF. RenderFile automatically builds a complete graph for rendering the file. In your application code, you then manually remove the renderer filters and insert the ASF Writer. This involves five basic steps:

  1. Add the ASF Writer to the graph.
  2. Disconnect the renderer filters and store the output pins they were connected to.
  3. Remove the renderer filters from the graph.
  4. Configure the ASF Writer.
  5. Connect the ASF Writer input pins to the output pins by using IGraphBuilder::Connect.

The following illustration shows typical ASF Writer filter graph configurations.

ASF Writer filter graph

Unlocking the Windows Media Format SDK

To access the Windows Media Format SDK, an application must provide a software certificate, also called a key, at run time. For details on obtaining the certificate, see the Windows Media Format SDK. A DirectShow application provides its certificate to the ASF Writer when it is added to the filter graph. The application must register as a key provider using the Component Object Model (COM) IServiceProvider and IObjectWithSite interfaces. Using this technique, the application implements a key provider class derived from IServiceProvider. This class implements the three standard COM methods—AddRef, QueryInterface, and Release—along with one additional method, QueryService, which is called by the filter graph manager. QueryService calls the Windows Media Format SDK method WMCreateCertificate and returns to the filter graph manager a pointer to the certificate that was created. If the certificate is valid, the filter graph manager allows the graph-building process to proceed.

Note To build an application, include Wmsdkidl.h for the prototype for WMCreateCertificate, and link to the Wmstub.lib that you received from Microsoft.

The following code example illustrates the basic steps in this process:

// Declare and implement a key provider class derived from IServiceProvider.

class CKeyProvider : public IServiceProvider {
public:
    // IUnknown interface
    STDMETHODIMP QueryInterface(REFIID riid, void ** ppv);
    STDMETHODIMP_(ULONG) AddRef();
    STDMETHODIMP_(ULONG) Release();

    CKeyProvider();

    // IServiceProvider
    STDMETHODIMP QueryService(REFIID siid, REFIID riid, void **ppv);

private:
    ULONG m_cRef;
};

CKeyProvider::CKeyProvider() : m_cRef(0)
{
}

//////////////////////////////////////////////////////////////////////////
//
// IUnknown methods
//
//////////////////////////////////////////////////////////////////////////

ULONG CKeyProvider::AddRef()
{
    return ++m_cRef;
}

ULONG CKeyProvider::Release()
{
    ASSERT(m_cRef > 0);

    m_cRef--;

    if (m_cRef == 0) {
        delete this;

        // Don't return m_cRef, because the object doesn't exist anymore.
        return((ULONG) 0);
    }

    return(m_cRef);
}

// We only support IUnknown and IServiceProvider.
HRESULT CKeyProvider::QueryInterface(REFIID riid, void ** ppv)
{
    if (riid == IID_IServiceProvider || riid == IID_IUnknown) {
        *ppv = (void *) static_cast<IServiceProvider *>(this);
        AddRef();
        return NOERROR;
    }

    return E_NOINTERFACE;
}

STDMETHODIMP CKeyProvider::QueryService(REFIID siid, REFIID riid, void **ppv)
{
    if (siid == __uuidof(IWMReader) && riid == IID_IUnknown) {
        IUnknown *punkCert;

        HRESULT hr = WMCreateCertificate(&punkCert);

        if (SUCCEEDED(hr)) {
            *ppv = (void *) punkCert;
        }

        return hr;
    }
    return E_NOINTERFACE;
}

////////////////////////////////////////////////////////////////////
//
// These examples illustrate the sequence of method calls
// in your application. Error checking is omitted for brevity.
//
///////////////////////////////////////////////////////////////////

// Create the filter graph manager, but don't add any filters.
IGraphBuilder *pGraph;
hr = CreateFilterGraph(&pGraph);

...

// Instantiate the key provider class, and AddRef it
// so that COM doesn't try to free our static object.

CKeyProvider prov;
prov.AddRef();  // Don't let COM try to free our static object.

// Give the graph an IObjectWithSite pointer to us for callbacks & QueryService.
IObjectWithSite* pObjectWithSite = NULL;

hr = pGraph->QueryInterface(IID_IObjectWithSite, (void**)&pObjectWithSite);
if (SUCCEEDED(hr))
   {
// Use the IObjectWithSite pointer to specify our key provider object.
// The filter graph manager will use this pointer to call
// QueryService to do the unlocking.
// If the unlocking succeeds, then we can build our graph.

pObjectWithSite->SetSite((IUnknown *) (IServiceProvider *) &prov);
    pObjectWithSite->Release();
   }

// Now build the graph as described above in "Building A Graph."


Microsoft TV Technologies

This section discusses how to use Microsoft® DirectShow® for analog and digital TV applications. The analog sections discuss how to write applications based on existing analog tuning cards such as the ATI All-In-Wonder. The digital sections discuss how to write applications based on a new generation of digital/analog tuner cards that support Microsoft® Broadcast Driver Architecture (BDA).

This section contains the following articles:

  • Writing Analog TV Applications
  • Writing Digital TV Applications
  • The Microsoft Tuning Model
  • BDA Digital TV Reference


Writing Analog TV Applications

This article contains the following sections:

  • Classes of Analog TV Hardware Devices
  • Analog TV Filter Graph
  • Building The Graph
  • Capturing VBI Data
  • Analog TV Tuning

Analog TV filter graphs are based on analog television tuner-capture cards. A single card will generally contain several devices: the tuner, zero or more crossbars for routing the signal, the analog-to-digital converter (also called the analog video decoder), and possibly a separate device for TV audio. The Microsoft® Windows® Driver Model (WDM) device drivers for each device on the card are supplied by the manufacturer or other third parties. These drivers work together with filters and plug-ins supplied by Microsoft to enable the devices to participate in a filter graph. The Microsoft-supplied components are the TV Tuner filter, the TV Audio filter, the Analog Video Crossbar filter, and the WDM Video Capture plug-in. In GraphEdit, these filters appear in the "WDM Streaming" categories; the friendly name of the filter will vary depending on the driver. Applications discover these filters using the System Device Enumerator. For details on how to discover these devices programmatically, see Enumerating Devices and Filters. For general information on using hardware devices in DirectShow, see How Hardware Devices Participate in the Filter Graph.

In addition to the device filters mentioned previously, an analog TV filter graph will also include kernel mode (KsProxy-based) and user mode filters supplied by Microsoft as part of DirectShow. These filters include the Tee/Sink-to-Sink Converter, VBI Surface Allocator, CC Decoder, Line 21 Decoder, Overlay Mixer, Video Renderer, and possibly others. These filters are discussed in more detail in a later section.

Classes of Analog TV Hardware Devices

In the context of building an analog TV filter graph, there are two basic classes of analog capture cards: (1) those that send the video data directly to video memory through a direct hardware connection called a video port, and (2) those that send the video data first to host memory via the PCI bus, or over a USB or IEEE 1394 connection, and then to the graphics card.

From an application's point of view, there are two basic differences in the filter graphs for video port devices and PCI/USB/1394 devices:

  1. Graphs based on video port devices will require an extra filter, the VBI Surface Allocator. This filter is needed to allocate extra video memory on the video graphics adapter for the VBI bitmaps. It connects to the VPVBI output pin on the capture filter. On PCI devices the Overlay Mixer can allocate this memory, so the VBI Surface Allocator is not needed.
  2. Graphs based on video port devices will use the Bt829 capture filter and graphs based on PCI (and 1394/USB) devices will use the Bt848 capture filter. Graphs using the Bt848 filter will not use the VBI Surface Allocator.

    Analog TV Filter Graph

    The following illustration shows an analog TV filter graph based on the ATI All-In-Wonder card. This graph renders video, audio, and closed-captioned text, and also captures the video and audio to an uncompressed AVI file. (Although this filter graph is somewhat complex, it can be created using the capture graph builder with only a few lines of code. Graph building is discussed later in this section.)

    ATI All-In-Wonder Filter Graph

    TV Tuner: This filter is always the first filter in the graph, although no data actually passes through it. Applications use its IAMTVTuner interface to set the channel-to-frequency mappings, perform channel selection and to obtain information about which video standard the hardware supports.

    Analog Video Crossbar: The crossbar filter is a routing device that applications use to set up the correct data paths for the input signals on the hardware. This filter supports the IAMCrossbar interface. The input pins on this filter represent the physical input from the antenna, cable, and/or auxiliary lines (such as a VCR). Any of the input signals can be routed to one or more of the outputs. The ATI graph illustrated previously has two crossbar filters. The upstream crossbar is for external inputs, and the second is for multiple inputs to the hardware video decoder (also called the analog-to-digital converter), which is represented by the capture filter in the graph. Other cards may have different crossbar configurations.

    Video Capture Filter: This kernel-mode filter represents the analog-to-digital converter on the hardware. It is the first filter in the graph that actually processes the video signal. Microsoft provides the driver that supports the Brooktree 829 capture chip used in video port devices, and IHVs supply drivers for the Brooktree 848, 878, and other video chips. All these drivers use the WDM Video Capture plug-in to provide property pages and expose their COM interfaces. The drivers and the plug-in appear as a single "filter" to applications. Applications use the IAMAnalogVideoDecoder interface on this filter to get and set the supported analog video format, the status of the horizontal sync, and the output bus. The capture filter is capable of creating two separate video streams for output, one for rendering and one for capture. The rendering pin (named VP for Video Port) always connects to input pin zero on the Overlay Mixer. The Overlay Mixer reference page contains more information about video port connections.

    The capture filter outputs the VBI data on a separate pin; some cards may output raw VBI data and some perform the VBI decoding in hardware. All the Microsoft VBI filters correctly handle both raw and decoded data. Since the All-In-Wonder card has a video port, the Bt829 capture filter is used; it has an output pin to the VBI Surface Allocator, which will correctly configure the video memory for the CC overlays that will be provided by the Line 21 Decoder. This filter connects to input pin 1 or greater on the Overlay Mixer.

    AVI Decompressor: The AVI Decompressor filter is a wrapper filter for Video Compression Manager codecs. In an analog TV capture graph, it wraps the MSYUV color space converter which converts the video stream from UYVY to RGB before sending it to the AVI Multiplexer.

    Audio Capture: The Audio Capture filter receives the digitized audio from the Audio Decoder output pin on the crossbar. Note that the data is received on the CD Audio input pin of the Audio Capture filter. This pin actually represents the internal input on the sound card, which can be from any internal source on the host system, not just the CD drive. The other input pins on the Audio Capture filter generally represent the analog inputs for external devices such as microphones, tape players, and so on. The exact pin configuration and pin names might vary on different sound cards. In the graph shown previously, the Audio Capture filter delivers the audio data to the AVI Mux filter.

    Note that this graph does not contain an Audio Renderer filter; this filter is not necessary when the TV card is connected to the sound card by an external cable (or "dongle") to the sound card's input jack. If this cable is not used, then the graph shown above would use the Smart Tee filter downstream from the Audio Capture filter to deliver audio to the Default DirectSound Device as well as to the AVI Mux.

    Tee/Sink-to-Sink Converter: This filter accepts the VBI information from the capture filter and splits it into separate streams for each of the data services present on the signal. Microsoft provides VBI codecs for Closed Caption, NABTS, and World Standard Teletext (WST). In the previous graph, the only service being captured is Closed Caption.

    CC Decoder: The CC VBI decoder is a kernel-mode stream class filter. It has two input pins, VBI and HWCC. It has up to eight output pins, each of which can select their own lines and substreams. Its job is to process captured VBI lines and deliver decoded CC data to the Line 21 Decoder and/or to interested applications. The first output pin is connected to the Line 21 Decoder.

    Line 21 Decoder: The Line 21 Decoder accepts decoded closed-captioned data from the CC Decoder and generates the bitmaps which will be overlaid on top of the video rectangle. This data is then passed to the Overlay Mixer.

    NABTS/FEC VBI Codec Filter (Not shown): The NABTS/FEC VBI Codec is a ring-0 stream class filter. It has two input pins, VBI and HWNABTS. It has up to eight output pins, each of which can select their own VBI scan lines and substreams. Its job is to process captured VBI lines and to distribute decoded and/or forward-error-corrected NABTS data to the BDA SLIP Deframer filter and then to BDA IP Sink, which makes the IP data available to any application via Winsock.

    WST Codec and WST Decoder filters (Not shown): These filters are ring-0 stream class filters that handle teletext data on PAL systems. The WST Codec has one input pin which receives raw VBI data. It has up to eight output pins, each of which can select their own lines and substreams. Its job is to process captured VBI lines and to distribute decoded teletext data to interested applications. The first output pin is connected to the WST Decoder which creates the bitmaps for the hardware overlay in the same way as the Line21 Decoder works for closed-captioned data.

    Overlay Mixer: This DirectShow filter performs the actual rendering of the video onto the system's video memory. It is used with both video port and non-video port types of hardware.

    Video Renderer: In all graphs that use the Overlay Mixer to render the video, the Video Renderer acts merely as a window manager that informs the Overlay Mixer where on the screen to place the video rectangle.

    Building The Graph

    An analog TV graph is simply one type of WDM video capture graph. It can be built using the capture graph builder, as discussed in the article How to Write a Capture Application and demonstrated in the AMCap sample application. As demonstrated in AMCap, the basic principle is to start with the capture filter and then add the downstream filters for each of its pins that you wish to render or capture. The upstream filters are added last. Although AMCap does show how to pull in the CC Decoder and Line 21 Decoder filters to render closed-captioned data, it does not demonstrate how to pull in other VBI-related filters for capturing NABTS or teletext data.

    Capturing VBI Data

    DirectShow provides kernel-mode filters for capturing NABTS, Line 21, and World Standard Teletext (WST) data (for PAL signals) from the vertical blanking interval (VBI) of an analog TV broadcast signal. These filters appear in GraphEdit under the WDM Streaming VBI Codecs category. The capture filter has an output pin that delivers raw VBI data to the Tee/Sink-to-Sink Converter, which examines the data for any NABTS IP data, Line 21 closed captioning, or teletext information that may be present on the signal, and creates an output pin for each data type. To add the filters for decoding closed-captioned or teletext data, use the ICaptureGraphBuilder2::RenderStream method on the appropriate output pin of the MSTee filter. The previous illustration shows the filters for capturing and rendering CC data, and the AMCap sample demonstrates how to add the closed-captioned filters to the graph. For NABTS IP data (such as interactive TV enhancements including Web pages and images), you must manually add and connect the chain of filters downstream from the Video Capture filter. The following illustration shows the VBI segment of a graph that handles both NABTS data and closed captions. Note the addition of the Tee/Sink-to-Sink Converter filter to split the VBI data into two streams.

    NABTS and closed captioning filter graph segment

    There are no application-callable interfaces on these kernel-mode filters. They simply function as a data pipeline that extracts SLIP-encoded IP packets from the VBI signal and passes them on to Winsock.

    For teletext data, the filters appear as shown in the following illustration.

    World Standard Teletext filter graph segment

    Some capture devices perform NABTS, teletext or CC decoding in hardware. When this is the case, the capture filter will expose a special output pin and the downstream decoder simply passes the data through without modifying it. No special programming is required by the application developer.

    Line 21 of the VBI contains not only closed-captioned text but can also contain URLs for Web pages associated with the current broadcast. This is described as "Transport B" in the ATVEF specification.

    Analog TV Tuning

    The basic order of operations when controlling the TV tuner is as follows:

    1. If necessary, establish a video path from the tuner through a crossbar to the video digitizer (capture filter) using the IAMCrossbar interface on the Analog Video Crossbar filter.
    2. Call the IAMTuner::put_Mode method to set the tuner card to the type of broadcast to be received (TV, AM radio, FM radio, and so on).
    3. Set the country code with IAMTuner::put_CountryCode to establish the correct TV channel-to-frequency mappings. See International Analog TV Tuning for more information on country codes.
    4. For each input on the tuner, call IAMTVTuner::put_InputType to set the input type to cable or antenna. Use IAMTVTuner::put_ConnectInput to select one of the available tuner inputs.
    5. Call IAMTVTuner::get_TVFormat to retrieve the current video format, and then use this value to set the Capture Filter with a call to IAMAnalogVideoDecoder::put_TVFormat.
    6. Call IAMTuner::put_Channel to begin viewing.


Writing Digital TV Applications

With the Microsoft® DirectX® 8.0 SDK and a digital TV tuner card that is compatible with Microsoft® Broadcast Driver Architecture (BDA), you can create an application for viewing digital TV broadcasts on the personal computer. Microsoft's architecture for digital television support on the PC can be broken up into the following components:

  • Broadcast Driver Architecture
    • Tuning and Demodulation
    • Demultiplexing
    • Digital TV Standards Support (DVB, ATSC)
    • Conditional Access (will be released in future versions of the Microsoft® Windows® operating system)
    • Electronic Program Guide (will be released in future versions of the Microsoft Windows operating system)
    • MSTV Guide Store (will be released in future versions of the Microsoft Windows operating system)
    • ATVEF (will be released in future versions of the Microsoft Windows operating system)
  • Tuning Model
    • The Tuning Model is a set of objects that encapsulate the complexities of tuning across various network types. The Tuning Model enables applications to tune to any available frequency or channel in a simple and uniform manner.
  • Video Control Architecture
    • The Video Control is an ActiveX® control that provides a scripting API for TV and DVD applications. It greatly simplifies the integration of TV and DVD features into applications. (will be released in future versions of the Microsoft Windows® operating system)

DirectX 8.0 includes all the filters and associated components necessary to create a basic digital TV filter graph, connect to ATSC (antenna or cable) or DVB-S transmissions, tune the graph and select substreams, capture raw PSI data (such as Electronic Program Guide information) and render the video on the screen.

DirectX 8.0 does NOT include the MSTV Guide Store, which persists EPG data from the PSI stream, or the component for rendering ATVEF enhancements such as Web pages and images for interactive TV. Digital TV applications based on DirectX 8.0 must therefore provide custom implementations for these tasks. DirectX 8.0 also does not provide the Video Control, which means that applications must implement their own code for building the filter graph.

This article contains the following sections:

  • Digital TV Filter Graph
  • Building the Filter Graph

Digital TV Filter Graph

The following illustration shows a basic BDA digital TV filter graph configured for reception of terrestrial ATSC broadcasts. The actual filter and pin names for the tuner, capture and MPEG-2 decoder filters will vary depending on the vendor.

Generic BDA Digital TV Filter Graph

Network Provider: A BDA Network Provider filter is always the first filter in the graph. This particular graph has the ATSC Network Provider. Microsoft also provides a DVB Network Provider for tuning to DVB networks. Third parties may also provide their own Network Provider that is customized for their own broadcasts. The Network Provider configures the downstream filters for a particular tuning space, which includes information on content multiplexing, modulation, and transmission standards. This filter implements the ITuner interface, which applications use to tune the device to the specified channel or frequency.

Digital TV Tuner: This kernel-mode KsProxy-based filter represents the tuner on the hardware device. It may or may not have any application-callable interfaces, depending on the implementation of the third-party driver. In the BDASample application, the tuner filter is assumed not to support ITuner, and so tuning is performed through the Network Provider, which communicates internally with the Tuner filter.

Digital TV Capture Filter: This kernel-mode KsProxy-based filter represents the demodulator/digitizer on the hardware device. Its single output pin delivers the MPEG-2 transport stream to the MPEG-2 Demultiplexer.

MPEG-2 Demultiplexer: In a digital TV graph, the MPEG-2 demultiplexer accepts the MPEG-2 transport stream from the capture filter and demultiplexes the stream. It typically has four output pins. Its first output pin delivers raw program service information (PSI) packets to the Transport Information Filter. The second pin delivers the video stream to the MPEG-2 decoder. The third pin delivers the audio to the audio decoder, and the fourth pin delivers data such as interactive TV enhancements.

Transport Information Filter: So that a receiver can properly acquire all the elementary streams related to a specific program and so that a receiver can tell what programs are contained in the stream, the transport stream will also contain many sets of tables that act as a catalog of information contained in the transport stream. Under direction of the Network Provider, the MPEG-2 Demultiplexer delivers these tables to the Transport Information Filter, which then parses these tables and provides the information to the Network Provider so that it can control the other receiver filters and nodes in the graph.

HDTV-capable MPEG-2 Decoder: A Digital TV filter graph requires a third-party decoder that is capable of decoding High Definition Television (HDTV) video streams. Some decoder implementations may operate on both audio and video streams in the same filter, while others may have separate filters for audio and video.

Overlay Mixer: This Microsoft® DirectShow® filter performs the actual rendering of the video onto the system's video memory.

Video Renderer: In all graphs that use the Overlay Mixer to render the video, the Video Renderer acts merely as a window manager that informs the Overlay Mixer where on the screen to place the video rectangle.

BDA MPE Filter: This filter extracts IP packets from the Multi-Protocol Encapsulation (MPE) stream and delivers them to IP Sink.

BDA IP Sink: This filter accepts IP packets and delivers them to the host system via Winsock, where interested applications can listen for and receive IP data streams such as interactive TV enhancements.

Building the Filter Graph

For DirectX 8.0, applications must build digital TV graphs by manually adding and connecting each filter. The Capture Graph Builder cannot be used. A sample application, BDASample, is included in the SDK. It demonstrates how to build a basic digital TV filter graph according to the steps outlined later in this section.

The following sections are ordered in roughly the typical sequence of operations that take place during run time. Notice that the building of the filter graph occurs after the tune request is submitted to the Network Provider with the ITuner::put_TuneRequest method. This is because the tune request contains information about the network type and other details that will determine which filters get pulled into the graph. The graph cannot be built until the Network Provider has this information. See The Microsoft® Tuning Model for more information on Tuning Spaces, Tune Requests, and related objects.

Obtain a Tuning Space

For DirectX 8.0, Broadcast Driver Architecture provides default Tuning Spaces for local analog cable and antenna, local ATSC antenna and cable, and DVB-S. A digital cable tuning space is also included, but it is for testing purposes only. To implement digital cable support in your application, overwrite the digital cable tuning space with the values you require, and also supply a default locator if necessary. To support international tuning or digital satellite broadcasts, you will need to create your own tuning space. For DVB tuning spaces, the application will have to provide a user interface that will enable the user to specify which digital television service they have subscribed to.

To obtain a tuning space, the application creates an instance of the SystemTuningSpaces object and uses the ITuningSpaceContainer::get_EnumTuningSpaces method to obtain a list of tuning spaces from which it can select one. This procedure is demonstrated in the BDASample application in the LoadTuningSpace method.

Although the Microsoft Tuning Model is designed to support analog tuning spaces, DirectX 8.0 does not include full support for analog TV tuning in a BDA filter graph. This support will be added in future releases of DirectX and in Microsoft® Windows®. In the meantime, analog TV graphs are supported with the same type of filter graph that DirectShow has traditionally used for analog TV capture. In DirectX 8.0 only digital network types are supported on a BDA filter graph. This means, for example, that if you wish to write an application that supports both digital and analog tuning, your application will need to create two separate filter graphs, and use the analog graph when the user selects an analog TV channel, and the BDA digital graph when the user selects a digital channel or frequency. In future releases of Microsoft Windows, analog and digital television and radio tuning spaces will all be provided, along with an Automation-compliant Video Control that will completely handle the graph-building process.

Create a Tune Request and Submit it to the Network Provider

Applications do not create Tune Requests directly. Instead, an application calls the ITuningSpace::CreateTuneRequest method, which returns an empty, uninitialized Tune Request. The application then calls the standard COM method QueryInterface on the object for a specific interface derived from ITuneRequest, such as IATSCChannelTuneRequest. The application can then use the returned interface to configure the Tune Request, persist it, and submit it to the Network Provider. But before it can submit the Tune Request, the application must first create an instance of the Filter Graph Manager, and then create an instance of the Network Provider filter and add it to the graph. It is important to realize that actually there is no such thing as a generic "Network Provider" filter; instead there is an "ATSC Network Provider," and a "DVB Network Provider." The specific object that is created is based on the network CLSID that is obtained from the Tuning Space object.

After the Network Provider has been added to the graph, use the QueryInterface method to obtain its ITuner interface. Then use the ITuner::put_TuneRequest method to pass the Tune Request to the Network Provider. This procedure is demonstrated in BDASample in graph.cpp in the LoadNetworkProvider function.

Add and Connect the Remaining Filters

Once the Network Provider has been configured with a Tune Request, the remaining filters can be added to the graph one at a time by adding and connecting each filter. See the BuildGraph, LoadAVSegment and LoadIPSegment functions in graph.cpp in the BDASample application.

Define Default Preferred Component Types

Note This procedure is not implemented in BDASample.

A "component" refers to a program substream. The default preferred component types are those types of substreams that a user wishes to activate by default. For example, a user may specify that a Spanish audio stream should be played whenever one is available. The application creates a set of preferred components by instantiating an empty Components collection object and filling it. The application can then persist and/or submit the Components object to the Tuner, which will check it whenever there are changes in the available substreams.

Select a Substream

Note This procedure is not implemented in BDASample.

To specify which substreams to activate or inactivate, an application must first submit a Tune Request to the Tuner. Once the Tuner tunes to the specified channel or frequency, it will fill in the Components collection in the Tune Request with information about each active and inactive substream. The application can then examine each component in this collection, and use the IComponent::put_Status method to activate or inactivate a particular substream.

Digital Tuning

After the initial Tune Request has been submitted, subsequent tuning is performed by submitting a new Tune Request to the Network Provider, as demonstrated in BDASample in the ChannelChange method in graph.cpp.


The Microsoft Tuning Model

Overview

The process of tuning a digital receiver involves a different set of parameters depending on the network type. The purpose of the Tuning Model is to encapsulate these differences within a standard set of objects and procedures for manipulating those objects, and thereby free the application from having to manage low-level tuning details. Whether an application is tuning to a program coming from a DVB-S provider, or a local analog broadcaster, the basic procedure will be the same. This procedure is also independent of the underlying hardware. All the objects of the Tuning Model support the standard COM interface IPersistPropertyBag and so can be persisted to any sort of storage mechanism.

It is important to note that applications based on Microsoft® DirectX® 8.0 will not realize the full benefits of the Microsoft Tuning Model, because DirectX 8.0 does not provide a standardized Guide Store and Tuning Space-aware Guide Store Loader. Future releases of DirectX and of Microsoft® Windows® are expected to include these components. The Guide Store Loader monitors the Program Service Information (PSI) stream on the Transport Information Filter, and automatically creates Tune Requests for all the available channels or frequencies in a tuning space, and stores them in the Guide Store database. With these components, all the application has to do is create a User Interface showing the available channels, and submit the pre-prepared Tune Request to the Network Provider when the user makes a selection. For DirectX 8.0, however, the application must be involved in the creation of Tune Requests (which requires knowledge of their semantics). The other alternative is to write your own Guide Store Loader and Guide Store.

Tuning Model Objects

The two primary objects in the Tuning Model are the Tuning Space and the Tune Request. The Tuning Space describes the provider or transmission source, for example, a local cable service or a digital satellite network. Applications use the Tuning Space Container to enumerate the available Tuning Spaces on the local system, and then use the Tuning Space to create the Tune Request. The application submits Tune Requests to the Network Provider, which is the source filter in the graph. The Network Provider extracts the necessary information from the Tune Request and passes that information down to the kernel-mode driver. The following illustration shows the high-level relationship between an application, the tuning model objects, the BDA filter graph, and the kernel mode drivers.

Overview of Broadcast Architecture

Tuning Spaces and Tune Requests

A Tuning Space describes a specific network provider. Examples of tuning spaces include EchoStar®, DirecTV®, local analog broadcast via antenna, local analog cable, and local digital broadcast via antenna. The tuning space information includes information about the type of network, such as terrestrial analog broadcast television, ATSC, DVB-T, DVB-C, or DVB-S. A tuning space defines the context for a tune request; a Tune Request is meaningless apart from a particular Tuning Space. Therefore, a Tuning Space object has the job of creating its associated Tune Request objects. For example, an ATSC Tuning Space object creates ATSC Tune Requests, a DVB-S Tuning Space object makes DVB-S Tune Requests, and so on. Tuning Space objects and Tune Request objects are Automation® compliant and can be configured either through script, Microsoft® Visual Basic®, or C/C++.

Matching Tuning Spaces to Tune Requests and the Network Provider

Because different network types carry different types of data in different formats, each tuning space will require a particular Network Provider in the filter graph. For example, to create a tune request for a channel that is broadcast in ATSC digital format, an application would begin with an ATSC tuning space, which supports IATSCTuningSpace, and has a network type of ATSC and is associated with a default locator (discussed later in this section) that has been configured with the IATSCLocator interface. When the application calls ITuningSpace::CreateTuneRequest, it will receive back an ITuneRequest interface pointer. The application uses that interface to query for the IATSCTuneRequest interface, and then uses that interface to configure the tune request. When the tune request is submitted, it must be submitted to the Microsoft ATSC Network Provider (or to some other third-party BDA-compliant tuner filter that supports ITuner as well as an ATSC tuning space).

Note For this version of Microsoft® Broadcast Driver Architecture, two Network Provider filters are provided, one for ATSC networks and one for DVB-S networks. No default Tuning Spaces are provided for any DVB-S providers because of the specific information required to define them. Applications must use the SystemTuningSpaces object (using the ITuningSpaceContainer interface in C++) to create their own DVB-S Tuning Spaces based on basic information provided by the user about the service they are subscribed to.

Other Tuning Model Objects

The Microsoft Tuning Model includes other objects besides the ones mentioned earlier in this section. The following illustration shows the general relationship between all of the Tuning Model objects. In C++ terms, this diagram shows relations between base classes. In the actual process of creating and submitting a Tune Request, an application will always work with derived classes that are all specific to the same type of network.

Generalized view of Tuning Model objects.

The Tuning Space Container searches the Registry for tuning spaces available on the system, and instantiates Tuning Space objects.

A Tuning Space plays three primary roles. For a specific program source, it describes the type of network, contains parsing rules for the "TV:" moniker namespace, and is a factory for Tune Request Objects. "TV:" Uniform Resource Identifiers (URIs) can be embedded in HTML or XML, and must be parsed in order to bind to the correct object instance. Binding is the COM terminology for obtaining a COM object from a Moniker. In this case, the Tuning Space provides the network-specific parsing, so that binding to a "TV:" URI will result in a Tune Request object for that Tuning Space.

Locator objects are associated with a Tuning Space and provide further information that will be used ultimately by the device driver to tune to a specified channel or frequency within a Tuning Space.

A component refers to an elementary stream within the MPEG-2 program stream, for example video, audio 1, audio 2, audio 3, data, Program Service Information (PSI) and so on. These values are filled in by the Network Provider after it has tuned to the new frequency.

Each component is associated with a component type object that contains information about the component, such as which language is being spoken on an audio elementary stream. An application will maintain a list of preferred Component Types for each user. The current user's list should be submitted to the Network Provider via ITuner. If no such list is provided, then the Network Provider will use the Default Preferred ComponentTypes list in the Tuning Space. Third parties can define new preferred component types. By maintaining a list of preferred component types for each user, the app should never have to deal directly with Components, except in exceptional circumstances. Exceptional circumstances would include: the preferred language is English, but the viewer decides they want to hear the German audio instead; the preferred audio track is AC-3, but the viewer wants to switch to a mono track.

When the Network Provider receives a Tune Request, and tunes to a particular channel or frequency, it fills in the Tune Request's Component list based on PSI information acquired by the Transport Information Filter. The Network Provider then compares that information to the preferred components types for the current user, and tunes to the appropriate elementary streams if any are available that match the user's preferences. After this initial Tune Request has been submitted, the application may obtain the current active Tune Request, and access the newly populated Components list. This Tune Request can be re-submitted with an updated Components list as user preferences dictate. An example of this would be changing the audio track to a different language than the default preference. The Preferred Components are only used if the Tune Request's Components list is empty or invalid. This is necessary because the Tune Request can be resubmitted multiple times with different Components activated or disabled.


BDA Digital TV Reference

This topic contains the following sections:

  • BDA COM Interfaces
  • Tuning Model Scriptable Objects


BDA COM Interfaces

The following Microsoft® Broadcast Driver Architecture (BDA) COM interfaces are accessible to C/C++ applications:

Tuning Space Interfaces

Applications can create or access a Tuning Space using the Tuning Space Container object, which supports ITuningSpaceContainer. You will never use the base class ITuningSpace interface directly; you will always use a derived interface that is specific to a particular network type.

ITuningSpace | Base class for specific tuning space interfaces.
IAnalogRadioTuningSpace | Tuning Space specific to terrestrial Radio networks.
IAnalogTVTuningSpace | Tuning Space specific to analog TV networks.
IATSCTuningSpace | Tuning Space specific to ATSC networks.
IDVBTuningSpace | Tuning Space specific to DVB networks.
ITuningSpaceContainer | Created by applications to create new Tuning Spaces or enumerate or modify existing ones.
IEnumTuningSpaces | Standard COM enumeration interface for Tuning Spaces.

Tune Request Interfaces

Tune requests are not created directly by applications. They are created through a call to ITuningSpace::CreateTuneRequest on the Tuning Space object. After receiving a pointer to the returned object, an application calls QueryInterface on that object for the network-specific interface that will be used to modify the Tune Request.

ITuneRequest | Exposed on Tune Request objects, which are created by a Tuning Space object. Applications can modify and submit Tune Requests to the Tuner.
IChannelTuneRequest | Implemented on Tune Request objects specific to analog TV networks.
IATSCChannelTuneRequest | Implemented on Tune request objects specific to ATSC TV networks.

Stream Component Interfaces

A "component" in this context refers to a substream within a broadcast. Applications create Component objects only in order to specify a set of default preferred component types that will be associated with a Tuning Space. The actual components of a broadcast stream can only be discovered after reception begins. The Network Provider at that point will fill in the Component object information and the application can then retrieve this information and use it, for example, to change the audio stream or determine which audio streams are currently available.

IComponent | Base class for specific component interfaces.
IComponentType | Base class for specific component type interfaces.
IComponentTypes | Provides a standard COM enumeration of component types.
IComponents | Provides a standard COM enumeration of components.
ILanguageComponentType | Component type associated with the language of the substream.
IMPEG2ComponentType | Implemented on a component type associated with an MPEG-2 stream type.
IATSCComponentType | Implemented on a component type that indicates whether the audio substream is in AC-3 format.
IEnumComponents | Implemented on a standard COM collection object containing all the active or inactive components on the current broadcast stream.

Locator Interfaces

Locator objects are used in some cases by the Network Provider and other filters in the graph to determine how and where to tune to implement a Tune Request. These interfaces are not used by applications except possibly for debugging purposes.

ILocator | Base class for network-type specific tuning space locators. Not used by applications.
IATSCLocator | Called by the Network Provider to obtain information about tuning within an ATSC network. Not used by applications.

Network Provider Interfaces

These interfaces are exposed on the Network Provider filter and enable the filter to process Tune Requests and other commands from an application.

ITuner | Base class interface for accepting Tune Requests and other data from an application. Supported on the Network Provider filter in the filter graph.
IScanningTuner | Supported on the Network Provider filter in the filter graph. Inherits from ITuner. Applications using the default Network Provider filter should QueryInterface for IScanningTuner, not ITuner.


IAnalogRadioTuningSpace

Microsoft DirectX 8.0

IAnalogRadioTuningSpace Interface

This interface is implemented on the AnalogRadioTuningSpace object.

MethodName | Description
ITuningSpace Methods
get_UniqueName | Retrieves a unique name for the Tuning Space. Can be either a short name, or a GUID.
put_UniqueName | Sets a unique name for the Tuning Space. Can be either a short name, or a GUID.
get_FriendlyName | Retrieves the localized, user-friendly name of the Tuning Space.
put_FriendlyName | Sets the localized, user-friendly name of the Tuning Space.
get_CLSID | Gets the CLSID of the tuning space as a BSTR.
get_NetworkType | Retrieves the network type GUID of the tuning space as a BSTR.
put_NetworkType | Sets the network type for this tuning space as a BSTR.
get__NetworkType | Retrieves the network type of the tuning space as a GUID.
put__NetworkType | Sets the network type for this tuning space as a REFCLSID.
CreateTuneRequest | Creates a COM object representing an empty (uninitialized) Tune Request.
EnumCategoryGUIDs | Creates an enumerator for the DirectShow category GUIDs, representing classes of filters that support the tuning space.
EnumDeviceMonikers | Creates an enumerator of device monikers representing the tuner inputs (filters) supporting this tuning space.
get_DefaultPreferredComponentTypes | Returns an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
put_DefaultPreferredComponentTypes | Creates an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
get_DefaultLocator | Retrieves the default Locator on the local system.
put_DefaultLocator | Sets the default Locator on the local system.
IAnalogRadioTuningSpace Methods
get_MinFrequency | Retrieves the minimum frequency for this tuning space.
put_MinFrequency | Sets the minimum frequency for this tuning space.
get_MaxFrequency | Retrieves the maximum frequency for this tuning space.
put_MaxFrequency | Sets the maximum frequency for this tuning space.
get_Step | Retrieves the step increment for this tuning space.
put_Step | Sets the step increment for this tuning space.

IAnalogRadioTuningSpace::get_MinFrequency

IAnalogRadioTuningSpace Interface

Retrieves the minimum frequency for this tuning space.

Syntax

HRESULT get_MinFrequency(
    long* MinFrequencyVal
    );

Parameters

MinFrequencyVal
[out, retval] Pointer to a variable of type long that receives the minimum frequency.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IAnalogRadioTuningSpace::put_MinFrequency

IAnalogRadioTuningSpace Interface

Sets the minimum frequency for this tuning space.

Syntax

HRESULT put_MinFrequency(
    long NewMinFrequencyVal
    );

Parameters

NewMinFrequencyVal
[in] Variable of type long that specifies the minimum frequency.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IAnalogRadioTuningSpace::get_MaxFrequency

IAnalogRadioTuningSpace Interface

Retrieves the maximum frequency for this tuning space.

Syntax

HRESULT get_MaxFrequency(
    long* MaxFrequencyVal
    );

Parameters

MaxFrequencyVal
[out, retval] Pointer to a variable of type long that receives the maximum frequency.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IAnalogRadioTuningSpace::put_MaxFrequency

IAnalogRadioTuningSpace Interface

Sets the maximum frequency for this tuning space.

Syntax

HRESULT put_MaxFrequency(
    long NewMaxFrequencyVal
    );

Parameters

NewMaxFrequencyVal
[in] Variable of type long that specifies the maximum frequency.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IAnalogRadioTuningSpace::get_Step

IAnalogRadioTuningSpace Interface

Retrieves the step increment for this tuning space.

Syntax

HRESULT get_Step(
    long* StepVal
    );

Parameters

StepVal
[out, retval] Pointer to a variable of type long that receives the stepping value.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IAnalogRadioTuningSpace::put_Step

IAnalogRadioTuningSpace Interface

Sets the step increment for this tuning space.

Syntax

HRESULT put_Step(
    long NewStepVal
    );

Parameters

NewStepVal
[in] Variable of type long that specifies the stepping increment.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IAnalogTVTuningSpace

Microsoft DirectX 8.0

IAnalogTVTuningSpace Interface

Represents a tuning space with a network type of Analog TV.

MethodName | Description
ITuningSpace Methods
get_UniqueName | Retrieves a unique name for the Tuning Space. Can be either a short name, or a GUID.
put_UniqueName | Sets a unique name for the Tuning Space. Can be either a short name, or a GUID.
get_FriendlyName | Retrieves the localized, user-friendly name of the Tuning Space.
put_FriendlyName | Sets the localized, user-friendly name of the Tuning Space.
get_CLSID | Gets the CLSID of the tuning space as a BSTR.
get_NetworkType | Retrieves the network type GUID of the tuning space as a BSTR.
put_NetworkType | Sets the network type for this tuning space as a BSTR.
get__NetworkType | Retrieves the network type of the tuning space as a GUID.
put__NetworkType | Sets the network type for this tuning space as a REFCLSID.
CreateTuneRequest | Creates a COM object representing an empty (uninitialized) Tune Request.
EnumCategoryGUIDs | Creates an enumerator for the DirectShow category GUIDs, representing classes of filters that support the tuning space.
EnumDeviceMonikers | Creates an enumerator of device monikers representing the tuner inputs (filters) supporting this tuning space.
get_DefaultPreferredComponentTypes | Returns an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
put_DefaultPreferredComponentTypes | Sets an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
get_DefaultLocator | Retrieves the default Locator on the local system.
put_DefaultLocator | Sets the default Locator on the local system.
IAnalogTVTuningSpace Methods
get_MinChannel | Gets the lowest channel number for this tuning space.
put_MinChannel | Sets the lowest channel number for this tuning space.
get_MaxChannel | Gets the highest channel number for this tuning space.
put_MaxChannel | Sets the highest channel number for this tuning space.
get_InputType | Gets the input type (antenna or cable) intended for the tuning space.
put_InputType | Sets the input type (antenna or cable) intended for the tuning space.
get_CountryCode | Gets the country code of the tuning space (based on TAPI country codes).
put_CountryCode | Sets the country code of the tuning space (based on TAPI country codes).

IAnalogTVTuningSpace::get_MinChannel

IAnalogTVTuningSpace Interface

Gets the lowest channel number for this tuning space.

Syntax

HRESULT get_MinChannel(
    short* MinChannelVal
    );

Parameters

MinChannelVal
[out, retval] Pointer to a variable of type short that receives the value for the lowest channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

An NTSC tuning space connected to an antenna will return a value of 2.

IAnalogTVTuningSpace::put_MinChannel

IAnalogTVTuningSpace Interface

Sets the lowest channel number for this tuning space.

Syntax

HRESULT put_MinChannel(
    short NewMinChannelVal
    );

Parameters

NewMinChannelVal
[in] Variable of type short that specifies the lowest channel number.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IAnalogTVTuningSpace::get_MaxChannel

IAnalogTVTuningSpace Interface

Gets the highest channel number for this tuning space.

Syntax

HRESULT get_MaxChannel(
    short* MaxChannelVal
    );

Parameters

MaxChannelVal
[out, retval] Pointer to a variable of type short that receives the value for the highest channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

For example, an NTSC tuning space connected to an antenna would return 69.

IAnalogTVTuningSpace::put_MaxChannel

IAnalogTVTuningSpace Interface

Sets the highest channel number for this tuning space.

Syntax

HRESULT put_MaxChannel(
    short NewMaxChannelVal
    );

Parameters

NewMaxChannelVal
[in] Variable of type short that specifies the highest channel number.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IAnalogTVTuningSpace::get_InputType

IAnalogTVTuningSpace Interface

Gets the input type (antenna or cable) intended for the tuning space.

Syntax

HRESULT get_InputType(
    TunerInputType* InputTypeVal
    );

Parameters

InputTypeVal
[out, retval] Pointer to a variable of type TunerInputType that receives the input type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IAnalogTVTuningSpace::put_InputType

IAnalogTVTuningSpace Interface

Sets the input type (antenna or cable) intended for the tuning space.

Syntax

HRESULT put_InputType(
    TunerInputType NewInputTypeVal
    );

Parameters

NewInputTypeVal
[in] Variable of type TunerInputType that specifies the input type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IAnalogTVTuningSpace::get_CountryCode

IAnalogTVTuningSpace Interface

Gets the country code of the tuning space (based on TAPI country codes).

Syntax

HRESULT get_CountryCode(
    long* CountryCodeVal
    );

Parameters

CountryCodeVal
[out, retval] Pointer to a variable of type long that receives the value for the country code.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The tuner can use the country code to locate a likely channel for frequency mapping.

IAnalogTVTuningSpace::put_CountryCode

IAnalogTVTuningSpace Interface

Sets the country code of the tuning space (based on TAPI country codes).

Syntax

HRESULT put_CountryCode(
    long NewCountryCodeVal
    );

Parameters

NewCountryCodeVal
[in] Variable of type long that specifies the country code.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The tuner can use the country code to locate a likely channel for frequency mapping.


IATSCChannelTuneRequest

Microsoft DirectX 8.0

IATSCChannelTuneRequest Interface

This interface is implemented on the ATSCChannelTuneRequest object.

MethodName | Description
ITuneRequest Methods
get_TuningSpace | Retrieves the Tuning Space object.
get_Components | Retrieves the collection of IComponent objects.
Clone | Returns a new copy of this tune request.
get_Locator | Called from the Network Provider to get the ILocator object associated with the requested broadcast.
put_Locator | Called from the Network Provider to set the ILocator object associated with the requested broadcast.
IChannelTuneRequest Methods
get_Channel | Gets the channel to be tuned.
put_Channel | Sets the channel to be tuned.
IATSCChannelTuneRequest Methods
get_MinorChannel | Gets the minor channel to be tuned.
put_MinorChannel | Sets the minor channel to be tuned.

IATSCChannelTuneRequest::get_MinorChannel

IATSCChannelTuneRequest Interface

Gets the minor channel to be tuned.

Syntax

HRESULT get_MinorChannel(
    short* MinorChannel
    );

Parameters

MinorChannel
[out, retval] Pointer to a variable of type short that receives the current minor channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IATSCChannelTuneRequest::put_MinorChannel

IATSCChannelTuneRequest Interface

Sets the minor channel to be tuned.

Syntax

HRESULT put_MinorChannel(
    short MinorChannel
    );

Parameters

MinorChannel
[in] Variable of type short that specifies the minor channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IATSCComponentType

Microsoft DirectX 8.0

IATSCComponentType Interface

The IATSCComponentType interface is implemented on ATSCComponentType objects and it enables applications to determine if this is an AC3 stream when the stream type is audio.

MethodName | Description
get_Flags | Returns a flag indicating whether the audio component is in AC-3 format.
put_Flags | Sets a flag indicating whether the audio component is in AC-3 format.

IATSCComponentType::get_Flags

IATSCComponentType Interface

Returns a flag indicating whether the audio component is in AC-3 format.

Syntax

HRESULT get_Flags(
    long* Flags
    );

Parameters

*Flags
[out, retval] Variable of type long that will receive the ATSCComponentTypeFlags flags.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The only defined flag is for AC-3 audio.
    typedef enum ATSCComponentTypeFlags {
        ATSCCT_AC3 = 0x00000001,
    } ATSCComponentTypeFlags;

IATSCComponentType::put_Flags

IATSCComponentType Interface

Sets a flag indicating whether the audio component is in AC-3 format.

Syntax

HRESULT put_Flags(
    long flags
    );

Parameters

flags
[in] Variable of type long; 0x1 specifies that the audio stream is AC-3.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The only defined flag is for AC-3 audio.
    typedef enum ATSCComponentTypeFlags {
        ATSCCT_AC3 = 0x00000001,
    } ATSCComponentTypeFlags;


IATSCLocator

Microsoft DirectX 8.0

IATSCLocator Interface

This interface is implemented on the ATSCLocator object.

ILocator Method Name | Description
Clone | Creates a copy of the Locator.
get_CarrierFrequency | Retrieves the frequency of the RF signal.
get_InnerFEC | Retrieves the type of inner forward error correction that is used.
get_InnerFECRate | Retrieves the inner FEC rate.
get_Modulation | Retrieves the modulation type.
get_OuterFEC | Retrieves the type of outer forward error correction that is used.
get_OuterFECRate | Sets the outer FEC rate.
get_SymbolRate | Gets the QPSK symbol rate.
put_CarrierFrequency | Sets the frequency of the RF signal.
put_InnerFEC | Sets the type of inner forward error correction that is used.
put_InnerFECRate | Sets the inner FEC rate.
put_Modulation | Sets the modulation type.
put_OuterFEC | Sets the type of inner forward error correction that is used.
put_OuterFECRate | Sets the outer FEC rate.
put_SymbolRate | Sets the QPSK symbol rate.
IATSCLocator Method Name | Description
get_PhysicalChannel | Retrieves the physical channel.
put_PhysicalChannel | Sets the physical channel.
get_TSID | Retrieves the transport stream ID.
put_TSID | Sets the transport stream ID.

IATSCLocator::get_PhysicalChannel

IATSCLocator Interface

Retrieves the physical channel.

Syntax

HRESULT get_PhysicalChannel(
    short* PhysicalChannel
    );

Parameters

*PhysicalChannel
[out, retval] Pointer to a variable of type short that receives the physical channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IATSCLocator::put_PhysicalChannel

IATSCLocator Interface

Sets the physical channel.

Syntax

HRESULT put_PhysicalChannel(
    short PhysicalChannel
    );

Parameters

PhysicalChannel
[in] Variable of type short that specifies the physical channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IATSCLocator::get_TSID

IATSCLocator Interface

Retrieves the transport stream ID.

Syntax

HRESULT get_TSID(
    short* TSID
    );

Parameters

*TSID
[out, retval] Pointer to a variable of type short that receives the transport stream ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IATSCLocator::put_TSID

IATSCLocator Interface

Sets the transport stream ID.

Syntax

HRESULT put_TSID(
    short TSID
    );

Parameters

TSID
[in] Variable of type short that specifies the transport stream ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IATSCTuningSpace

Microsoft DirectX 8.0

IATSCTuningSpace Interface

The IATSCTuningSpace inherits from ITuningSpace and IAnalogTVTuningSpace. IATSCTuningSpace is implemented on objects that represent an ATSC network type. These objects are created by the Tuning Space Container based on information in the Registry. An IATSCTuningSpace object creates tune requests that expose IATSCChannelTuneRequest.

MethodName | Description
ITuningSpace Methods
get_UniqueName | Retrieves a unique name for the Tuning Space. Can be either a short name, or a GUID.
put_UniqueName | Sets a unique name for the Tuning Space. Can be either a short name, or a GUID.
get_FriendlyName | Retrieves the localized, user-friendly name of the Tuning Space.
put_FriendlyName | Sets the localized, user-friendly name of the Tuning Space.
get_CLSID | Gets the CLSID of the tuning space as a BSTR.
get_NetworkType | Retrieves the network type GUID of the tuning space as a BSTR.
put_NetworkType | Sets the network type for this tuning space as a BSTR.
get__NetworkType | Retrieves the network type of the tuning space as a GUID.
put__NetworkType | Sets the network type for this tuning space as a REFCLSID.
CreateTuneRequest | Creates a COM object representing an empty (uninitialized) Tune Request.
EnumCategoryGUIDs | Creates an enumerator for the DirectShow category GUIDs, representing classes of filters that support the tuning space.
EnumDeviceMonikers | Creates an enumerator of device monikers representing the tuner inputs (filters) supporting this tuning space.
get_DefaultPreferredComponentTypes | Returns an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
put_DefaultPreferredComponentTypes | Sets an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
get_DefaultLocator | Retrieves the default Locator on the local system.
put_DefaultLocator | Sets the default Locator on the local system.
IAnalogTVTuningSpace Methods
get_MinChannel | Gets the lowest channel number for this tuning space.
put_MinChannel | Sets the lowest channel number for this tuning space.
get_MaxChannel | Gets the highest channel number for this tuning space.
put_MaxChannel | Sets the highest channel number for this tuning space.
get_InputType | Gets the input type (antenna or cable) intended for the tuning space.
put_InputType | Sets the input type (antenna or cable) intended for the tuning space.
get_CountryCode | Gets the country code of the tuning space (based on TAPI country codes).
put_CountryCode | Sets the country code of the tuning space (based on TAPI country codes).
IATSCTuningSpace Methods
get_MinMinorChannel | Gets the lowest minor channel number ever allowed for this tuning space.
put_MinMinorChannel | Sets the lowest minor channel number ever allowed for this tuning space.
get_MaxMinorChannel | Gets the highest minor channel number for this tuning space.
put_MaxMinorChannel | Sets the highest minor channel number for this tuning space.
get_MinPhysicalChannel | Gets the lowest physical channel number ever allowed for this tuning space.
put_MinPhysicalChannel | Sets the lowest physical channel number ever allowed for this tuning space.
get_MaxPhysicalChannel | Gets the highest physical channel number ever allowed for this tuning space.
put_MaxPhysicalChannel | Sets the highest physical channel number ever allowed for this tuning space.

IATSCTuningSpace::get_MinMinorChannel

IATSCTuningSpace Interface

Gets the lowest minor channel number ever allowed for this tuning space.

Syntax

HRESULT get_MinMinorChannel(
    short* MinMinorChannelVal
    );

Parameters

MinMinorChannelVal
[out, retval] Pointer to a variable of type short that receives the lowest minor channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IATSCTuningSpace::put_MinMinorChannel

IATSCTuningSpace Interface

Sets the lowest minor channel number ever allowed for this tuning space.

Syntax

HRESULT put_MinMinorChannel(
    short NewMinMinorChannelVal
    );

Parameters

NewMinMinorChannelVal
[in] Variable of type short that specifies the lowest minor channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This property must be set after setting the MaxMinorChannel property to avoid the case where the minimum minor channel is greater than the maximum minor channel. Both properties default to -1 (not set).

IATSCTuningSpace::get_MaxMinorChannel

IATSCTuningSpace Interface

Gets the highest minor channel number for this tuning space.

Syntax

HRESULT get_MaxMinorChannel(
    short* MaxMinorChannelVal
    );

Parameters

MaxMinorChannelVal
[out, retval] Pointer to a variable of type short that receives the highest minor channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IATSCTuningSpace::put_MaxMinorChannel

IATSCTuningSpace Interface

Gets the highest minor channel number for this tuning space.

Syntax

HRESULT put_MaxMinorChannel(
    short NewMaxMinorChannelVal
    );

Parameters

NewMaxMinorChannelVal
[in] Variable of type short that specifies the highest minor channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This property must be set before setting the MinMinorChannel property to avoid the case where the minimum minor channel is greater than the maximum minor channel. Both properties default to -1 (not set).

IATSCTuningSpace::get_MinPhysicalChannel

IATSCTuningSpace Interface

Sets the lowest physical channel number for this tuning space.

Syntax

HRESULT get_MinPhysicalChannel(
    short* MinPhysicalChannelVal
    );

Parameters

MinPhysicalChannelVal
[out, retval] Pointer to a variable of type short that receives the lowest physical channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IATSCTuningSpace::put_MinPhysicalChannel

IATSCTuningSpace Interface

Sets the lowest physical channel number for this tuning space.

Syntax

HRESULT put_MinPhysicalChannel(
    short NewMinPhysicalChannelVal
    );

Parameters

NewMinPhysicalChannelVal
[in] Variable of type short that specifies the lowest physical channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IATSCTuningSpace::get_MaxPhysicalChannel

IATSCTuningSpace Interface

Gets the highest physical channel number for this tuning space.

Syntax

HRESULT get_MaxPhysicalChannel(
    short* MaxPhysicalChannelVal
    );

Parameters

MaxPhysicalChannelVal
[out, retval] Pointer to a variable of type short that receives the highest physical channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IATSCTuningSpace::put_MaxPhysicalChannel

IATSCTuningSpace Interface

Sets the highest physical channel number for this tuning space.

Syntax

HRESULT put_MaxPhysicalChannel(
    short NewMaxPhysicalChannelVal
    );

Parameters

NewMaxPhysicalChannelVal
[in] Variable of type short that specifies the highest physical channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IChannelTuneRequest

Microsoft DirectX 8.0

IChannelTuneRequest Interface

The IChannelTuneRequest interface is implemented on TuneRequest objects that are specific to analog TV. The interface enables an application to create Tune Requests for analog TV networks.

MethodName | Description
ITuneRequest Methods
get_TuningSpace | Retrieves the Tuning Space object.
get_Components | Retrieves the collection of IComponent objects.
Clone | Returns a new copy of this tune request.
get_Locator | Called from the Network Provider to get the ILocator object associated with the requested broadcast.
put_Locator | Called from the Network Provider to set the ILocator object associated with the requested broadcast.
IChannelTuneRequest Methods
get_Channel | Gets the channel to be tuned.
put_Channel | Sets the channel to be tuned.

IChannelTuneRequest::get_Channel

IChannelTuneRequest Interface

Gets the channel to be tuned.

Syntax

HRESULT get_Channel(
    short* Channel
    );

Parameters

Channel
[out, retval] Pointer to a variable of type short that receives the current channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IChannelTuneRequest::put_Channel

IChannelTuneRequest Interface

Sets the channel to be tuned.

Syntax

HRESULT put_Channel(
    short Channel
    );

Parameters

Channel
[in] Variable of type short that specifies the channel.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

If the value specified for Channel is less than the minimum channel set for the Tuning Space, it will "wrap around" to the maximum channel value. Likewise, if the value specified for Channel is greater than the maximum channel set for the Tuning Space, it will "wrap around" to the minimum channel value.


IComponent

Microsoft DirectX 8.0

IComponent Interface

The IComponent interface is the base class interface for all Component objects and it describes the general characteristics of a component, which is typically an elementary stream within the program stream. The derived interfaces such as IMPEG2Component inherit from IComponent and describe the properties of a component that are specific to a given network type. Component objects are created and attached to the Tune Request by the Transport Information Filter (TIF) after reception has begun. All Component objects also support IPersistPropertyBag.

MethodName | Description
get_Type | Retrieves an IComponentType object describing the general characteristics of the Component.
put_Type | Sets an IComponentType object describing the general characteristics of the Component.
get_DescLangID | Retrieves the language for presentation of the description.
put_DescLangID | Sets the language for presentation of the description.
get_Status | Retrieves the requested or actual status of the component.
put_Status | Sets the requested or actual status of the component.
get_Description | Retrieves the description of the component.
put_Description | Sets the description of the component.
Clone | Creates a new copy of the component.

IComponent::Clone

IComponent Interface

Creates a new copy of the component.

Syntax

HRESULT Clone(
    IComponent** NewComponent
    );

Parameters

NewComponent
[out, retval] Address of an IComponent interface pointer that will be set to the new Component.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponent::get_Type

IComponent Interface

Retrieves an IComponentType object describing the general characteristics of the Component.

Syntax

HRESULT get_Type(
    IComponentType** CT
    );

Parameters

CT
[out, retval] Address of an IComponentType interface pointer that will be set to the retrieved Component.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponent::put_Type

IComponent Interface

Sets an IComponentType object describing the general characteristics of the Component.

Syntax

HRESULT put_Type(
    IComponentType* CT
    );

Parameters

CT
[in] Pointer to an IComponentType object that specifies the new values for the Component.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Using the IComponent base class interface, it is possible to set the Type to be NULL. If you try to do this with the derived IMPEG2Component class interface, this method will return E_POINTER. The IMPEG2Component object cannot have the base IComponentType class interface as the set type - this will return Type Mismatch (0x80020005).

IComponent::get_DescLangID

IComponent Interface

Retrieves the language for presentation of the description.

Syntax

HRESULT get_DescLangID(
    short* LangID
    );

Parameters

*LangID
[out, retval] Pointer to a variable of type short that will receive the language ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This is the language of the descriptive info in the component object. It is not the same as the language ID in language component type which defines the language of the stream content.

IComponent::put_DescLangID

IComponent Interface

Sets the language for presentation of the description.

Syntax

HRESULT put_DescLangID(
    short LangID
    );

Parameters

LangID
[in] Variable of type short that specifies the language ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This is the language of the descriptive info in the component object. It is not the same as the language ID in language component type which defines the language of the stream content. An application can modify this value in order to activate a different language substream.

IComponent::get_Status

IComponent Interface

Retrieves the requested or actual status of the component.

Syntax

HRESULT get_Status(
    ComponentStatus* Status
    );

Parameters

*Status
[out, retval] Pointer to a ComponentStatus enum that receives the status value.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

typedef enum ComponentStatus
    {
        [helpstring("Component is selected")] StatusActive,
        [helpstring("Component is not selected")] StatusInactive,
        [helpstring("Component is unavailable")] StatusUnavailable,
    } ComponentStatus;

When a tuner adds a component to the Components collection, it can indicate whether the component is active or not. An application can attempt to set this status, and resubmit a tune request. The tuner will update the status. From the enumeration Active, Inactive, Unavailable. The Unavailable status is only set by a tuner in response to a request to activate, when the component is not really available.

IComponent::put_Status

IComponent Interface

Sets the requested or actual status of the component.

Syntax

HRESULT put_Status(
    ComponentStatus Status
    );

Parameters

Status
[in] A variable of type ComponentStatus that specifies the status value.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Use this method to activate or inactivate a stream component (substream).

See Also

get_Status

IComponent::get_Description

IComponent Interface

Retrieves the description of the component.

Syntax

HRESULT get_Description(
    BSTR* Description
    );

Parameters

*Description
[out, retval] Pointer to a variable of type BSTR that will receive the description.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

IComponent::put_Description

IComponent Interface

Sets the description of the component.

Syntax

HRESULT put_Description(
    BSTR Description
    );

Parameters

Description
[in] Variable of type BSTR that contains the new description.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is called by the Guide Store, not by the application.


IComponents

Microsoft DirectX 8.0

IComponents Interface

A "component" in the context of digital television refers to a substream within the program stream. For example, a program stream may have three audio streams in different languages; in this case each audio stream is a "component" of the program stream. The IComponents interface is implemented on the Components object, which is a collection of Component objects. The Components object enables applications to enumerate components within a program stream and perform operations related to individual components in the collection. All Components objects also support IPersistPropertyBag.

MethodName | Description
get_Count | Gets the number of Component objects in the collection.
get__NewEnum | Enumeration method to support For...Each loops in Automation clients.
EnumComponents | Returns an IEnumComponents enumerator for all components in the collection.
get_Item | Enables the caller to access a component by index.
Add | Adds a Component object to the collection.
Remove | Removes a Component object from the collection.
Clone | Creates a new copy of the collection.

IComponents::get_Count

IComponents Interface

Gets the number of Component objects in the collection.

Syntax

HRESULT get_Count(
    long* Count
    );

Parameters

Count
[out, retval] Pointer to a variable of type long that receives the number of Components.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponents::get__NewEnum

IComponents Interface

Enumeration method to support For...Each loops in Automation clients.

Syntax

HRESULT get__NewEnum(
    IEnumVARIANT** ppNewEnum
    );

Parameters

ppNewEnum
[out, retval] Address of an IEnumVARIANT interface pointer that will receive the enumeration.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is provided to enable scripting and VB applications to iterate through the collection in a For...Each loop. C++ applications should use the EnumComponents method.

IComponents::EnumComponents

IComponents Interface

Returns an IEnumComponents enumerator for all components in the collection.

Syntax

HRESULT EnumComponents(
    IEnumComponents** ppNewEnum
    );

Parameters

ppNewEnum
[out, retval] Address of an IEnumComponents interface pointer that will receive the new enumeration.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponents::get_Item

IComponents Interface

Enables the caller to access a component by index.

Syntax

HRESULT get_Item(
    VARIANT Index,
    IComponent** ppComponent
    );

Parameters

Index
[in] Variable of type VARIANT specifying the zero-based index in the collection.
ppComponent
[out, retval] Address of an IComponent interface pointer that will receive the Component object at the specified index.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponents::Add

IComponents Interface

Adds a Component object to the collection.

Syntax

HRESULT Add(
    IComponent* Component,
    VARIANT* NewIndex
    );

Parameters

Component
[in] Pointer to the Component object to be added.
NewIndex
[out, retval] Pointer to a VARIANT that will receive the index of the Component after it has been added.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponents::Remove

IComponents Interface

Removes a Component object from the collection.

Syntax

HRESULT Remove(
    VARIANT Index
    );

Parameters

Index
[in] Variable of type VARIANT that specifies the index number of the Component to be removed.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponents::Clone

IComponents Interface

Creates a new copy of the collection.

Syntax

HRESULT Clone(
    IComponents** NewList
    );

Parameters

NewList
[out, retval] Address of an IComponents interface pointer that will be set to the new Components object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IComponentType

Microsoft DirectX 8.0

IComponentType Interface

The IComponentType interface is implemented on ComponentType objects, which contains methods for setting and retrieving various properties for a Component. Every Component object has an associated ComponentType object that is set or retrieved with the get_Type and put_Type methods.

MethodName | Description
Clone | Creates a new copy of this component type.
get_Category | Retrieves the component category.
get_MediaFormatType | Retrieves the DirectShow media format type as a BSTR.
get__MediaFormatType | Retrieves the DirectShow media format type as a GUID.
get_MediaMajorType | Retrieves the DirectShow media major type as a BSTR.
get__MediaMajorType | Retrieves the DirectShow media major type as a GUID.
get_MediaSubType | Retrieves the DirectShow media subtype as a BSTR.
get__MediaSubType | Retrieves the DirectShow media subtype as a GUID.
get_MediaType | Retrieves the DirectShow AM_MEDIA_TYPE media type structure for the component.
put_Category | Sets the component category.
put_MediaFormatType | Sets the DirectShow media format type.
put__MediaFormatType | Sets the DirectShow media format type.
put_MediaMajorType | Sets the DirectShow media major type.
put__MediaMajorType | Sets the DirectShow media major type.
put_MediaSubType | Sets the DirectShow media subtype.
put__MediaSubType | Sets the DirectShow media subtype.
put_MediaType | Sets the DirectShow AM_MEDIA_TYPE media type structure for the component.

IComponentType::Clone

IComponentType Interface

Creates a new copy of this component type.

Syntax

HRESULT Clone(
    IComponentType** NewCT
    );

Parameters

NewCT
[out, retval] Address of the IComponentType interface pointer that will be set to the returned interface.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentType::get_Category

IComponentType Interface

Retrieves the component category.

Syntax

HRESULT get_Category(
    ComponentCategory* Category
    );

Parameters

Category
[out, retval] Pointer to a ComponentCategory datatype that will receive the category.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The ComponentCategory enum is defined in bdatypes.h as follows:
typedef enum ComponentCategory
{
    CategoryNotSet = -1,
    CategoryOther = 0,
    CategoryVideo = 1,
    CategoryAudio = 2,
    CategoryText = 3,
    CategoryData = 4,
} ComponentCategory;

IComponentType::get_MediaFormatType

IComponentType Interface

Retrieves the DirectShow media format type as a BSTR.

Syntax

HRESULT get_MediaFormatType(
    BSTR* MediaFormatType
    );

Parameters

MediaFormatType
[out, retval] Pointer to a BSTR that will receive the GUID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentType::get__MediaFormatType

IComponentType Interface

Retrieves the DirectShow media format type as a GUID.

Syntax

HRESULT get__MediaFormatType(
    GUID *MediaFormatType
    );

Parameters

MediaFormatType
[out, retval] Pointer to a GUID that will receive the format type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

IComponentType::get_MediaMajorType

IComponentType Interface

Retrieves the DirectShow media major type as a BSTR.

Syntax

HRESULT get_MediaMajorType(
    BSTR* MediaMajorType
    );

Parameters

MediaMajorType
[out, retval] Pointer to a BSTR that will receive the GUID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentType::get__MediaMajorType

IComponentType Interface

Retrieves the DirectShow media format type as a GUID.

Syntax

HRESULT get__MediaMajorType(
    GUID *MediaMajorType
    );

Parameters

MediaMajorType
[out, retval] Pointer to a GUID that will receive the major type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

IComponentType::get_MediaSubType

IComponentType Interface

Retrieves the DirectShow media subtype as a BSTR.

Syntax

HRESULT get_MediaSubType(
    BSTR* MediaSubType
    );

Parameters

MediaSubType
[out, retval] Pointer to a BSTR that will receive the GUID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentType::get__MediaSubType

IComponentType Interface

Retrieves the DirectShow media subtype as a GUID.

Syntax

HRESULT get__MediaSubType(
    GUID *MediaSubType
    );

Parameters

MediaSubType
[out, retval] Pointer to a GUID that will receive the major type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

IComponentType::get_MediaType

IComponentType Interface

Retrieves the DirectShow AM_MEDIA_TYPE media type structure for the component.

Syntax

HRESULT get_MediaType(
    AM_MEDIA_TYPE* MediaType
    );

Parameters

MediaType
[out, retval] Pointer to an AM_MEDIA_TYPE structure that will be filled in with the values associated with the current ComponentType.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentType::put_Category

IComponentType Interface

Sets the component category.

Syntax

HRESULT put_Category(
    ComponentCategory Category
    );

Parameters

Category
[in] A ComponentCategory value that specifies the new category for this component type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The ComponentCategory enum is defined in bdatypes.h as follows:
typedef enum ComponentCategory
{
    CategoryNotSet = -1,
    CategoryOther = 0,
    CategoryVideo = 1,
    CategoryAudio = 2,
    CategoryText = 3,
    CategoryData = 4,
} ComponentCategory;

IComponentType::put_MediaFormatType

IComponentType Interface

Sets the DirectShow media format type.

Syntax

HRESULT put_MediaFormatType(
    BSTR MediaFormatType
    );

Parameters

MediaFormatType
[in] BSTR that specifies the GUID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentType::put__MediaFormatType

IComponentType Interface

Sets the DirectShow media format type.

Syntax

HRESULT put__MediaFormatType(
    REFCLSID MediaFormatType
    );

Parameters

MediaFormatType
[in] REFCLSID that specifies the media format type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

IComponentType::put_MediaMajorType

IComponentType Interface

Sets the DirectShow media major type.

Syntax

HRESULT put_MediaMajorType(
    BSTR MediaMajorType
    );

Parameters

MediaMajorType
[in] BSTR that specifies the GUID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentType::put__MediaMajorType

IComponentType Interface

Sets the DirectShow media major type.

Syntax

HRESULT put__MediaMajorType(
    REFCLSID MediaMajorType
    );

Parameters

MediaMajorType
[in] REFCLSID that specifies the media major type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

IComponentType::put_MediaSubType

IComponentType Interface

Sets the DirectShow media subtype.

Syntax

HRESULT put_MediaSubType(
    BSTR MediaSubType
    );

Parameters

MediaSubType
[in] BSTR that specifies the GUID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentType::put__MediaSubType

IComponentType Interface

Sets the DirectShow media subtype.

Syntax

HRESULT put__MediaSubType(
    REFCLSID MediaSubType
    );

Parameters

MediaSubType
[in] REFCLSID that specifies the media sub type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

IComponentType::put_MediaType

IComponentType Interface

Sets the DirectShow AM_MEDIA_TYPE media type structure for the component.

Syntax

HRESULT put_MediaType(
    AM_MEDIA_TYPE MediaType
    );

Parameters

MediaType
[in] AM_MEDIA_TYPE structure that specifies the major type, subtype, format, etc.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IComponentTypes

Microsoft DirectX 8.0

IComponentTypes Interface

The ComponentTypes object enables applications to enumerate, add, remove and retrieve individual ComponentType objects. All ComponentTypes objects also support IPersistPropertyBag.

MethodName | Description
get_Count | Returns the number of Component Types in the collection.
get__NewEnum | Enumeration method to support For...Each loops in Automation clients.
EnumComponentTypes | Returns an IEnumComponentTypes enumerator for all component types in the collection.
get_Item | Retrieves the IComponentType interface pointer at the specified index number.
put_Item | Replaces the ComponentType object at the specified index with a new ComponentType object.
Add | Adds a new ComponentType object to the collection.
Remove | Removes the ComponentType object at the specified index number.
Clone | Creates a new copy of the collection.

IComponentTypes::Clone

IComponentTypes Interface

Creates a new copy of the collection.

Syntax

HRESULT Clone(
    IComponentTypes** NewList
    );

Parameters

NewList
[out, retval] Address of an IComponentTypes interface pointer that will be set to the new ComponentTypes object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentTypes::get_Count

IComponentTypes Interface

Returns the number of Component Types in the collection.

Syntax

HRESULT get_Count(
    long* Count
    );

Parameters

Count
[out, retval] Pointer to a variable of type long that will receive the number of items in the collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentTypes::get__NewEnum

IComponentTypes Interface

Enumeration method to support For...Each loops in Automation clients.

Syntax

HRESULT get__NewEnum(
    IEnumVARIANT** ppNewEnum
    );

Parameters

ppNewEnum
[out, retval] Address of a interface pointer to an IEnumVARIANT object that will receive the new collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is provided to enable scripting and VB applications to iterate through the collection in a For...Each loop. C++ applications should use the EnumComponents method.

IComponentTypes::EnumComponentTypes

IComponentTypes Interface

Returns an IEnumComponentTypes enumerator for all component types in the collection.

Syntax

HRESULT EnumComponentTypes(
    IEnumComponentTypes** ppNewEnum
    );

Parameters

ppNewEnum
[out, retval] Address of an IEnumComponentTypes interface pointer that will receive the new collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentTypes::get_Item

IComponentTypes Interface

Retrieves the IComponentType interface pointer at the specified index number.

Syntax

HRESULT get_Item(
    VARIANT Index,
    IComponentType** ppComponentType
    );

Parameters

Index
[in] The index number of the object to retrieve.
ppComponentType
[out, retval] Address of an IComponentType interface pointer that will be set to the object at the specified index.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentTypes::put_Item

IComponentTypes Interface

Replaces the ComponentType object at the specified index with a new ComponentType object.

Syntax

HRESULT put_Item(
    VARIANT Index,
    IComponentType* ComponentType
    );

Parameters

Index
[in] Index number of the item to be replaced.
ComponentType
[in] Pointer to the IComponentType object that will be inserted into the collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentTypes::Add

IComponentTypes Interface

Adds a new ComponentType object to the collection.

Syntax

HRESULT Add(
    IComponentType* ComponentType,
    VARIANT* NewIndex
    );

Parameters

ComponentType
[in] Pointer to the IComponentType object that will be added to the collection.
NewIndex
[out, retval] The index number of the ComponentType after it has been added to the collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IComponentTypes::Remove

IComponentTypes Interface

Removes the ComponentType object at the specified index number.

Syntax

HRESULT Remove(
    VARIANT Index
    );

Parameters

Index
[in] Index of the item to remove.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IDVBSLocator

Microsoft DirectX 8.0

IDVBSLocator Interface

This interface is implemented on the DVBSLocator object. It provides information to enable a tuner to acquire a DVBS transport stream.

ILocator Method Name | Description
Clone | Creates a copy of the Locator.
get_CarrierFrequency | Retrieves the frequency of the RF signal.
get_InnerFEC | Retrieves the type of inner forward error correction that is used.
get_InnerFECRate | Retrieves the inner FEC rate.
get_Modulation | Retrieves the modulation type.
get_OuterFEC | Retrieves the type of outer forward error correction that is used.
get_OuterFECRate | Sets the outer FEC rate.
get_SymbolRate | Gets the QPSK symbol rate.
put_CarrierFrequency | Sets the frequency of the RF signal.
put_InnerFEC | Sets the type of inner forward error correction that is used.
put_InnerFECRate | Sets the inner FEC rate.
put_Modulation | Sets the modulation type.
put_OuterFEC | Sets the type of inner forward error correction that is used.
put_OuterFECRate | Sets the outer FEC rate.
put_SymbolRate | Sets the QPSK symbol rate.
IDVBSLocator Method Name | Description
get_Azimuth | Retrieves the azimuth setting used for positioning the satellite dish.
get_Elevation | Retrieves the elevation of the satellite in tenths of a degree.
get_OrbitalPosition | Retrieves the setting for the satellite's orbital position.
get_SignalPolarisation | Retrieves the signal polarization.
get_WestPosition | Retrieves a value indicating whether the orbital position is given in east or west longitude.
put_Azimuth | Adjusts the azimuth setting used for positioning the satellite dish.
put_Elevation | Sets the elevation of the satellite in tenths of a degree.
put_OrbitalPosition | Sets the setting for the satellite's orbital position.
put_SignalPolarisation | Sets the signal polarization.
put_WestPosition | Sets the longitudinal position as west longitude or east longitude.

IDVBSLocator::get_Azimuth

IDVBSLocator Interface

Retrieves the azimuth setting used for positioning the satellite dish.

Syntax

HRESULT get_Azimuth(
    short* Azimuth
    );

Parameters

Azimuth
[out, retval] Pointer to a variable of type short that receives the azimuth in tenths of a degree.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBSLocator::get_Elevation

IDVBSLocator Interface

Retrieves the elevation of the satellite in tenths of a degree.

Syntax

HRESULT get_Elevation(
    short* Elevation
    );

Parameters

Elevation
[out, retval] Pointer to a variable of type short that receives the elevation setting in tenths of a degree.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBSLocator::get_OrbitalPosition

IDVBSLocator Interface

Retrieves the setting for the satellite's orbital position.

Syntax

HRESULT get_OrbitalPosition(
    short* longitude
    );

Parameters

longitude
[out, retval] Pointer to a variable of type short that receives the longitude setting in tenths of a degree.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBSLocator::get_SignalPolarisation

IDVBSLocator Interface

Retrieves the signal polarization.

Syntax

HRESULT get_SignalPolarisation(
    Polarisation* PolarisationVal
    );

Parameters

PolarisationVal
[out, retval] Pointer to a variable of type Polarisation that receives the polarization value.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.
The Polarisation enumeration is defined in bdatypes.h as follows:
    typedef enum {
        BDA_POLARISATION_NOT_SET = -1,
        BDA_POLARISATION_NOT_DEFINED = 0,
        BDA_POLARISATION_LINEAR_H = 1,
        BDA_POLARISATION_LINEAR_V = 2,
        BDA_POLARISATION_CIRCULAR_L = 3,
        BDA_POLARISATION_CIRCULAR_R = 4,
        BDA_POLARISATION_MAX = 5
    } Polarisation;

IDVBSLocator::get_WestPosition

IDVBSLocator Interface

Retrieves a value indicating whether the orbital position is given in east or west longitude.

Syntax

HRESULT get_WestPosition(
    VARIANT_BOOL* WestLongitude
    );

Parameters

WestLongitude
[out, retval] Pointer to a variable of type VARIANT_BOOL; a value of true means "west longitude."

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBSLocator::put_Azimuth

IDVBSLocator Interface

Adjusts the azimuth setting used for positioning the satellite dish.

Syntax

HRESULT put_Azimuth(
    short Azimuth
    );

Parameters

Azimuth
[in] Variable of type short that specifies the azimuth in tenths of a degree.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBSLocator::put_Elevation

IDVBSLocator Interface

Sets the elevation of the satellite in tenths of a degree.

Syntax

HRESULT put_Elevation(
    short Elevation
    );

Parameters

longitude
[in] Variable of type short that specifies for the locator the satellite's elevation in tenths of a degree.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBSLocator::put_OrbitalPosition

IDVBSLocator Interface

Sets the setting for the satellite's orbital position.

Syntax

HRESULT put_OrbitalPosition(
    short longitude
    );

Parameters

longitude
[in] Variable of type short that specifies the satellite's longitude in tenths of a degree.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBSLocator::put_SignalPolarisation

IDVBSLocator Interface

Sets the signal polarization.

Syntax

HRESULT put_SignalPolarisation(
    Polarisation PolarisationVal
    );

Parameters

PolarisationVal
[in] Variable of type Polarisation that specifies the signal polarization value.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The Polarisation enumeration is defined in bdatypes.h as follows:
    typedef enum {
        BDA_POLARISATION_NOT_SET = -1,
        BDA_POLARISATION_NOT_DEFINED = 0,
        BDA_POLARISATION_LINEAR_H = 1,
        BDA_POLARISATION_LINEAR_V = 2,
        BDA_POLARISATION_CIRCULAR_L = 3,
        BDA_POLARISATION_CIRCULAR_R = 4,
        BDA_POLARISATION_MAX = 5
    } Polarisation;

IDVBSLocator::put_WestPosition

IDVBSLocator Interface

Sets the longitudinal position as west longitude or east longitude.

Syntax

HRESULT put_WestPosition(
    VARIANT_BOOL WestLongitude
    );

Parameters

WestLongitude
[in] Variable of type VARIANT_BOOL that specifies whether the following longitude values that follow will be west or east longitude. True means "west longitude."

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IDVBTLocator

Microsoft DirectX 8.0

IDVBTLocator Interface

This interface is implemented on the DVBTLocator object. It provides information to enable a tuner to acquire a DVBT transport stream. The data types are defined in bdatypes.h. (DVB-T is not supported in the version of Broadcast Architecture that ships with the Microsoft® DirectX® 8 SDK.)

ILocator Method Name | Description
Clone | Creates a copy of the Locator.
get_CarrierFrequency | Retrieves the frequency of the RF signal.
get_InnerFEC | Retrieves the type of inner forward error correction that is used.
get_InnerFECRate | Retrieves the inner FEC rate.
get_Modulation | Retrieves the modulation type.
get_OuterFEC | Retrieves the type of outer forward error correction that is used.
get_OuterFECRate | Sets the outer FEC rate.
get_SymbolRate | Gets the QPSK symbol rate.
put_CarrierFrequency | Sets the frequency of the RF signal.
put_InnerFEC | Sets the type of inner forward error correction that is used.
put_InnerFECRate | Sets the inner FEC rate.
put_Modulation | Sets the modulation type.
put_OuterFEC | Sets the type of inner forward error correction that is used.
put_OuterFECRate | Sets the outer FEC rate.
put_SymbolRate | Sets the QPSK symbol rate.
IDVBTLocator Method Name | Description
get_Bandwidth | Retrieves the bandwidth of the frequency in megahertz, usually 7 or 8.
get_Guard | Retrieves the guard interval.
get_HAlpha | Retrieves the hierarchy alpha.
get_LPInnerFEC | Retrieves the inner FEC type of the low-priority stream.
get_LPInnerFECRate | Retrieves the inner FEC rate of the low-priority stream.
get_Mode | Receives the transmission mode.
get_OtherFrequencyInUse | Indicates whether the frequency is being used by another DVB-T broadcaster.
put_Bandwidth | Sets the bandwidth of the frequency in megahertz, usually 7 or 8.
put_Guard | Sets the guard interval.
put_HAlpha | Sets the hierarchy alpha.
put_LPInnerFEC | Sets the inner FEC type of the low-priority stream.
put_LPInnerFECRate | Sets the inner FEC rate of the low-priority stream.
put_Mode | Sets the transmission mode.
put_OtherFrequencyInUse | Specifies whether the frequency is being used by another DVB-T broadcaster.

IDVBTLocator::get_Bandwidth

IDVBTLocator Interface

Retrieves the bandwidth of the frequency in megahertz, usually 7 or 8.

Syntax

HRESULT get_Bandwidth(
    long* BandWidthVal
    );

Parameters

BandWidthVal
[out, retval] Pointer to a variable of type long that receives the bandwidth value.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTLocator::get_Guard

IDVBTLocator Interface

Retrieves the guard interval.

Syntax

HRESULT get_Guard(
    GuardInterval* GI
    );

Parameters

GI
[out, retval] Pointer that receives a valid GuardInterval value.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

typedef enum GuardInterval {
    BDA_GUARD_NOT_SET = -1,
    BDA_GUARD_NOT_DEFINED = 0,
    BDA_GUARD_1_32 = 1, // Guard interval is 1/32
    BDA_GUARD_1_16, // Guard interval is 1/16
    BDA_GUARD_1_8, // Guard interval is 1/8
    BDA_GUARD_1_4, // Guard interval is 1/4
    BDA_GUARD_MAX,
} GuardInterval;

IDVBTLocator::get_HAlpha

IDVBTLocator Interface

Retrieves the hierarchy alpha.

Syntax

HRESULT get_HAlpha(
    HierarchyAlpha* Alpha
    );

Parameters

Alpha
[out, retval] A value from the HierarchyAlpha enum.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

typedef enum HierarchyAlpha {
    BDA_HALPHA_NOT_SET = -1,
    BDA_HALPHA_NOT_DEFINED = 0,
    BDA_HALPHA_1 = 1, // Hierarchy alpha is 1.
    BDA_HALPHA_2, // Hierarchy alpha is 2.
    BDA_HALPHA_4, // Hierarchy alpha is 4.
    BDA_HALPHA_MAX,
} HierarchyAlpha;

IDVBTLocator::get_LPInnerFEC

IDVBTLocator Interface

Retrieves the inner FEC type of the low-priority stream.

Syntax

HRESULT get_LPInnerFEC(
    FECMethod* FEC
    );

Parameters

FEC
[out, retval] Pointer to a variable of type FECMethod that receives the FEC type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTLocator::get_LPInnerFECRate

IDVBTLocator Interface

Retrieves the inner FEC rate of the low-priority stream.

Syntax

HRESULT get_LPInnerFECRate(
    BinaryConvolutionCodeRate* FEC
    );

Parameters

FEC
[out, retval] Pointer to a BinaryConvolutionCodeRate value that receives the inner FEC rate.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

BinaryConvolutionCodeRate is defined in bdatypes.h as follows:

typedef enum {
    BDA_BCC_RATE_NOT_SET = -1,
    BDA_BCC_RATE_NOT_DEFINED = 0,
    BDA_BCC_RATE_1_2 = 1,
    BDA_BCC_RATE_2_3 = 2,
    BDA_BCC_RATE_3_4 = 3,
    BDA_BCC_RATE_3_5 = 4,
    BDA_BCC_RATE_4_5 = 5,
    BDA_BCC_RATE_5_6 = 6,
    BDA_BCC_RATE_5_11 = 7,
    BDA_BCC_RATE_7_8 = 8,
    BDA_BCC_RATE_MAX = 9
} BinaryConvolutionCodeRate;

IDVBTLocator::get_Mode

IDVBTLocator Interface

Receives the transmission mode.

Syntax

HRESULT get_Mode(
    TransmissionMode* mode
    );

Parameters

mode
[out, retval] A value from the TransmissionMode enum.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

typedef enum TransmissionMode {
    BDA_XMIT_MODE_NOT_SET = -1,
    BDA_XMIT_MODE_NOT_DEFINED = 0,
    BDA_XMIT_MODE_2K = 1, // Transmission uses 1705 carriers (use a 2K FFT)
    BDA_XMIT_MODE_8K, // Transmission uses 6817 carriers (use an 8K FFT)
    BDA_XMIT_MODE_MAX,
} TransmissionMode;

IDVBTLocator::get_OtherFrequencyInUse

IDVBTLocator Interface

Indicates whether the frequency is being used by another DVB-T broadcaster.

Syntax

HRESULT get_OtherFrequencyInUse(
    VARIANT_BOOL* OtherFrequencyInUseVal
    );

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTLocator::put_Bandwidth

IDVBTLocator Interface

Sets the bandwidth of the frequency in megahertz, usually 7 or 8.

Syntax

HRESULT put_Bandwidth(
    long BandwidthVal
    );

Parameters

BandwidthVal
[in] Variable of type long that specifies the bandwidth.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTLocator::put_Guard

IDVBTLocator Interface

Sets the guard interval.

Syntax

HRESULT put_Guard(
    GuardInterval GI
    );

Parameters

GI
[in] Variable of type GuardInterval that specifies the guard interval.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTLocator::put_HAlpha

IDVBTLocator Interface

Sets the heirarchy alpha.

Syntax

HRESULT put_HAlpha(
    HierarchyAlpha Alpha
    );

Parameters

Alpha
[in] Variable of type HierarchyAlpha that specifies the hierarchy alpha.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

typedef enum HierarchyAlpha {
    BDA_HALPHA_NOT_SET = -1,
    BDA_HALPHA_NOT_DEFINED = 0,
    BDA_HALPHA_1 = 1, // Hierarchy alpha is 1.
    BDA_HALPHA_2, // Hierarchy alpha is 2.
    BDA_HALPHA_4, // Hierarchy alpha is 4.
    BDA_HALPHA_MAX,
} HierarchyAlpha;

IDVBTLocator::put_LPInnerFEC

IDVBTLocator Interface

Sets the inner FEC type of the low-priority stream.

Syntax

HRESULT put_LPInnerFEC(
    FECMethod FEC
    );

Parameters

FEC
[in] Variable of type FECMethod that specifies the FEC type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTLocator::put_LPInnerFECRate

IDVBTLocator Interface

Sets the inner FEC rate of the low-priority stream.

Syntax

HRESULT put_LPInnerFECRate(
    BinaryConvolutionCodeRate FEC
    );

Parameters

FEC
[in] Variable of type BinaryConvolutionCodeRate that specifies the rate.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTLocator::put_Mode

IDVBTLocator Interface

Sets the transmission mode.

Syntax

HRESULT put_Mode(
    TransmissionMode mode
    );

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTLocator::put_OtherFrequencyInUse

IDVBTLocator Interface

Specifies whether the frequency is being used by another DVB-T broadcaster.

Syntax

HRESULT put_OtherFrequencyInUse(
    VARIANT_BOOL OtherFrequencyInUseVal
    );

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IDVBTuneRequest

Microsoft DirectX 8.0

IDVBTuneRequest Interface

This interface is implemented on the DVBTuneRequest object.

ITuneRequest Method Name | Description
get_TuningSpace | Retrieves the Tuning Space object.
get_Components | Retrieves the collection of IComponent objects.
Clone | Returns a new copy of this tune request.
get_Locator | Called from the Network Provider to get the ILocator object associated with the requested broadcast.
put_Locator | Called from the Network Provider to set the ILocator object associated with the requested broadcast.
IDVBTuneRequest Method Name | Description
get_ONID | Retrieves the original network ID.
get_SID | Sets the service ID.
get_TSID | Retrieves the transport stream ID.
put_ONID | Sets the original network ID.
put_SID | Retrieves the service ID.
put_TSID | Sets the transport stream ID.

IDVBTuneRequest::get_ONID

IDVBTuneRequest Interface

Retrieves the original network ID.

Syntax

HRESULT get_ONID(
    short* ONID
    );

Parameters

ONID
[out, retval] Pointer to a variable of type short that receives the original network ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTuneRequest::get_SID

IDVBTuneRequest Interface

Retrieves the service ID for the network.

Syntax

HRESULT get_SID(
    short* SID
    );

Parameters

SID
[out, retval] Pointer to a variable of type short that receives the service ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTuneRequest::get_TSID

IDVBTuneRequest Interface

Retrieves the transport stream ID.

Syntax

HRESULT get_TSID(
    short* TSID
    );

Parameters

TSID
[out, retval] Pointer to a variable of type short that receives the transport stream ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTuneRequest::put_ONID

IDVBTuneRequest Interface

Sets the original network ID.

Syntax

HRESULT put_ONID(
    short ONID
    );

Parameters

ONID
[in] Variable of type short that specifies the original network ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTuneRequest::put_SID

IDVBTuneRequest Interface

Sets the service ID.

Syntax

HRESULT put_SID(
    short SID
    );

Parameters

SID
[in] Variable of type short that specifies the service ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IDVBTuneRequest::put_TSID

IDVBTuneRequest Interface

Sets the transport stream ID.

Syntax

HRESULT put_TSID(
    short TSID
    );

Parameters

TSID
[in] Variable of type short that specifies the transport stream ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IDVBTuningSpace

Microsoft DirectX 8.0

IDVBTuningSpace Interface

This interface is implemented on the DVBTuningSpace object.

MethodName | Description
ITuningSpace Methods
get_UniqueName | Retrieves a unique name for the Tuning Space. Can be either a short name, or a GUID.
put_UniqueName | Sets a unique name for the Tuning Space. Can be either a short name, or a GUID.
get_FriendlyName | Retrieves the localized, user-friendly name of the Tuning Space.
put_FriendlyName | Sets the localized, user-friendly name of the Tuning Space.
get_CLSID | Gets the CLSID of the tuning space as a BSTR.
get_NetworkType | Retrieves the network type GUID of the tuning space as a BSTR.
put_NetworkType | Sets the network type for this tuning space as a BSTR.
get__NetworkType | Retrieves the network type of the tuning space as a GUID.
put__NetworkType | Sets the network type for this tuning space as a REFCLSID.
CreateTuneRequest | Creates a COM object representing an empty (uninitialized) Tune Request.
EnumCategoryGUIDs | (Currently not implemented.) Creates an enumerator for the DirectShow category GUIDs, representing classes of filters that support the tuning space.
EnumDeviceMonikers | (Currently not implemented.) Creates an enumerator of device monikers representing the tuner inputs (filters) supporting this tuning space.
get_DefaultPreferredComponentTypes | Returns an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
put_DefaultPreferredComponentTypes | Creates an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
get_FrequencyMapping | Retrieves the frequency mapping previously created by the network provider by a call to put_FrequencyMapping.
put_FrequencyMapping | Creates a frequency/channel map, frequency/transponder map, or whatever other mapping from carrier frequencies to frequency identifiers is appropriate for the tuning space.
get_DefaultLocator | Retrieves the default Locator on the local system.
put_DefaultLocator | Sets the default Locator on the local system.
IDVBTuningSpace Methods
get_SystemType | Retrieves the DVB system type.
put_SystemType | Sets the DVB system type.

IDVBTuningSpace::get_SystemType

IDVBTuningSpace Interface

Retrieves the system type.

Syntax

HRESULT get_SystemType(
    DVBSystemType* SysType
    );

Parameters

SysType
[out, retval] Pointer to a variable of type DVDSystemType that receives the system type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

typedef enum DVBSystemType {
    DVB_Cable,
    DVB_Terrestrial,
    DVB_Satellite,
} DVBSystemType;

IDVBTuningSpace::put_SystemType

IDVBTuningSpace Interface

Sets the system type.

Syntax

HRESULT put_SystemType(
    DVBSystemType SysType
    );

Parameters

SysType
[in] Variable of type DVDSystemType that specifies the system type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

typedef enum DVBSystemType {
    DVB_Cable,
    DVB_Terrestrial,
    DVB_Satellite,
} DVBSystemType;


IEnumComponents

Microsoft DirectX 8.0

IEnumComponents Interface

The IEnumComponents interface provides a standard COM enumeration object for the Components (substreams) in a given program stream. C++ applications should use this interface instead of IComponents to enumerate Component objects in a specified program stream.

MethodName | Description
Next | Retrieves the next n elements in the collection.
Skip | Skip the specified element in the collection without retrieving it.
Reset | Reset the enumerator to the beginning of the collection.
Clone | Create a new copy of the entire collection.

IEnumComponents::Next

IEnumComponents Interface

Retrieves the next n elements in the collection.

Syntax

HRESULT Next(
    ULONG celt,
    IComponent** rgelt,
    ULONG* pceltFetched
    );

Parameters

celt
[in] Variable of type ULONG that specifies the number of elements to retrieve.
rgelt
[out, size_is(celt), length_is(*pceltFetched)] Address of an array of IComponent interface pointers that will receive the retrieved Component objects.
pceltFetched
[out] Pointer to a variable of type ULONG that receives the number of elements actually retrieved.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumComponents::Skip

IEnumComponents Interface

Skip the specified element in the collection without retrieving it.

Syntax

HRESULT Skip(
    ULONG celt
    );

Parameters

celt
[in] Variable of type ULONG specifying the element to skip.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumComponents::Reset

IEnumComponents Interface

Reset the enumerator to the beginning of the collection.

Syntax

HRESULT Reset();

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumComponents::Clone

IEnumComponents Interface

Create a new copy of the entire collection.

Syntax

HRESULT Clone(
    IEnumComponents** ppEnum
    );

Parameters

ppEnum
[out] Address of an IEnumComponents interface pointer that will be set to the new collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The application must release this new collection when done with it.


IEnumComponentTypes

Microsoft DirectX 8.0

IEnumComponentTypes Interface

This interface is implemented on a standard COM collection of ComponentType objects associated with a given broadcast stream, and returned through a call to IComponentTypes::EnumComponentTypes.

MethodName | Description
Clone | Creates a new copy of the entire collection and all its sub-objects.
Next | Retrieves the next n elements in the collection.
Reset | Moves the iterator to the beginning of the collection.
Skip | Skips the element at the specified index.

IEnumComponentTypes::Clone

IEnumComponentTypes Interface

Creates a new copy of the collection and all its sub-objects.

Syntax

HRESULT Clone(
    IEnumComponentTypes** ppEnum
    );

Parameters

ppEnum
[out] Address of an IEnumComponentTypes interface pointer that will be set to the returned collection object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumComponentTypes::Next

IEnumComponentTypes Interface

Retrieves the next n elements in the collection.

Syntax

HRESULT Next(
    ULONG celt,
    IComponentType** rgelt,
    ULONG* pceltFetched
    );

Parameters

celt
[in] The number of elements to retrieve.
rgelt
[out, size_is(celt), length_is(*pceltFetched)] Address of an array of IComponentType interface pointers that will receive the returned ComponentType objects.
pceltFetched
[out] Pointer to a variable of type ULONG that will receive the number of elements actually retrieved.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumComponentTypes::Reset

IEnumComponentTypes Interface

Moves the iterator to the beginning of the collection.

Syntax

HRESULT Reset();

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumComponentTypes::Skip

IEnumComponentTypes Interface

Skips the element at the specified index.

Syntax

HRESULT Skip(
    ULONG celt
    );

Parameters

celt
[in] Index of the element to skip.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IEnumTuningSpaces

Microsoft DirectX 8.0

IEnumTuningSpaces Interface

This interface is implemented on a standard COM collection of tuning space objects on the local system and returned through a call to ITuningSpaceContainer::EnumTuningSpaces.

MethodName | Description
Next | Retrieves the next n elements in the collection.
Skip | Skips the specified element in the collection.
Reset | Moves the iterator to the beginning of the collection.
Clone | Creates a new copy of the collection and all its sub-objects.

IEnumTuningSpaces::Next

IEnumTuningSpaces Interface

Retrieves the next n elements in the collection.

Syntax

HRESULT Next(
    ULONG celt,
    ITuningSpace** rgelt,
    ULONG* pceltFetched
    );

Parameters

celt
[in] The number of elements to retrieve.
rgelt
[out, size_is(celt), length_is(*pceltFetched)] Address of an array of ITuningSpace interface pointers that will receive the retrieved tuning space objects.
pceltFetched
[out] Pointer to a variable of type ULONG that receives the number of elements actually retrieved.

Return Value

Returns S_OK if successful. This method will succeed even if celt is zero. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumTuningSpaces::Skip

IEnumTuningSpaces Interface

Skip the specified element in the collection.

Syntax

HRESULT Skip(
    ULONG celt
    );

Parameters

celt
[in] The index of the element to skip.

Return Value

Returns S_OK if successful. This method will succeed even if celt is zero. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumTuningSpaces::Reset

IEnumTuningSpaces Interface

Moves the iterator to the beginning of the collection.

Syntax

HRESULT Reset();

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumTuningSpaces::Clone

IEnumTuningSpaces Interface

Create a new copy of the collection and all its sub-objects.

Syntax

HRESULT Clone(
    IEnumTuningSpaces** ppEnum
    );

Parameters

ppEnum
[out] Address of an IEnumTuningSpaces interface pointer that will receive the returned interface.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


ILocator

Microsoft DirectX 8.0

ILocator Interface

The ILocator base class interface is implemented (through its derived interfaces such as IATSCLocator) on Locator objects that contain information about the tuning space. Locator objects are generally used by the Network Provider filter to help a tuner find and acquire the transport stream. Applications do not use Locator objects except possibly for debugging purposes. All Locator objects also support IPersistPropertyBag.

MethodName | Description
Clone | Creates a copy of the Locator.
get_CarrierFrequency | Retrieves the frequency of the RF signal.
get_InnerFEC | Retrieves the type of inner forward error correction that is used.
get_InnerFECRate | Retrieves the inner FEC rate.
get_Modulation | Retrieves the modulation type.
get_OuterFEC | Retrieves the type of outer forward error correction that is used.
get_OuterFECRate | Sets the outer FEC rate.
get_SymbolRate | Gets the QPSK symbol rate.
put_CarrierFrequency | Sets the frequency of the RF signal.
put_InnerFEC | Sets the type of inner forward error correction that is used.
put_InnerFECRate | Sets the inner FEC rate.
put_Modulation | Sets the modulation type.
put_OuterFEC | Sets the type of inner forward error correction that is used.
put_OuterFECRate | Sets the outer FEC rate.
put_SymbolRate | Sets the QPSK symbol rate.

ILocator::Clone

ILocator Interface

Creates a copy of the Locator.

Syntax

HRESULT Clone(
    ILocator **NewLocator
    );

Parameters

NewLocator
[out, retval] Address of an ILocator interface pointer that will receive the returned interface.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ILocator::get_CarrierFrequency

ILocator Interface

Retrieves the frequency of the RF signal.

Syntax

HRESULT get_CarrierFrequency(
    long* Frequency
    );

Parameters

Frequency
[out, retval] Pointer to a variable of type long that receives the frequency value.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ILocator::get_InnerFEC

ILocator Interface

Retrieves the type of forward error correction that is used.

Syntax

HRESULT get_InnerFEC(
    FECMethod* FEC
    );

Parameters

FEC
[out, retval] Pointer to a variable of type FECMethod that receives the inner forward FEC.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

FECMethod is defined in bdatypes.h as follows:
typedef enum FECMethod {
    BDA_FEC_METHOD_NOT_SET = -1,
    BDA_FEC_METHOD_NOT_DEFINED = 0,
    BDA_FEC_VITERBI = 1,          // FEC is a Viterbi Binary Convolution.
    BDA_FEC_RS_204_188,       // The FEC is Reed-Solomon 204/188 (outer FEC)
    BDA_FEC_MAX,
} FECMethod;

ILocator::get_InnerFECRate

ILocator Interface

Retrieves the inner FEC rate.

Syntax

HRESULT get_InnerFECRate(
    BinaryConvolutionCodeRate* FEC
    );

Parameters

FEC
[out, retval] Pointer to a variable of type BinaryConvolutionCodeRate that receives the inner FEC rate.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

BinaryConvolutionCodeRate is defined in bdatypes.h as follows:

typedef enum {
    BDA_BCC_RATE_NOT_SET = -1,
    BDA_BCC_RATE_NOT_DEFINED = 0,
    BDA_BCC_RATE_1_2 = 1,
    BDA_BCC_RATE_2_3 = 2,
    BDA_BCC_RATE_3_4 = 3,
    BDA_BCC_RATE_3_5 = 4,
    BDA_BCC_RATE_4_5 = 5,
    BDA_BCC_RATE_5_6 = 6,
    BDA_BCC_RATE_5_11 = 7,
    BDA_BCC_RATE_7_8 = 8,
    BDA_BCC_RATE_MAX = 9
} BinaryConvolutionCodeRate;

ILocator::get_Modulation

ILocator Interface

Retrieves the modulation type.

Syntax

HRESULT get_Modulation(
    ModulationType* Modulation
    );

Parameters

Modulation
[out, retval] Pointer that receives the new modulation type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

See put_Modulation for the definition of ModulationType.

ILocator::get_OuterFEC

ILocator Interface

Retrieves the type of outer forward error correction that is used.

Syntax

HRESULT get_OuterFEC(
    FECMethod* FEC
    );

Parameters

FEC
[out, retval] Pointer to a variable of type FECMethod that receives the outer forward FEC.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

See get_InnerFEC for the definition of FECMethod.

ILocator::get_OuterFECRate

ILocator Interface

Retrieves the outer FEC rate.

Syntax

HRESULT get_OuterFECRate(
    BinaryConvolutionCodeRate* FEC
    );

Parameters

FEC
[out, retval] Pointer to a variable of type BinaryConvolutionCodeRate that receives the outer FEC rate.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ILocator::get_SymbolRate

ILocator Interface

Retrieves the QPSK symbol rate.

Syntax

HRESULT get_SymbolRate(
    long* Rate
    );

Parameters

Rate
[out, retval] Pointer to a variable of type long that receives the QPSK symbol rate.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.

ILocator::put_CarrierFrequency

ILocator Interface

Sets the frequency of the RF signal.

Syntax

HRESULT put_CarrierFrequency(
    long Frequency
    );

Parameters

Frequency
[in] Variable of type long that specifies the frequency value.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ILocator::put_InnerFEC

ILocator Interface

Sets the type of inner forward error correction that is used.

Syntax

HRESULT put_InnerFEC(
    FECMethod FEC
    );

Parameters

FEC
[in] Variable of type FECMethod that specifies the inner FEC.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ILocator::put_InnerFECRate

ILocator Interface

Sets the inner FEC rate.

Syntax

HRESULT put_InnerFECRate(
    BinaryConvolutionCodeRate FEC
    );

Parameters

FEC
[in] Variable of type BinaryConvolutionCodeRate that specifies the inner FEC rate.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ILocator::put_Modulation

ILocator Interface

Sets the modulation type.

Syntax

HRESULT put_Modulation(
    ModulationType Modulation
    );

Parameters

Modulation
[in] Specifies the modulation type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The ModulationType enum is defined in bdatypes.h as follows:
typedef enum {
    BDA_MOD_NOT_SET = -1,
    BDA_MOD_NOT_DEFINED = 0,
    BDA_MOD_16QAM = 1,
    BDA_MOD_32QAM = 2,
    BDA_MOD_64QAM = 3,
    BDA_MOD_80QAM = 4,
    BDA_MOD_96QAM = 5,
    BDA_MOD_112QAM = 6,
    BDA_MOD_128QAM = 7,
    BDA_MOD_160QAM = 8,
    BDA_MOD_192QAM = 9,
    BDA_MOD_224QAM = 10,
    BDA_MOD_256QAM = 11,
    BDA_MOD_320QAM = 12,
    BDA_MOD_384QAM = 13,
    BDA_MOD_448QAM = 14,
    BDA_MOD_512QAM = 15,
    BDA_MOD_640QAM = 16,
    BDA_MOD_768QAM = 17,
    BDA_MOD_896QAM = 18,
    BDA_MOD_1024QAM = 19,
    BDA_MOD_QPSK = 20,
    BDA_MOD_BPSK = 21,
    BDA_MOD_OQPSK = 22,
    BDA_MOD_8VSB = 23,
    BDA_MOD_16VSB = 24,
    BDA_MOD_ANALOG_AMPLITUDE = 25,
    BDA_MOD_ANALOG_FREQUENCY = 26,
    BDA_MOD_MAX = 27
} ModulationType;

ILocator::put_OuterFEC

ILocator Interface

Sets the type of outer forward error correction that is used.

Syntax

HRESULT put_OuterFEC(
    FECMethod FEC
    );

Parameters

FEC
[in] Variable of type FECMethod that specifies the outer forward error correction.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ILocator::put_OuterFECRate

ILocator Interface

Sets the outer FEC rate.

Syntax

HRESULT put_OuterFECRate(
    BinaryConvolutionCodeRate FEC
    );

Parameters

FEC
[in] Variable of type BinaryConvolutionCodeRate that specifies the outer FEC rate.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

BinaryConvolutionCodeRate is defined in bdatypes.h as follows:
typedef enum {
    BDA_BCC_RATE_NOT_SET = -1,
    BDA_BCC_RATE_NOT_DEFINED = 0,
    BDA_BCC_RATE_1_2 = 1,
    BDA_BCC_RATE_2_3 = 2,
    BDA_BCC_RATE_3_4 = 3,
    BDA_BCC_RATE_3_5 = 4,
    BDA_BCC_RATE_4_5 = 5,
    BDA_BCC_RATE_5_6 = 6,
    BDA_BCC_RATE_5_11 = 7,
    BDA_BCC_RATE_7_8 = 8,
    BDA_BCC_RATE_MAX = 9
} BinaryConvolutionCodeRate;

ILocator::put_SymbolRate

ILocator Interface

Sets the QPSK symbol rate.

Syntax

HRESULT put_SymbolRate(
    long Rate
    );

Parameters

Rate
[in] Variable of type long that specifies the QPSK symbol rate.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.


ILanguageComponentType

Microsoft DirectX 8.0

ILanguageComponentType Interface

The ILanguageComponentType interface is implemented on LanguageComponentType objects, which define the language of the stream content. Not all streams have a language component.

MethodName | Description
get_LangID | Retrieves the language of the stream content.
put_LangID | Sets the language of the stream content.

ILanguageComponentType::get_LangID

ILanguageComponentType Interface

Retrieves the LCID that identifies the language.

Syntax

HRESULT get_LangID(
    short* LangID
    );

Parameters

LangID
[out, retval] Pointer to a variable of type short that receives the LCID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

LangID is a Win32 LANGID. There is a separate language ID in the base IComponent that defines the language of the description.

ILanguageComponentType::put_LangID

ILanguageComponentType Interface

Specifies the LCID that identifies the language

Syntax

HRESULT put_LangID(
    short LangID
    );

Parameters

LangID
[in] Variable of type short that specifies the LCID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IMPEG2Component

Microsoft DirectX 8.0

IMPEG2Component Interface

The IMPEG2Component interface contains methods for getting and setting properties on an MPEG2 elementary stream.

IComponent Method Name | Description
get_Type | Retrieves an IComponentType object describing the general characteristics of the Component.
put_Type | Sets an IComponentType object describing the general characteristics of the Component.
get_DescLangID | Retrieves the language for presentation of the description.
put_DescLangID | Sets the language for presentation of the description.
get_Status | Retrieves the requested or actual status of the component.
put_Status | Sets the requested or actual status of the component.
get_Description | Retrieves the description of the component.
put_Description | Sets the description of the component.
Clone | Creates a new copy of the component.
IMPEG2Component Method Name | Description
get_PCRPID | Returns the MPEG2 Packet ID for this substream's timestamps.
get_PID | Get the packet identifier for this substream.
get_ProgramNumber | Gets the program number, which provides a reverse lookup to PAT.
put_PCRPID | Sets the MPEG2 Packet ID for this substream's timestamps.
put_PID | Set the packet identifier for this substream.
put_ProgramNumber | Sets the program number, which provides a reverse lookup to PAT.

IMPEG2Component::get_PCRPID

IMPEG2Component Interface

Returns the MPEG2 Packet ID for this Substream's Timestamps.

Syntax

HRESULT get_PCRPID(
    short *PCRPID
    );

Parameters

PCRPID
[out, retval] Pointer to a variable of type short that receives the value of the packet ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IMPEG2Component::get_PID

IMPEG2Component Interface

Get the packet identifier for this substream.

Syntax

HRESULT get_PID(
    short *PID
    );

Parameters

PID
[out, retval] Pointer to a variable of type short that receives the packet identifier.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IMPEG2Component::get_ProgramNumber

IMPEG2Component Interface

Gets the program number, which provides a reverse lookup to PAT.

Syntax

HRESULT get_ProgramNumber(
    short *ProgramNumber
    );

Parameters

ProgramNumber
[out, retval] Pointer to a variable of type short that receives the program number.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IMPEG2Component::put_PCRPID

IMPEG2Component Interface

Sets the MPEG2 Packet ID for this substream's timestamps.

Syntax

HRESULT put_PCRPID(
    short PCRPID
    );

Parameters

PCRPID
[in] Variable of type short that specifies the packet ID.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IMPEG2Component::put_PID

IMPEG2Component Interface

Sets the packet identifier for this substream.

Syntax

HRESULT put_PID(
    short PID
    );

Parameters

PID
[in] Variable of type short that specifies the packet identifier.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IMPEG2Component::put_ProgramNumber

IMPEG2Component Interface

Sets the program number, which provides a reverse lookup to PAT.

Syntax

HRESULT put_ProgramNumber(
    short ProgramNumber
    );

Parameters

ProgramNumber
[in] Variable of type short that specifies the program number.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IMPEG2ComponentType

Microsoft DirectX 8.0

IMPEG2ComponentType Interface

This interface inherits from IComponentLanguageType and is implemented on IMPEG2ComponentType objects. It enables applications to set and retrieve information about MPEG2 stream types.

MethodName | Description
get_StreamType | Retrieves the stream type.
put_StreamType | Sets the stream type.

IMPEG2ComponentType::get_StreamType

IMPEG2ComponentType Interface

Retrieves the stream type.

Syntax

HRESULT get_StreamType(
    MPEG2StreamType* MP2StreamType
    );

Parameters

MP2StreamType
[out, retval] Pointer to a variable of type MPEG2StreamType that receives the stream type value.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

    typedef enum MPEG2StreamType {
    BDA_UNITIALIZED_MPEG2STREAMTYPE = -1,
        Reserved1 = 0x0,
        ISO_IEC_11172_2_VIDEO	= Reserved1 + 1,
        ISO_IEC_13818_2_VIDEO	= ISO_IEC_11172_2_VIDEO + 1,
        ISO_IEC_11172_3_AUDIO	= ISO_IEC_13818_2_VIDEO + 1,
        ISO_IEC_13818_3_AUDIO	= ISO_IEC_11172_3_AUDIO + 1,
        ISO_IEC_13818_1_PRIVATE_SECTION = ISO_IEC_13818_3_AUDIO + 1,
        ISO_IEC_13818_1_PES		= ISO_IEC_13818_1_PRIVATE_SECTION + 1,
        ISO_IEC_13522_MHEG		= ISO_IEC_13818_1_PES + 1,
        ANNEX_A_DSM_CC			= ISO_IEC_13522_MHEG + 1,
        ITU_T_REC_H_222_1		= ANNEX_A_DSM_CC + 1,
        ISO_IEC_13818_6_TYPE_A	= ITU_T_REC_H_222_1 + 1,
        ISO_IEC_13818_6_TYPE_B	= ISO_IEC_13818_6_TYPE_A + 1,
        ISO_IEC_13818_6_TYPE_C	= ISO_IEC_13818_6_TYPE_B + 1,
        ISO_IEC_13818_6_TYPE_D	= ISO_IEC_13818_6_TYPE_C + 1,
        ISO_IEC_13818_1_AUXILIARY = ISO_IEC_13818_6_TYPE_D + 1,
        ISO_IEC_13818_1_RESERVED = ISO_IEC_13818_1_AUXILIARY + 1,
        USER_PRIVATE			= ISO_IEC_13818_1_RESERVED + 1
    } MPEG2StreamType;

IMPEG2ComponentType::put_StreamType

IMPEG2ComponentType Interface

Sets the MPEG2 stream type.

Syntax

HRESULT put_StreamType(
    MPEG2StreamType MP2StreamType
    );

Parameters

MP2StreamType
[in] Variable of type MPEG2StreamType that specifies the stream type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

    typedef enum MPEG2StreamType {
    BDA_UNITIALIZED_MPEG2STREAMTYPE = -1,
        Reserved1 = 0x0,
        ISO_IEC_11172_2_VIDEO	= Reserved1 + 1,
        ISO_IEC_13818_2_VIDEO	= ISO_IEC_11172_2_VIDEO + 1,
        ISO_IEC_11172_3_AUDIO	= ISO_IEC_13818_2_VIDEO + 1,
        ISO_IEC_13818_3_AUDIO	= ISO_IEC_11172_3_AUDIO + 1,
        ISO_IEC_13818_1_PRIVATE_SECTION = ISO_IEC_13818_3_AUDIO + 1,
        ISO_IEC_13818_1_PES		= ISO_IEC_13818_1_PRIVATE_SECTION + 1,
        ISO_IEC_13522_MHEG		= ISO_IEC_13818_1_PES + 1,
        ANNEX_A_DSM_CC			= ISO_IEC_13522_MHEG + 1,
        ITU_T_REC_H_222_1		= ANNEX_A_DSM_CC + 1,
        ISO_IEC_13818_6_TYPE_A	= ITU_T_REC_H_222_1 + 1,
        ISO_IEC_13818_6_TYPE_B	= ISO_IEC_13818_6_TYPE_A + 1,
        ISO_IEC_13818_6_TYPE_C	= ISO_IEC_13818_6_TYPE_B + 1,
        ISO_IEC_13818_6_TYPE_D	= ISO_IEC_13818_6_TYPE_C + 1,
        ISO_IEC_13818_1_AUXILIARY = ISO_IEC_13818_6_TYPE_D + 1,
        ISO_IEC_13818_1_RESERVED = ISO_IEC_13818_1_AUXILIARY + 1,
        USER_PRIVATE			= ISO_IEC_13818_1_RESERVED + 1
    } MPEG2StreamType;


ISignalEvents

Microsoft DirectX 8.0

ISignalEvents Interface

This is a standard COM IConnectionPoint interface. Implement this interface in your application to receive information about the strength of the current signal. Calling ITuner::TriggerSignalEvents will cause the Tuner to send OnSignal events continuously to your application.

ISignalEvents::OnSignal

ISignalEvents Interface

Informs an application of the strength of the current signal.

Syntax

HRESULT OnSignal(long* Strength );

Parameters

Strength
[out] Pointer to a variable of type long that will receive the new signal strength value.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IScanningTuner

Microsoft DirectX 8.0

IScanningTuner Interface

IScanningTuner inherits from ITuner and permits direct control of a tuner that supports searching for valid programming. The client must provide a valid tuning space (via ITuner::put_TuningSpace or ITuner::put_TuneRequest) before calling any of the methods in this interface. This interface is meant to be used in conjunction with the ITunerEvents outbound interface.

MethodName | Description
ITuner Methods
get_TuningSpace | Gets the Tuning Space currently in effect for the tuner.
put_TuningSpace | Sets the Tuning Space currently in effect for the tuner.
EnumTuningSpaces | Creates an enumerator for the Tuning Spaces preferred by this implementation.
get_TuneRequest | Gets the Tune Request currently in effect for the tuner.
put_TuneRequest | Sets the Tune Request currently in effect for the tuner.
Validate | Returns a value indicating that the Tune Request can be carried out.
get_PreferredComponentTypes | Gets the collection of ComponentType objects used for default component selection.
put_PreferredComponentTypes | Sets the collection of ComponentType objects used for default component selection.
get_SignalStrength | Retrieves the tuner-specific signal strength metric.
TriggerSignalEvents | Puts the tuner into a mode where ISignalEvents::OnSignal will be repeatedly called.
IScanningTuner Methods
SeekUp | Changes the channel to the next higher channel with valid programming.
SeekDown | Changes the channel to the next lower channel with valid programming.
ScanUp | Changes the channel to the next higher channel with valid programming, pauses for the specified number of milliseconds, then repeats until canceled.
ScanDown | Changes the channel to the next lower channel with valid programming, pauses for the specified number of milliseconds, then repeats… until canceled.
AutoProgram | Scans for all channels with valid programming.

IScanningTuner::SeekUp

IScanningTuner Interface

Changes the channel to the next higher channel with valid programming.

Syntax

HRESULT SeekUp();

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method returns immediately, and the seek continues in the background. The seek can be canceled by calling any other tuning operation.

IScanningTuner::SeekDown

IScanningTuner Interface

Changes the channel to the next lower channel with valid programming.

Syntax

HRESULT SeekDown();

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method returns immediately, and the seek continues in the background. The seek can be canceled by calling any other tuning operation.

IScanningTuner::ScanUp

IScanningTuner Interface

Changes the channel to the next higher channel with valid programming, pauses for the specified number of milliseconds, then repeats until canceled.

Syntax

HRESULT ScanUp(
    long MillisecondsPause
    );

Parameters

MillisecondsPause
[in] Variable of type long that specifies the number of milliseconds to pause.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The call returns immediately, while the scan continues in the background. The scan can be canceled by calling any other tuning operation.

IScanningTuner::ScanDown

IScanningTuner Interface

Changes the channel to the next lower channel with valid programming, pauses for the specified number of milliseconds, then repeats until canceled.

Syntax

HRESULT ScanDown(
    long MillisecondsPause
    );

Parameters

MillisecondsPause
[in] Variable of type long that specifies the number of milliseconds to pause.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The call returns immediately, while the scan continues in the background. The scan can be canceled by calling any other tuning operation.

IScanningTuner::AutoProgram

IScanningTuner Interface

Scans for all channels with valid programming.

Syntax

HRESULT AutoProgram();

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method returns immediately, and the scan continues in the background. If the device allows it, the scan can be canceled by calling any other tuning operation. Otherwise, the scan will complete once all channels have been visited once. Internal devices will likely have a software implementation of this feature, and will collect fine-tuning information resulting from the scan. External devices will likely implement this feature, so this is just a means to trigger the process.


ITuneRequest Interface

All ITuneRequest objects also support IPersistPropertyBag.

MethodName | Description
get_TuningSpace | Retrieves the Tuning Space object.
get_Components | Retrieves the collection of IComponent objects.
Clone | Returns a new copy of this tune request.
get_Locator | Called from the Network Provider to get the ILocator object associated with the requested broadcast.
put_Locator | Called from the Network Provider to set the ILocator object associated with the requested broadcast.

ITuneRequest::get_TuningSpace

ITuneRequest Interface

Retrieves the Tuning Space object.

Syntax

HRESULT get_TuningSpace(
    ITuningSpace** TuningSpace
    );

Parameters

TuningSpace
[out, retval] Address of an ITuningSpace interface pointer that will be set to the returned object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuneRequest::get_Components

ITuneRequest Interface

Retrieves the collection of IComponent objects.

Syntax

HRESULT get_Components(
    IComponents** Components
    );

Parameters

Components
[out, retval] Address of an IComponents interface pointer that will be set to the returned object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

There is always a Components collection associated with a Tune Request, but that collection can be empty.

ITuneRequest::Clone

ITuneRequest Interface

Returns a new copy of this tune request.

Syntax

HRESULT Clone(
    ITuneRequest** NewTuneRequest
    );

Parameters

NewTuneRequest
[out, retval] Address of an ITuneRequest interface pointer that will be set to the new object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method performs a "deep copy" of the object; in other words it copies all sub-objects as well, including Components, LanguageComponents, and so on.

ITuneRequest::get_Locator

ITuneRequest Interface

Called from the Network Provider to get the ILocator object associated with the requested broadcast.

Syntax

HRESULT get_Locator(
    ILocator** Locator
    );

Parameters

Locator
[out, retval] Address of an ILocator interface pointer that will be set to the new object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The locator is used by the network provider and transport information filter (TIF) to obtain information about how or where to acquire the requested broadcast. This information includes the modulation scheme, error correction methods, and frequency. This information is typically of no interest to applications, since applications are not involved in the low-level details of tuning.

ITuneRequest::put_Locator

ITuneRequest Interface

Called from the Network Provider to set the ILocator object associated with the requested broadcast.

Syntax

HRESULT put_Locator(
    ILocator* Locator
    );

Parameters

Locator
[in] Pointer to an ILocator interface that specifies the new locator.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


ITunerEvents

Microsoft DirectX 8.0

ITunerEvents Interface

This is a standard COM IConnectionPoint interface. Implement this interface in your application to receive event notifications from the Tuner object whenever it tunes to a new frequency or channel. This provides a way to receive a TuneRequest object with its components collection updated to reflect the substreams actually available on the new channel or frequency.

ITunerEvents::OnTune

ITunerEvents Interface

Informs an application when the tuner filter tunes to a new frequency.

Syntax

  HRESULT OnTune(
  ITuneRequest** Request,
    long* Strength
    );

Parameters

Request
[in] Address of an ITuneRequest interface pointer that will receive the TuneRequest object whose Components collection has been filled in to reflect the substreams available on the new channel or frequency.
Strength
[in] Pointer to a variable of type long representing the signal strength of the new channel or frequency.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.
-->


ITuningSpace

Microsoft DirectX 8.0

ITuningSpace Interface

The ITuningSpace interface is the base class that provides the common functionality for all network-specific tuning spaces. The Tuning Space Container will never co-create an instance of an object that exposes only ITuningSpace, but always an object that supports some interface derived from ITuningSpace, such as IASTCTuningSpace.

MethodName | Description
get_UniqueName | Retrieves a unique name for the Tuning Space. Can be either a short name, or a GUID.
put_UniqueName | Sets a unique name for the Tuning Space. Can be either a short name, or a GUID.
get_FriendlyName | Retrieves the localized, user-friendly name of the Tuning Space.
put_FriendlyName | Sets the localized, user-friendly name of the Tuning Space.
get_CLSID | Gets the CLSID of the tuning space as a BSTR.
get_NetworkType | Retrieves the network type of the tuning space as a BSTR.
put_NetworkType | Sets the network type for this tuning space as a BSTR.
get__NetworkType | Retrieves the network type of the tuning space as a GUID.
put__NetworkType | Sets the network type for this tuning space as a REFCLSID.
CreateTuneRequest | Creates a COM object representing an empty (uninitialized) Tune Request.
EnumCategoryGUIDs | (Currently not implemented.) Creates an enumerator for the DirectShow category GUIDs, representing classes of filters that support the tuning space.
EnumDeviceMonikers | (Currently not implemented.) Creates an enumerator of device monikers representing the tuner inputs (filters) supporting this tuning space.
get_DefaultPreferredComponentTypes | Returns an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
put_DefaultPreferredComponentTypes | Creates an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.
get_FrequencyMapping | Retrieves the frequency mapping previously created by the network provider by a call to put_FrequencyMapping.
put_FrequencyMapping | Creates a frequency/channel map, frequency/transponder map, or whatever other mapping from carrier frequencies to frequency identifiers is appropriate for the tuning space.
get_DefaultLocator | Retrieves the default Locator on the local system.
put_DefaultLocator | Sets the default Locator on the local system.
Clone | Creates a new copy of the tuning space.

ITuningSpace::get_UniqueName

ITuningSpace Interface

Retrieves a unique name for the Tuning Space. Can be either a short name, or a GUID.

Syntax

HRESULT get_UniqueName(
    BSTR* Name
    );

Parameters

Name
[out, retval] Pointer to a variable of type BSTR that receives the unique name.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The unique name can be any string that is globally unique.

ITuningSpace::put_UniqueName

ITuningSpace Interface

Sets a unique name for the Tuning Space. Can be either a short name, or a GUID.

Syntax

HRESULT put_UniqueName(
    BSTR Name
    );

Parameters

Name
[in] Variable of type BSTR that specifies the unique name.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuningSpace::get_FriendlyName

ITuningSpace Interface

Retrieves the localized, user-friendly name of the Tuning Space.

Syntax

HRESULT get_FriendlyName(
    BSTR* Name
    );

Parameters

Name
[out, retval] Pointer to a variable of type BSTR that receives the user-friendly name.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuningSpace::put_FriendlyName

ITuningSpace Interface

Sets the localized, user-friendly name of the Tuning Space.

Syntax

HRESULT put_FriendlyName(
    BSTR Name
    );

Parameters

Name
[in] Variable of type BSTR that specifies the user-friendly name.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuningSpace::get_CLSID

ITuningSpace Interface

Gets the CLSID of the tuning space as a BSTR.

Syntax

HRESULT get_CLSID(
    BSTR* SpaceCLSID
    );

Parameters

SpaceCLSID
[out, retval] Pointer to a variable of type BSTR that receives the CLSID of the tuning space.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method provides script access to the IPersist::GetClassID method.

ITuningSpace::get_NetworkType

ITuningSpace Interface

Retrieves the network type of the tuning space as a BSTR.

Syntax

HRESULT get_NetworkType(
    BSTR* NetworkTypeGuid
    );

Parameters

NetworkTypeGuid
[out, retval] Pointer to a variable of type BSTR that receives the GUID that indicates the network type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Use the GUID retrieved in this method as the CLSID when creating the Network Provider filter when building the filter graph. This method is provided for Visual Basic® and scripting applications. C++ applications should use get__NetworkType to retrieve the network type as a native GUID data type.

ITuningSpace::put_NetworkType

ITuningSpace Interface

Specifies the network type of the tuning space as a BSTR.

Syntax

HRESULT put_NetworkType(
    BSTR NetworkTypeGuid
    );

Parameters

NetworkTypeGuid
[in] Variable of type BSTR that specifies the network type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is provided for Visual Basic® and scripting applications. C++ applications should use put__NetworkType.

ITuningSpace::get__NetworkType

ITuningSpace Interface

Retrieves the network type of the tuning space as a GUID.

Syntax

HRESULT get_NetworkType(
    GUID* NetworkTypeGuid
    );

Parameters

NetworkTypeGuid
[out, retval] Pointer to a variable of type GUID that receives the network type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Use the GUID retrieved in this method as the CLSID when creating the Network Provider filter when building the filter graph.

ITuningSpace::put__NetworkType

ITuningSpace Interface

Specifies the network type of the tuning space as a REFCLSID.

Syntax

HRESULT put__NetworkType(
    REFCLSID NetworkTypeGuid
    );

Parameters

NetworkTypeGuid
[in] Variable of type REFCLSID that specifies the network type.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuningSpace::CreateTuneRequest

ITuningSpace Interface

Creates a COM object representing an empty (uninitialized) Tune Request.

Syntax

HRESULT CreateTuneRequest(
    ITuneRequest** TuneRequest
    );

Parameters

TuneRequest
[out, retval] Address of an ITuneRequest interface pointer that receives the new Tune Request object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method returns the ITuneRequest base class interface, but this interface cannot be used to create a tune request. To create a tune request you must use the derived interface that is associated with the type of tuning space you are using. To obtain the derived interface, call QueryInterface on the returned ITuneRequest object and specify the required interface. The following table shows the relationships between tuning spaces and tune requests.

Tuning Space | Tune Request
IAnalogTVTuningSpace | IID_IChannelTuneRequest
IAnalogRadioTuningSpace | IID_IChannelTuneRequest
IDVBTuningSpace | IID_IDVBTuneRequest
IATSCTuningSpace | IID_IATSCChannelTuneRequest

ITuningSpace::EnumCategoryGUIDs

ITuningSpace Interface

(Currently not implemented.) Creates an enumerator for the DirectShow category GUIDs, representing classes of filters that support the tuning space.

Syntax

HRESULT EnumCategoryGUIDs(
    IEnumGUID** ppEnum
    );

Parameters

ppEnum
[out, retval] Address of an IEnumGUID interface pointer that receives the returned enumeration object.

Return Value

Returns E_NOTIMPL.

Remarks

This method is hidden from automation languages.

ITuningSpace::EnumDeviceMonikers

ITuningSpace Interface

(Currently not implemented.) Creates an enumerator of device monikers representing the tuner inputs (filters) supporting this tuning space.

Syntax

HRESULT EnumDeviceMonikers(
    IEnumMoniker** ppEnum
    );

Parameters

ppEnum
[out, retval] Address of an IEnumMoniker interface pointer that receives the returned enumeration object.

Return Value

Returns E_NOTIMPL.

Remarks

This method is hidden from automation languages.

ITuningSpace::get_DefaultPreferredComponentTypes

ITuningSpace Interface

Returns an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.

Syntax

HRESULT get_DefaultPreferredComponentTypes(
    IComponentTypes** ComponentTypes
    );

Parameters

ComponentTypes
[out, retval] Address of an IComponentTypes interface pointer that receives the returned collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

A "component" in this context means a stream within the program. An example of a "preferred component" would be an audio stream in English. When multiple components or streams are available, the Tuner will always attempt to play the preferred ones first.

ITuningSpace::put_DefaultPreferredComponentTypes

ITuningSpace Interface

Creates an enumeration of the preferred component types, which specify parameters such as the preferred audio stream.

Syntax

HRESULT put_DefaultPreferredComponentTypes(
    IComponentTypes* NewComponentTypes
    );

Parameters

NewComponentTypes
[in] Pointer to an IComponentTypes interface on the ComponentTypes object that specifies the default preferred component types.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuningSpace::get_FrequencyMapping

ITuningSpace Interface

Retrieves the frequency mapping previously created by the network provider by a call to put_FrequencyMapping.

Syntax

HRESULT get_FrequencyMapping(
    BSTR* pMapping
    );

Parameters

pMapping
[out, retval] BSTR that receives the frequency mappings created by the network provider.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The BSTR is treated as a binary blob. It is expected to contain embedded nulls, and it may be formatted internally in whatever fashion the network provider sees fit.

ITuningSpace::put_FrequencyMapping

ITuningSpace Interface

Creates a frequency/channel map, frequency/transponder map, or whatever other mapping from carrier frequencies to frequency identifiers is appropriate for the tuning space.

Syntax

HRESULT put_FrequencyMapping(
    BSTR Mapping
    );

Parameters

Mapping
[in] BSTR that contains the frequency mappings.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is used by the network provider to store a string that contains the frequency mappings. The

ITuningSpace::get_DefaultLocator

ITuningSpace Interface

Retrieves the default Locator on the local system.

Syntax

HRESULT get_DefaultLocator(
    ILocator** LocatorVal
    );

Parameters

LocatorVal
[out, retval] Address of a pointer that receives the returned ILocator interface.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The default locator can be used as a starting point for the IScanningTuner object after installation

ITuningSpace::put_DefaultLocator

ITuningSpace Interface

Sets the default Locator on the local system.

Syntax

HRESULT put_DefaultLocator(
    ILocator* LocatorVal
    );

Parameters

LocatorVal
[in] Pointer to an ILocator interface on the object to be set as the default Locator.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The default locator can be used as a starting point for the IScanningTuner object after installation

ITuningSpace::Clone

ITuningSpace Interface

Creates a new copy of the tuning space.

Syntax

HRESULT Clone(
    ITuningSpace** NewTS
    );

Parameters

NewTS
[out, retval] Address of an ITuningSpace interface pointer that will be set to the new TuningSpace object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


ITuningSpaces

Microsoft DirectX 8.0

ITuningSpaces Interface

This interface is implemented on the SystemTuningSpaces object and provides methods to retrieve the tuning spaces available on the host system.

MethodName | Description
get_Count | Returns the number of tuning spaces in the collection.
get_EnumTuningSpaces | Convenience function so C++ applications don't have to unpack a VARIANT datatype.
get_Item | Returns the specified item in the collection.
get__NewEnum | Helper method for Visual Basic and script applications. Not used in C++.

ITuningSpaces::get_Count

ITuningSpaces Interface

Returns the number of tuning spaces in the collection.

Syntax

HRESULT get_Count(
    long* Count
    );

Parameters

Count
[out, retval] Pointer to a variable of type long that receives the number of items in the collection.

Return Value

Returns S_OK if successful.

ITuningSpaces::get_EnumTuningSpaces

ITuningSpaces Interface

Convenience function so C++ applications don't have to unpack a VARIANT datatype.

Syntax

HRESULT get_EnumTuningSpaces(
    IEnumTuningSpaces** NewEnum
    );

Parameters

NewEnum
[out, retval] Address of an IEnumTuningSpaces interface pointer that receives the new collection.

Return Value

Returns S_OK if successful.

ITuningSpaces::get_Item

ITuningSpaces Interface

Returns the specified item in the collection.

Syntax

HRESULT get_Item(
    VARIANT varIndex,
    ITuningSpace** TuningSpace
    );

Parameters

varIndex
[in] String or index number that specifies the item to return.
TuningSpace
[out, retval] Address of the returned ITuningSpace interface pointer.

Return Value

Returns S_OK if successful.

ITuningSpaces::get__NewEnum

ITuningSpaces Interface

Helper method for Visual Basic and script applications. Not used in C++.

Syntax

HRESULT get__NewEnum(
    IEnumVARIANT** NewEnum
    );

Parameters

NewEnum
[out, retval] Address of an IEnumVariant interface pointer.

Return Value

Returns S_OK if successful.

Remarks

This method enables Microsoft® Visual Basic® and script applications to retrieve items in a For...Next loop.


ITuningSpaceContainer

Microsoft DirectX 8.0

ITuningSpaceContainer Interface

The ITuningSpaceContainer interface is implemented on the SystemTuningSpaces object, which enables an application to access and modify all the Tuning Spaces defined on the local system.

MethodName | Description
get_Count | Retrieves the number of Tuning Spaces currently available on the local system.
get__NewEnum | Enumeration method to support For...Each loops in Automation clients.
get_Item | Retrieves the Tuning Space object at the specified index.
put_Item | Saves the Tuning Space object at the specified index.
TuningSpacesForCLSID | Retrieves a collection of Tuning Spaces that match the specified CLSID string. (For use by Automation clients.)
_TuningSpacesForCLSID | Retrieves a collection of Tuning Spaces that match the specified CLSID. (For use by C++ clients.)
TuningSpacesForName | Retrieves a collection of Tuning Spaces that match the specified friendly name.
FindID | Retrieves the local unique ID number for the specified Tuning Space.
Add | Adds a new, persistent, Tuning Space to the system.
get_EnumTuningSpaces | Retrieves a collection of all Tuning Spaces available on the local system.
Remove | Permanently removes a Tuning Space from the system.
put_MaxCount | Retrieve the maximum number of tuning spaces allowed on the system.
get_MaxCount | Set the maximum number of tuning spaces allowed on the system.

ITuningSpaceContainer::get_Count

ITuningSpaceContainer Interface

Retrieves the number of Tuning Spaces currently available on the local system.

Syntax

HRESULT get_Count(
    long *Count
    );

Parameters

Count
[out, retval] Pointer to a variable of type long that receives the number of Tuning Spaces.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuningSpaceContainer::get_MaxCount

ITuningSpaceContainer Interface

Retrieves the maximum number of tuning spaces allowed on the system.

Syntax

HRESULT get_MaxCount(
    long *MaxCount
    );

Parameters

MaxCount
[out, retval] Pointer to a variable of type long that receivces the maximum number of tuning spaces.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuningSpaceContainer::get__NewEnum

ITuningSpaceContainer Interface

Enumeration method to support For...Each loops in Automation clients.

Syntax

HRESULT get__NewEnum(
    IEnumVARIANT **NewEnum
    );

Parameters

NewEnum
[out, retval] Address of an IEnumVARIANT interface pointer that will be set to the returned collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method is provided to enable scripting and VB applications to iterate through the collection in a For...Each loop. C++ applications should use the get_EnumTuningSpaces method.

ITuningSpaceContainer::get_Item

ITuningSpaceContainer Interface

Retrieves an ITuningSpace object at the specified index.

Syntax

HRESULT get_Item(
    VARIANT varIndex,
    ITuningSpace **ppTuningSpace
    );

Parameters

varIndex
[in] Variable of type VARIANT specifying the index of the item to retrieve.
ppTuningSpace
[out, retval] Address of an ITuningSpace interface pointer that will be set to the returned interface.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuningSpaceContainer::put_Item

ITuningSpaceContainer Interface

Saves the Tuning Space object at the specified index.

Syntax

HRESULT put_Item(
    VARIANT varIndex,
    ITuningSpace *pTuningSpace
    );

Parameters

varIndex
[in] Variable of type VARIANT specifying the index of the item to set.
pTuningSpace
[in] Pointer to the ITuningSpace interface on the object that will be persisted to the system.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Using the methods of ITuningSpace, an application can modify an existing Tuning Space and then use ITuningSpaceContainer::put_Item to save the changes to disk.

ITuningSpaceContainer::TuningSpacesForCLSID

ITuningSpaceContainer Interface

Retrieves a collection of Tuning Spaces that match the CLSID string. (For use by Automation clients.)

Syntax

HRESULT TuningSpacesForCLSID(
    BSTR SpaceCLSID,
    ITuningSpaces **ppTuningSpaces
    );

Parameters

SpaceCLSID
[in] String representation of the CLSID of the Tuning Space.
ppTuningSpaces
[out, retval] Address of an ITuningSpaces interface pointer that will be set to the returned collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This method enables Automation clients to specify a CLSID with a BSTR; internally it simply calls _TuningSpacesForCLSID.

ITuningSpaceContainer::_TuningSpacesForCLSID

ITuningSpaceContainer Interface

Retrieves a collection of Tuning Spaces that match the specified CLSID. (For use by C++ clients.)

Syntax

HRESULT _TuningSpacesForCLSID(
    REFCLSID SpaceCLSID,
    ITuningSpaces **ppTuningSpaces
    );

Parameters

SpaceCLSID
[in] Variable of type REFCLSID specifying the type of Tuning Space to retrieve.
ppTuningSpaces
[out, retval] Address of an ITuningSpaces interface pointer that will be set to the returned collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

C++ applications should use this method, not TuningSpacesForCLSID.

ITuningSpaceContainer::TuningSpacesForName

ITuningSpaceContainer Interface

Retrieves a collection of Tuning Spaces that match the specified friendly name.

Syntax

HRESULT TuningSpacesForName(
    BSTR Name,
    ITuningSpaces **ppTuningSpaces
    );

Parameters

Name
[in] String representation of the friendly name for Tuning Space type.
ppTuningSpaces
[out, retval] Address of an ITuningSpaces interface pointer that will be set to the returned collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuningSpaceContainer::FindID

ITuningSpaceContainer Interface

Retrieves the local unique ID number for the specified Tuning Space.

Syntax

HRESULT FindID(
    ITuningSpace *pTuningSpace,
    long *pID
    );

Parameters

pTuningSpace
[in] Pointer to the ITuningSpace interface on the object whose ID will be retrieved.
pID
[out, retval] Pointer to a variable of type long that will receive the ID number.

Return Value

Returns S_OK if successful or E_INVALIDARG if TuningSpace does not point to a valid object.

ITuningSpaceContainer::Add

ITuningSpaceContainer Interface

Adds a new, persistent, Tuning Space to the system.

Syntax

HRESULT Add(
    ITuningSpace *pTuningSpace,
    VARIANT *pNewIndex
    );

Parameters

pTuningSpace
[in] Pointer to the ITuningSpace interface on the new Tuning Space object to be added to the system.
pNewIndex
[out, retval] Pointer to a variable of type VARIANT that will receive the index number of the new Tuning Space in the current collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The ITuningSpaceContainer::Add() method starts adding objects with an index of 1. The IComponentTypes::Add() method and all other collections begin at 0.

ITuningSpaceContainer::get_EnumTuningSpaces

ITuningSpaceContainer Interface

Retrieves a collection of all Tuning Spaces available on the local system.

Syntax

HRESULT get_EnumTuningSpaces(
    IEnumTuningSpaces **ppEnum
    );

Parameters

ppEnum
[out, retval] Address of an IEnumTuningSpaces interface pointer that will be set to the returned collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

C++ applications use this method to get the initial list of Tuning Spaces defined on the local system.

ITuningSpaceContainer::put_MaxCount

ITuningSpaceContainer Interface

Sets the maximum number of tuning spaces allowed on the system.

Syntax

HRESULT put_MaxCount(
    long MaxCount
    );

Parameters

MaxCount
[in] Variable of type long that specifies the maximum number of tuning spaces.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuningSpaceContainer::Remove

ITuningSpaceContainer Interface

Permanently removes a Tuning Space from the system.

Syntax

HRESULT Remove(
    VARIANT Index
    );

Parameters

Index
[in] Variable of type VARIANT specifying the index number of the Tuning Space to remove from the system.

Return Value

Returns S_OK if successful. If the specified Tuning Space was invalid or corrupted in the Registry, this method will delete whatever information is there and return S_FALSE.


ITuner

Microsoft DirectX 8.0

ITuner Interface

ITuner is implemented on the Network Provider filter.

MethodName | Description
get_TuningSpace | Gets the Tuning Space currently in effect for the Network Provider.
put_TuningSpace | Sets the Tuning Space for the Network Provider.
EnumTuningSpaces | Creates a collection of the Tuning Spaces preferred by this implementation.
get_TuneRequest | Gets the Tune Request currently in effect for the Network Provider.
put_TuneRequest | Sets the Tune Request for the Network Provider.
Validate | Returns a value indicating that the Tune Request can be carried out.
get_PreferredComponentTypes | Gets the collection of ComponentType objects used for default component selection.
put_PreferredComponentTypes | Sets the collection of ComponentType objects used for default component selection.
get_SignalStrength | Retrieves the Network Provider-specific signal strength metric.
TriggerSignalEvents | Puts the Network Provider into a mode where ISignalEvents::OnSignal will be repeatedly called.

ITuner::get_TuningSpace

ITuner Interface

Gets the Tuning Space currently in effect for the Network Provider.

Syntax

HRESULT get_TuningSpace(
    ITuningSpace** TuningSpace
    );

Parameters

TuningSpace
[out, retval] Address of an ITuningSpace interface pointer that will be set to the current Tuning Space.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuner::put_TuningSpace

ITuner Interface

Sets the Tuning Space for the Network Provider.

Syntax

HRESULT put_TuningSpace(
    ITuningSpace* TuningSpace
    );

Parameters

TuningSpace
[in] Pointer to the Tuning Space that will be set in the Network Provider.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

ITuner::EnumTuningSpaces

ITuner Interface

Creates a collection of Tuning Spaces preferred by this implementation.

Syntax

HRESULT EnumTuningSpaces(
    IEnumTuningSpaces** ppEnum
    );

Parameters

ppEnum
[out, retval] Address of a IEnumTuningSpaces interface pointer that will be set to the returned collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

This list is a subset of the compatible tuning spaces for this implementation.

ITuner::get_TuneRequest

ITuner Interface

Gets the Tune Request currently in effect for the Network Provider.

Syntax

HRESULT get_TuneRequest(
    ITuneRequest** TuneRequest
    );

Parameters

TuneRequest
[out, retval] Address of an ITuneRequest interface pointer that will be set to the returned object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

After a Tune Request is submitted to the Tuner, its Components collection will be filled in. By calling get_TuneRequest after tuning to the program, an application can determine which components are currently available for that program, and then use the IComponent::put_Status method on the Component objects in the collection to activate or inactivate them. This is how an application, for example, changes from an English audio stream to a Spanish audio stream.

ITuner::put_TuneRequest

ITuner Interface

Sets the Tune Request currently in effect for the Network Provider.

Syntax

HRESULT put_TuneRequest(
    ITuneRequest* TuneRequest
    );

Parameters

TuneRequest
[in] Pointer to an ITuneRequest object that will be used to set the Network Provider.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Calling this method initiates a tuning operation based on the properties of the Tune Request. The tuning operation may be asynchronously attempted.

ITuner::Validate

ITuner Interface

Returns a value indicating that the Tune Request can be carried out.

Syntax

HRESULT Validate(
    ITuneRequest* TuneRequest
    );

Parameters

TuneRequest
[in] Pointer to the Tune Request object

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Takes an IUnknown* as input. the Network Provider will first Query for its preferred Tune Request interface(s). If any are found, the Network Provider will validate that the tune request could be carried out. If none are available, it will then query for its preferred Tuning Space interface(s). If any are found, the Network Provider will validate that if could configure itself for the given tuning space.

ITuner::get_PreferredComponentTypes

ITuner Interface

Gets the collection of ComponentType objects used for default component selection.

Syntax

HRESULT get_PreferredComponentTypes(
    IComponentTypes** ComponentTypes
    );

Parameters

ComponentTypes
[out, retval] Address of an IComponentTypes interface pointer that receives the collection of ComponentType objects.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

When a program ends, there may be a new set of substreams ("components") available, so at that time the Tuner will automatically examine the list of preferred component types and select a substream based on that list. If no list is available, the Tuner will make a selection based on other factors. Applications call this method simply to examine the current list.

ITuner::put_PreferredComponentTypes

ITuner Interface

Sets the collection of ComponentType objects used for default component selection.

Syntax

HRESULT put_PreferredComponentTypes(
    IComponentTypes* ComponentTypes
    );

Parameters

ComponentTypes
[in] Pointer to an IComponentTypes interface that contains the collection of ComponentType objects.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Applications create a list of preferred component types by instantiating an empty ComponentTypes collection, filling it, then submitting it to the Tuner using put_PreferredComponentTypes.

ITuner::get_SignalStrength

ITuner Interface

Retrieves the Network Provider-specific signal strength metric.

Syntax

HRESULT get_SignalStrength(
    long* Strength
    );

Parameters

Strength
[out, retval] Pointer to a variable of type long that receives the signal strength.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

-1 means can't determine, 0 means not tuned, highest value means best signal. For digital tuners, this also accounts for the FEC bit error rate (BER).

ITuner::TriggerSignalEvents

ITuner Interface

Puts the Network Provider into a mode where ISignalEvents::OnSignal will be repeatedly called.

Syntax

HRESULT TriggerSignalEvents(
    long Interval
    );

Parameters

Interval
[in] Variable of type long that specifies the interval at which to send the trigger events.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Returns E_NOTIMPL if this mode isn't supported. Takes an interval in milliseconds, specifying the rate at which Signal events are generated.


Tuning Model Scriptable Objects

The following Automation-compliant objects are accessible from applications written in Microsoft® Visual Basic®, VBScript, and JScript. For DirectX® 8, Automation support for applications based on Broadcast Driver Architecture is limited and it may be easier to simply access these methods directly using C++, since the graph-building code in the application must be written in that language. These Automation objects will become useful with the introduction of the Video Control in future versions of Microsoft Windows®. For this release, the methods and properties of these objects are represented only in JScript syntax. Visual Basic developers can view data type information by viewing the objects in the Object Browser.

Tuning Space Objects

These objects are used to implement a generic way to tune to a particular program independent of the network type or network provider. Applications generally do not use these objects because applications that use the Guide Store do not need to construct their own Tune Requests. Applications obtain ready-made Tune Requests from the Guide Store and submit them to the Video Control.

AnalogRadioTuningSpace | Tuning Space specific to terrestrial Radio networks.
AnalogTVTuningSpace | Tuning Space specific to analog TV networks.
ATSCTuningSpace | Tuning Space specific to ATSC networks.
DVBTuningSpace | Tuning Space specific to DVB networks.
SystemTuningSpaces | Created by applications to create new Tuning Spaces or enumerate or modify existing ones.

Tune Request Objects

Tune requests are created through a call to ITuningSpace::CreateTuneRequest on the Tuning Space object. Applications generally will not create their own TuneRequests, but will obtain them from the Guide Store.

ChannelTuneRequest | Implemented on Tune Request objects specific to analog TV networks.
ATSCChannelTuneRequest | Implemented on Tune request objects specific to ATSC TV networks.
DVBTuneRequest | Implemented on Tune request objects specific to DVB TV networks.

Stream Component Objects

A "component" in this context refers to a substream within a broadcast. The actual components of a broadcast stream can only be discovered after reception begins. The Network Provider at that point will fill in the Component object information.

Component | Base class for specific component Objects.
ComponentType | Base class for specific component type Objects.
ComponentTypes | Provides a standard COM enumeration of component types.
Components | Provides a standard COM enumeration of components.
LanguageComponentType | Component type associated with the language of the substream.
MPEG2ComponentType | Implemented on a component type associated with an MPEG-2 stream type.
ATSCComponentType | Implemented on a component type that indicates whether the audio substream is in AC-3 format.

Locator Objects

Locator objects are used in some cases by the Network Provider and other filters in the graph to determine how and where to tune to implement a Tune Request. These Objects are not used by applications.

Locator | Base class for network-type specific tuning space locators. Not used by applications.
ATSCLocator | Called by the Network Provider to obtain information about tuning within an ATSC network. Not used by applications.
DVBTLocator | Called by the Network Provider to obtain information about tuning within an DVB-T network. Not used by applications.
DVBSLocator | Called by the Network Provider to obtain information about tuning within an DVB-S network. Not used by applications.


AnalogRadioTuningSpace

Microsoft DirectX 8.0

AnalogRadioTuningSpace Object

The AnalogRadioTuningSpace object represents an AM or FM analog radio tuning space.

Method or Property Name | Description
CLSID | Retrieves the CLSID of the tuning space.
CreateTuneRequest | Create a Tune Request object specific to this tuning space.
DefaultLocator | Sets or retrieves the initial default Locator that the Tuner may use after installation.
DefaultPreferredComponentTypes | Components collection object containing the default preferred component types specified by the user or application.
FriendlyName | The localized, user-friendly name of the Tuning Space.
MaxFrequency | largest frequency(khz) ever used by this tuning space.
MinFrequency | The smallest frequency(khz) ever used by this tuning space.
NetworkType | The Network Type CLSID.
Step | The default step value(khz) to next frequency for this tuning space.
UniqueName | The globally unique name of the Tuning Space.

AnalogRadioTuningSpace.CLSID Property

AnalogRadioTuningSpace Object

Retrieves the CLSID of the tuning space.

Syntax

AnalogRadioTuningSpace.CLSID

Remarks

This property is read only.

AnalogRadioTuningSpace.CreateTuneRequest Method

AnalogRadioTuningSpace Object

Create a Tune Request object specific to this tuning space.

Syntax

AnalogRadioTuningSpace.CreateTuneRequest()

Return Value

Returns an TuneRequest object.

AnalogRadioTuningSpace.DefaultLocator Property

AnalogRadioTuningSpace Object

Sets or retrieves the initial default Locator object that the Tuner may use after installation.

Syntax

AnalogRadioTuningSpace.DefaultLocator

Remarks

This property is read-write.

AnalogRadioTuningSpace.DefaultPreferredComponentTypes Property

AnalogRadioTuningSpace Object

Components collection object containing the default preferred component types specified by the user or application.

Syntax

AnalogRadioTuningSpace.DefaultPreferredComponentTypes

Remarks

This property is read-write.

AnalogRadioTuningSpace.FriendlyName Property

AnalogRadioTuningSpace Object

User-friendly name of the Tuning Space.

Syntax

AnalogRadioTuningSpace.FriendlyName

Remarks

This property is read-write.

AnalogRadioTuningSpace.MaxFrequency Property

AnalogRadioTuningSpace Object

Largest frequency(khz) ever used by this tuning space.

Syntax

AnalogRadioTuningSpace.MaxFrequency

Remarks

This property is read-write.

AnalogRadioTuningSpace.MinFrequency Property

AnalogRadioTuningSpace Object

Smallest frequency(khz) ever used by this tuning space.

Syntax

AnalogRadioTuningSpace.MinFrequency

Remarks

This property is read-write.

AnalogRadioTuningSpace.NetworkType Property

AnalogRadioTuningSpace Object

The network Type CLSID.

Syntax

AnalogRadioTuningSpace.NetworkType

Remarks

This property is read-write.

AnalogRadioTuningSpace.Step Property

AnalogRadioTuningSpace Object

Default step value(khz) to next frequency for this tuning space.

Syntax

AnalogRadioTuningSpace.Step

Remarks

This property is read-write.

AnalogRadioTuningSpace.UniqueName Property

AnalogRadioTuningSpace Object

The globally unique name of the Tuning Space.

Syntax

AnalogRadioTuningSpace.UniqueName

Remarks

This property is read-write.


AnalogTVTuningSpace

Microsoft DirectX 8.0

AnalogTVTuningSpace Object

Represents an analog TV tuning space.

Method or Property Name | Description
CLSID | Retrieves the CLSID of the tuning space.
CountryCode | International dialing prefix for country of physical broadcast source.
CreateTuneRequest | Create a Tune Request object.
DefaultLocator | Sets or retrieves the initial default Locator that the Tuner may use after installation.
DefaultPreferredComponentTypes | Components collection object containing the default preferred component types specified by the user or application.
FriendlyName | User-friendly name of the Tuning Space.
InputType | Input type for this tuning space.
MaxChannel | Largest channel number ever provided by this tuning space.
MinChannel | Smallest channel number ever provided by this tuning space.
NetworkType | Network Type (CLSID).
UniqueName | Unique name of the Tuning Space.

AnalogTVTuningSpace.CLSID Property

AnalogTVTuningSpace Object

Retrieves the CLSID of the tuning space.

Syntax

AnalogTVTuningSpace.CLSID

Remarks

This property is read only.

AnalogTVTuningSpace.CountryCode Property

AnalogTVTuningSpace Object

International dialing prefix for country of physical broadcast source.

Syntax

AnalogTVTuningSpace.CountryCode

Remarks

This property is read-write.

AnalogTVTuningSpace.CreateTuneRequest Method

AnalogTVTuningSpace Object

Create a Tune Request object.

Syntax

AnalogTVTuningSpace.CreateTuneRequest()

Return Value

Returns a ChannelTuneRequest object.

AnalogTVTuningSpace.DefaultLocator Property

AnalogTVTuningSpace Object

Sets or retrieves the initial default Locator object that the Tuner may use after installation.

Syntax

AnalogTVTuningSpace.DefaultLocator

Remarks

This property is read-write.

AnalogTVTuningSpace.DefaultPreferredComponentTypes Property

AnalogTVTuningSpace Object

Components collection object containing the default preferred component types specified by the user or application.

Syntax

AnalogTVTuningSpace.DefaultPreferredComponentTypes

Remarks

This property is read-write.

AnalogTVTuningSpace.FriendlyName Property

AnalogTVTuningSpace Object

User-friendly name of the Tuning Space.

Syntax

AnalogTVTuningSpace.FriendlyName

Remarks

This property is read-write.

AnalogTVTuningSpace.InputType Property

AnalogTVTuningSpace Object

Input type for this tuning space.

Syntax

AnalogTVTuningSpace.InputType

Remarks

This property is read-write.

AnalogTVTuningSpace.MaxChannel Property

AnalogTVTuningSpace Object

Largest channel number ever provided by this tuning space.

Syntax

AnalogTVTuningSpace.MaxChannel

Remarks

This property is read-write.

AnalogTVTuningSpace.MinChannel Property

AnalogTVTuningSpace Object

Smallest channel number ever provided by this tuning space.

Syntax

AnalogTVTuningSpace.MinChannel

Remarks

This property is read-write.

AnalogTVTuningSpace.NetworkType Property

AnalogTVTuningSpace Object

Network Type (CLSID).

Syntax

AnalogTVTuningSpace.NetworkType

Remarks

This property is read-write.

AnalogTVTuningSpace.UniqueName Property

AnalogTVTuningSpace Object

Unique name of the Tuning Space.

Syntax

AnalogTVTuningSpace.UniqueName

Remarks

This property is read-write.


ATSCChannelTuneRequest

Microsoft DirectX 8.0

ATSCChannelTuneRequest Object

Represents a tune request valid for ATSC network types.

Method or Property Name | Description
Channel | Channel
Clone | Create a new copy of this tune request.
Components | Components collection.
Locator | Locator Object.
MinorChannel | Minor Channel.
TuningSpace | Tuning Space object.

ATSCChannelTuneRequest.Channel Property

ATSCChannelTuneRequest Object

Channel.

Syntax

ATSCChannelTuneRequest.Channel

Remarks

This property is read-write.

ATSCChannelTuneRequest.Clone Method

ATSCChannelTuneRequest Object

Create a new copy of this tune request.

Syntax

ATSCChannelTuneRequest.Clone()

Return Value

Returns an ATSCChannelTuneRequest object that is a copy of the current object.

ATSCChannelTuneRequest.Components Property

ATSCChannelTuneRequest Object

Components collection.

Syntax

ATSCChannelTuneRequest.Components

Remarks

This property is read only.

ATSCChannelTuneRequest.Locator Property

ATSCChannelTuneRequest Object

Locator Object.

Syntax

ATSCChannelTuneRequest.Locator

Remarks

This property is read-write.

ATSCChannelTuneRequest.MinorChannel Property

ATSCChannelTuneRequest Object

Minor Channel.

Syntax

ATSCChannelTuneRequest.MinorChannel

Remarks

This property is read-write.

ATSCChannelTuneRequest.TuningSpace Property

ATSCChannelTuneRequest Object

Tuning Space object.

Syntax

ATSCChannelTuneRequest.TuningSpace

Remarks

This property is read only.


ATSCComponentType

Microsoft DirectX 8.0

ATSCComponentType Object

Represents an ATSC component type.

Method or Property Name | Description
Category | General category of component.
Clone | Create a copy of this component type.
Flags | ATSC Component Type Flags.
LangID | Language Identifier for Substream Content Language.
StreamType | MPEG2 Stream Type.

ATSCComponentType.Category Property

ATSCComponentType Object

General category of component.

Syntax

ATSCComponentType.Category

Remarks

This property is read-write.

ATSCComponentType.Clone Method

ATSCComponentType Object

Create a copy of this component type.

Syntax

ATSCComponentType.Clone()

Return Value

Returns an ATSCComponentType object that is a copy of the current object.

ATSCComponentType.Flags Property

ATSCComponentType Object

ATSC Component Type Flags.

Syntax

ATSCComponentType.Flags

Possible Values

1 if the audio stream is AC-3; otherwise 0.

Remarks

This property is read-write.

ATSCComponentType.LangID Property

ATSCComponentType Object

Language Identifier for Substream Content Language.

Syntax

ATSCComponentType.LangID

Remarks

This property is read-write.

ATSCComponentType.StreamType Property

ATSCComponentType Object

MPEG2 Stream Type.

Syntax

ATSCComponentType.StreamType

Remarks

This property is read-write.


ATSCLocator

Microsoft DirectX 8.0

ATSCLocator Object

Locator object for an ATSC network type.

Method or Property Name | Description
CarrierFrequency | Carrier Frequency(DecaHertz).
Clone | Copy the Locator.
InnerFEC | Inner Fec Type.
InnerFECRate | Inner Fec Rate.
InnerFECRate | Inner Fec Rate.
Modulation | Modulation Type.
OuterFEC | Outer Fec Type.
OuterFECRate | Outer Fec Rate.
PhysicalChannel | Physical Channel.
TSID | Transport Stream ID.
SymbolRate | Sets or retrieves the QPSK symbol rate.

ATSCLocator.CarrierFrequency Property

ATSCLocator Object

Carrier Frequency(DecaHertz).

Syntax

ATSCLocator.CarrierFrequency

Remarks

This property is read-write.

ATSCLocator.Clone Method

ATSCLocator Object

Copy the Locator.

Syntax

ATSCLocator.Clone()

Return Value

Returns an ATSCLocator object that is a copy of the current object.

ATSCLocator.InnerFEC Property

ATSCLocator Object

Inner Fec Type.

Syntax

ATSCLocator.InnerFEC

Remarks

This property is read-write.

ATSCLocator.InnerFECRate Property

ATSCLocator Object

Inner Fec Rate.

Syntax

ATSCLocator.InnerFECRate

Remarks

This property is read only.

ATSCLocator.InnerFECRate Property

ATSCLocator Object

Inner Fec Rate.

Syntax

ATSCLocator.InnerFECRate

Remarks

This property is read only.

ATSCLocator.Modulation Property

ATSCLocator Object

Modulation Type.

Syntax

ATSCLocator.Modulation

Remarks

This property is read-write.

ATSCLocator.OuterFEC Property

ATSCLocator Object

Outer Fec Type.

Syntax

ATSCLocator.OuterFEC

Remarks

This property is read-write.

ATSCLocator.OuterFECRate Property

ATSCLocator Object

Outer Fec Rate.

Syntax

ATSCLocator.OuterFECRate

Remarks

This property is read-write.

ATSCLocator.PhysicalChannel Property

ATSCLocator Object

Physical Channel.

Syntax

ATSCLocator.PhysicalChannel

Remarks

This property is read-write.

ATSCLocator.TSID Property

ATSCLocator Object

Transport Stream ID.

Syntax

ATSCLocator.TSID

Remarks

This property is read-write.

ATSCLocator.SymbolRate Property

ATSCLocator Object

Sets or retrieves the QPSK symbol rate.

Syntax

ATSCLocator.SymbolRate

Remarks

This property is read-write. QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.


ATSCTuningSpace

Microsoft DirectX 8.0

ATSCTuningSpace Object

Represents a tuning space with an ATSC network type.

Method or Property Name | Description
CLSID | Retrieves the CLSID of the tuning space.
CountryCode | International dialing prefix for country of physical broadcast source.
CreateTuneRequest | Create a Tune Request object.
DefaultLocator | Sets or retrieves the initial default Locator that the Tuner may use after installation.
DefaultPreferredComponentTypes | Components collection object containing the default preferred component types specified by the user or application.
FriendlyName | User-friendly name of the Tuning Space.
InputType | Input type for this tuning space.
MaxChannel | Largest channel number ever provided by this tuning space.
MaxMinorChannel | Largest minor channel number ever provided by this tuning space.
MaxPhysicalChannel | Largest physical channel number ever provided by this tuning space.
MinChannel | Smallest channel number ever provided by this tuning space.
MinMinorChannel | Smallest minor channel number ever provided by this tuning space.
MinPhysicalChannel | Smallest physical channel number ever provided by this tuning space.
NetworkType | Network Type (CLSID).
UniqueName | Unique name of the Tuning Space.
CLSID Retrieves the CLSID of the tuning space.

ATSCTuningSpace.CLSID Property

ATSCTuningSpace Object

International dialing prefix for country of physical broadcast source.

Syntax

ATSCTuningSpace.CLSID

Remarks

This property is read only.

ATSCTuningSpace.CountryCode Property

ATSCTuningSpace Object

International dialing prefix for country of physical broadcast source.

Syntax

ATSCTuningSpace.CountryCode

Remarks

This property is read-write.

ATSCTuningSpace.CreateTuneRequest Method

ATSCTuningSpace Object

Create a Tune Request object.

Syntax

ATSCTuningSpace.CreateTuneRequest()

Return Value

Returns an ATSCChannelTuneRequest object.

ATSCTuningSpace.DefaultLocator Property

ATSCTuningSpace Object

Sets or retrieves the initial default Locator object that the Tuner may use after installation.

Syntax

ATSCTuningSpace.DefaultLocator

Remarks

This property is read-write.

ATSCTuningSpace.DefaultPreferredComponentTypes Property

ATSCTuningSpace Object

Components collection object containing the default preferred component types specified by the user or application.

Syntax

ATSCTuningSpace.DefaultPreferredComponentTypes

Remarks

This property is read-write.

ATSCTuningSpace.FriendlyName Property

ATSCTuningSpace Object

User-friendly name of the Tuning Space.

Syntax

ATSCTuningSpace.FriendlyName

Remarks

This property is read-write.

ATSCTuningSpace.InputType Property

ATSCTuningSpace Object

Input type for this tuning space.

Syntax

ATSCTuningSpace.InputType

Remarks

This property is read-write.

ATSCTuningSpace.MaxChannel Property

ATSCTuningSpace Object

Largest channel number ever provided by this tuning space.

Syntax

ATSCTuningSpace.MaxChannel

Remarks

This property is read-write.

ATSCTuningSpace.MaxMinorChannel Property

ATSCTuningSpace Object

Largest minor channel number ever provided by this tuning space.

Syntax

ATSCTuningSpace.MaxMinorChannel

Remarks

This property is read-write. This property must be set before setting the MinMinorChannel property to avoid the case where the minimum minor channel is greater than the maximum minor channel. Both properties default to -1 (not set).

ATSCTuningSpace.MaxPhysicalChannel Property

ATSCTuningSpace Object

Largest physical channel number ever provided by this tuning space.

Syntax

ATSCTuningSpace.MaxPhysicalChannel

Remarks

This property is read-write.

ATSCTuningSpace.MinChannel Property

ATSCTuningSpace Object

Smallest channel number ever provided by this tuning space.

Syntax

ATSCTuningSpace.MinChannel

Remarks

This property is read-write.

ATSCTuningSpace.MinMinorChannel Property

ATSCTuningSpace Object

Smallest minor channel number ever provided by this tuning space.

Syntax

ATSCTuningSpace.MinMinorChannel

Remarks

This property is read-write. This property must be set after setting the MaxMinorChannel property to avoid the case where the minimum minor channel is greater than the maximum minor channel. Both properties default to -1 (not set).

ATSCTuningSpace.MinPhysicalChannel Property

ATSCTuningSpace Object

Smallest physical channel number ever provided by this tuning space.

Syntax

ATSCTuningSpace.MinPhysicalChannel

Remarks

This property is read-write.

ATSCTuningSpace.MinPhysicalChannel Property

ATSCTuningSpace Object

Smallest physical channel number ever provided by this tuning space.

Syntax

ATSCTuningSpace.MinPhysicalChannel

Remarks

This property is read only.

ATSCTuningSpace.NetworkType Property

ATSCTuningSpace Object

Network Type (CLSID).

Syntax

ATSCTuningSpace.NetworkType

Remarks

This property is read-write.

ATSCTuningSpace.UniqueName Property

ATSCTuningSpace Object

Unique name of the Tuning Space.

Syntax

ATSCTuningSpace.UniqueName

Remarks

This property is read-write.


ChannelTuneRequest Object

Represents a tune request valid for an analog TV network type.

Method or Property Name | Description
Channel | Gets or sets the channel for this Tune Request.
Clone | Create a new copy of this tune request.
Components | Components collection.
Locator | Locator Object.
TuningSpace | Tuning Space object.

ChannelTuneRequest.Channel Property

ChannelTuneRequest Object

Channel.

Syntax

ChannelTuneRequest.Channel

Remarks

This property is read-write. If the value specified for Channel is less than the minimum channel set for the Tuning Space, it will "wrap around" to the maximum channel value. Likewise, if the value specified for Channel is greater than the maximum channel set for the Tuning Space, it will "wrap around" to the minimum channel value.

ChannelTuneRequest.Clone Method

ChannelTuneRequest Object

Create a new copy of this tune request.

Syntax

ChannelTuneRequest.Clone(NewTuneRequest)

Return Value

Returns a ChannelTuneRequest object that is a copy of the current object.

ChannelTuneRequest.Components Property

ChannelTuneRequest Object

Components collection.

Syntax

ChannelTuneRequest.Components

Remarks

This property is read only.

ChannelTuneRequest.Locator Property

ChannelTuneRequest Object

Locator Object.

Syntax

ChannelTuneRequest.Locator

Remarks

This property is read-write.

ChannelTuneRequest.TuningSpace Property

ChannelTuneRequest Object

Tuning Space object.

Syntax

ChannelTuneRequest.TuningSpace

Remarks

This property is read only.


Component

Microsoft DirectX 8.0

Component Object

Represents a component or substream on the current broadcast stream.

Method or Property Name | Description
Clone | Copy Component.
DescLangID | Language Identifier for Description Language.
Description | Component Description.
Status | Component Status.
Type | Component Type.

Component.Clone Method

Component Object

Copy Component.

Syntax

Component.Clone()

Return Value

Returns a Component object that is a copy of the current object.

Component.DescLangID Property

Component Object

Language Identifier for Description Language.

Syntax

Component.DescLangID

Remarks

This property is read-write.

Component.Description Property

Component Object

Component Description.

Syntax

Component.Description

Remarks

This property is read only.

Component.Status Property

Component Object

Component Status.

Syntax

Component.Status

Remarks

This property is read-write.

Component.Type Property

Component Object

Component Type.

Syntax

Component.Type

Remarks

This property is read only.


Components

Microsoft DirectX 8.0

Components Object

Represents a collection of Component objects.

Method or Property Name | Description
Add | Add the Component to the collection.
Clone | Create a new copy of this object.
Count | Number of items in the collection.
Item | Get the Component at the specified index.
Remove | Remove the Component at the specified index.

Components.Add Method

Components Object

Add the Component to the collection.

Syntax

Components.Add(Component)

Parameters

Component The Component object to add to the collection..

Return Value

If successful, returns the index value for the newly-added object.

Remarks

See Also

Components.Clone Method

Components Object

Create a new copy of this object.

Syntax

Components.Clone

Remarks

See Also

Components.Count Property

Components Object

Number of items in the collection.

Syntax

Components.Count

Remarks

This property is read only.

See Also

Components.Item Property

Components Object

Get the Component at the specified index.

Syntax

Components.Item(Index,ppComponent)

Parameters

Index The index of the item to retrieve..

Possible Values

Returns a Component object.

Remarks

This property is read only.

See Also

Components.Remove Method

Components Object

Remove the Component at the specified index.

Syntax

Components.Remove(Index)

Parameters

Index Index value of the Component object to remove from the collection.

Return Value

Remarks

See Also


ComponentType

Microsoft DirectX 8.0

ComponentType Object

In DVB program streams, a component refers to an elementary stream, such as an audio stream. The ComponentType object describes the properties of that elementary stream.

Method or Property Name | Description
Category | General category of component.
Clone | Create a copy of this component type.
MediaFormatType | DirectShow MediaType Format GUID.
MediaMajorType | DirectShow MediaType Major Type GUID.
MediaSubType | DirectShow MediaType Sub Type GUID.

ComponentType.Category Property

ComponentType Object

General category of component.

Syntax

ComponentType.Category

Remarks

This property is read-write.

See Also

ComponentType.Clone Method

ComponentType Object

Create a copy of this component type.

Syntax

ComponentType.Clone();

Return Value

Returns a new ComponentType object whose values are identical to the current object.

Remarks

See Also

ComponentType.MediaFormatType Property

ComponentType Object

DirectShow MediaType Format GUID.

Syntax

ComponentType.MediaFormatType

Remarks

This property is read-write.

See Also

ComponentType.MediaMajorType Property

ComponentType Object

DirectShow MediaType Major Type GUID.

Syntax

ComponentType.MediaMajorType

Remarks

This property is read-write.

See Also

ComponentType.MediaSubType Property

ComponentType Object

DirectShow MediaType Sub Type GUID.

Syntax

ComponentType.MediaSubType

Remarks

This property is read-write.

See Also


ComponentTypes

Microsoft DirectX 8.0

ComponentTypes Object

Represents a collection of ComponentType objects.

Method or Property Name | Description
Add | Append the ComponentType to the collection.
Clone | Create a copy of this collection.
Count | Number of items in the collection.
Item | Get the ComponentType at the specified index.
Remove | Clear the collection.

ComponentTypes.Add Method

ComponentTypes Object

Append the ComponentType to the collection.

Syntax

ComponentTypes.Add(ComponentType)

Parameters

ComponentType The ComponentType object to add to the collection.

Return Value

If successful, returns the index value of the newly-added object.

Remarks

See Also

ComponentTypes.Clone Method

ComponentTypes Object

Create a new copy of this object.

Syntax

ComponentTypes.Clone

ComponentTypes.Count Property

ComponentTypes Object

Number of items in the collection.

Syntax

ComponentTypes.Count

Remarks

This property is read only.

See Also

ComponentTypes.Item Property

ComponentTypes Object

Get the ComponentType at the specified index.

Syntax

ComponentTypes.Item(Index,ComponentType)

Parameters

Index Index of the ComponentType object in the collection.

Possible Values

Returns a ComponentType object.

Remarks

This property is read-write.

See Also

ComponentTypes.Remove Method

ComponentTypes Object

Clear the collection.

Syntax

ComponentTypes.Remove(Index)

Parameters

Index Index of the ComponentType object to remove.

Return Value

Remarks

See Also


DVBSLocator

Microsoft DirectX 8.0

DVBSLocator Object

Locator object for a DVBS network type.

Method or Property Name | Description
Azimuth | Azimuth in tenths of a degree.
CarrierFrequency | Carrier Frequency(DecaHertz).
Clone | Copy the Locator.
Elevation | Elevation of the satellite in tenths of a degree.
InnerFEC | Inner FEC Type.
InnerFECRate | Inner FEC Rate.
Modulation | Modulation Type.
OrbitalPosition | Longitude in tenths of a degree.
OuterFEC | Outer FEC Type.
OuterFECRate | Outer FEC Rate.
SignalPolarisation | Signal Polarisation Type.
SymbolRate | Sets or retrieves the QPSK symbol rate.
WestPosition | VARIANT_TRUE means orbital position specifies west longitude.

DVBSLocator.Azimuth Property

DVBSLocator Object

Azimuth in tenths of a degree.

Syntax

DVBSLocator.Azimuth

Remarks

This property is read-write.

DVBSLocator.CarrierFrequency Property

DVBSLocator Object

Carrier Frequency(DecaHertz).

Syntax

DVBSLocator.CarrierFrequency

Remarks

This property is read-write.

DVBSLocator.Clone Method

DVBSLocator Object

Copy the Locator.

Syntax

DVBSLocator.Clone()

Return Value

Returns a DVBSLocator object that is a copy of the current object.

DVBSLocator.Elevation Property

DVBSLocator Object

Elevation of the satellite in tenths of a degree.

Syntax

DVBSLocator.Elevation

Remarks

This property is read-write.

DVBSLocator.InnerFEC Property

DVBSLocator Object

Inner FEC Type.

Syntax

DVBSLocator.InnerFEC

Remarks

This property is read-write.

DVBSLocator.InnerFECRate Property

DVBSLocator Object

Inner FEC Rate.

Syntax

DVBSLocator.InnerFECRate

Remarks

This property is read only.

DVBSLocator.Modulation Property

DVBSLocator Object

Modulation Type.

Syntax

DVBSLocator.Modulation

Remarks

This property is read-write.

DVBSLocator.OrbitalPosition Property

DVBSLocator Object

Longitude in tenths of a degree.

Syntax

DVBSLocator.OrbitalPosition

Remarks

This property is read-write.

DVBSLocator.OuterFEC Property

DVBSLocator Object

Outer FEC Type.

Syntax

DVBSLocator.OuterFEC

Remarks

This property is read-write.

DVBSLocator.OuterFECRate Property

DVBSLocator Object

Outer FEC Rate.

Syntax

DVBSLocator.OuterFECRate

Remarks

This property is read-write.

DVBSLocator.SignalPolarisation Property

DVBSLocator Object

Signal Polarisation Type.

Syntax

DVBSLocator.SignalPolarisation

Remarks

This property is read-write.

DVBSLocator.SymbolRate Property

DVBSLocator Object

Sets or retrieves the QPSK symbol rate.

Syntax

DVBSLocator.SymbolRate

Remarks

This property is read-write. QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.

See Also

DVBSLocator.WestPosition Property

DVBSLocator Object

VARIANT_TRUE means orbital position specifies west longitude.

Syntax

DVBSLocator.WestPosition

Remarks

This property is read-write.


DVBTLocator

Microsoft DirectX 8.0

DVBTLocator Object

Locator object for a DVBT network type.

Method or Property Name | Description
Bandwidth | Bandwidth.
CarrierFrequency | Carrier Frequency(DecaHertz).
Clone | Copy the Locator.
Guard | Guard Interval.
HAlpha | Hierarchical Alpha.
InnerFEC | Inner Fec Type.
InnerFECRate | Inner Fec Rate.
InnerFECRate | Inner Fec Rate.
LPInnerFEC | Inner Fec Type for Low Priority Stream.
LPInnerFECRate | Inner Fec Rate for Low Priority Stream.
Mode | Transmission Mode.
Modulation | Modulation Type.
OtherFrequencyInUse | Hierarchical Alpha.
OuterFEC | Outer Fec Type.
OuterFECRate | Outer Fec Rate.
SymbolRate | Sets or retrieves the QPSK symbol rate.

DVBTLocator.Bandwidth Property

DVBTLocator Object

Bandwidth.

Syntax

DVBTLocator.Bandwidth

Remarks

This property is read-write.

DVBTLocator.CarrierFrequency Property

DVBTLocator Object

Carrier Frequency(DecaHertz).

Syntax

DVBTLocator.CarrierFrequency

Remarks

This property is read-write.

DVBTLocator.Clone Method

DVBTLocator Object

Copy the Locator.

Syntax

DVBTLocator.Clone()

Return Value

Returns a DVBTLocator object that is a copy of the current object.

DVBTLocator.Guard Property

DVBTLocator Object

Guard Interval.

Syntax

DVBTLocator.Guard

Remarks

This property is read-write.

DVBTLocator.HAlpha Property

DVBTLocator Object

Hierarchical Alpha.

Syntax

DVBTLocator.HAlpha

Remarks

This property is read-write.

DVBTLocator.InnerFEC Property

DVBTLocator Object

Inner Fec Type.

Syntax

DVBTLocator.InnerFEC

Remarks

This property is read-write.

DVBTLocator.InnerFECRate Property

DVBTLocator Object

Inner Fec Rate.

Syntax

DVBTLocator.InnerFECRate

Remarks

This property is read only.

DVBTLocator.InnerFECRate Property

DVBTLocator Object

Inner Fec Rate.

Syntax

DVBTLocator.InnerFECRate

Remarks

This property is read only.

DVBTLocator.LPInnerFEC Property

DVBTLocator Object

Inner Fec Type for Low Priority Stream.

Syntax

DVBTLocator.LPInnerFEC

Remarks

This property is read-write.

DVBTLocator.LPInnerFECRate Property

DVBTLocator Object

Inner Fec Rate for Low Priority Stream.

Syntax

DVBTLocator.LPInnerFECRate

Remarks

This property is read-write.

DVBTLocator.Mode Property

DVBTLocator Object

Transmission Mode.

Syntax

DVBTLocator.Mode

Remarks

This property is read-write.

DVBTLocator.Modulation Property

DVBTLocator Object

Modulation Type.

Syntax

DVBTLocator.Modulation

Remarks

This property is read-write.

DVBTLocator.OtherFrequencyInUse Property

DVBTLocator Object

Hierarchical Alpha.

Syntax

DVBTLocator.OtherFrequencyInUse

Remarks

This property is read-write.

DVBTLocator.OuterFEC Property

DVBTLocator Object

Outer Fec Type.

Syntax

DVBTLocator.OuterFEC

Remarks

This property is read-write.

DVBTLocator.OuterFECRate Property

DVBTLocator Object

Outer Fec Rate.

Syntax

DVBTLocator.OuterFECRate

Remarks

This property is read-write.

DVBTLocator.SymbolRate Property

DVBTLocator Object

Sets or retrieves the QPSK symbol rate.

Syntax

DVBTLocator.SymbolRate

Remarks

This property is read-write. QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.

See Also


DVBTuneRequest

Microsoft DirectX 8.0

DVBTuneRequest Object

Represents a tune request valid for a DVB network type.

Method or Property Name | Description
Clone | Create a new copy of this tune request.
Components | Components collection.
Locator | Locator Object.
ONID | Original Network ID.
SID | Service ID.
TSID | Transport Stream ID.
TuningSpace | Tuning Space object.

DVBTuneRequest.Clone Method

DVBTuneRequest Object

Create a new copy of this tune request.

Syntax

DVBTuneRequest.Clone()

Return Value

Returns a DVBTuneRequest object that is a copy of the current object.

DVBTuneRequest.Components Property

DVBTuneRequest Object

Components collection.

Syntax

DVBTuneRequest.Components

Remarks

This property is read only.

DVBTuneRequest.Locator Property

DVBTuneRequest Object

Locator Object.

Syntax

DVBTuneRequest.Locator

Remarks

This property is read-write.

DVBTuneRequest.ONID Property

DVBTuneRequest Object

Original Network ID.

Syntax

DVBTuneRequest.ONID

Remarks

This property is read-write.

DVBTuneRequest.SID Property

DVBTuneRequest Object

Service ID.

Syntax

DVBTuneRequest.SID

Remarks

This property is read-write.

DVBTuneRequest.TSID Property

DVBTuneRequest Object

Transport Stream ID.

Syntax

DVBTuneRequest.TSID

Remarks

This property is read-write.

DVBTuneRequest.TuningSpace Property

DVBTuneRequest Object

Tuning Space object.

Syntax

DVBTuneRequest.TuningSpace

Remarks

This property is read only.


DVBTuningSpace Object

Represents a tuning space with a DVB network type.

Method or Property Name | Description
CLSID | Retrieves the CLSID of the tuning space.
CreateTuneRequest | Create a DVBTuneRequest object.
DefaultLocator | Sets or retrieves the initial default Locator that the Tuner may use after installation.
DefaultPreferredComponentTypes | Components collection object containing the default preferred component types specified by the user or application.
FrequencyMapping | Sets or retrieves a string containing channel-frequency mappings as defined by the Network Provider.
FriendlyName | User-friendly name of the Tuning Space.
NetworkType | Network Type (CLSID).
SystemType | Type of DVB System.
UniqueName | Unique name of the Tuning Space.

DVBTuningSpace.CLSID Property

DVBTuningSpace Object

Retrieves the CLSID of the tuning space.

Syntax

DVBTuningSpace.CLSID

Remarks

This property is read only.

DVBTuningSpace.CreateTuneRequest Method

DVBTuningSpace Object

Create a DVBTuneRequest object.

Syntax

DVBTuningSpace.CreateTuneRequest()

Return Value

Returns a DVBTuneRequest object.

DVBTuningSpace.DefaultLocator Property

DVBTuningSpace Object

Sets or retrieves the initial default Locator object that the Tuner may use after installation.

Syntax

DVBTuningSpace.DefaultLocator

Remarks

This property is read-write.

DVBTuningSpace.DefaultPreferredComponentTypes Property

DVBTuningSpace Object

Components collection object containing the default preferred component types specified by the user or application.

Syntax

DVBTuningSpace.DefaultPreferredComponentTypes

Remarks

This property is read-write.

DVBTuningSpace.FrequencyMapping Property

DVBTuningSpace Object

Sets or retrieves a string containing channel-frequency mappings as defined by the Network Provider.

Syntax

DVBTuningSpace.FrequencyMapping

Possible Values

A String containing the mapping table defined by the Network Provider.

Remarks

This property is read-write. The string can contain a frequency/channel map, frequency/transponder map, or whatever other mapping from carrier frequencies to frequency identifiers is appropriate for the tuning space.

DVBTuningSpace.FriendlyName Property

DVBTuningSpace Object

User-friendly name of the Tuning Space.

Syntax

DVBTuningSpace.FriendlyName

Remarks

This property is read-write.

DVBTuningSpace.NetworkType Property

DVBTuningSpace Object

Network Type (CLSID).

Syntax

DVBTuningSpace.NetworkType

Remarks

This property is read-write.

DVBTuningSpace.SystemType Property

DVBTuningSpace Object

Type of DVB System.

Syntax

DVBTuningSpace.SystemType

Remarks

This property is read-write.

DVBTuningSpace.UniqueName Property

DVBTuningSpace Object

Unique name of the Tuning Space.

Syntax

DVBTuningSpace.UniqueName

Remarks

This property is read-write.


LanguageComponentType

Microsoft DirectX 8.0

LanguageComponentType Object

Represents the language component type for a single component (substream) in a broadcast stream.

Method or Property Name | Description
Category | General category of component.
Clone | Create a copy of this component type.
LangID | Language Identifier for Substream Content Language.

LanguageComponentType.Category Property

LanguageComponentType Object

General category of component.

Syntax

LanguageComponentType.Category

Remarks

This property is read-write.

LanguageComponentType.Clone Method

LanguageComponentType Object

Create a copy of this component type.

Syntax

LanguageComponentType.Clone()

Return Value

Returns a LanguageComponentType object that is a copy of the current object.

LanguageComponentType.LangID Property

LanguageComponentType Object

Language Identifier for Substream Content Language.

Syntax

LanguageComponentType.LangID

Remarks

This property is read-write.


MPEG2Component

Microsoft DirectX 8.0

MPEG2Component Object

Represents a single component (substream) in an MPEG-2 broadcast stream.

Method or Property Name | Description
Clone | Copy Component.
DescLangID | Language Identifier for Description Language.
Description | Component Description.
PCRPID | MPEG2 Packet ID for this Substream's Timestamps.
PID | MPEG2 Packet ID for this Substream.
ProgramNumber | MPEG2 Program Number.
Status | Component Status.
Type | Component Type.

MPEG2Component.Clone Method

MPEG2Component Object

Copy Component.

Syntax

MPEG2Component.Clone()

Return Value

Returns an MPEG2Component object that is a copy of the current object.

MPEG2Component.DescLangID Property

MPEG2Component Object

Language Identifier for Description Language.

Syntax

MPEG2Component.DescLangID

Remarks

This property is read-write.

MPEG2Component.Description Property

MPEG2Component Object

Component Description.

Syntax

MPEG2Component.Description

Remarks

This property is read only.

MPEG2Component.PCRPID Property

MPEG2Component Object

MPEG2 Packet ID for this Substream's Timestamps.

Syntax

MPEG2Component.PCRPID

Remarks

This property is read-write.

MPEG2Component.PID Property

MPEG2Component Object

MPEG2 Packet ID for this Substream.

Syntax

MPEG2Component.PID

Remarks

This property is read-write.

MPEG2Component.ProgramNumber Property

MPEG2Component Object

MPEG2 Program Number.

Syntax

MPEG2Component.ProgramNumber

Remarks

This property is read-write.

MPEG2Component.Status Property

MPEG2Component Object

Component Status.

Syntax

MPEG2Component.Status

Remarks

This property is read-write.

MPEG2Component.Type Property

Object

Component Type.

Syntax

MPEG2Component.Type

Remarks

This property is read only.


MPEG2ComponentType

Microsoft DirectX 8.0

MPEG2ComponentType Object

Represents the stream type for a single component in an MPEG-2 stream.

Method or Property Name | Description
Category | General category of component.
Clone | Create a copy of this component type.
LangID | Language Identifier for Substream Content Language.
StreamType | MPEG2 Stream Type.

MPEG2ComponentType.Category Property

MPEG2ComponentType Object

General category of component.

Syntax

MPEG2ComponentType.Category

Remarks

This property is read-write.

MPEG2ComponentType.Clone Method

MPEG2ComponentType Object

Create a copy of this component type.

Syntax

MPEG2ComponentType.Clone()

Return Value

Returns an MPEG2ComponentType object that is a copy of the current object.

MPEG2ComponentType.LangID Property

MPEG2ComponentType Object

Language Identifier for Substream Content Language.

Syntax

MPEG2ComponentType.LangID

Remarks

This property is read-write.

MPEG2ComponentType.StreamType Property

MPEG2ComponentType Object

MPEG2 Stream Type.

Syntax

MPEG2ComponentType.StreamType

Remarks

This property is read-write.


SystemTuningSpaces Object

The SystemTuningSpaces Object contains a collection of all Tuning Spaces currently available on the local system and provides methods for adding new tuning spaces or removing existing ones.

Method or Property Name | Description
Add | Add a new Tuning Space to the collection. This tuning space will be persisted unless removed
Count | Number of items in the collection.
FindID | Find Local ID Number of the specified Tuning Space.
Item | Find the Tuning Space with the specified Index or update an existing tuning space in the collection.
MaxCount | Retrieve the maximum number of items allowed in the collection.
Remove | Remove a Tuning Space from the collection. this tuning space will be deleted from the registry.
TuningSpacesForCLSID | Returns the collection of Tuning Spaces with the same implementation.
TuningSpacesForName | Returns the collection of Tuning Spaces matching the name.

SystemTuningSpaces.Add Method

SystemTuningSpaces Object

Add a new Tuning Space to the collection. This tuning space will be persisted unless removed.

Syntax

SystemTuningSpaces.Add(TuningSpace)

Parameters

TuningSpace The tuning space object to add (ATSCTuningSpace, DVBTuningSpace, etc.).

Return Value

If successful, returns the index of the newly-added object.

SystemTuningSpaces.Count Property

SystemTuningSpaces Object

Number of items in the collection.

Syntax

SystemTuningSpaces.Count

Remarks

This property is read only.

SystemTuningSpaces.FindID Method

SystemTuningSpaces Object

Find the local unique ID Number of the specified tuning space.

Syntax

SystemTuningSpaces.FindID(TuningSpace)

Parameters

TuningSpace The object whose ID you wish to retrieve.

Return Value

If successful, returns the ID of the specified object.

SystemTuningSpaces.Item Property

SystemTuningSpaces Object

Find the Tuning Space with the specified Index or update an existing tuning space in the collection.

Syntax

SystemTuningSpaces.Item(varIndex)

Parameters

varIndex The index of the tuning space object to set or retrieve.

Possible Values

Any valid tuning space object (ATSCTuningSpace, DVBTuningSpace, etc.)

Remarks

This property is read-write. Setting the Tuning Space object will persist the change to the backing store.

SystemTuningSpaces.MaxCount Property

SystemTuningSpaces Object

Retrieve the maximum number of items allowed in the collection.

Syntax

SystemTuningSpaces.MaxCount

Remarks

This property is read only from script. A C++ application can modify this value or it can also be modified in the registry.

SystemTuningSpaces.Remove Property

SystemTuningSpaces Object

Remove a Tuning Space from the collection. This tuning space will be deleted from the registry.

Syntax

SystemTuningSpaces.Remove

Remarks

This property is read-write.

SystemTuningSpaces.TuningSpacesForCLSID Method

SystemTuningSpaces Object

Returns the collection of Tuning Spaces with the same implementation.

Syntax

SystemTuningSpaces.TuningSpacesForCLSID(SpaceCLSID)

Parameters

SpaceCLSID The CLSID of the tuning spaces to search for.

Return Value

If successful, returns a SystemTuningSpaces object containing a collection of tuning space objects matching the CLSID.

SystemTuningSpaces.TuningSpacesForName Method

SystemTuningSpaces Object

Returns the collection of Tuning Spaces matching the name.

Syntax

SystemTuningSpaces.TuningSpacesForName(Name)

Parameters

Name The locally unique name of the Tuning Spaces to search for.

Return Value

If successful, returns a SystemTuningSpaces object containing the tuning spaces that match the specified name.


Writing DirectShow Filters

If you are developing a filter for use in a Microsoft® DirectShow® filter graph, read the articles in this section. Application developers in general should not be concerned with these topics since applications do not access filters or the filter graph at the level discussed in this section.

  • DirectShow Architecture for Filter Developers
  • DirectShow and COM
  • Transform Filters
  • Video Renderers
  • Capture Filters
  • Exposing Capture and Compression Formats
  • Filter Categories
  • File Formats


DirectShow Architecture for Filter Developers

This section describes the Microsoft® DirectShow® architecture at a level of detail appropriate to filter development. Before reading the articles in this section, you should read the articles in Getting Started. If you are writing a DirectShow application but not developing any filters, you can probably safely skip this section, or else skim through it.

  • How Filters Connect
  • Data Flow for Filter Developers
  • Time and Clocks in DirectShow
  • Quality-Control Management


How Filters Connect

This article describes how filters connect in Microsoft® DirectShow®. The article is intended for filter developers. If you are writing a DirectShow application, you can probably ignore the details presented here.

This article contains the following topics:

  • Pin Connections
  • Negotiating Media Types
  • Negotiating Allocators
  • Reconnecting Pins

Pin Connections

Filters connect at their pins, through the IPin interface. Output pins connect to input pins. Each pin connection has a media type, described by the AM_MEDIA_TYPE structure.

An application connects filters by calling methods on the filter graph manager, never by calling methods on the filters or pins themselves. The application can directly specify the filters to connect, by calling the IFilterGraph::ConnectDirect or IGraphBuilder::Connect method. Or it can connect filters indirectly with one of the graph-building methods, such as IGraphBuilder::RenderFile.

For the connection to succeed, both filters must be in the filter graph. The application can add a filter to the graph by calling the IFilterGraph::AddFilter method. The filter graph manager can also create filters add them to the graph. In either case, the filter graph manager calls the filter's IBaseFilter::JoinFilterGraph method to notify the filter.

The general outline of the connection process is the following:

  1. The filter graph manager calls IPin::Connect on the output pin, passing a pointer to the input pin.
  2. If the output pin accepts the connection, it calls IPin::ReceiveConnection on the input pin.
  3. If the input pin also accepts the connection, the connection attempt succeeds and the pins are connected.

Some pins can be disconnected and reconnected while the filter is active. This type of reconnection is called a dynamic reconnection. For more information, see Dynamic Graph Building. However, most filters do not support dynamic reconnection.

Filters are usually connected in downstream order—in other words, the filter's input pins are connected before its output pins. A filter should always support this order of connection. Some filters also support connections in the opposite order—output pins first, followed by input pins. For example, it might be possible to connect a MUX filter's output pin to a file-writer filter, before connecting the MUX filter's input pins.

Negotiating Media Types

When the filter graph manager calls the IPin::Connect method, it has several options for specifying a media type:

  • Complete type: If the media type is fully specified, the pins attempt to connect with that type. If they cannot, the connection attempt fails.
  • Partial media type: A media type is partial if the major type, subtype, or format type is GUID_NULL. The value GUID_NULL acts as a "wildcard," indicating that any value is acceptable. The pins negotiate a type that is consistent with the partial type.
  • No media type: If the filter graph manager passes a NULL pointer, the pins can agree to any media type that is acceptable to both pins.

If the pins do connect, the connection always has a complete media type. The purpose of the media type given by the filter graph manager is to limit the possible connection types.

During the negotiation process, the output pin proposes a media type by calling the input pin's IPin::ReceiveConnection method. The input pin can accept or reject the proposed type. This process repeats until either the input pin accepts a type, or the output pin runs out of types and the connection fails.

How an output pin selects media types to propose depends on the implementation. In the DirectShow base classes, the output pin calls IPin::EnumMediaTypes on the input pin. This method returns an enumerator that enumerates the input pin's preferred media types. Failing that, the output pin enumerates its own preferred types.

Negotiating Allocators

When two pins connect, they need a mechanism for exchanging media data. The mechanism is called the transport. In general, the DirectShow architecture is neutral about transports. Two filters can agree to connect using any transport that both support.

The most common transport is the local memory transport. With this transport, media data is held in main memory. An object called an allocator is responsible for allocating memory buffers. The allocator supports the IMemAllocator interface. (For more information, see Data Flow in the Filter Graph.) Input pins support local memory transport by exposing the IMemInputPin interface. The output pin queries for the interface during the connection process.

Both pins share the same allocator. When they connect, the pins negotiate which pin will supply the allocator, as follows:

  1. Optionally, the output pin calls IMemInputPin::GetAllocatorRequirements. This method retrieves the input pin's buffer requirements, such as memory alignment. In general, the output pin should honor the input pin's request, unless there is a good reason not to.
  2. Optionally, the output pin calls IMemInputPin::GetAllocator. This method requests an allocator from the input pin. The input pin provides one, or returns an error code.
  3. The output pin selects an allocator. It can use one provided by the input pin, or provide one itself. The outpin calls IMemInputPin::NotifyAllocator to inform the input pin of the selection.

Note that step 3 is the only required step in this process.

If a filter chooses an allocator from a downstream input pin, the filter must use the allocator only to deliver samples to that input pin. It must not use the allocator to deliver samples to other pins.

Reconnecting Pins

During a pin connection, a filter might need to disconnect and reconnect one of its other pins. For example:

  • Suppose that a filter's input pin is already connected with a certain media type. When the output pin attempts to connect, it might be unable to find a media type compatible with the input type. To complete the downstream connection, the filter must reconnect the input pin, using another type.
  • To reduce copying, some transform filters modify data in place. (See the CTransInPlacerFilter base class for an example.) The filter does not provide its own allocator. When the output pin connects, the filter reconnects the input pin and offers the downstream filter's allocator to the upstream filter. In this way, all three filters can share one allocator, minimizing the total buffer requirements.

To reconnect, the filter calls IFilterGraph::Reconnect or IFilterGraph2::ReconnectEx on the filter graph manager. The filter graph manager asynchronously disconnects and reconnects the pins. The ReconnectEx method is preferable, because it specifies a media type. Otherwise, the filter that initiates the reconnection must store the intended media type internally.

The filter must not attempt a reconnection unless the new connection is guaranteed to succeed. Otherwise, the pin will be left disconnected, causing graph errors. If the filter reconnects with a new media type, it must specify a media type known to be valid. If in doubt, call the IPin::QueryAccept method.

Also, the filter should request the reconnection from inside the IPin::Connect method, on the same thread. If the IPin::Connect method returns on one thread, while another thread makes the reconnection request, the filter graph manager might run the graph before it makes the reconnection, causing graph errors.


Data Flow for Filter Developers

This article describes in detail how data moves through the filter graph. It is intended for developers who are writing their own custom filters. For a general introduction to how Microsoft® DirectShow® handles data flow, see Data Flow in the Filter Graph.

This article focuses on the local memory transport, using the IMemInputPin and IMemAllocator interfaces. It contains the following sections:

  • Push versus Pull
  • Generating New Samples
  • Processing a Sample
  • New Segment
  • End of Stream
  • Flushing
  • Threads and Critical Sections

Push versus Pull

The role of a source filter is to introduce data into the graph. It can follow one of two models, the push model or the pull model.

  • In the push model, the source filter creates samples on its own thread and delivers them to the downstream filter. The downstream filter processes the samples and delivers them to the next filter. Each filter repeats these steps, until the samples reach the renderer.
  • In the pull model, the filter that is immediately downstream from the source filter requests data from the source filter. The downstream filter delivers the samples to the next filter, as in the push model.

The push model is typical of live sources, such as video cameras. The pull model is typical of file readers, where the downstream filter is a file parser, such as the AVI Splitter filter.

Generating New Samples

This section describes how source filters generate media samples.

Push Model

In the push model, the source filter initiates the process, as follows:

  1. The source filter calls IMemAllocator::GetBuffer to retrieve an empty media sample.
  2. The source filter fills the media sample with data. How this occurs depends entirely on the nature of the source.
  3. The source filter calls IMemInputPin::Receive on the downstream input pin, passing it a pointer to the sample's IMediaSample interface.
  4. The downstream filter can either process the sample before returning from Receive, or else hold the sample and process it afterward. If the downstream filter holds the sample, it calls IUnknown::AddRef on the sample.
  5. The source filter calls IUnknown::Release on the sample.

At this point, the downstream filter might hold a reference count on the sample, so the source filter cannot simply re-use the sample. To deliver the next sample, it must call IMemAlloctor::GetBuffer again, as described in step 1.

Note To deliver multiple samples, in step 3 the source filter could call IMemInputPin::ReceiveMultiple instead.

Pull Model

In the pull model, the parser filter requests data from the source filter. The parser filter uses the IAsyncReader interface on the source filter's output pin, as follows:

  1. The parser filter calls IMemAllocator::GetBuffer to retrieve an empty media sample.
  2. It calls IAsyncReader::Request to request data from the source filter.
  3. While the source filter is retrieving the data, the parser calls IAsyncReader::WaitForNext. This method waits until the request from step 2 is completed.
  4. The parser filter processes the data and delivers it downstream.

Steps 2–3 perform an asynchronous read operation. The parser can request a synchronous read operation instead, using the IAsyncReader::SyncRead or IAsyncReader::SyncReadAligned method.

Processing a Sample

When a filter's input pin receives a sample, the filter processes the data in the sample and then delivers the sample to the next downstream filter. As the previous section described, the filter can do all of its processing while inside the Receive method, or it can hold the sample and process it afterward.

Within the call to Receive, the input pin has the option of blocking the upstream filter's calling thread. You can query the input pin's behavior by calling the IMemInputPin::ReceiveCanBlock method. If the return value is S_OK, the pin might block on a call to Receive. If the return value is S_FALSE, the pin will never block on calls to Receive. Based on the return value, the upstream filter might use a separate worker thread to deliver samples.

Some filters process samples in place, without copying any data. Other filters copy the data before processing it. Obviously, it is better to process samples in place whenever possible, to avoid the overhead of unneeded copy operations.

The input pin can reject samples by returning an error code or S_FALSE in its Receive method. The value S_FALSE indicates that the pin is flushing data (see Flushing). An error code indicates some other problem. For example, if the filter is stopped, the return value is VFW_E_WRONG_STATE. If a pin rejects a sample, the filter calls the IPin::EndOfStream method on the input pins connected to it. Also, if an error occurred, the filter sends an EC_ERRORABORT event to the filter graph manager. After a pin has rejected a sample, the upstream filter stops sending data. It can start again after the flush completes, or when the graph is stopped and restarted.

The filter must serialize all of its Receive calls to a given input pin.

New Segment

At the beginning of each new stream, the source filter (or a parser filter) must call IPin::NewSegment. This method specifies the start and stop times of the stream, relative to the original source, and the playback rate. The filter calls NewSegment when streaming starts, and after a seek operation. Stream time resets to zero after each new segment, and samples delivered after the new segment are time-stamped starting from zero.

Segment information enables certain filters to process samples correctly. For example, in a format such as MPEG-1, a filter might need a key frame beyond the stop time, in order to construct the intermediate frames. The segment information informs the filter of the actual stop time. Regardless of whether the filter uses the segment information or not, it passes the NewSegment call downstream. The NewSegment calls must be serialized with other streaming calls, such as Receive.

End of Stream

When a source filter has no more data to send, it calls the IPin::EndOfStream method on the downstream input pin. The downstream filter propagates the call to the next filter. Eventually the EndOfStream call reaches the renderer filter. The renderer filter sends an EC_COMPLETE event to the filter graph manager.

The filter graph manager does not immediately forward the EC_COMPLETE notification to the application. Instead, it waits until all the streams signal EC_COMPLETE. The application does not receive an EC_COMPLETE notice until all the streams have completed. To determine the number of streams in the graph, the filter graph manager counts the number of filters that support IMediaSeeking or IMediaPosition and have a rendered input pin. A rendered input pin is an input pin with no corresponding outputs. The IPin::QueryInternalConnections method returns zero for a rendered input pin. As another option, a filter can implement the IAMFilterMiscFlags interface and return the AM_FILTER_MISC_FLAGS_IS_RENDERER flag.

A filter must serialize EndOfStream calls with other streaming calls, such as Receive.

Flushing

Flushing is the process of discarding all the pending samples in the graph. Flushing enables the graph to be more responsive when events alter the normal data flow. For example, in a seek operation, old data is flushed from the graph before new data is introduced. If the graph contains multiple streams, it is possible to flush individual streams separately.

Flushing is a two-stage process:

  • The source filter calls IPin::BeginFlush on a connected input pin. In response, the downstream filter stops accepting samples from upstream. The call to BeginFlush propagates downstream until it reaches the renderer.
  • The source filter calls IPin::EndFlush on the input pin. Pending data is flushed from the stream, and the call propagates downstream.

When an input pin's BeginFlush method is called, the filter performs the following actions:

  1. Calls BeginFlush on downstream input pins.
  2. Rejects any further calls that stream data, including Receive and EndOfStream.
  3. Unblocks any upstream filters that are blocked waiting for a sample from the filter's allocator. Filters often decommit their allocators for this purpose.
  4. Exits from any waits that block streaming. For example, renderer filters block when paused. They also block when they are waiting to render a sample at the correct stream time. The filter must unblock, so that samples queued upstream can be delivered and rejected. This step ensures that all the filters in the streaming chain are eventually unblocked.

When the EndFlush method is called, the filter performs the following actions:

  1. Waits for all queued samples to be discarded.
  2. Frees any buffered data. This step can sometimes be performed in the BeginFlush method. However, BeginFlush is not synchronized with the streaming thread. The filter must not process or buffer any more data between the call to BeginFlush and the call to EndFlush.
  3. Clears any pending EC_COMPLETE notifications.
  4. Calls EndFlush downstream.

At this point, the filter can accept samples again. All samples are guaranteed to be more recent than the flush.

In the pull model, the parser filter initiates flushing rather than the source filter. The sequence of events is the same, except that the parser also calls BeginFlush and EndFlush on the source filter's output pin.

Threads and Critical Sections

In any DirectShow application, at least two important threads are running. The first is the application thread. This thread initiates changes in the state of the filter graph. State changes include running, pausing, and stopping the graph; connecting and disconnecting pins; adding filters to the graph; and removing filters from the graph. The second important thread is the streaming thread, in which pins receive and deliver samples. A separate streaming thread is necessary so that the application thread can block (for example, while the application interacts with the user) without interrupting the data flow.

Filters can also create threads. For example, in its IMemInputPin::Receive method, a filter can return immediately and process the received samples on a separate thread. Some filters also use a separate thread to queue samples for delivery.

Because filter operations are multithreaded, it is crucial that a filter serialize certain operations. Otherwise, race conditions can result. For example, consider the following code, which checks if there is a reference clock and gets the current time:

if (m_pClock != NULL)  // Is there a reference clock?
{
    m_pClock->GetTime(&rtTimeNow);
    // More code, not shown...
}

Suppose that the streaming thread executes this code, and that the code is not protected. Between the if statement and the following line, the application thread might call IMediaFilter::SetSyncSource and set the reference clock to NULL. As a result, the streaming thread dereferences the NULL pointer. An exception occurs, and the application crashes.

To prevent race conditions, filters use two critical sections. The first is the streaming lock. It serializes streaming operations. The second is the filter lock. It serializes state changes, and protects the integrity of the state information.

A filter holds the streaming lock when it processes the following method calls:

  • IMemInputPin::Receive
  • IMemInputPin::ReceiveMultiple
  • IPin::EndOfStream
  • IPin::NewSegment

A filter holds the filter lock when it processes the following types of calls:

  • State changes: IBaseFilter::JoinFilterGraph, IMediaFilter::Pause, IMediaFilter::Run, IMediaFilter::Stop, IQualityControl::SetSink.
  • Reference clock: IMediaFilter::GetSyncSource, IMediaFilter::SetSyncSource.
  • Pin operations: IBaseFilter::FindPin, IPin::Connect, IPin::ConnectedTo, IPin::ConnectionMediaType, IPin::Disconnect, IPin::ReceiveConnection.
  • Allocator functions: IMemInputPin::GetAllocator, IMemInputPin::NotifyAllocator.
  • Flushing: IPin::BeginFlush, IPin::EndFlush.

The preceding list is not meant to be exhaustive. When you implement a filter, you must consider which methods change the filter state, and which methods perform streaming operations.

Critical sections create the potential for deadlocks. To avoid deadlocks, streaming methods should never hold the filter lock. The reason for this rule is that some streaming operations cannot complete until the filter graph finishes a state transition. For example, renderers block Receive calls while paused. If the upstream filter holds the filter lock when it calls Receive, it can create a circular wait condition. The streaming thread is waiting for the graph to switch out of paused state, but that state transition can never occur, because the application thread waits to obtain the filter lock.

The following diagram illustrates this deadlock.

In the Stop and EndFlush methods, streaming operations must be synchronized with the filter state. Otherwise, the filter might continue to deliver old samples after the state transition. In the Stop method, care must be taken to avoid deadlock. First hold the filter lock and decommit the input pin's allocator. Then hold the streaming lock. Decomitting the allocator guarantees that calls to Receive will fail, and thus not block. (See CTransformFilter::Stop for an implementation.) In a flush operation, the BeginFlush method starts rejecting samples. The EndFlush method holds the streaming lock.


Time and Clocks in DirectShow

This article gives an overview of time and clocks in the Microsoft® DirectShow® architecture. It contains the following sections.

  • Reference Clocks
  • Clock Times
  • Time Stamps and Media Times
  • Live Sources

Reference Clocks

One function of the filter graph manager is to synchronize the filters in the graph. To accomplish this, the filter graph manager and the filters all rely on a single clock, called the reference clock. Any object that supports the IReferenceClock interface can serve as a reference clock. A filter with access to a hardware timer can provide a clock (an example is the audio renderer), or the filter graph manager can create one that uses the system time.

At run time, the filter graph manager selects a reference clock and calls IMediaFilter::SetSyncSource on all the filters to inform them of the choice. An application can override the filter graph manager's choice by calling SetSyncSource on the filter graph manager. Only do this if you have a particular reason to prefer another clock.

The filter graph manager uses the following heuristic to select the reference clock.

  • If any filter in the graph can provide a reference clock, use that filter. Exception: If the graph contains live sources, choose only a source filter clock.
  • If no filter provides a suitable clock, use the system time.

Reference clocks measure time in 100-nanosecond intervals. To retrieve a clock's current time, call the IReferenceClock::GetTime method. A clock's baseline—the time from which it starts counting—depends on the clock's implementation, so the particular time value it returns is not inherently meaningful. What matters is that it returns monotonically increasing values at a rate of one per 100 nanoseconds.

Clock Times

DirectShow defines two related clock times: reference time and stream time.

  • Reference time is the absolute time returned by the reference clock.
  • Stream time is defined relative to when the graph last started running.
    • While the graph is running, stream time equals reference time minus start time.
    • While the graph is paused, stream time remains at the stream time when it was paused.
    • While the graph is stopped, stream time is zero.
    • After a seek operation, stream time resets to zero.

When an application calls IMediaControl::Run to run the filter graph, the filter graph manager calls IMediaFilter::Run on each filter. To compensate for the slight amount of time it takes for the filters to start running, the filter graph manager specifies a start time slightly in the future.

Time Stamps and Media Times

A media sample has two time-based properties: a time stamp, and a media time.

Time Stamps

The time stamp defines the sample's start and finish times, measured in stream time. The time stamp is sometimes called the presentation time.

When a renderer filter receives a sample, it schedules rendering based on the time stamp. If the sample arrives late, or has no time stamp, the filter renders the sample immediately. Otherwise, the filter waits until the sample's start time before it renders the sample. (It waits for the start time by calling the IReferenceClock::AdviseTime method.)

Source filters and parser filters are responsible for setting the correct time stamps on the samples they process. Use the following guidelines.

  • File playback: The first sample is time stamped with a start time of zero. Subsequent time stamps are determined by the sample length and the playback rate.
  • Video and audio capture: Every sample is time stamped with a start time equal to the stream time when it was captured. Video preview frames are an exception. Because of graph latency, a preview frame that is time stamped with the current stream time will always arrive late at the video renderer. This may cause the renderer to drop frames, in an attempt at quality control. Therefore, preview frames should not be time stamped. For information about quality control, see Quality-Control Management.

To set the time stamp on a sample, call the IMediaSample::SetTime method.

Media Time

Media time specifies the sample's original position within a seekable medium, such as a file on disk. For video, media time represents the frame number. For audio, media time represents the sample number in the packet. For example, if each packet contains one second of 44.1 kilohertz (kHz) audio, the first packet has a media start time of zero and a media stop time of 44100. Renderer filters can determine whether frames or samples have been dropped by checking for gaps in the media times.

Whereas the time stamp depends on factors outside the source, such as seeking and playback rate, the media time is always calculated relative to the original source.

To set the media time on a sample, call the IMediaSample::SetMediaTime method.

Live Sources

A live source, also called a push source, receives media data in real time. Examples include video capture and network broadcasts. In general, a live source cannot control the rate at which data arrives. A live-source filter should implement the IAMPushSource interface on its output pin. The filter graph manager uses this interface to address two problems that can arise when a live source is rendered.

  • Latency
  • Rate Matching

Latency

A filter's latency is the amount of time it takes the filter to process a sample. For live sources, the latency is determined by the size of the buffer used to hold samples. Suppose that the filter graph renders a video source with a latency of 33 milliseconds (ms), and an audio source with a latency of 500 ms. Each video frame arrives at the video renderer about 470 ms before the matching audio sample reaches the audio renderer. Unless the graph compensates for the difference, the audio and video will not be synchronized.

The filter graph manager does not synchronize live sources unless the application enables synchronization by calling the IAMGraphStreams::SyncUsingStreamOffset method. If synchronization is enabled, the filter graph manager queries each source filter for the IAMPushSource interface. For every filter that supports IAMPushSource, the graph calls IAMLatency::GetLatency to retrieve the filter's expected latency, and from these values determines the maximum expected latency. The graph then calls IAMPushSource::SetStreamOffset to give each source filter a stream offset, which that filter adds to the time stamps that it generates.

Rate Matching

If a renderer filter schedules samples using one reference clock, but the source filter produces them using a different clock, glitches can occur in playback. If the renderer runs faster than the source, there will be gaps in the data. If the renderer runs slower than the source, samples will "bunch up," and at some point data will need to be dropped. Typically a live source cannot control its production rate, so instead the renderer matches clock rates with the source.

To perform rate matching, a renderer filter must set its clock according to another clock. The choice of clocks depends on how the source filter generates time stamps.

  • If the source filter generates time stamps from a reference clock, and the renderer can access the same clock, then the renderer sets its clock to the reference clock. In this case, the source filter must not be using the renderer's own clock as the reference clock. Otherwise, the renderer will be matching rates with itself, possibly causing its clock to drift.
  • If the source filter generates time stamps from a private clock—that is, a clock that the renderer cannot access—the renderer adjusts its clock rate based on the time stamps on incoming samples.
  • If the source filter is not generating time stamps at all, the renderer calculates the source filter's delivery rate based on the number of bytes delivered and the bytes per second declared in the format block.

The renderer calls IAMPushSource::GetPushSourceFlags on the source filter to determine how the source filter sets its time stamps. Currently, only the audio renderer performs rate matching, because glitches in audio playback are more noticeable than glitches in video.


Quality-Control Management

Quality control is a mechanism for adjusting the rate of data flow through the filter graph in response to run-time performance. If a renderer filter is receiving too much data or too little data, it can send a quality message. The quality message requests an adjustment in the data rate. By default, quality messages travel upstream from the renderer until they reach a filter that can respond (if any). An application can also implement a custom quality manager. In that case, the renderer passes quality messages directly to the application's quality manager.

This article contains the following topics.

  • Quality Messages
  • Default Quality Control

Quality Messages

Quality messages are defined with the Quality structure. This structure contains the following members:

  • Type: Either Famine, indicating that the filter is receiving too little data, or Flood, indicating that the filter is receiving too much data.
  • Proportion: The requested adjustment in the data rate, from a baseline of 1000. For example, 750 indicates 75% and 1500 indicates 150%.
  • Late: Reference time indicating how late the most recent sample arrived. The value is negative if the sample arrived early.
  • TimeStamp: The time stamp on the most recent sample.

For example, suppose that a sample with a time stamp of 240 milliseconds (ms) reaches the renderer at 280 ms, stream time. The renderer creates a quality message of type Famine. The sample arrived 40 ms late, so the Late member is 400000. (All reference times are in 100-nanosecond units.) The TimeStamp member is 2400000.

For the Proportion member, the renderer might use a running average to calculate the value. Perhaps samples have been arriving on time, and this sample is an anomaly. In that case the renderer might request only a small correction. On the other hand, if samples are consistently late, the renderer might request a larger correction.

Quality control is handled through the IQualityControl interface. It contains two methods.

  • Notify: Sends a quality message.
  • SetSink: Specifies a custom quality manager.

An object that implements IQualityControl receives quality messages through its Notify method. It can either handle the message or pass the message to another object. If the application calls the object's SetSink method, the object should delegate quality control to the specified quality manager.

Default Quality Control

The filter base classes implement some default behaviors for video quality control.

Quality messages start at the renderer. The base class for video renderers is CBaseVideoRenderer, which has the following behavior:

  1. When the video renderer receives a sample, it compares the time stamp on the sample with the current reference time.
  2. The video renderer generates a quality message. In the base class, the Proportion member of the quality message is limited to a range of 500 (50%) to 2000 (200%). Values outside this range could result in abrupt quality changes.
  3. By default, the video renderer sends the quality message to the upstream output pin (the pin connected to its input pin). Applications can override this behavior by calling the SetSink method.

What happens next depends on the upstream filter. Typically, this is a transform filter. The base class for transform filters is CTransformFilter, which uses the CTransformInputPin and CTransformOutputPin classes to implement input and output pins. Together, these classes have the following behavior:

  1. The CTransformOutputPin::Notify method calls CTransformFilter::AlterQuality, a private method on the filter base class.
  2. Derived filters can override AlterQuality to handle the quality message. By default, AlterQuality ignores the quality message.
  3. If AlterQuality does not handle the quality message, the output pin calls CBaseInputPin::PassNotify, a private method on the filter's input pin.
  4. PassNotify passes the quality message to the appropriate place—the next upstream output pin, or a custom quality manager.

Assuming that no transform filter handles the quality message, the message eventually reaches the output pin on the source filter. In the base classes, CBasePin::Notify returns E_NOTIMPL. How a particular source filter handles quality messages depends on the nature of the source. Some sources, such as live video capture, cannot perform meaningful quality control. Other sources can adjust the rate at which they deliver samples.

The following diagram illustrates the default behavior.

Quality control in the base classes.

The base video renderer implements IQualityControl::Notify, which means you can pass quality messages to the renderer itself. If you set the Proportion member to a value less than 1000, the video renderer inserts a wait period between each frame that it renders, in effect slowing down the renderer. (You might do this to reduce system usage, for example.) For more information, see CBaseVideoRenderer::ThrottleWait. Setting the Proportion member to a value greater than 1000 has no effect.


DirectShow and COM

This section contains the following articles.

  • How to Implement IUnknown
  • How to Create a DLL
  • How to Register DirectShow Filters


How to Implement IUnknown

Microsoft® DirectShow® is based on the Component Object Model (COM). If you write your own filter, you must implement it as a COM object. The DirectShow base classes provide a framework from which to do this. Using the base classes is not required, but it can simplify the development process. This article describes some of the internal details of COM objects and their implementation in the DirectShow base classes.

This article assumes that you know how to program COM client applications—in other words, that you understand the methods in IUnknown—but does not assume any prior experience developing COM objects. DirectShow handles many of the details of developing a COM object. If you have experience developing COM objects, you should read the section Using CUnknown, which describes the CUnknown base class.

COM is a specification, not an implementation. It defines the rules that a component must follow; putting those rules into effect is left to the developer. In DirectShow, all objects derive from a set of C++ base classes. The base class constructors and methods do most of the COM "bookkeeping" work, such as keeping a consistent reference count. By deriving your filter from a base class, you inherit the functionality of the class. To use base classes effectively, you need a general understanding of how they implement the COM specification.

This article contains the following topics.

  • How IUnknown Works
  • Using CUnknown
  • Summary

How IUnknown Works

The methods in IUnknown enable an application to query for interfaces on the component and manage the component's reference count. This section contains the following topics.

  • Reference Count
  • Interface Queries
  • Aggregation and Delegation

Reference Count

The reference count is an internal variable, incremented in the AddRef method and decremented in the Release method. The base classes manage the reference count and synchronize access to the reference count among multiple threads.

Interface Queries

Querying for an interface is also straightforward. The caller passes two parameters: an interface identifier (IID), and the address of a pointer. If the component supports the requested interface, it sets the pointer to the interface, increments its own reference count, and returns S_OK. Otherwise, it sets the pointer to NULL and returns E_NOINTERFACE. The following pseudocode shows the general outline of the QueryInterface method. Component aggregation, described in the next section, introduces some additional complexity.

if (IID == IID_IUnknown)
    set pointer to (IUnknown *)this
    AddRef
    return S_OK

else if (IID == IID_ISomeInterface)
    set pointer to (ISomeInterface *)this
    AddRef
    return S_OK

else if ...

else
    set pointer to NULL
    return E_NOINTERFACE

The only difference between the QueryInterface method of one component and the QueryInterface method of another is the list of IIDs that each component tests. For every interface that the component supports, the component must test for the IID of that interface.

Aggregation and Delegation

Component aggregation must be transparent to the caller. Therefore, the aggregate must expose a single IUnknown interface, with the aggregated component deferring to the outer component's implementation. Otherwise, the caller would see two different IUnknown interfaces in the same aggregate. If the component is not aggregated, it uses its own implementation.

To support this behavior, the component must add a level of indirection. A delegating IUnknown delegates the work to the appropriate place: to the outer component, if there is one, or to the component's internal version. A nondelegating IUnknown does the work, as described in the previous section.

The delegating version is public and keeps the name IUnknown. The nondelegating version is renamed INonDelegatingUnknown. This name is not part of the COM specification, because it is not a public interface.

When the client creates an instance of the component, it calls the IClassFactory::CreateInstance method. One parameter is a pointer to the aggregating component's IUnknown interface, or NULL if the new instance is not aggregated. The component uses this parameter to store a member variable indicating which IUnknown interface to use, as shown in the following example.

CMyComponent::CMyComponent(IUnknown *pOuterUnkown)
{
    if (pOuterUnknown == NULL)
        m_pUnknown = (IUnknown *)(INonDelegatingUnknown *)this;
    else
        m_pUnknown = pOuterUnknown;

    [ ... more constructor code ... ]
}

Each method in the delegating IUnknown calls its nondelegating counterpart, as shown in the following example.

HRESULT QueryInterface(REFIID iid, void **ppv)
{
    return m_pUnknown->QueryInterface(iid, ppv);
}

By the nature of delegation, the delegating methods look identical in every component. Only the nondelegating versions change.

Using CUnknown

DirectShow implements IUnknown in a base class called CUnknown. You can use CUnknown to derive other classes, overriding only the methods that change across components. Most of the other base classes in DirectShow derive from CUnknown, so your component can inherit directly from CUnknown or from another base class.

This section contains the following topics.

  • INonDelegatingUnknown
  • IUnknown
  • Class Constructor

INonDelegatingUnknown

CUnknown implements INonDelegatingUnknown. It manages reference counts internally, and in most situations your derived class can inherit the two reference-counting methods with no change. Be aware that CUnknown deletes itself when the reference count drops to zero. On the other hand, you must override NonDelegatingQueryInterface, because the method in the base class returns E_NOINTERFACE if it receives any IID other than IID_IUnknown. In your derived class, test for the IIDs of interfaces that you support, as shown in the following example.

STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv)
{
    if (riid == IID_ISomeInterface)
    {
        return GetInterface((ISomeInterface*)this, ppv);
    }
    // default
    return CUnknown::NonDelegatingQueryInterface(riid, ppv);
}

The utility function GetInterface sets the pointer, increments the reference count in a thread-safe way, and returns S_OK. In the default case, call the base class method and return the result. If you derive from another base class, call its NonDelegatingQueryInterface method instead. This enables you to support all the interfaces that the parent class supports.

IUnknown

As mentioned earlier, the delegating version of IUnknown is the same for every component, because it does nothing more than invoke the correct instance of the nondelegating version. For convenience, the header file Combase.h contains a macro, DECLARE_IUNKNOWN, which declares the three delegating methods as inline methods. It expands to the following code.

STDMETHODIMP QueryInterface(REFIID riid, void **ppv) {
    return GetOwner()->QueryInterface(riid,ppv);
};
STDMETHODIMP_(ULONG) AddRef() {
    return GetOwner()->AddRef();
};
STDMETHODIMP_(ULONG) Release() {
    return GetOwner()->Release();
};

The utility function GetOwner retrieves a pointer to the IUnknown interface of the component that owns this component. For an aggregated component, the owner is the outer component. Otherwise, the component owns itself. Include the DECLARE_IUNKNOWN macro in the public section of your class definition.

Class Constructor

Your class constructor should invoke the constructor method for the parent class, in addition to anything it does that is specific to your class. The following example is a typical constructor method.

CMyComponent(TCHAR *tszName, LPUNKNOWN pUnk, HRESULT *phr)
    : CUnknown(tszName, pUnk, phr)
{
    /* Other initializations */
};

The method takes the following parameters, which it passes directly to the CUnknown constructor method.

  • tszName specifies a name for the component.
  • pUnk is a pointer to the aggregating IUnknown.
  • pHr is a pointer to an HRESULT value, indicating the success or failure of the method.

Summary

The following example shows a derived class that supports IUnknown and a hypothetical interface named ISomeInterface.

class CMyComponent : public CUnknown, public ISomeInterface
{
public:

    DECLARE_IUNKNOWN;

    STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv)
    {
        if( riid == IID_ISomeInterface )
        {
            return GetInterface((ISomeInterface*)this, ppv);
        }
        return CUnknown::NonDelegatingQueryInterface(riid, ppv);
    }

    CMyComponent(TCHAR *tszName, LPUNKNOWN pUnk, HRESULT *phr)
        : CUnknown(tszName, pUnk, phr)
    {
        /* Other initializations */
    };

    // More declarations will be added later.
};

This example illustrates the following points.

  • The CUnknown class implements the IUnknown interface. The new component inherits from CUnknown and from any interfaces that the component supports. The component could derive instead from another base class that inherits from CUnknown.
  • The DECLARE_IUNKNOWN macro declares the delegating IUnknown methods as inline methods.
  • The CUnknown class provides the implementation for INonDelegatingUnknown.
  • To support an interface other than IUnknown, the derived class must override the NonDelegatingQueryInterface method and test for the IID of the new interface.
  • The class constructor invokes the constructor method for CUnknown.

The next step in writing a filter is to enable an application to create new instances of the component. This requires an understanding of DLLs and their relation to class factories and class constructor methods. For more information, see How to Create a DLL.


How to Create a DLL

This article describes how to implement a component as a dynamic-link library (DLL) in Microsoft® DirectShow®. This article is a continuation from How to Implement IUnknown, which describes how to implement the IUnknown interface by deriving your component from the CUnknown base class.

This article contains the following sections.

  • Class Factories and Factory Templates
  • Factory Template Array
  • DLL Functions

Registering a DirectShow filter (as opposed to a generic COM object) requires some additional steps that are not covered in this article. For information on registering filters, see How to Register DirectShow Filters.

Class Factories and Factory Templates

Before a client creates an instance of a COM object, it creates an instance of the object's class factory, using a call to the CoGetClassObject function. The client then calls the class factory's IClassFactory::CreateInstance method. It is the class factory that actually creates the component and returns a pointer to the requested interface. (The CoCreateInstance function combines these steps, inside the function call.)

The following illustration shows the sequence of method calls.

CoGetClassObject calls the DllGetClassObject function, which is defined in the DLL. This function creates the class factory and returns a pointer to an interface on the class factory. DirectShow implements DllGetClassObject for you, but the function relies on your code in a specific way. To understand how it works, you must understand how DirectShow implements class factories.

A class factory is a COM object dedicated to creating another COM object. Each class factory has one type of object that it creates. In DirectShow, every class factory is an instance of the same C++ class, CClassFactory. Class factories are specialized by means of another class, CFactoryTemplate, also called the factory template. Each class factory holds a pointer to a factory template. The factory template contains information about a specific component, such as the component's class identifier (CLSID), and a pointer to a function that creates the component.

The DLL declares a global array of factory templates, one for each component in the DLL. When DllGetClassObject makes a new class factory, it searches the array for a template with a matching CLSID. Assuming it finds one, it creates a class factory that holds a pointer to the matching template. When the client calls IClassFactory::CreateInstance, the class factory calls the instantiation function defined in the template.

The following illustration shows the sequence of method calls.

The benefit of this architecture is that you can define just a few things that are specific to your component, such as the instantiation function, without implementing the entire class factory.

Factory Template Array

The factory template contains the following public member variables:

const WCHAR *              m_Name;                // Name
const CLSID *              m_ClsID;               // CLSID
LPFNNewCOMObject           m_lpfnNew;             // Function to create an instance
                                                  //   of the component
LPFNInitRoutine            m_lpfnInit;            // Initialization function (optional)
const AMOVIESETUP_FILTER * m_pAMovieSetup_Filter; // Set-up information (for filters)

The two function pointers, m_lpfnNew and m_lpfnInit, use the following type definitions:

typedef CUnknown *(CALLBACK *LPFNNewCOMObject)(LPUNKNOWN pUnkOuter, HRESULT *phr);
typedef void (CALLBACK *LPFNInitRoutine)(BOOL bLoading, const CLSID *rclsid);

The first is the instantiation function for the component. The second is an optional initialization function. If you provide an initialization function, it is called from inside the DLL entry-point function. (The DLL entry-point function is discussed later in this article.)

Suppose you are creating a DLL that contains a component named CMyComponent, which inherits from CUnknown. You must provide the following items in your DLL:

  • The initialization function, a private method that returns a new instance of CMyComponent.
  • A global array of factory templates, named g_Templates. This array contains the factory template for CMyComponent.
  • A global variable named g_cTemplates that specifies the size of the array.

The following example shows how to declare these items.

// Private method that returns a new instance.
CUnknown * WINAPI CMyComponent::CreateInstance(LPUNKNOWN pUnk, HRESULT *pHr)
{
    CMyComponent *pNewObject = new CMyComponent(NAME("My Component"), pUnk, pHr );
    if (pNewObject == NULL) {
        *phr = E_OUTOFMEMORY;
    }
    return pNewObject;
}

CFactoryTemplate g_Templates[1] =
{
    {
      L"My Component",                // Name
      &CLSID_MyComponent,             // CLSID
      CMyComponent::CreateInstance,   // Method to create an instance of MyComponent
      NULL,                           // Initialization function
      NULL                            // Set-up information (for filters)
    }
};
int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);

The CreateInstance method calls the class constructor and returns a pointer to the new class instance. The parameter pUnk is a pointer to the aggregating IUnknown. You can simply pass this parameter to the class constructor. The parameter pHr is a pointer to an HRESULT value. The class constructor sets this to an appropriate value, but if the constructor fails, set the value to E_OUTOFMEMORY.

The NAME macro generates a string in debug builds but resolves to NULL in retail builds. It is used in this example to give the component a name that appears in debug logs but does not occupy memory in the final version.

CreateInstance is a private method, so it can have any name. The class factory receives a pointer to it in the factory template. However, g_Templates and g_cTemplates are global variables that the class factory expects to find, so they must have exactly those names.

DLL Functions

A DLL must implement the following functions so that it can be registered, unregistered, and loaded into memory.

  • DllMain: The DLL entry point. The name DllMain is a placeholder for the library-defined function name. The DirectShow implementation uses the name DllEntryPoint. For more information, see the Platform SDK.
  • DllGetClassObject: Creates a class factory instance. Described in the previous sections.
  • DllCanUnloadNow: Queries whether the DLL can safely be unloaded.
  • DllRegisterServer: Creates registry entries for the DLL.
  • DllUnregisterServer: Removes registry entries for the DLL.

Of these, the first three are implemented by DirectShow. If your factory template provides an initialization function in the m_lpfnInit member variable, that function is called from inside the DLL entry-point function. For more information on when the system calls the DLL entry-point function, see DllMain in the Platform SDK.

You must implement DllRegisterServer and DllUnregisterServer, but DirectShow provides a function named AMovieDllRegisterServer2 that does the necessary work. Your component can simply wrap this function, as shown in the following example.

STDAPI DllRegisterServer()
{
    return AMovieDllRegisterServer2( TRUE );
}

STDAPI DllUnregisterServer()
{
    return AMovieDllRegisterServer2( FALSE );
}

However, within DllRegisterServer and DllUnregisterServer you can customize the registration process as needed. If your DLL contains a filter, you might need to do some additional work. For more information, see How to Register DirectShow Filters.

In your module-definition (.def) file, export all the DLL functions except for the entry-point function. The following is an example .def file.

EXPORTS
    DllGetClassObject PRIVATE
    DllCanUnloadNow PRIVATE
    DllRegisterServer PRIVATE
    DllUnregisterServer PRIVATE

You can register the DLL using the Regsvr32.exe utility.


Register DirectShow Objects

Microsoft DirectX 8.0

How to Register DirectShow Filters

This article describes how to make a Microsoft® DirectShow® filter self-registering. It contains the following sections:

  • Layout of the Registry Keys
  • Registering a Filter
  • Unregistering a Filter

This article does not describe how to create a DLL. For information on creating DLLs, see How to Create a DLL.

Layout of the Registry Keys

DirectShow filters are registered in two places:

  • The DLL that contains the filter is registered as the filter's COM server. When an application calls CoCreateInstance to create the filter, the Microsoft® Windows® COM library uses this registry entry to locate the DLL.
  • Information about the filter is registered within a filter category, so that the system device enumerator and the filter mapper can locate it.

The registry entry for the DLL is:

HKEY_CLASSES_ROOT
    CLSID
        Filter CLSID
            REG_SZ: (Default) = Friendly name

            InprocServer32
                REG_SZ: (Default) = File name of the DLL
                REG_SZ: ThreadingModel = Both

The registry entry for the filter information is:

HKEY_CLASSES_ROOT
    CLSID
        Category
            Instance
                Filter CLSID
                    REG_SZ: CLSID = Filter CLSID
                    REG_BINARY: Filter Data = Filter information
                    REG_SZ: FriendlyName = Friendly name

Category is the GUID of a filter category. The filter information is packed into a binary format. The IFilterMapper2 interface unpacks this data when it searches the registry for a filter.

Registering a Filter

To register a filter, perform the following steps:

  1. Declare filter information.
  2. In the factory template for the filter, include a pointer to the filter information.
  3. Implement the DllRegisterServer function.

The sections that follow describe these steps in detail.

Declare Filter Information

The first step is to declare the filter information. DirectShow defines a set of structures for describing filters, pins, and media types:

AMOVIESETUP_FILTER | Describes a filter.
AMOVIESETUP_PIN | Describes a pin.
AMOVIESETUP_MEDIATYPE | Describes a media type.

These structures are nested. The filter structure has a pointer to an array of pin structures, and each pin structure has a pointer to an array of media-type structures. The structures provide enough information for the IFilterMapper2 interface to locate a filter. They are not a complete description of a filter. For example, if the filter creates multiple instances of the same pin, you should declare only one AMOVIESETUP_PIN structure for that pin. Also, a filter is not required to support every combination of media types that it registers.

Declare the set-up structures as global variables within your DLL. The following example shows a filter with one output pin:

static const WCHAR g_wszName[] = L"Some Filter";

AMOVIESETUP_MEDIATYPE sudMediaTypes[] = {
    { &MEDIATYPE_Video, &MEDIASUBTYPE_RGB24 },
    { &MEDIATYPE_Video, &MEDIASUBTYPE_RGB32 },
};

AMOVIESETUP_PIN sudOutputPin = {
    L"",            // Obsolete, not used.
    FALSE,          // Is this pin rendered?
    TRUE,           // Is it an output pin?
    FALSE,          // Can the filter create zero instances?
    FALSE,          // Does the filter create multiple instances?
    &GUID_NULL,     // Obsolete.
    NULL,           // Obsolete.
    2,              // Number of media types.
    sudMediaTypes   // Pointer to media types.
};

AMOVIESETUP_FILTER sudFilterReg = {
    &CLSID_SomeFilter,      // Filter CLSID.
    g_wszName,              // Filter name.
    MERIT_NORMAL,           // Merit.
    1,                      // Number of pin types.
    &sudPins                // Pointer to pin information.
};

The filter name is declared as a static global variable, because it will be used again elsewhere.

Declare the Factory Template

The next step is to declare the factory template for your filter. A factory template is a C++ class that contains information for the class factory. In your DLL, declare a global array of factory templates, one for each filter or COM component in your DLL. The array must be named g_Templates. For more information about factory templates, see How to Create a DLL.

The m_pAMovieSetup_Filter member of the factory template is a pointer to the AMOVIESETUP_FILTER structure described previously. The following example shows a factory template, using the structure given in the previous example:

CFactoryTemplate g_Templates[] =
{
    {
        g_wszName,                      // Name.
        &CLSID_SomeFilter,              // CLSID.
        CSomeFilter::CreateInstance,    // Creation function.
        NULL,
        &sudFilterReg                   // Pointer to filter information.
    }
};
int g_cTemplates = sizeof(g_Templates) / sizeof(g_Templates[0]);

Implement DllRegisterServer

The final step is to implement the DllRegisterServer function. The DLL that contains the component must export this function. The function will be called by a set-up application, or when the user runs the Regsvr32.exe tool.

The following example shows a minimal implementation of DlLRegisterServer:

STDAPI DllRegisterServer(void)
{
    return AMovieDllRegisterServer2(TRUE);
}

The DirectShow function AMovieDllRegisterServer2 creates registry entries for every component in the g_Templates array. However, this function has some limitations. First, it assigns every filter to the CLSID_LegacyAmFilterCategory category. Not all filters belong in this category. Capture filters and compression filters, for example, have their own categories. (For a list of categories, see Filter Categories.) Second, if your filter supports a hardware device, you might need to register two pieces of information that AMovieDLLRegisterServer2 does not handle: the medium and the pin category. A medium defines a method of communication in a hardware device, such as a bus. The pin category defines the function of a pin. For information on mediums, see KSPIN_MEDIUM in the Microsoft® Windows® Driver Development Kit (DDK). For a list of pin categories, see Pin Property Set.

If you want to specify the filter category, the medium, or the pin category, call the IFilterMapper2::RegisterFilter method from within DllRegisterServer. This method takes a pointer to a REGFILTER2 structure, which specifies information about the filter.

To complicate matters somewhat, the REGFILTER2 structure supports two different formats for registering pins. The dwVersion member specifies the format:

  • If dwVersion is 1, the pin format is AMOVIESETUP_PIN (described previously).
  • If dwVersion is 2, the pin format is REGFILTERPINS2.

The REGFILTERPINS2 structure includes entries for pin mediums and pin categories. Also, it uses bit flags for some items that AMOVIESETUP_PIN declares as Boolean values.

The following example shows how to call IFilterMapper2::RegisterFilter from inside DllRegisterServer:

REGFILTER2 rf2FilterReg = {
    1,              // Version 1 (no pin mediums or pin category).
    MERIT_NORMAL,   // Merit.
    1,              // Number of pins.
    &sudPins        // Pointer to pin information.
};

STDAPI DllRegisterServer(void)
{
    HRESULT hr;
    IFilterMapper2 *pFM2 = NULL;

    hr = AMovieDllRegisterServer2(TRUE);
    if (FAILED(hr))
        return hr;

    hr = CoCreateInstance(CLSID_FilterMapper2, NULL, CLSCTX_INPROC_SERVER,
            IID_IFilterMapper2, (void **)&pFM2);

    if (FAILED(hr))
        return hr;

    hr = pFM2->RegisterFilter(
        CLSID_SomeFilter,                // Filter CLSID.
        g_wszName,                       // Filter name.
        NULL,                            // Device moniker.
        &CLSID_VideoCompressorCategory,  // Video compressor category.
        g_wszName,                       // Instance data.
        &rf2FilterReg                    // Pointer to filter information.
    );
    pFM2->Release();
    return hr;
}

Unregistering a Filter

To unregister a filter, implement the DllUnregisterServer function. Within this function, call the DirectShow AMovieDllRegisterServer2 function with a value of FALSE. If you called IFilterMapper2::RegisterFilter when you registered the filter, call the IFilterMapper2::UnregisterFilter method here.

The following example shows how to unregister a filter:

STDAPI DllUnregisterServer()
{
    HRESULT hr;
    IFilterMapper2 *pFM2 = NULL;

    hr = AMovieDllRegisterServer2(FALSE);
    if (FAILED(hr))
        return hr;

    hr = CoCreateInstance(CLSID_FilterMapper2, NULL, CLSCTX_INPROC_SERVER,
            IID_IFilterMapper2, (void **)&pFM2);

    if (FAILED(hr))
        return hr;

    hr = pFM2->UnregisterFilter(&CLSID_VideoCompressorCategory,
            g_wszName, CLSID_SomeFilter);

    pFM2->Release();
    return hr;
}


Transform Filters

This section describes how to create a transform filter, types of transform filters, how to use the transform base classes, which base class member functions to override and when, and how to connect transform filters.

  • Creating a Transform Filter
  • Using the CTransformFilter and CTransInPlaceFilter Transform Base Classes
  • Connecting Transform Filters
  • Write a Transform Filter in C/C++
  • About Compression Filters
  • About Effect Filters


Creating a Transform Filter

Transform filters transform the media data that comes into their input pins and send the transformed data out their output pins. Transform filters can be used to compress and decompress data, to split audio and visual data, or to apply effects, such as contrast or warbling, to media data. Microsoft® DirectShow® contains several sample transform filters that perform different kinds of transformations.

This article steps through the process of creating a transform filter that uses the DirectShow C++ class library. It covers five basic steps, and in the last step shows how to override the required member functions in your derived class to implement the transform filter. It answers two common questions that arise when creating transform filters: Which base class do I use? and How do I override member functions?

This article contains the following sections.

  • Write a Transform Filter
  • Determine if the Filter Must Copy Media Samples
  • Determine Which Base Classes to Use
  • Instantiate the Filter
  • Make Added Interfaces Available Through NonDelegatingQueryInterface
  • Override the Base Class Member Functions

For more information, see the following articles.

  • Filters
  • Write a Transform Filter in C/C++
  • Using the CTransformFilter and CTransInPlaceFilter Transform Base Classes
  • Connecting Transform Filters

Write a Transform Filter

Writing a transform filter can be broken into the following discrete steps.

  1. Determine if the filter must copy media samples or can handle them in place.

    The fewer copies in the media stream, the better. However, some filters require a copy operation; this influences the choice of base classes.

  2. Determine which base classes to use and derive the filter class (and pin classes, if necessary) from the base classes.

    In this step, create the header or headers for your filter. In many cases, you can use the transform base classes, derive your class from the correct transform filter class, and override a few member functions. In other cases, you can use the more generic base classes. These classes implement most of the connection and negotiation mechanism; but these classes also allow more flexibility at the cost of overriding more member functions.

  3. Add the code necessary to instantiate the filter.

    This step requires adding a static CreateInstance member function to your derived class and also a global array that contains the name of the filter, a CLSID, and a pointer to that member function.

  4. Add a NonDelegatingQueryInterface member function to pass out any unique interfaces in your filter.

    This step addresses the Component Object Model (COM) aspects of implementing interfaces, other than those in the base classes.

  5. Override the appropriate base class member functions.

    This includes writing the transform function that is unique to your filter and overriding a few member functions that are necessary for the connection process, such as setting the allocator size or providing media types.

Determine if the Filter Must Copy Media Samples

Because every copy operation uses valuable CPU cycles, filter developers are encouraged to avoid copying the media samples, if possible. It is best to write the filter to modify media samples in place on an allocator acquired from another filter. In some cases, this is not possible, and a copy operation must be performed.

Where no copy is needed, the run-time overhead of a transform-inplace filter is scarcely more than that of a function; however, by packaging the transform as a filter, you get the full flexibility of the filter graph architecture.

Some reasons that a filter might be written as a copy transform filter rather than a transform-inplace filter include the following:

  • If the transformation generates more data on output than space provided in the allocator of the input (for example, a decompressor filter), or if the transformation generates less data on output and must consolidate memory.
  • If the original media data must be preserved; this is the case with the splitter, where the transform filter splits off a stream of data.
  • If a decompressor filter is performing temporal compression, relying on adjacent frames for delta information. In this case, a separate copy must be made, primarily because the decompressor cannot allow another filter to have access to the original data to modify it.
  • If the filter relies on a queue; for example, a filter that creates a queue to help smooth the delivery of irregularly spaced video frames would need to copy the samples.

Determine Which Base Classes to Use

Before choosing a base class for your transform filter, you must first decide whether your filter needs more than one input and output pin. If it does, you should derive your filter class from CBaseFilter.

If your filter needs to perform a video transform, you should derive your filter class from CVideoTransformFilter.

Otherwise, you should derive your filter class from CTransformFilter or CTransInPlaceFilter. To determine which one to use, you must decide whether your filter must copy media samples or can transform them in place. Because every copy operation uses valuable CPU cycles, filter developers should avoid copying media samples, if possible. It is best to write a filter to modify media samples in place on an allocator acquired from another filter. In some cases, this isn't possible, and you must perform a copy operation.

Where no copy is needed, the run-time overhead of a transform-inplace filter isn't much more than that of a function. However, by packaging the transform as a filter, you get the full flexibility of the filter graph architecture.

Some reasons that you might write a filter as a copy transform filter rather than a transform-inplace filter are:

  • If the transformation generates more data on output than there is space already allocated for the input (for example, a decompressor filter), or if the transformation generates less data on output and must consolidate memory.
  • If the original media data must be preserved. This is the case with the splitter, where the transform filter splits off a stream of data.
  • If a decompressor filter is performing temporal compression, relying on adjacent frames for information about what has changed frame to frame. In this case, you must make a separate copy, primarily because the decompressor can't allow another filter to have access to the original data to modify it.
  • If the filter relies on a queue; for example, a filter that creates a queue to help smooth the delivery of irregularly spaced video frames would need to copy the samples.

Once you determine whether the transform filter will copy media samples or transform them in place, you must decide which base class or classes to use and which member functions you must override and implement. You can then define your derived classes.

Some member functions in the base classes must be overridden in your derived class because they are either declared as pure virtual in the base classes (they have no implementation), or have default implementations that do nothing but return an error value.

You derive your filter class from the transform base classes CTransformFilter, CTransInPlaceFilter, or CVideoTransformFilter, or from the more generic CBaseFilter filter class. Most of the connection, media type, and allocator negotiation code is handled in the base classes and inherited by the transform classes. The transform classes make it possible to create a filter by deriving just one filter class (no pin classes). The transform classes make assumptions about the workings of transform filters that make the process of creating a transform filter easier.

To learn more about CTransformFilter and CTransInPlaceFilter and which of their member functions are typically overridden by the derived class, see Using the CTransformFilter and CTransInPlaceFilter Transform Base Classes.

Instantiate the Filter

All filters must add code to let the base classes instantiate the filter. To instantiate a filter, you must include two pieces of code in your filter: a static CreateInstance member function in the derived filter class, and a means of informing the class factory in the base classes how to access this function.

Typically, the CreateInstance member function calls the constructor for the derived filter class. The following examples show how to implement the CreateInstance member function.

CUnknown *CGargle::CreateInstance(LPUNKNOWN punk, HRESULT *phr) {

    CGargle *pNewObject = new CGargle(NAME("Gargle Filter"), punk, phr);
    if (pNewObject == NULL) {
        *phr = E_OUTOFMEMORY;
    }

    return pNewObject;
} // CreateInstance

To communicate with the class factory, declare a global array of CFactoryTemplate objects as g_Templates and provide the name of your filter, the class identifier (CLSID) of your filter, and a pointer to the static CreateInstance member function that creates your filter object.

// Needed for the CreateInstance mechanism
CFactoryTemplate g_Templates[2]=
    { { L"Gargle filter"              , &CLSID_Gargle , CGargle::CreateInstance          }
    , { L"Gargle filter Property Page", &CLSID_GargProp, CGargleProperties::CreateInstance}
    };

int g_cTemplates = sizeof(g_Templates)/sizeof(g_Templates[0]);

You can add additional parameters to the CFactoryTemplate templates if you want your filter to be self-registering. For more information on this, see How to Register DirectShow Filters.

Finally, link your filter to Strmbase.lib and export DllGetClassObject and DllCanUnloadNow using a .def file.

Make Added Interfaces Available Through NonDelegatingQueryInterface

Only filters that add interfaces that are not in the base classes, such as those required for creating property pages, need implement the IUnknown member functions (called INonDelegatingUnknown in the base classes). The base classes provide default implementations of the IUnknown methods. IUnknown methods in any COM-based code retrieve interfaces from an object, and increment and decrement the reference counts of those interfaces. For example, the IUnknown::QueryInterface method retrieves interfaces from an object.

DirectShow defines a special IUnknown class called INonDelegatingUnknown, whose methods do the same thing as IUnknown. (The reason for the name change is so that objects can be aggregated.) The NonDelegatingQueryInterface method is called whenever some object or application wants to query a pin or filter for any interfaces it implements. If your filter implements any interface outside those listed in the base class implementation, you will need to override the NonDelegatingQueryInterface method to return a pointer to the implemented interface. For example, the following code example overrides the member function to distribute references to the ISpecifyPropertyPages and IPersistStream interfaces.

// Reveal our persistent stream, property pages, and IGargle interfaces.
STDMETHODIMP CGargle::NonDelegatingQueryInterface(REFIID riid, void **ppv) {

    if (riid == IID_IGargle) {
        return GetInterface((IGargle *) this, ppv);
    } else if (riid == IID_ISpecifyPropertyPages) {
        return GetInterface((ISpecifyPropertyPages *) this, ppv);
    } else if (riid == IID_IPersistStream) {
        AddRef();     // add a reference count to ourselves
        *ppv = (void *)(IPersistStream *)this;
        return NOERROR;

    } else {
        return CTransInPlaceFilter::NonDelegatingQueryInterface(riid, ppv);
    }
} // NonDelegatingQueryInterface

Note This sample calls the CTransInPlaceFilter implementation of the member function to finish up.

Override the Base Class Member Functions

When you determine which base class to use( see Determine Which Base Classes to Use), you write the header and define which member function to implement. You decide either to derive your filter class from the transform base classes (CTransformFilter or CTransInPlaceFilter), or from the more generic CBaseFilter filter class. In this section, you learn how to override the following member functions.

  • Override the Transform Member Function
  • Override the CheckInputType Member Function
  • Override the CheckTransform Member Function
  • Override the DecideBufferSize Member Function
  • Override the GetMediaType Member Function
  • Override Pin Member Functions
  • Override the CBaseOutput::DecideAllocator Member Function

Override the Transform Member Function

The Transform member function in your derived class is called each time the IMemInputPin::Receive method on the input pin of the filter is called to transfer another sample. Place the code that performs the actual purpose of the filter in this member function, or in the functions called from here. Copy transform filters will likely have a private Copy member function associated with the transform code, while transform-inplace functions will simply modify the code in one buffer.

Override the CheckInputType Member Function

During the pin connection, the CheckMediaType member function of the input pin is called to determine whether the proposed media type is acceptable. The CTransformInputPin::CheckMediaType member function is implemented to call the CheckInputType member function of the derived filter class with the media type. You must implement this to accommodate the media types your filter can handle. The following code sample outlines part of the CGargle::CheckInputType member function, which rejects any media type but MEDIATYPE_Audio.

HRESULT CGargle::CheckInputType(const CMediaType *pmt) {
    ...
    // Reject non-Audio type
    if (pmt->majortype != MEDIATYPE_Audio) {
        return E_INVALIDARG;
    }

Override the CheckTransform Member Function

Copy transform filters can transform the media type from the input pin to output pin. Therefore, if the output pin is connected (so its media type is known), when the CTransformInputPin::CheckMediaType member function is called during connection, the CheckTransform member function of the derived class is called to verify that the transform from the input type to the output type is valid. It is also called when CTransformOutputPin::CheckMediaType is called.

In the CTransInPlaceFilter class, this member function is implemented in the base class header file to simply return S_OK, because the functions from CTransformFilter that call this member function are overridden in CTransInPlaceFilter to call CheckInputType instead. This assumes that the media type doesn't change in a transform-inplace filter, as it might in a copy transform filter.

Override the DecideBufferSize Member Function

Copy transform filters might be required to set the properties of the allocator into which they are copying. This is likely if the downstream filter has provided a newly created allocator (that is, one that hasn't passed an allocator from farther downstream), or if the output pin is forced to create its own allocator. In this case, the pure virtual CBaseOutputPin::DecideBufferSize member function is called from the CBaseOutputPin::DecideAllocator member function, and the derived class fills in the requirements for the buffer by calling the IMemAllocator::SetProperties method on the allocator object to which it has a reference.

The CTransInPlaceFilter::DecideBufferSize method is never called, because the allocator of another filter is always in use. It is implemented in the base class header file to return E_UNEXPECTED.

Override the GetMediaType Member Function

Pins provide enumerators to enable other objects to determine the pin's media type. A pin provides the media type enumerator (the IEnumMediaTypes interface), which the pin base classes implement to call the GetMediaType member function in the pin class. In the copy transform filter classes, each pin's CTransformOutputPin::GetMediaType member function simply calls the virtual CTransformFilter::GetMediaType member function in the filter class. Your derived class must implement this member function to provide each supported media type in a list of media types.

In the transform-inplace classes, the enumerators form a transparent channel between the filters upstream and downstream from the transform filter. If the transform filter's input pin must perform an enumeration, it obtains an enumerator from the downstream filter's input pin. If the output pin must perform an enumeration, it obtains an enumerator from the upstream filter's output pin. One consequence of this is that transform-inplace filters can't connect to each other unless at least one of them is connected to something else, because neither of the transform-inplace filters can propose any media type for the connection.

Override Pin Member Functions

If you derived your filter class from the transform classes and want more than one input or output pin, you must override the pin class (for example, CTransformInputPin or CTransformOutputPin). If you override the pin class, you must also override the GetPin member function of CTransformFilter or CTransInPlaceFilter, so that you can create pin objects from your derived classes. If you override one of the pin classes (for example, CTransformInputPin) and override GetPin to create the pin object, you must also override GetPin to create the other pin object of the same base class (for example, CTransformOutputPin).

If you want more than one input or output pin, it is often simpler to derive your filter from CBaseFilter rather than from one of the transform classes.

Override the CBaseOutput::DecideAllocator Member Function

The base classes implement CBaseOutputPin::DecideAllocator to let the output pin automatically use the downstream pin's allocator. One of the most common alterations in the derived class is to force the use of an object's own allocator (or one from an upstream filter). In the DirectShow model, for example, a source filter pushes media samples onto the next filter and requires its own allocator. For example, if you write a transform-inplace filter and insert it between a source filter and a decompressor filter, the transform filter must present the source filter's allocator to the decompressor. Therefore, you must override the CBaseOutputPin::DecideAllocator member function.


Using the CTransformFilter and CTransInPlaceFilter Transform Base Classes

This article describes the classes provided for creating a transform filter. It is background information that you should read before reading the article Creating a Transform Filter, which walks through the steps of creating a transform filter.

This article contains the following sections.

  • Introducing the CTransformFilter and CTransInPlaceFilter Classes
  • What the Derived Class Must Provide
  • A Sample Transform Filter Declaration

Introducing the CTransformFilter and CTransInPlaceFilter Classes

The easiest solution for writing a transform filter is to use the transform filter classes, which work well for most types of transform filters. Typically, a noncopying transform filter is derived from the CTransInPlaceFilter class and its associated pin classes; a copy transform filter is derived from the CTransformFilter filter class and its associated pin classes.

Transform filter classes are hierarchical, with the transform-inplace classes at the bottom of the hierarchy tree. CTransInPlaceFilter is derived from CTransformFilter, which is derived from CBaseFilter, as shown in the following illustration.

CTransInPlaceFilter class hierarchy

The CTransInPlaceInputPin class is derived from the CTransformInputPin class. The CTransformInputPin class is derived from the CBaseInputPin class, as shown in the following illustration.

CTransInPlaceInputPin class hierarchy

The CTransInPlaceOutputPin class is derived from the CTransformOutputPin class. The CTransformOutputPin class is derived from the CBaseOutputPin class, as shown in the following illustration.

CTransInPlaceOutputPin class hierarchy

Copy transform and transform-inplace classes share many features, because the transform-inplace classes derive almost all member functions from the copy transform classes. The principal additions made by the transform classes over the base classes is that all required pin member functions are implemented - so for default implementation, you need only to derive a main filter class (from CTransInPlaceFilter or CTransformFilter).

What the Derived Class Must Provide

The derived filter class must provide a few member functions, typically to:

  • Determine if the filter accepts the media type.
  • Specify the count and size of any required allocators (for copy transforms only).
  • Provide the transform functionality of the filter.

All derived filter classes must implement a static CFactoryTemplate::CreateInstance function. You can also choose to override the CBaseFilter::GetSetupData member function to make your filter self-registering. Beyond this, your classes must override a few member functions in the transform base classes. For more information about instantiating the filter, see Creating a Transform Filter.

If your derived filter class is based on the CTransformFilter class, you must override the following member functions.
Transform | Implement transform.
CheckInputType | Verify support of media type.
CheckTransform | Verify support for transforming this type (for debugging builds only).
DecideBufferSize | Set size and count when copying.
GetMediaType | Suggest media types for the output pin.

If your derived filter class is based on the CTransInPlaceFilter class, override the following member functions.
Transform | Implement transform.
CheckInputType | Verify support of media type.

Beyond providing your transform filter with a default implementation by providing the minimum overrides, you can override other member functions to provide more specialized behavior. Which member functions you override, of course, depends on what you want your filter to do. For example, you must override the GetPin and GetPinCount member functions if you want to have more than one input pin and one output pin on the filter.

Also, several base class member functions, such as BreakConnect or CompleteConnect, are called as notifications to your filter through the pins. Typically, most of these member functions exist only on the pins. In the classes based on CTransformFilter, the pin functions are implemented to call similarly named functions in the filter class. This means that the member functions you most likely will want to override are all collected into one filter class, so you can leave the pin classes unchanged, making implementation smaller and easier. These member functions are as follows:
Member function | Reason to override
NonDelegatingQueryInterface | To distribute any interfaces added in the derived class.
GetPinCount | If adding more pins to the transform filter.
GetPin | If adding more pins to the transform filter.
CheckConnect | To obtain extra interfaces at connect time or for other reasons.
BreakConnect | To release extra interfaces when connection is broken or for other reasons.
CompleteConnect | To perform some action at the end of connection (such as reconnecting the input pin).
SetMediaType | To be notified when the media type has been set.
StartStreaming | To be notified when entering the streaming state.
StopStreaming | To be notified when exiting the streaming state.
AlterQuality | To do anything with quality-control messages other than passing them on.

A Sample Transform Filter Declaration

This sample illustrates a true minimalist filter, which does nothing except demonstrate the least you must implement for a filter. It uses the transform-inplace classes and derives its filter class from the CTransInPlaceFilter class. Following is the class declaration for the derived filter class CNullNull.

// CNullNull
//
class CNullNull
    : public CTransInPlaceFilter
{

public:

    static CUnknown *CreateInstance(LPUNKNOWN punk, HRESULT *phr);

    DECLARE_IUNKNOWN;

    LPAMOVIESETUP_FILTER GetSetupData()
    {
        return &sudNullNull;
    }

private:

    // Constructor. Just calls the base class constructor.
    CNullNull(TCHAR *tszName, LPUNKNOWN punk, HRESULT *phr)
        : CTransInPlaceFilter (tszName, punk, CLSID_NullNull, phr)
    { }

    // Overrides the pure virtual Transform of CTransInPlaceFilter base class.
    // The "real work" of a transform is done by altering *pSample.
    // The Null transform leaves it alone.
    HRESULT Transform(IMediaSample *pSample){ return NOERROR; }

    // This filter accepts any input type.
    // (It would return S_FALSE for any it did not accept.)
    HRESULT CheckInputType(const CMediaType* mtIn) { return S_OK; }
};

This example illustrates the following basic member functions required in the base class.
CreateInstance | Needed by every filter so that it can be instantiated as a COM object.
GetSetupData | Overrides CBaseFilter::GetSetupData and is used to provide the class with information required to register this particular filter. In this case, it provides the address of a structure defined in the Nullnull.cpp file included in the SDK.
CNullNull | Class constructor, which typically just calls the base class constructor.
Transform | Overrides CTransInPlaceFilter::Transform and does the main work of CNullNull, which in this case is nothing.
CheckInputType | Overrides CTransInPlaceFilter::CheckInputType to verify the media type during connection, and in this case accepts any media type offered, since it will simply pass it along to the next filter in line.

Note that, strictly speaking, GetSetupData is required only if you want your filter to be self-registering. However, since the base classes implement this feature and it is easy to implement, it is a good idea to include this in your base class.


Connecting Transform Filters

This article describes some of the connection issues faced when creating a transform filter. Connecting any two filters requires negotiating which media types to use and deciding on a common allocator for passing samples. Since transform filters are connected on both sides, and since some transform filters use the media types and allocators of other filters in the graph, it is important to understand the concepts involved in transform filter connections.

This article contains the following sections.

  • How Allocator Negotiation Works
  • Connecting Filter Graphs: An Example
  • Establishing Media Type Connections

How Allocator Negotiation Works

For information about the connection process, including media type and allocator negotiation, see How Filters Connect. When you are determining your transform filter characteristics, it might help for you to understand the model of allocator negotiation for transform filters.

If your transform filter requires copying, then it will copy media samples from a buffer established by its input pin to a buffer established by its output pin. These buffers are provided by allocators that might actually be located in other filters, perhaps even several filters removed if the filters in between do not copy the data.

A copying transform filter typically tries to use the allocator of the upstream filter for its input pin, and the allocator of the downstream filter for its output pin. During the connection process, the output pin of the upstream filter determines which allocator to use for the upstream transport, so the input pin of the copy transform must be prepared to create an allocator for the upstream transport if its IMemInputPin::GetAllocator method is called by the connecting output pin. The base classes provide a way to create a new allocator from the input pin of any connection.

On the other hand, transform-inplace filters do not make copies, but rather modify the data in an existing buffer. These filters should always offer the allocator from the downstream filter to the upstream filter. This requires a reconnection, because the filter does not know about the downstream filter when its input pin is first connected. Also, because in-place transforms do not change the media type, the media type from the downstream filter should be offered to the upstream filter upon reconnection.

Connecting Filter Graphs: An Example

To better understand the allocation model for a transform-inplace filter, the following illustration shows a simple and common example of a filter graph.

Filter graph example

This simple example demonstrates the model of the transform-inplace filter offering its downstream allocator to its upstream filter. Consider what happens when InPlace E is connected to VidRen F.

Upon connection, the video renderer filter (VidRen F) offers its allocator for use by the upstream in-place filter (InPlace E). Because it is a transform-inplace filter, InPlace E offers the allocator to the next filter upstream, InPlace D, and so on. This reconnection and renegotiation occurs until it encounters either the source filter or a copy transform filter. In this case it meets a decompressor, CopyDec C. (The copy transform filter cannot offer its allocator upstream, because it must perform a copy operation.) So the decompressor will write directly to the video renderer's buffer, which might be a DirectDraw® surface. This demonstrates why it is a good practice to write a transform filter as a transform-inplace filter and pass allocators from the renderer upstream, if possible.

On the other hand, consider filters InPlace B and CopyDec C. What if the downstream filter from a transform-inplace filter is a copy transform filter instead of a renderer? In this case, the copy transform filter will offer to create its own allocator on its input pin (the base classes handle this), and the transform-inplace filter can then offer that allocator downstream upon reconnection (the same as if it were connected to a renderer filter).

However, even though CopyDec C can create its own allocator (from its IMemInputPin::GetAllocator method), the source filter, Source A, uses its own buffer - say, a file. So when InPlace B connects to CopyDec C, InPlace B will have accepted the source filter's allocator already and will force that allocator to be used for the transport between itself and the decompressor filter. InPlace B can then provide the upstream filter, Source A, with the option of using the allocator offered by CopyDec C, but the source filter will refuse this allocator so that an extra copy does not have to be made from the file buffer to the decompressor's input buffer.

Therefore, any upstream filter can force the use of its allocator downstream but should have good reason to do so (such as if it already has a buffer). In this example, only one copy is being made (by the decompression filter) between the file buffer and the video memory.

Establishing Media Type Connections

When pins from different filters are connected, they must both agree on a common media type for the samples they will exchange. A quick review of the connection mechanism might help highlight how transform filters handle media type negotiations.

This section contains the following topics.

  • The Connection Process: A Summary
  • When Reconnections Occur

The Connection Process: A Summary

When one filter's output pin is called by the filter graph manager to connect to an input pin of a second filter, the IPin::Connect method is called. This, in turn, calls CBaseOutputPin::CheckConnect to obtain interfaces from the connected pin and CBasePin::AgreeMediaType to find a common media type.

AgreeMediaType calls CBasePin::TryMediaTypes, which uses media type enumerators to query the pins for preferred media types. IEnumMediaTypes is an interface on the connected input pin that TryMediaTypes uses first. The base classes use IEnumMediaTypes to repeatedly call a CBasePin member function called GetMediaType for each media type in the list. You use this member function in your input and output pin classes to return the media types that your pin prefers.

TryMediaTypes calls the output pin's CheckMediaType member function with each input type returned. You must use CheckMediaType to verify whether this type is acceptable. If no media types are found (for example GetMediaType might not even be used on the connected input pin, or might return an unacceptable media type), then AgreeMediaType obtains a media type enumerator for the output pin and tries each of these in turn. Again, the GetMediaType member function of the derived output pin is called for each type. In this case, it can determine media types by inquiring about any existing connection established by the filter's input pin.

When Reconnections Occur

For transform filters that do not modify the media type from input pin to output pin (such as most in-place transforms and many copy transforms), a reconnection scheme must be in place for offering the downstream filter's media type to the upstream filter. To understand this, consider the media type negotiation of the transform-inplace Filter B in the following illustration.

Diagram showing arrangement of filters and pins

The input pin of Filter B is connected first and establishes a media type with the upstream output pin (AOutPin). When the output pin of Filter B is connected next, it must use the enumerator from the output pin of the connected upstream filter (AOutPin), because it does not have one of its own.

If the pin of the downstream filter, CInPin, can accept this, then the connection is complete. However, assume that Filter C does not agree to this media type but proposes a media type that Filter B can handle.

Before deciding that it can handle the media type, Filter B calls the IPin::QueryAccept method on AOutPin to ensure that it is acceptable. If no media type can be found that is acceptable for all the filters, then the BOutPin to CInPin connection will fail. (It is possible to find that a transform-inplace filter will connect to either its upstream or its downstream neighbors, but not both simultaneously.)

If a suitable type is found, BOutPin must force a reconnection on the entire filter, and pass the established media type (the media type of CInPin) to AOutPin, when AOutPin and BInPin are connected again.


Write a Transform Filter in C/C++

A transform filter takes media input and alters it in some way. When you design a transform filter, your filter class derives from one of the transform base classes, CTransformFilter, CTransInPlaceFilter, or CVideoTransformFilter, or from the more generic CBaseFilter class. Which base class you choose depends on whether your filter must copy media samples or can transform them in place. See Determine Which Base Classes to Use for more information.

The filter graph manager can use the functions of the base classes your filter derives from to fit your filter into the filter graph and automatically create the connections between your filters. The filter mapper uses your filter's registry information to configure the filter graph.

For the simplest transform filter (for example, one that has only one input pin and one output pin), you can derive your filter class from CTransformFilter and override only the Transform and CheckInputType functions. If you need custom features, you can override additional functions to create your own connections, pins, and other filter features and capabilities. See Override the Base Class Member Functions for more information. You can also derive your filter class from CBaseFilter and override its methods.

This section discusses how to:

  • Define and Instantiate Your Filter Class
  • Override CheckInputType (does not apply to filter classes derived from CBaseFilter)
  • Override the Transform Function (does not apply to filter classes derived from CBaseFilter)
  • Access Additional Interfaces
  • Create Registry Information

Every transform filter must implement code to perform all the preceding steps except access additional interfaces.

For background information about transform filters, see:

  • Determine Which Base Classes to Use
  • Override the Base Class Member Functions

For information on registering a filter or making it self-registering, see How to Register DirectShow Filters.

Define and Instantiate Your Filter Class

The following steps show you how to define and instantiate your filter class.

  1. Determine the base classes from which to derive your filter class (and pin classes, if necessary). Typically, your transform filter class derives from the CTransformFilter, CTransInPlaceFilter, or CVideoTransformFilter transform base classes, or from the more generic CBaseFilter class. If you want to transform video media (especially AVI data), derive from CVideoTransformFilter. If your filter must copy the input media samples, derive from CTransformFilter. If your filter can transform the sampled media in place, derive from CTransInPlaceFilter. If you don't want the simple transform filter support provided in the transform base classes, but prefer to implement your own member functions, derive from CBaseFilter. See Determine Which Base Classes to Use for more information.

    In the following example, the filter class derives from CTransInPlaceFilter.

        class CMyFilter  : public CTransInPlaceFilter
  2. Implement the IUnknown interface for your object.

    In the public section of your filter class definition, create an instance of CUnknown, and then call the DECLARE_IUNKNOWN macro.

        public:
        static CUnknown *WINAPI CreateInstance(LPUNKNOWN punk, HRESULT
    *phr);
        DECLARE_IUNKNOWN;
  3. Define your constructor. Also, define your Transform and CheckInputType functions (this does not apply if your filter class is derived from CBaseFilter).

    In the private section of your filter class definition, define your constructor by calling the constructor of the transform filter class you derived from, and then add code to perform the transform and check the input type. For example:

        // Define your constructor by calling the constructor of
    // CTransInPlaceFilter.
    CMyFilter(TCHAR *tszName, LPUNKNOWN punk, HRESULT *phr)
    : CTransInPlaceFilter (tszName, punk, CLSID_MyFilter, phr)
    { }

    // Add the transform code.
    HRESULT Transform(IMediaSample *pSample){
    // Transform code here
    }

    // Add code to check the input type.
    HRESULT CheckInputType(const CMediaType* mtIn) {
    // Input checking code here
    }
  4. Implement CreateInstance for your filter object. Typically, CreateInstance calls the constructor of your filter class. For example:
        CUnknown * WINAPI CMyFilter::CreateInstance(LPUNKNOWN punk, HRESULT *phr) {
    CMyFilter *pNewObject = new CMyFilter(NAME("Description of My Filter"),
        punk, phr );
    if (pNewObject == NULL) {
        *phr = E_OUTOFMEMORY;
    }
    return pNewObject;
    }
  5. Declare a global array g_Templates of CFactoryTemplate objects to inform the default class factory code how to access the CreateInstance function:
        CFactoryTemplate g_Templates[]=
        {   { L"My Filter"
            , &CLSID_MyFilter
            , CMyFilter::CreateInstance  // function called by class factory
            , NULL
            , &sudMyFilter }     // address of the AMOVIESETUP_FILTER structure,
                                 //   or NULL if no structure exists
    };
    int g_cTemplates = sizeof(g_Templates)/sizeof(g_Templates[0]);

    The g_cTemplates variable defines the number of class factory templates (CFactoryTemplate) for the filter. Each of these templates provides a link between COM and the filter and are used to create the base object for the filter. At a minimum, the filter has one template that provides the address of its own CreateInstance function, which, when called, creates the base object.

    You can add additional parameters to the CFactoryTemplate templates to add property pages. For information about using CFactoryTemplate in registration, see How to Register DirectShow Filters.

  6. Generate a GUID for your filter object.

    For information about generating GUIDs in general, see "GUID Creation and Optimizations" and "The uuidgen Utility" in the Platform SDK.

    To generate a GUID in Microsoft® Visual C++® 5.x, choose Create GUID from the Tools menu. By default, the GUID is in DEFINE_GUID format, which is the format you want. Click the Copy button. Put the cursor in your source file beneath the include statements, and choose Paste from the Edit menu. The inserted code will look like the following example, except that it will have its own unique number and CLSID. Insert the code before your class definition in the header file or main file.

        // {3FA5D260-AF2F-11d0-AE9C-00A0C91F0841}
    DEFINE_GUID(CLSID_MyFilter,
    0x3fa5d260, 0xaf2f, 0x11d0, 0xae, 0x9c, 0x0, 0xa0, 0xc9, 0x1f, 0x8, 0x41);

Override CheckInputType

You must override the CheckInputType function to determine if the proposed input to your filter is valid. (This does not apply to filter classes derived from CBaseFilter.) Your implementation should return an error for media types it can't support. The media types your filter supports are listed in the AMOVIESETUP_MEDIATYPE structure. For example:

    HRESULT CMyFilter::CheckInputType(const CMediaType *pmt)
    {
       if (pmt->majortype != MEDIATYPE_Video) {
           return S_FALSE;
       }
           else return S_OK;
       }

Override the Transform Function

To perform the desired transformation on your input media, your must override the Transform function of your transform base class, or implement your own transformation functions. (This does not apply to filter classes derived from CBaseFilter.)

For example, consider the following code from the Contrast sample. You override the CContrast::Transform function as follows:

    HRESULT CContrast::Transform(IMediaSample *pIn, IMediaSample *pOut)
    {
            HRESULT hr = Copy(pIn, pOut);
        if (FAILED(hr)) {
            return hr;
        }
            return Transform(pOut);

    }

The first CContrast::Transform function copies the media data, and then passes the copy (pointed to by the pOut parameter) to a second Transform function. The first Transform function in the Contrast sample is an overloaded function, and the second form of the Transform function performs an in-place transform on the copy of the input media, as shown in the following code fragment.

    HRESULT CContrast::Transform(IMediaSample *pMediaSample)
    {
        signed char ContrastLevel;
        ContrastLevel = m_ContrastLevel;
        AM_MEDIA_TYPE *pAdjustedType = NULL;

        pMediaSample->GetMediaType(&pAdjustedType);
      HRESULT hr = Transform(&AdjustedType, ContrastLevel);
        pMediaSample->SetMediaType(&AdjustedType);
        return NOERROR;
    }

Note that the second form of the overloaded Transform function calls a third form of the overloaded Transform function.

Access Additional Interfaces

If your filter implements any interfaces that aren't implemented in the base classes, you must override the NonDelegatingQueryInterface function and return pointers to the implemented interfaces.

  1. In the public section of your filter class definition, declare NonDelegatingQueryInterface:
        STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void ** ppv);
  2. In the implementation section of your class, implement the NonDelegatingQueryInterface function. For example:
        // Reveal persistent stream and property pages.
    STDMETHODIMP CMyFilter::NonDelegatingQueryInterface(REFIID riid, void **ppv)
    {
        if (riid == IID_IPersistStream) {
          AddRef( );   // Add a reference count. Be sure to release when done.
         *ppv = (void *) (IPersistStream *) this;
          return NOERROR;
       }
       else if (riid == IID_ISpecifyPropertyPages) {
             return GetInterface((ISpecifyPropertyPages *) this, ppv);
       }
       else {
          return CTransInPlaceFilter::NonDelegatingQueryInterface(riid, ppv);
       }
    }

Create Registry Information

The filter graph manager uses your filter's registry entries to configure your filter and its connections. You provide your filter's registry information in the AMOVIESETUP_MEDIATYPE, AMOVIESETUP_PIN, and AMOVIESETUP_FILTER structures. Typically, these structures are at the beginning of your filter implementation code. For more information about using these structures, see How to Register DirectShow Filters.

Perform the following steps to provide the three structures you need for filter registration.

  1. Provide the AMOVIESETUP_MEDIATYPE structure. This structure holds registry information about the media types your filter supports. For example:
        const AMOVIESETUP_MEDIATYPE sudPinTypes =
                    { &MEDIATYPE_Video             // major type
                    , &MEDIASUBTYPE_NULL}  ;       // minor type

    The possible major types are MEDIATYPE_Stream, MEDIATYPE_Video, and MEDIATYPE_Audio.

  2. Provide the AMOVIESETUP_PIN structure. This structure holds registry information about the pins your filter supports.
  3. Provide the AMOVIESETUP_FILTER structure. This structure holds registry information about your filter object: its CLSID, description, number of pins, the pin structure's name, and your filter's merit. The merit controls the order in which the filter graph manager accesses your filter. Possible merit values are MERIT_PREFERRED, MERIT_NORMAL, MERIT_UNLIKELY, and MERIT_DO_NOT_USE. For a description of merit values, see IFilterMapper::RegisterFilter. The following code shows an example of an AMOVIESETUP_FILTER structure.
        const AMOVIESETUP_FILTER
    sudMyFilter = { &CLSID_MyFilter         // clsID
                , L"My Filter Description"  // strName
                , MERIT_UNLIKELY            // dwMerit
                , 2                         // nPins
                , sudpPins };               // lpPin


About Compression Filters

A compression filter is a specialized type of transform filter. Compression filters (compressors) accept data, use a compression scheme to transform the data, and pass the compressed data downstream.

Microsoft® DirectShow® includes an AVI Compressor filter and an ACM Wrapper filter, which will use any Microsoft Video for Windows® video or audio codec to compress data. You can write your own compressor filter if you need to compress data in a format that isn't supported by the default filters that DirectShow provides.

To begin writing a compression filter, write a transform filter that includes one input pin and one output pin. For more information about writing a transform filter, see the following articles.

  • Creating a Transform Filter
  • Using the CTransformFilter and CTransInPlaceFilter Transform Base Classes
  • Connecting Transform Filters

After you've written a transform filter, you should review the following points when completing your compression filter.

  • Register your filter.

    Register your compression filter by using the AMovieDllRegisterServer2 function. This enables applications to enumerate your filter with all the other compression filters on the system..

  • Implement the recommended compressor interfaces.

    It is strongly recommended that you implement the IAMStreamConfig interface on the output pin of all compression filters and IAMVideoCompression on the output pin of video compressors so that applications can access the compression features of your filter.

    IAMStreamConfig enables you to inform applications about the formats to which you can compress data, and enables the application to configure your compressor to compress to a particular data type.

    IAMVideoCompression enables an application set video-specific settings, like key-frame frequency, that do not appear in the AM_MEDIA_TYPE structure.


About Effect Filters

In Microsoft® DirectShow®, effect filters are defined as filters that apply an effect to media data, but don't change the media type.

Because the input and output media formats are the same, and the applied effect can't change the format, effect filters often contain a code that checks the media formatting. If the filter derives from one of the transform filter base classes, CTransformFilter or CTransInPlaceFilter, the filter typically checks the format with the CheckMediaType, CTransformFilter::CheckInputType, and CheckTransform methods. If the filter doesn't derive from one of the transform filter base classes, its pins typically check the format by calling the CBasePin::CheckMediaType member function.

You should choose a base class for your effect filter class that provides the greatest amount of the functionality you need. Often, the base class will be one of the transform filter base classes. If none of the higher-level base classes support your required functionality, you can choose CBaseFilter or CBasePin as your base class.

Your effect filter must implement the IPersistStream interface if you want to save the state of your effects in GraphEdit. To access this interface, derive your effect filter class from CPersistStream and query for the IPersistStream interface. Saving the filter's state can be helpful during design, but it is often useful to have the effect filter return to a default state when GraphEdit closes it, in which case you don't need to implement IPersistStream.

If you want the user to be able to manipulate the effect, you must create and display your effect filter's property page and provide a mechanism for returning the user's input to the filter. To do this, implement a property page class, the ISpecifyPropertyPages interface (which exposes property pages), and a custom interface that changes property page values. Typically, property pages use controls such as a slider, button, or check box to receive user input. You also must provide the resource file that displays the controls on the property page.

To implement the property page class, create a class that derives from CBasePropertyPage and implement the OnReceiveMessage method, the CPersistStream::SetDirty method, and a data member for each effect parameter. To access the two interfaces, derive your effect filter class from ISpecifyPropertyPages and the custom interface, and then query for the interfaces. You can query for all the interfaces you need by overriding the NonDelegatingQueryInterface method as shown in the following code example (IGargle is the custom interface).

STDMETHODIMP CGargle::NonDelegatingQueryInterface(REFIID riid, void **ppv)
{
    CheckPointer(ppv,E_POINTER);
    if (riid == IID_IGargle) {
        return GetInterface((IGargle *) this, ppv);
    } else if (riid == IID_ISpecifyPropertyPages) {
        return GetInterface((ISpecifyPropertyPages *) this, ppv);
    } else if (riid == IID_IPersistStream) {
        return GetInterface((IPersistStream *) this, ppv);
    } else {
        return CTransInPlaceFilter::NonDelegatingQueryInterface(riid, ppv);
    }
}

The effect filter's custom interface typically supplies a put and a get method for each effect parameter. For example, the IGargle custom interface supplies put_GargleRate and get_GargleRate methods. The IContrast custom interface in the Contrast sample supplies put_ContrastLevel and get_ContrastLevel methods. When the user accesses one of the controls on the property page, the page generates a windows message. The property page class's OnReceiveMessage member function handles this message. The following code fragment from the Contrast sample demonstrates this message generation and handling. IDB_DEFAULT is the resource ID of the Default button. The user clicks this button to set the video contrast to its default state. The CContrastProperties class implements the property page and the IContrast::put_DefaultContrastLevel method sets the contrast level to its default value.

BOOL CContrastProperties::OnReceiveMessage(HWND hwnd, UINT uMsg,
    WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
       case WM_COMMAND:
        {
          if (LOWORD(wParam) == IDB_DEFAULT)
            {
            pIContrast()->put_DefaultContrastLevel();
            SendMessage(m_hwndSlider, TBM_SETPOS, TRUE, 0L);
              SetDirty();
        }
            return (LRESULT) 1;
        }
...

Effect filters use critical sections internally to protect the global filter state. Effect filters can lock a critical section to ensure that data flow through the filter graph is serialized and that the global filter state doesn't change while an effect is occurring. DirectShow locks a critical section by declaring a CAutoLock class object. Typically, effect filters lock the critical section as soon as they enter the function that applies the effect. For example, in the following code fragment, the function that applies the effect is MessItAbout:

// Declare the critical section data member in
// the effect filter class definition.
CCritSec   m_GargleLock;

void CGargle::MessItAbout(PBYTE pb, int cb)
{
    CAutoLock foo(&m_GargleLock);

The put and get methods of the effect properties (for example, put_GargleRate) typically lock the critical section so effect values can't change in the middle of an update.


Video Renderers

This section describes how to write and use video renderers, both full-screen and custom renderers. It discusses how and why to support a full-screen renderer, and how to handle notifications, state changes, and dynamic format changes in a custom renderer.

  • Full-Screen Video Renderer
  • Alternative Video Renderers
  • Source and Target Rectangles in Video Renderers


Full-Screen Video Renderer

This article explains the logic used by the default IVideoWindow plug-in distributor (PID), when an application instructs it to render the video in full-screen mode. Substitute renderer filters can use the IVideoWindow PID for communication with applications. Developers of substitute renderers should be aware of how this PID searches the filter graph for the best means of representing full-screen video, when requested to render in full-screen mode.

This article contains the following sections.

  • Using the IVideoWindow PID to Implement Full-Screen Support
  • Finding a Filter That Supports Full-Screen Mode
  • Finding a Filter That Can Be Stretched Full-Screen at No Cost
  • Supplying a Full-Screen Renderer Filter
  • Stretching the Output of a Renderer Full-Screen
  • Implications of Full-Screen Support for the Application

Using the IVideoWindow PID to Implement Full-Screen Support

Microsoft® DirectShow® implements full-screen support in a number of ways that depend on what hardware resources are available. An application can support full-screen video playback through the IVideoWindow interface provided by the filter graph manager. An application can have its own implementation of full-screen playback, but it can probably make better use of resources by using the IVideoWindow implementation.

The IVideoWindow plug-in distributor (PID) tries three different options for implementing full-screen support when an application requests full-screen mode. The option is typically chosen the first time the filter graph enters full-screen mode. While in full-screen mode, no IVideoWindow methods can be called (apart from accessing the full-screen property). Any attempts to do so will return the VFW_E_IN_FULLSCREEN_MODE message. The PID searches in the following order for a filter that supports IVideoWindow and that has one of these characteristics:

  1. The filter supplies full-screen mode directly.
  2. The filter allows its window to be stretched to full screen without penalty.
  3. The filter can be replaced by a full-screen renderer.

If none of these three options are found, the default is to simply stretch the video of a filter that supports IVideoWindow to full-screen, ignoring the performance penalties.

Finding a Filter That Supports Full-Screen Mode

The first option is to search for a filter in the filter graph that supports full-screen mode directly. When asked to go into full-screen mode, the IVideoWindow PID first scans all filters supporting IVideoWindow in the filter graph. The PID calls IVideoWindow::get_FullScreenMode on each filter and, if the filter returns E_NOTIMP (the default), assumes that the filter has no inherent support for full-screen playback. If the filter returns anything else, then that filter becomes the nominated filter for full-screen playback. This means that any calls to the filter graph manager to set the full-screen mode on or off will be sent directly to that nominated filter. This mechanism allows filters to be extended to support full-screen support directly. Most normal window-based renderers do not need to support this feature.

Finding a Filter That Can Be Stretched Full-Screen at No Cost

If a full-screen rendering filter can't be found, then the PID tries to find a filter supporting the IVideoWindow interface that can have its window stretched full-screen without penalty. The PID does this by scanning the list of filters in the filter graph that support IVideoWindow. For each filter found, the PID calls IVideoWindow::GetMaxIdealImageSize. If a filter indicates that its window can be stretched full-screen at no cost, then that becomes the nominated filter.

If that nominated filter is then requested to render full-screen, the PID resets a number of the filter's IVideoWindow properties and stretches the window to full-screen. This typically means setting a null owner, changing the window styles to not show the border or the caption, and updating the window position to match the current display size. When full-screen mode is switched off, the properties on the filter will be reset to the state prior to the full-screen mode.

Most video renderers supporting IVideoWindow cannot return the maximum ideal image size until they have been activated (either paused or running), because that is when they allocate their resources. For this reason, when scanning the list of filters while the filter graph is in a stopped state, the PID pauses each filter before calling IVideoWindow::GetMaxIdealImageSize. After calling this method, the filter is stopped again.

Supplying a Full-Screen Renderer Filter

If neither of the previous options were successful, then the PID finds the first available filter in the filter graph that supports an IVideoWindow interface, and assumes that it is the current video renderer filter.

If no filters that support IVideoWindow are available, the call to change to full-screen mode will return VFW_E_NO_FULLSCREEN. When asked to change into full-screen mode, the PID asks the current renderer if it can support full-screen mode efficiently. If so, no graph changes are made. If not, the PID stops the filter graph (if it is not already stopped), disconnects the current renderer, reconnects the DirectShow full-screen renderer in its place, and restores the original filter graph when it's done. When switching out of full-screen mode, the opposite occurs. That is, the full-screen renderer is disconnected and the original filter is reconnected. The state of the filter graph is likewise restored. The full-screen renderer is a specialized renderer that uses the display changing capabilities provided by Microsoft® DirectDraw®. For example, it might switch the full-screen display 320 × 240 when it might have been in, for example, 1024 × 768. By switching to lower resolution modes, it can cheaply implement full-screen rendering without having to stretch images.

The full-screen renderer currently implements 320 × 200 × 8/16 bits per pixel, 320 × 240 × 8/16, 640 × 400 × 8/16, 640 × 400 × 8/16, 640 × 480 × 8/16, 800 × 600 × 8/16, 1024 × 768 × 8/16, 1152 × 864 × 8/16, and 1280 × 1024 × 8/16 display modes. The Mode X renderer supports the IFullScreenVideo interface. When the Mode X renderer is connected, it loads the display modes DirectDraw has made available. The number of modes available can be obtained through IFullScreenVideo::CountModes. Information on each mode is available by calling IFullScreenVideo::GetModeInfo and IFullScreenVideo::IsModeAvailable. An application can enable and disable any modes by calling the SetEnabled flag with OATRUE or OAFALSE. The current value can be queried for with IFullScreenVideo::IsModeEnabled.

Another way to set the modes enabled is to use the clip loss factor. This defines the amount of video that can be lost when deciding which display mode to use. Assuming the decoder cannot compress the video, then playing, for example, an MPEG file that is 352 × 288 pixels into a 320 × 200 display will lose over 40 percent of the image. The clip loss factor specifies the upper range of clipping loss that is permissible. To allow typical MPEG video to be played in 320 × 200 it defaults to 50 percent. You can set the clip loss factor with IFullScreenVideo::SetClipFactor.

Stretching the Output of a Renderer Full-Screen

After trying the first three options, the final option for implementing full-screen support is to pick any filter enabled by IVideoWindow and stretch its window full-screen, regardless of the resulting poor performance. Essentially, the first filter in the filter graph that is enabled by the IVideoWindow interface becomes the nominated filter. This filter is then used in the same manner as if it was a filter that could be stretched full-screen without sacrificing performance (that is, the owner is reset, the styles changed, and the window position changed to match the display extents).

The cost of stretching a window full-screen where there is an implicit performance penalty varies, depending on the resolution currently displayed. The worst scenario is one in which the user is using a relatively high resolution (for example, 1024 × 768) and the images must be stretched by the renderer using GDI. This is likely to provide very low frame throughput and is used only as a last resort.

Implications of Full-Screen Support for the Application

While the interface exposed to applications is relatively simple, the underlying implementation can be more complex. The full-screen renderer has some special properties that application developers should be aware of. In particular, the renderer changes display modes only when activated (either paused or running). Therefore, if the filter graph is stopped when switching to full-screen mode, no change might be obviously visible until the filter graph is started again. When the filter graph is subsequently run, the display mode will change and the full-screen rendering will start.

If a window is being stretched full-screen (that is, no full-screen renderer is being used), the change will be viewable when the full-screen mode is set, regardless of state. If full-screen playback is being supported directly by a filter in the filter graph, it might elect to copy the behavior of the full-screen renderer and switch to full-screen only when activated. The filter supporting full-screen playback might have to do this, because the resources they require to play full-screen might not be available until then. Therefore, an application should avoid setting full-screen mode when stopped.

This makes sense in a user interface context as well, because if full-screen mode is set when the filter graph is stopped, users are unlikely to be able to start the graph running without switching out of full-screen mode (that is, tabbing back to the original application).

All renderers that implement IVideoWindow send event codes to the filter graph manager when their windows are activated or deactivated. When in full-screen mode, the PID watches for these event codes. When it sees a window that it made full-screen being deactivated, it will automatically switch out of full-screen mode and send an EC_FULLSCREEN_LOST notification to the application event queue. This is the only interference caused by the PID; all other user interface is left open to the application as described in the remainder of this article.

One of the most important aspects of full-screen playback is that when in full-screen mode, no window can be displayed on top of the full-screen window. In fact, when the full-screen renderer switches display modes, it disables all GDI output for other applications, so displaying a window on top of a full-screen window is actually impossible. Any user interactions with the computer must be done through hot keys.

Whatever mechanism the PID ultimately uses to implement full-screen playback, it always ensures that the message drain property is set on the window executing the playback. (The message drain specifies a window that will be forwarded all Windows® messages sent to the renderer.) So, even if the full-screen renderer is used, as long as a message drain has previously been set on the filter graph manager's IVideoWindow interface, all messages will be passed on to that renderer.

Because the message drain is set on the appropriate window, an application can rely on receiving all mouse and keyboard messages when in full-screen mode, regardless of which filter is implementing it. An application can use this fact to implement hot-key support for seeking, for example. However, properties can be set only when not in full-screen mode, so if the only time an application is required to catch messages is when it is in full-screen mode, it must set the message drain before setting full-screen on. Likewise, the message drain can be reset only after setting full-screen mode off.

One other application consideration is that, when in full-screen mode, any source and destination rectangles set through IBasicVideo will not be adhered to. The PID resets these rectangles when switching to full-screen mode. It does this because not all filters implementing full-screen support can guarantee to support IBasicVideo as well.


Alternative Video Renderers

This article describes some of the more complicated implementation requirements of a renderer; these apply to most renderers, although some aspects are video-specific (such as EC_REPAINT and other notifications). In particular, it discusses how to handle various notifications, state changes, and format changes. It also provides a summary of the notifications that a renderer is responsible for sending to the filter graph manager.

This article contains the following sections.

  • Writing an Alternative Renderer
  • Handling End-of-stream and Flushing Notifications
  • Handling State Changes and Pause Completion
  • Handling Termination
  • Handling Dynamic Format Changes
  • Handling Persistent Properties
  • Handling EC_REPAINT Notifications
  • Handling Notifications in Full-Screen Mode
  • Summary of Notifications

Writing an Alternative Renderer

Microsoft® DirectShow® provides a window-based video renderer; it also provides a full-screen renderer in the run-time installation. You can use the DirectShow base classes to write alternative video renderers. For alternative renderers to interact correctly with DirectShow-based applications, the renderers must adhere to the guidelines outlined in this article. You can use the CBaseRenderer and CBaseVideoRenderer classes to help follow these guidelines when implementing an alternative video render. Because of the ongoing development of DirectShow, review your implementation periodically to ensure that the renderers are compatible with the most recent version of DirectShow.

This article discusses many notifications that a renderer is responsible for handling. A brief review of DirectShow notifications might help to set the stage. There are essentially three kinds of notifications that occur in DirectShow:

  • Stream notifications, which are events that occur in the media stream and are passed from one filter to the next. These can be begin-flushing, end-flushing or end-of-stream notifications and are sent by calling the appropriate method on the downstream filter's input pin (for example IPin::BeginFlush).
  • Filter graph manager notifications, which are events sent from a filter to the filter graph manager such as EC_COMPLETE. This is accomplished by calling the IMediaEventSink::Notify method on the filter graph manager.
  • Application notifications, which are retrieved from the filter graph manager by the controlling application. An application calls the IMediaEvent::GetEvent method on the filter graph manager to retrieve these events. Often, the filter graph manager passes through the events it receives to the application.

This article discusses the responsibility of the renderer filter in handling stream notifications it receives and in sending appropriate filter graph manager notifications.

Handling End-of-stream and Flushing Notifications

An end-of-stream notification begins at an upstream filter (such as the source filter) when that filter detects that it can send no more data. It is passed through every filter in the graph and eventually ends at the renderer, which is responsible for subsequently sending an EC_COMPLETE notification to the filter graph manager. Renderers have special responsibilities when it comes to handling these notifications.

A renderer receives an end-of-stream notification when its input pin's IPin::EndOfStream method is called by the upstream filter. A renderer should note this notification and continue to render any data it has already received. Once all remaining data has been received, the renderer should send an EC_COMPLETE notification to the filter graph manager. The EC_COMPLETE notification should be sent only once by a renderer each time it reaches the end of a stream. Furthermore, EC_COMPLETE notifications must never be sent except when the filter graph is running. Therefore, if the filter graph is paused when a source filter sends an end-of-stream notification, then EC_COMPLETE should not be sent until the filter graph is finally run.

Any calls to the IMemInputPin::Receive or IMemInputPin::ReceiveMultiple methods after an end-of-stream notification is signaled should be rejected. E_UNEXPECTED is the most appropriate error message to return in this case.

When a filter graph is stopped, any cached end-of-stream notification should be cleared and not resent when next started. This is because the filter graph manager always pauses all filters just before running them so that proper flushing occurs. So, for example, if the filter graph is paused and an end-of-stream notification is received, and then the filter graph is stopped, the renderer should not send an EC_COMPLETE notification when it is subsequently run. If no seeks have occurred, the source filter will automatically send another end-of-stream notification during the pause state that precedes a run state. If, on the other hand, a seek has occurred while the filter graph is stopped, then the source filter might have data to send, so it won't send an end-of-stream notification.

Video renderers often depend on end-of-stream notifications for more than the sending of EC_COMPLETE notifications. For example, if a stream has finished playing (that is, an end-of-stream notification is sent) and another window is dragged over a video renderer window, a number of WM_PAINT window messages will be generated. The typical practice for running video renderers is to refrain from repainting the current frame upon receipt of WM_PAINT messages (based on the assumption that another frame to be drawn will be received). However, when the end-of-stream notification has been sent, the renderer is in a waiting state; it is still running but is aware that it will not receive any additional data. Under these circumstances, the renderer customarily draws the playback area black.

Handling flushing is an additional complication for renderers. Flushing is carried out through a pair of IPin methods called BeginFlush and EndFlush. Flushing is essentially an additional state that the renderer must handle. It is illegal for a source filter to call BeginFlush without calling EndFlush, so hopefully the state is short and discrete; however, the renderer must correctly handle data or notifications it receives during the flush transition.

Any data received after calling BeginFlush should be rejected immediately by returning E_UNEXPECTED. Furthermore, any cached end-of-stream notification should also be cleared when a renderer is flushed. A renderer will typically be flushed in response to a seek. The flush ensures that old data is cleared from the filter graph before fresh samples are sent. (Typically, the playing of two sections of a stream, one after another, is best handled through deferred commands rather than waiting for one section to finish and then issuing a seek command.)

Handling State Changes and Pause Completion

A renderer filter behaves the same as any other filter in the filter graph when its state is changed, with the following exception. After being paused, the renderer will have some data queued, ready to be rendered when subsequently run. When the video renderer is stopped, it holds on to this queued data. This is an exception to the DirectShow rule that no resources should be held by filters while the filter graph is stopped.

The reason for this exception is that by holding resources, the renderer will always have an image with which to repaint the window if it receives a WM_PAINT message. It also has an image to satisfy methods, such as CBaseControlVideo::GetStaticImage, that request a copy of the current image. Another effect of holding resources is that holding on to the image stops the allocator from being decommitted, which in turn makes the next state change occur much faster because the image buffers are already allocated.

A video renderer should render and release samples only while running. While paused, the filter might render them (for example, when drawing a static poster image in a window), but should not release them. Audio renderers will do no rendering while paused (although they can perform other activities, such as preparing the wave device, for example). The time at which the samples should be rendered is obtained by combining the stream time in the sample with the reference time passed as a parameter to the IMediaControl::Run method. Renderers should reject samples with start times less than or equal to end times.

When an application pauses a filter graph, the filter graph does not return from its IMediaControl::Pause method until there is data queued at the renderers. In order to ensure this, when a renderer is paused, it should return S_FALSE if there is no data waiting to be rendered. If it has data queued, then it can return S_OK.

The filter graph manager checks all return values when pausing a filter graph, to ensure that the renderers have data queued. If one or more filters are not ready, then the filter graph manager polls the filters in the graph by calling GetState. The GetState method takes a time-out parameter. A filter (typically a renderer) that is still waiting for data to arrive before completing the state change returns VFW_S_STATE_INTERMEDIATE if the GetState method expires. Once data arrives at the renderer, GetState should be returned immediately with S_OK.

In both the intermediate and completed state, the reported filter state will be State_Paused. Only the return value indicates whether the filter is really ready or not. If, while a renderer is waiting for data to arrive, its source filter sends an end-of-stream notification, then that should also complete the state change.

Once all filters actually have data waiting to be rendered, the filter graph will complete its pause state change.

Handling Termination

Video renderers must correctly handle termination events from the user. This implies correctly hiding the window and knowing what to do if a window is subsequently forced to be displayed. Also, video renderers must notify the filter graph manager when its window is destroyed (or more accurately, when the renderer is removed from the filter graph) to free resources.

If the user closes the video window (for instance by pressing ALT+F4), the convention is to hide the window immediately and send an EC_USERABORT notification to the filter graph manager. This notification is passed through to the application, which will stop the graph playing. After sending EC_USERABORT, a video renderer should reject any additional samples delivered to it.

The abort flag should be left on by the renderer until it is subsequently stopped, at which point it should be reset so that an application can override the user action and continue playing the graph if it desires. If ALT+F4 is pressed while the video is running, the window will be hidden and all further samples delivered will be rejected. If the window is subsequently shown (perhaps through IVideoWindow::put_Visible), then no EC_REPAINT notifications should be generated.

The video renderer should also send the EC_WINDOW_DESTROYED notification to the filter graph when the video renderer is terminating. In fact, it is best to handle this when the renderer's IBaseFilter::JoinFilterGraph method is called with a null parameter (indicating that the renderer is about to be removed from the filter graph), rather than waiting until the actual video window is destroyed. Sending this notification enables the plug-in distributor in the filter graph manager to pass on resources that depend on window focus to other filters (such as audio devices).

Handling Dynamic Format Changes

Video renderers in DirectShow accept only video formats that can be drawn efficiently. For example, the window-based run-time renderer will accept only the RGB format that matches the current display device mode (for example, RGB565 when the display is set to 65,536 colors). As a last resort, it also accepts 8-bit palettized formats, as most display cards can draw this format efficiently. When the renderer has Microsoft® DirectDraw® loaded, it might later ask the source filter to switch to something that can be written onto a DirectDraw surface and drawn directly through display hardware. In some cases, the renderer's upstream filter might try to change the video format while the video is playing. This often occurs when a video stream has a palette change. It is most often the video decompressor that initiates a dynamic format change.

An upstream filter attempting to change formats dynamically should always call the IPin::QueryAccept method on the renderer input pin (for filters based on CTransformFilter, this is implemented in CTransformFilter::CheckInputType). The formats a renderer will allow an upstream filter to change dynamically are undefined. However, at a very minimum, it should allow the upstream filter to change palettes. When an upstream filter changes media types, it will attach the format to the first sample delivered in that new type. If the renderer holds many samples in a queue waiting to be rendered, it should delay changing the format until the sample with the type change is actually about to be rendered.

Whenever a format change is detected by the video renderer, it should send an EC_DISPLAY_CHANGED notification. Most video renderers pick a format during connection so that the format can be drawn efficiently through GDI. If the user changes the current display mode without restarting the computer, a renderer might find itself with a bad image format connection and should send this notification. The first parameter should be the pin that needs reconnecting. The filter graph manager will arrange for the filter graph to be stopped and the pin reconnected. During the subsequent reconnection, the renderer can accept a more appropriate format.

Whenever a video renderer detects a palette change in the stream it should send the EC_PALETTE_CHANGED notification to the filter graph manager. The DirectShow video renderers detect whether a palette has really changed in dynamic format or not. The video renderers do this not only to filter out the number of EC_PALETTE_CHANGED notifications sent but also to reduce the amount of palette creation, installation, and deletion required.

Finally, the video renderer might also detect that the size of the video has changed, in which case, it should send the EC_VIDEO_SIZE_CHANGED notification. An application might use this notification to negotiate space in a compound document. The actual video dimensions are available through the IBasicVideo control interface. The DirectShow renderers detect whether the video has actually changed size or not prior to sending these events.

Handling Persistent Properties

All properties set through the IBasicVideo and IVideoWindow interfaces are meant to be persistent across connections. Therefore, disconnecting and reconnecting a renderer should show no effects on the window size, position, or styles. However, if the video dimensions change between connections, the renderer should reset the source and destination rectangles to their defaults. The source and destination positions are set through the IBasicVideo interface.

Both IBasicVideo and IVideoWindow provide enough access to properties to allow an application to save and restore all the data in the interface in a persistent format. This will be useful to applications that must save the exact configuration and properties of filter graphs during an editing session and restore them later.

Handling EC_REPAINT Notifications

The EC_REPAINT notification is sent only when the renderer is either paused or stopped. This notification signals to the filter graph manager that the renderer needs data. If the filter graph is stopped when it receives one of these notifications, it will pause the filter graph, wait for all filters to receive data (by calling GetState), and then stop it again. When stopped, a video renderer should hold on to the image so that subsequent WM_PAINT messages can be handled.

Therefore, if a video renderer receives a WM_PAINT message when stopped or paused, and it has nothing with which to paint its window, then it should send EC_REPAINT to the filter graph manager. If an EC_REPAINT notification is received while paused, then the filter graph manager calls IMediaPosition::put_CurrentPosition with the current position (that is, seeks to the current position). This causes the source filters to flush the filter graph and causes new data to be sent through the filter graph.

A renderer must send only one of these notifications at a time. Therefore, once the renderer sends a notification, it should ensure no more are sent until some samples are delivered. The conventional way to do this is to have a flag to signify that a repaint can be sent, which is turned off after an EC_REPAINT notification is sent. This flag should be reset once data is delivered or when the input pin is flushed, but not if end-of-stream is signaled on the input pin.

If the renderer does not monitor its EC_REPAINT notifications, it will flood the filter graph manager with EC_REPAINT requests (which are relatively expensive to process). For example, if a renderer has no image to draw, and another window is dragged across the window of the renderer in a full-drag operation, the renderer receives multiple WM_PAINT messages. Only the first of these should generate an EC_REPAINT event notification from the renderer to the filter graph manager.

A renderer should send its input pin as the first parameter to the EC_REPAINT notification. By doing this, the attached output pin will be queried for IMediaEventSink, and if supported, the EC_REPAINT notification will be sent there first. This enables output pins to handle repaints before the filter graph must be touched. This will not be done if the filter graph is stopped, because no buffers would be available from the decommitted renderer allocator.

If the output pin cannot handle the request and the filter graph is running, then the EC_REPAINT notification is ignored. An output pin must return NOERROR (S_OK) from IMediaEventSink::Notify to signal that it processed the repaint request successfully. The output pin will be called on the filter graph manager worker thread, which avoids having the renderer call the output pin directly, and so sidesteps any deadlock issues. If the filter graph is stopped or paused and the output doesn't handle the request, then the default processing is done.

Handling Notifications in Full-Screen Mode

The IVideoWindow plug-in distributor (PID) in the filter graph manages full-screen playback. It will swap a video renderer out for a specialist full-screen renderer, stretch a window of a renderer to full screen, or have the renderer implement full-screen playback directly. To interact in full-screen protocols, a video renderer should send an EC_ACTIVATE notification whenever its window is either activated or deactivated. In other words, an EC_ACTIVATE notification should be sent for each WM_ACTIVATEAPP message a renderer receives.

When a renderer is being used in full-screen mode, these notifications manage the switching into and out of that full-screen mode. Window deactivation typically occurs when a user presses ALT+TAB to switch to another window, which the DirectShow full-screen renderer uses as a cue to return to typical rendering mode.

When the EC_ACTIVATE notification is sent to the filter graph manager upon switching out of full-screen mode, the filter graph manager sends an EC_FULLSCREEN_LOST notification to the controlling application. The application might use this notification to restore the state of a full-screen button, for example. The EC_ACTIVATE notifications are used internally by DirectShow to manage full-screen switching on cues from the video renderers.

Summary of Notifications

This section lists the filter graph notifications that a renderer can send.

Event notification | Description
EC_ACTIVATE | Sent by video renderers in full-screen rendering mode for each WM_ACTIVATEAPP message received.
EC_COMPLETE | Sent by renderers after all data has been rendered.
EC_DISPLAY_CHANGED | Sent by video renderers when a display format changes.
EC_PALETTE_CHANGED | Sent whenever a video renderer detects a palette change in the stream.
EC_REPAINT | Sent by stopped or paused video renderers when a WM_PAINT message is received and there is no data to display. This causes the filter graph manager to generate a frame to paint to the display.
EC_USERABORT | Sent by video renderers to signal a closure that the user requested (for example, a user closing the video window).
EC_VIDEO_SIZE_CHANGED | Sent by video renderers whenever a change in native video size is detected.
EC_WINDOW_DESTROYED | Sent by video renderers when the filter is removed or destroyed so that resources that depend on window focus can be passed to other filters.


Source and Target Rectangles in Video Renderers

There are three sizes found in the VIDEOINFO, VIDEOINFOHEADER, and VIDEOINFOHEADER2 format structures of video media types. This article explains what they are and how they work.

First, there is a size in the bmiHeader member of these structures. The bmiHeader member is a BITMAPINFOHEADER structure with its own width and height members, bmiHeader.biWidth and bmiHeader.biHeight.

Second, there is a rectangle in the rcSource member of these structures; and last, there is a rectangle in the rcTarget member of these structures.

Assume you have two filters, A and B, and that these filters are connected to each other (A on the left, or upstream, and B on the right, or downstream) with a certain video media type.

The buffers that pass between filters A and B have the size (bmiHeader.biWidth, bmiHeader.biHeight). Filter A should take a portion of its input video determined by rcSource and stretch that video to fill the rcTarget portion of the buffer. The portion of the input video to use is based on how rcSource compares to the (biWidth, biHeight) size of the media type that filters A and B originally connected with. If rcSource is empty, filter A uses its entire input video. If rcTarget is empty, filter A fills the entire output buffer.

For example, assume filter A is receiving video data that is 160 × 120 pixels. Assume also that filter A is connected to filter B with the following media type.

(biWidth, biHeight): 320, 240
rcSource: (0, 0, 0, 0)
rcTarget: (0, 0, 0, 0)

This means that filter A will stretch the video it receives by 2 in both the x and y directions, and fill a 320 × 240 output buffer.

As another example, assume filter A is receiving 160 × 120 video data, and that it is connected to filter B with the following media type.

(biWidth, biHeight): 320, 240
rcSource: (0, 0, 160, 240)
rcTarget: (0, 0, 0, 0)

The rcSource member is relative to the connected buffer size of 320, 240. Because the specified rcSource (0, 0, 160, 240) is the left half of the buffer, filter A will take the left half of its input video, or the (0, 0, 80, 120) portion, and stretch the video to a size of (320, 240) (by 4 in the x direction, and by 2 in the y direction) and filling the 320 × 240 output buffer.

Now assume that filter A calls GetBuffer, and the media sample returned has a media type attached to it, signifying that filter B wants filter A to provide a different size or kind of video than it has previously been providing. Assume the new media type is:

(biWidth, biHeight): 640, 480
rcSource: (0, 0, 160, 120)
rcTarget: (0, 0, 80, 60)

This means that the media sample has a buffer that is 640 × 480 in size. The rcSource member is relative to the original connected media type (320, 240) not to the new media type of (640, 480), so rcSource specifies that the top-left corner (25%) of the input video is to be used. This portion of the input video is placed in the top-left (80, 60) pixels of the 640 × 480 output buffer, as specified by rcTarget of (0, 0, 80, 60). Because filter A is receiving 160 × 120 video, the top-left corner of the input video is an (80, 60) piece, the same size of the output bitmap, and no stretching is required.

Filter A will place no data in the other pixels of the output buffer, and will leave those bits untouched. The rcSource member is bounded by the biWidth and biHeight of the original connected media type between filters A and B, and rcTarget is bounded by the new biWidth and biHeight of the media sample. In the preceding example, rcSource could not go outside the boundaries of (0, 0, 320, 240) and rcTarget could not go outside the boundaries of (0, 0, 640, 480).


Capture Filters

This section describes how to create a capture filter.

  • Write a Video Capture Filter
  • Write an Audio Capture Filter


Write a Video Capture Filter

This article outlines important points to consider when writing a video capture filter. Microsoft® DirectShow® includes a standard VFW Video Capture filter.

This article contains the following sections.

  • Capture and Preview Pin Requirements
  • Optimizing Capture Versus Preview (Optional)
  • Registering a Video Capture Filter
  • Producing Data
  • Controlling Individual Streams
  • Time Stamping
  • Frame Rates
  • Implementing IAMDroppedFrames
  • Necessary Interfaces

Capture and Preview Pin Requirements

The capture pin and preview pin (if there is one) of the capture filter must support the IKsPropertySet interface. Applications call this interface to ask "what category of pin are you?" by getting the AMPROPERTY_PIN_CATEGORY value of the AMPROPSETID_Pin property set. The value you return is typically either the PIN_CATEGORY_CAPTURE or PIN_CATEGORY_PREVIEW GUID. For more information, see Pin Property Set. A capture filter must support IKsPropertySet or an application can't tell how to connect the filter in a filter graph.

You can name the pin anything you want and you can have other output pins for any additional purposes that you want. If your pin name begins with the tilde (~) character, the filter graph will not automatically render that pin when an application calls IGraphBuilder::RenderFile. For instance, if you have a capture filter with both a capture pin and a preview pin, you might want to name the capture pin "~capture" and the preview pin "preview." Given those names, if an application renders that filter in a graph, the preview pin will be connected to a video renderer, and nothing will be connected to the capture filter, which is probably what you want to happen by default. This can also apply to pins that are just informational and are not meant to be rendered, or need to be enumerated so that their properties can be set.

The tilde (~) prefix only affects the behavior of RenderFile and intelligent connect (IGraphBuilder::Connect). Note that intelligent connect can still be used to connect pins with this property if they implement the IPin::Connect method. However, output pins of intermediate filters which are being used to complete the connection which have the tilde at the start of their name will not be connected as part of the intelligent connection attempt.

For more details about audio capture filters, see Audio Capture Pin Requirements.

The following sample code demonstrates how to implement IKsPropertySet on a capture pin.

//
// PIN CATEGORIES - let the world know that it is a CAPTURE pin.
//

HRESULT CMyCapturePin::Set(REFGUID guidPropSet, DWORD dwPropID,
                           LPVOID pInstanceData, DWORD cbInstanceData,
                           LPVOID pPropData, DWORD cbPropData)
{
    return E_NOTIMPL;
}

// To get a property, the caller allocates a buffer which the called
// function fills in. To determine necessary buffer size, call Get with
// pPropData=NULL and cbPropData=0.
HRESULT CMyCapturePin::Get(REFGUID guidPropSet, DWORD dwPropID,
                           LPVOID pInstanceData, DWORD cbInstanceData,
                           LPVOID pPropData,
                           DWORD cbPropData, DWORD *pcbReturned)
{
    if (guidPropSet != AMPROPSETID_Pin)
        return E_PROP_SET_UNSUPPORTED;

    if (dwPropID != AMPROPERTY_PIN_CATEGORY)
        return E_PROP_ID_UNSUPPORTED;

    if (pPropData == NULL && pcbReturned == NULL)
        return E_POINTER;

    if (pcbReturned)
        *pcbReturned = sizeof(GUID);

    if (pPropData == NULL)
        return S_OK;

    if (cbPropData < sizeof(GUID))
        return E_UNEXPECTED;

    *(GUID *)pPropData = PIN_CATEGORY_CAPTURE;
    return S_OK;
}

// QuerySupported must either return E_NOTIMPL or correctly indicate
// if getting or setting the property set and property is supported.
// S_OK indicates the property set and property ID combination is
HRESULT CMyCapturePin::QuerySupported(REFGUID guidPropSet, DWORD dwPropID,
                                      DWORD *pTypeSupport)
{
    if (guidPropSet != AMPROPSETID_Pin)
        return E_PROP_SET_UNSUPPORTED;

    if (dwPropID != AMPROPERTY_PIN_CATEGORY)
        return E_PROP_ID_UNSUPPORTED;

    if (pTypeSupport)
        *pTypeSupport = KSPROPERTY_SUPPORT_GET;
    return S_OK;
}

Optimizing Capture Versus Preview (Optional)

When your filter is running and capturing data, you must send a copy of the frame from your preview pin as well as from your capture pin. If you can do hardware-assisted preview - through an overlay, for example - and if you have a preview pin, you can use the IOverlay interface transport for your preview pin instead of the IMemInputPin interface. Using IOverlay is optional. If you can't do hardware-assisted preview, only send a frame out the preview pin if you have some spare time. Don't do it if it will make you drop any frames - the capture pin has priority.

For example, you might deliver a frame from the preview pin only if you have nothing to send from the capture pin right now and the downstream filter has released all buffers previously delivered from the capture pin.

If you can capture only one format of data, and the preview and capture pins must therefore produce the same media type, or if you want information about how to properly reconnect pins, read on. Otherwise, skip this section.

Send data of the same format from the preview and capture pins. If the filter graph manager reconnects your capture pin with a different format, you must reconnect your preview pin with the same format to make it work. If your capture pin is connected but your preview pin is not, you must allow only your preview pin to connect with the same media type as the capture pin. They must match.

The following sample code shows how the reconnection should work.

// The capture pin cannot accept a media type if the preview pin is
// connected to a filter that won't accept the new media type. The
// preview pin must always output the same type as the capture pin.
CCapturePin::CheckMediaType(CMediaType *pmt)
{
    if (m_pMyPreviewPin->IsConnected()) {
        // Does the preview pin's connection like this type?
          if (m_pMyPreviewPin->GetConnected()->QueryAccept(pmt) != NOERROR) {
            // Sorry, the preview pin can't reconnect with this new type.
            return E_INVALIDARG;
        }
    }

    // You decide if you like this media type or not, maybe by
    // knowing what the capture pin will connect with. But don't
    // worry; when the capture pin is connected, you will be
    // reconnected to use the same format.

    return NOERROR;
}

// The preview pin can only accept the media type
// that the capture pin is using.
CPreviewPin::CheckMediaType(CMediaType *pmt)
{
    CMediaType cmt = m_pMyCapturePin->m_mt;
     if (m_pMyCapturePin->IsConnected() && *pmt != cmt)
        // Sorry, the preview pin is only allowed to connect with
        // the same format as the capture pin.
        return E_INVALIDARG;

    else if (!m_pMyCapturePin->IsConnected())
        // You decide if you like this media type or not, maybe by
        // knowing what the capture pin will connect with. But don't
        // worry; when the capture pin is connected, you will be
        // reconnected to use the same format.

    // If the capture pin is connected, and this is the same media type,
    // you are OK.
    return NOERROR;
}

// The capture pin is being told to use a certain media type.
// Now the preview pin must be made to use that same media type.
CCapturePin::SetMediaType(CMediaType *pmt);
{
    if (m_pMyPreviewPin->IsConnected()) {

    // You need to reconnect the preview pin with this media type.
      if (m_pMyPreviewPin->GetConnected()->QueryAccept(pmt) == NOERROR) {

        // The other filter that the preview pin is connected to
        // can accept this new media type, so simply reconnect.
        m_pFilter->m_pGraph->Reconnect(m_pMyPreviewPin);
    }
    }
}

Registering a Video Capture Filter

You must register your filter in the video capture filter category. See AMovieDllRegisterServer2 for more information.

Producing Data

Produce data on capture and preview pins only when the filter graph is in a running state. You do not send data from your pins when the filter graph is paused. This will confuse the filter graph unless you return VFW_S_CANT_CUE from the CBaseFilter::GetState function, warning the filter graph that you do not send data when paused. The following code shows you what to do.

CMyVidcapFilter::GetState(DWORD dw, FILTER_STATE *State)
{
    *State = m_State;
    if (m_State == State_Paused)
        return VFW_S_CANT_CUE;
    else
        return S_OK;
}

Controlling Individual Streams

All output pins should support the IAMStreamControl interface, so an application can turn each pin on or off individually (for instance, to preview without capturing). IAMStreamControl enables you to switch between preview and capture without rebuilding a different graph.

Time Stamping

When you capture a frame and are sending it, time stamp the frame with the time the graph's clock says it is when the frame is captured. The end time is the start time plus the duration. For example, if you are capturing at 10 frames per second, and the graph's clock says 200,000,000 units at the time the frame is captured, the sample is stamped (200000000, 201000000) (there are 10,000,000 units per second).

A preview frame should have no time stamp because of latency problems. The latency is due to the fact that, if the time of the sample is the graph's time when it leaves the preview pin, by the time the sample gets to the renderer, it will be late. Therefore the renderer may choose not to draw the sample in order to save time and "catch up," which can't happen for a live stream. Implementing IAMStreamControl requires time stamps, so you can choose not to implement stream control on the preview pin, only time stamp the preview pin sample when there are outstanding requests to start or stop, or live with the latency problem.

You should set the media time of the sample you deliver; also set the regular time stamp for your capture pin. The media time is the frame number of the sample. For example, if you are capturing and sending frames and frame 3 gets dropped, you would set the media time values to be (0,1) (1,2) (2,3) (4,5) (5,6) and so on. This informs the downstream filters if any video frames were dropped even when the regular time stamps are a little random because the clock being used is not the video digitizing clock.

Also, if you are in a running state, and then pause, and then run again, you must not send a sample with a time stamp less than the last one you sent before pausing. Time stamps can never go back in time, not even back to before a pause occurred.

Frame Rates

The frame rate at which your filter should produce data is determined by the AvgTimePerFrame field of the VIDEOINFOHEADER of the media type your output pin is connected with. You may not be able to capture at any arbitrary frame rate, but only certain rates. If your pin is connected with a media type that asks for a frame rate you can't provide, you should provide frames at the next lowest frame rate possible. For instance, if your media type has AvgTimePerFrame = 333333 (approximately 1/30 of a second, meaning 30 frames per second), and you can only capture 29.97 or 35 frames per second, you should provide frames at 29.97 frames per second, since that is the closest value lower than 30 that you can provide. You can provide a higher frame rate than asked if the frame rate you provide does not create frame durations more than 1 microsecond shorter than requested, since the AvgTimePerFrame may simply have rounding errors. If the AvgTimePerFrame field is 0, you can supply frames at any default frame rate that you like.

Implementing IAMDroppedFrames

A capture filter's video output pin should always implement the IAMDroppedFrames interface.

When a capture filter runs, it sends frame numbers beginning with the sequence 0, 1, 2, 3 (numbers will be missing if frames were dropped). The time stamp of each frame sent corresponds to the filter graph clock's time when the image was digitized. The end time is the start time plus the video frame's duration.

Set the media time of each sample by using CMediaSample::SetMediaTime and using frame numbers for the start and end times. For example, the start-time and end-time sequence might appear as follows: (0,1) (1,2) (2,3). A downstream filter can easily tell that a frame was dropped by checking for gaps in the frame number sequence rather than by looking for gaps in the regular time stamps. The following start-time and end-time sequence reveals that frame number 3 was dropped: (1,2) (2,3) (4,5) (5,6).

Every time a capture filter goes from State_Stopped to State_Paused, it should reset all counts to zero.

If your filter runs, pauses, and then runs again, you must continue to deliver frames as if it never paused. The first frame after the second run can't be time stamped earlier than the last frame sent before the pause. That is, your filter must always increment the media time of each sample sent. Never send the same frame number twice, and never go back in time.

Necessary Interfaces

Read about the following interfaces and consider implementing them. You should implement these interfaces to provide functionality that applications might rely on, so these interfaces are strongly recommended.

  • Implement IAMDroppedFrames on your filter or on each output pin that sends data.
  • Implement IAMStreamConfig on each output pin that sends video data.
  • Implement IAMStreamControl on each output pin that sends data.
  • Implement IAMVideoCompression on each output pin that sends video data.


Write an Audio Capture Filter

This article outlines important points to consider when writing an audio capture filter. Microsoft® DirectShow® includes a standard Audio Capture filter.

This article contains the following sections.

  • Audio Capture Pin Requirements
  • Registering an Audio Capture Filter
  • Producing Data
  • Controlling Individual Streams
  • Time Stamping
  • Necessary Interfaces

Audio Capture Pin Requirements

The capture filter's capture pin and preview pin (if there is one) must support the IKsPropertySet interface. See Capture and Preview Pin Requirements for more details and sample code for implementing IKsPropertySet on your capture pin.

You must have one input pin for every sound source the capture card can mix before it digitizes the audio. For instance, if your sound card has a line in, microphone in, and CD-ROM input, you would have three input pins. You don't typically connect these input pins to any other filters - you just support the IAMAudioInputMixer interface on each pin and an application will set recording levels, balance, treble, and so on, on each pin using that interface.

Registering an Audio Capture Filter

You must register your filter in the audio capture filter category. For more information, see the AMovieDllRegisterServer2 function.

Producing Data

Produce data on the capture pin only when the filter graph is in a running state. Do not send data from your pins when the filter graph is paused. This will confuse the filter graph unless you return VFW_S_CANT_CUE from the CBaseFilter::GetState function, which warns the filter graph that you do not send data when paused. The following code sample shows how to do this.

CMyVidcapFilter::GetState(DWORD dw, FILTER_STATE *State)
{
    *State = m_State;
    if (m_State == State_Paused)
        return VFW_S_CANT_CUE;
    else
        return S_OK;
}

Controlling Individual Streams

All output pins should support the IAMStreamControl interface, so an application can turn each pin on or off individually (for instance, to preview without capturing). IAMStreamControl enables you to switch between preview and capture without rebuilding a different graph.

Time Stamping

When you send captured audio samples, the starting time stamp for each group equals the start time of the graph's clock when the first sample in the packet was captured. The ending time stamp equals the start time plus the duration that the audio packet represents. If your audio capture filter is not providing the clock, the time stamps won't match up exactly (where the end of one package is the same as the beginning time stamp of the next package), but that's acceptable. See Write a Video Capture Filter for time stamping examples.

You should also set the media time of the sample you deliver, as well as the regular time stamp. The media time is the sample number in the packet. So if you are sending one-second packets of 44.1 kilohertz (kHz) audio, you would set media time values of (0, 44100) (44100, 88200), and so on. This enables the downstream filters to know if any audio samples were dropped, even when the regular time stamps are a little random because the clock being used is not the audio digitizing clock.

One other thing: If the filter graph is in a running state, and then paused, and then run again, you must not produce a sample with a time stamp less than the last one you produced before pausing. Time stamps can never go back in time, not even back to before a pause occurred.

Necessary Interfaces

Read about the following interfaces and consider implementing them. You should implement these interfaces to provide functionality that applications might rely on, so these interfaces are strongly recommended.

  • Implement IAMDroppedFrames on your filter or on each output pin that sends data.
  • Implement IAMStreamConfig on each output pin that sends data.
  • Implement IAMStreamControl on each output pin that sends data.
  • Implement IAMAudioInputMixer on your filter and on each input pin.


Exposing Capture and Compression Formats

This article describes how to return capture and compression formats by using the IAMStreamConfig::GetStreamCaps method. This method can get more information about accepted media types than the traditional way of enumerating a pin's media types, so it should typically be used instead. For information about traditional media type enumeration, see Establishing Media Type Connections. GetStreamCaps can return information about the kinds of formats allowed for audio or video. Additionally, this article provides some sample code that demonstrates how to reconnect the input pin of a transform filter to ensure your filter can produce a particular output.

The GetStreamCaps method returns an array of pairs of media type and capabilities structures. The media type is an AM_MEDIA_TYPE structure and the capabilities are represented either by an AUDIO_STREAM_CONFIG_CAPS structure or a VIDEO_STREAM_CONFIG_CAPS structure. The first section in this article presents a video example and the second presents an audio example.

This article contains the following topics.

  • Video Capabilities
  • Audio Capabilities
  • Reconnecting Your Input to Ensure Specific Output Types

Video Capabilities

The IAMStreamConfig::GetStreamCaps method presents video capabilities in an array of pairs of AM_MEDIA_TYPE and VIDEO_STREAM_CONFIG_CAPS structures. You can use this to expose all the formats and resolutions supported on a pin as discussed below.

For audio-related examples of GetStreamCaps, see Audio Capabilities.

Suppose your capture card supports JPEG format at all resolutions between 160 × 120 pixels and 320 × 240 pixels, inclusive. The difference between supported resolutions is one in this case because you add or subtract one pixel from each supported resolution to get the next supported resolution. This difference in supported resolutions is called granularity.

Suppose your card also supports the size 640 × 480. The following illustrates this single resolution and the above range of resolutions (all sizes between 160 × 120 pixels and 320 × 240 pixels).

Illustration of JPEG support at all sizes between 160 × 120 pixels and 320 × 240 pixels, and 640 × 480

Also, suppose it supports 24-bit color RGB format at resolutions between 160 × 120 and 320 × 240, but with a granularity of 8. The following illustration shows some of the valid sizes in this case.

Illustration of RGB support at sizes between 160 × 120 and 320 × 240 with a granularity of 8

To put it another way, and listing more resolutions, the following are all among the list of valid resolutions.

  • 160 × 120
  • 168 × 120
  • 168 × 128
  • 176 × 128
  • 176 × 136
  • ... additional resolutions ...
  • 312 × 232
  • 320 × 240

Use GetStreamCaps to expose these color format and dimension capabilities by offering a media type of 320 × 240 JPEG (if that is your default or preferred size) coupled with minimum capabilities of 160 × 120, maximum capabilities of 320 × 240, and a granularity of 1. The next pair you expose by using GetStreamCaps is a media type of 640 × 480 JPEG coupled with a minimum of 640 × 480 and a maximum of 640 × 480 and a granularity of 0. The third pair includes a media type of 320 × 240, 24-bit RGB with minimum capabilities of 160 × 120, maximum capabilities of 320 × 240, and a granularity of 8. In this way you can publish almost every format and capability your card might support. An application that must know what compression formats you provide can get all the pairs and make a list of all the unique subtypes of the media types.

A filter obtains its media type source and target rectangles from the VIDEOINFOHEADER structure's rcSource and rcTarget members, respectively. Filters do not have to support source and target rectangles.

The cropping rectangle described throughout the IAMStreamConfig documentation is the same as the VIDEOINFOHEADER structure's rcSource rectangle for the output pin.

The output rectangle described throughout the IAMStreamConfig documentation is the same as the biWidth and biHeight members of the output pin's BITMAPINFOHEADER structure.

If a filter's output pin is connected to a media type with nonempty source and target rectangles, then your filter is required to stretch the input format's source subrectangle into the output format's target subrectangle. The source subrectangle is stored in the VIDEO_STREAM_CONFIG_CAPS structure's InputSize member.

For example, consider the following video compressor scenario: The input image is in RGB format and has a size of 160 × 120 pixels. The source rectangle's upper-left corner is at coordinate (20,20), and its lower-right corner is at (30,30). The output image is in MPEG format with a size of 320 × 240. The target rectangle's upper-left corner is at (0,0) and its lower-right corner is at (100,100). In this case, the filter should take a 10 × 10 piece of the 160 × 120 RGB source bitmap, and make it fill the top 100 × 100 area of a 320 × 240 bitmap, leaving the rest of the 320 × 240 bitmap untouched. The following illustration shows this scenario.

Illustration of video compressor stretching subrectangle of image between source and target rectangles

A filter might not support this and can fail to connect with a media type where rcSource and rcTarget are not empty.

The VIDEOINFOHEADER structure exposes information about a filter's data rate capabilities. For example, suppose you connected your output pin to the next filter with a certain media type (either directly or by using the media type passed by the CMediaType::SetFormat function). Look at the dwBitRate member of that media type's VIDEOINFOHEADER format structure to see what data rate you should compress the video to. If you multiply the number of units of time per frame in the VIDEOINFOHEADER structure's AvgTimePerFrame member by the data rate in the dwBitRate member and divide by 10,000,000 (the number of units per second), you can figure out how many bytes each frame should be. You can produce a smaller sized frame, but never a larger one. To determine the frame rate for a video compressor or for a capture filter, use AvgTimePerFrame from your output pin's media type.

Audio Capabilities

For audio capabilities, IAMStreamConfig::GetStreamCaps returns an array of pairs of AM_MEDIA_TYPE and AUDIO_STREAM_CONFIG_CAPS structures. As with video, you can use this to expose all kinds of audio capabilities on the pin, such as data rate and whether it supports mono or stereo.

For video-related examples relating to GetStreamCaps, see Video Capabilities.

Suppose you support pulse code modulation (PCM) wave format (as represented by the Microsoft® Win32® PCMWAVEFORMAT structure) at sampling rates of 11,025, 22,050, and 44,100 samples per second, all at 8- or 16-bit mono or stereo. In this case, you would offer two pairs of structures. The first pair would have an AUDIO_STREAM_CONFIG_CAPS capability structure saying you support a minimum of 11,025 to a maximum of 22,050 samples per second with a granularity of 11,025 samples per second (granularity is the difference between supported values); an 8-bit minimum to a 16-bit maximum bits per sample with a granularity of 8 bits per sample; and one-channel minimum and two-channel maximum. The first pair's media type would be your default PCM format in that range, perhaps 22 kilohertz (kHz), 16-bit stereo. Your second pair would be a capability showing 44,100 for both minimum and maximum samples per second; 8-bit (minimum) and 16-bit (maximum) bits per sample, with a granularity of 8 bits per sample; and one-channel minimum and two-channel maximum. The media type would be your default 44 kHz format, perhaps 44 kHz 16-bit stereo.

If you support non-PCM wave formats, the media type returned by this method can show which non-PCM formats you support (with a default sample rate, bit rate, and channels) and the capabilities structure accompanying that media type can describe which other sample rates, bit rates, and channels you support.

Reconnecting Your Input to Ensure Specific Output Types

Filters implement the IAMStreamConfig::SetFormat method to set the audio or video stream's format before pins are connected. Additionally, if your output pin is already connected and you can provide a new type, then reconnect your pin. If the other pin your filter is connected to can't accept the media type, fail this call and leave your connection alone.

Transform filters that do not know what output types their pins can provide should refuse any calls to SetFormat and IAMStreamConfig::GetStreamCaps with the error code VFW_E_NOT_CONNECTED until their input pin is connected.

If your pin knows what types it can provide even when your input is not connected, it is okay to offer and accept them as usual. For more information, see Connecting Transform Filters.

In certain cases it is useful to reconnect pins when you are offering a format on an established connection. For example, if you can compress video into format X but only if you get 24-bit RGB input, and you can turn 8-bit RGB input into compressed format Y, you can either:

  1. Offer and accept both X and Y in GetStreamCaps and SetFormat all the time, or,
  2. Only offer format X if your input is connected as 24, and only offer Y if your input is connected as 8. Fail both GetStreamCaps and SetFormat if your input is not connected.

No matter which one you choose, you will need some reconnecting code that looks like this:

// Overridden to do fancy reconnecting footwork
//
HRESULT MyOutputPin::CheckMediaType(const CMediaType *pmtOut)
{
    HRESULT hr;
    CMediaType *pmtEnum;
    BOOL fFound = FALSE;
    IEnumMediaTypes *pEnum;

    if (!m_pFilter->m_pInput->IsConnected()) {
        return VFW_E_NOT_CONNECTED;
    }

    // Quickly verify that the media type is not bogus here.
    //

    // If SetFormat was previously called, fail this call if the media type
    // isn't an exact match.

    // Accept this output type like normal; nothing fancy required.
    hr = m_pFilter->CheckTransform(&m_pFilter->m_pInput->CurrentMediaType(),
        pmtOut);
    if (hr == NOERROR)
        return hr;

    DbgLog((LOG_TRACE,3,TEXT("Can't accept this output media type")));
    DbgLog((LOG_TRACE,3,TEXT(" But how about reconnecting the input...")));

    // Attempt to find an acceptable type by reconnecting the input pin.
    // The pin the input pin connects to might be able to provide a type
    // that the pin can convert into the necessary type.
    hr = m_pFilter->m_pInput->GetConnected()->EnumMediaTypes(&pEnum);
    if (hr != NOERROR)
        return E_FAIL;
    while (1) {
        hr = pEnum->Next(1, (AM_MEDIA_TYPE **)&pmtEnum, &j);

    // All out of enumerated types.
    if (hr == S_FALSE || j == 0) {
        break;
    }

    // Can the pin convert between these?
    hr = m_pFilter->CheckTransform(pmtEnum, pmtOut);

    if (hr != NOERROR) {
        DeleteMediaType(pmtEnum);
        continue;
    }

    // OK, it offers an acceptable type, but will it accept it now?
    hr = m_pFilter->m_pInput->GetConnected()->QueryAccept(pmtEnum);
    // Nope.
    if (hr != NOERROR) {
        DeleteMediaType(pmtEnum);
        continue;
    }
    // OK.
    fFound = TRUE;
    DbgLog((LOG_TRACE,2,TEXT("This output type is only acceptable after
                                reconnecting the input.")));

    // All done with this.
    DeleteMediaType(pmtEnum);
    break;
    }
    pEnum->Release();

    if (!fFound)
        DbgLog((LOG_TRACE,3,TEXT("*NO! Reconnecting the input won't help")));

    return fFound ? NOERROR : VFW_E_INVALIDMEDIATYPE;
}

HRESULT MyOutputPin::SetFormat(AM_MEDIA_TYPE *pmt)
{
    HRESULT hr;
    LPWAVEFORMATEX lpwfx;
    DWORD dwSize;

    if (pmt == NULL)
    return E_POINTER;

    // To make sure streaming isn't in the middle of starting/stopping:
    CAutoLock cObjectLock(&m_pFilter->m_csFilter);

    if (m_pFilter->m_State != State_Stopped)
    return VFW_E_NOT_STOPPED;

    // Possible output formats depend on the input format.
    if (!m_pFilter->m_pInput->IsConnected())
    return VFW_E_NOT_CONNECTED;

    // Already using this format.
    if (IsConnected() && CurrentMediaType() == *pmt)
    return NOERROR;

    // See if this type is acceptable.
    if ((hr = CheckMediaType((CMediaType *)pmt)) != NOERROR) {
    DbgLog((LOG_TRACE,2,TEXT("IAMStreamConfig::SetFormat rejected")));
    return hr;
    }

    // If connecting to another filter, make sure the filter likes it.
    if (IsConnected()) {
    hr = GetConnected()->QueryAccept(pmt);
    if (hr != NOERROR)
        return VFW_E_INVALIDMEDIATYPE;
    }

    // Now make a note that from now on, this is the only format allowed,
    // and refuse anything but this in the CheckMediaType code above.

    // Changing the format means reconnecting if necessary.
    if (IsConnected())
        m_pFilter->m_pGraph->Reconnect(this);

    return NOERROR;
}

// Overridden to complete the fancy reconnection footwork:
//
HRESULT MyWrapper::SetMediaType(PIN_DIRECTION direction,const CMediaType *pmt)
{
    HRESULT hr;

    // Set the OUTPUT type.
    if (direction == PINDIR_OUTPUT) {

    // Uh oh. As part of the fancy reconnection, the input pin might be asked to
    // provide a media type it cannot provide without reconnection
    // to a different type.
    if (m_pInput && m_pInput->IsConnected()) {

        // If the pin can actually provide this type now, don't worry.
            hr = CheckTransform(&m_pInput->CurrentMediaType(),
                    &m_pOutput->CurrentMediaType());
        if (hr == NOERROR)
        return hr;

                DbgLog((LOG_TRACE,2,TEXT("*Set OUTPUT requires RECONNECT of INPUT!")));

        // Reconnect the input pin.
        return m_pGraph->Reconnect(m_pInput);

    }

    return NOERROR;
    }

    return NOERROR;
}


Filter Categories

If you use the GraphEdit sample tool that comes with the Microsoft® DirectX® SDK, and choose Insert Filters from the Graph menu, you will notice that the Microsoft® DirectShow® filters on the system are grouped into categories. The DirectShow Filters category is the generic category that most filters fall into. New filters will be registered in this category by default. GraphEdit does not display empty categories.

However, if your filter is one of the following kinds of filters, you should make sure that your filter appears in the proper category.

  • Audio Capture Sources—generate audio data from an external device.
  • Audio Compressors—compress PCM audio.
  • Audio Renderers—play audio a data on a local set of speakers.
  • External Renderers—sends data to an external peripheral (for example, 1394 DV camera).
  • Device Control—controls the transport of a video tape machine (for example, 1394 DV camera).
  • Midi Renderers—play MIDI data on a local set of speakers.
  • Video Capture Sources—generate video data from an external device.
  • Video Compressors—turn RGB video into compressed video.

For information on how to register your filters by category, see the AMovieDllRegisterServer2 function topic, which contains sample code for registering a Video Compressor filter. For additional information, see How to Register DirectShow Filters.


File Formats

This section describes file formats in different files used in Microsoft® DirectShow®.

  • DV Data in the AVI File Format
  • Registering a Custom File Type


DV Data in the AVI File Format

Microsoft has specified the format for storage of digital video (DV) data in AVI files. Conforming to this specification will ensure that the AVI files authored in this format will be compatible with future versions of the Microsoft® DirectShow® digital video architecture for the Microsoft® Windows® platform.

This article provides background information to understand the format of Audio-Video Interleaved (AVI) files containing DV audio and video data, or information for programmers who use DV-AVI files on other platforms. Applications that read or write AVI files should use the Async File Source filter with the AVI Splitter filter and the AVI MUX filter with the File Writer filter and their associated interfaces provided in the DirectShow architecture, rather than developing the routines to perform these services. These filters simplify the programming requirements for accessing these files.

This article also describes the format of AVI files containing DV data. Specific FOURCCs (four-character codes) for interleaved DV data streams and DV compressor/decompressor stream handlers are defined. The stream format structure for DV data is defined. Specifications for two methods of storing DV data in the AVI file format are specified.

It is assumed that the reader is familiar with the DV data format. (This format is defined in the Specification of Consumer-use Digital VCRs, also called the Blue Book).

This article contains the following sections.

  • Types of DV AVI Files
  • AVI RIFF File Reference
  • AVI 2.0 File Format Extensions

For more information about resource interchange file format (RIFF) files, see the Windows Software Development Kit (SDK) Multimedia Programmer's Guide and Multimedia Programmer's Reference.

For more information about AVI files, see Chapter 6 of the Microsoft Video for Windows Development Kit version 1.1 Programmer's Guide and version 1.02 of the OpenDML AVI File Format Extensions published by the OpenDML AVI M-JPEG File Format Subcommittee, February 28, 1996.

For more information on compressors and decompressors, see the Video Compression and Decompression Drivers section of the Windows DDK Documentation in the MSDN Library.

Types of DV AVI Files

There are two types of DV AVI files:

  • AVI Files Containing One DV Data Stream
  • AVI Files Containing DV Video as a 'vids' Stream and DV Audio as 'auds' Streams

AVI Files Containing One DV Data Stream

Interleaved DV data can be stored in its native format as a single stream within an AVI RIFF file. This has the advantage of using the minimum amount of data storage for DV. The primary disadvantage is that this file format is not backward-compatible with Video for Windows, because it doesn't contain either a video 'vids' or an audio 'auds' stream. Support is provided for the interleaved DV stream through the DV Muxer and DV Splitter filters provided with DirectShow.

DV data can be stored in a single stream within an AVI RIFF file by specifying the 'iavs' (interleaved audio and video stream) FOURCC (four-character code) in the fccType member and either of the 'dvsd', 'dvhd', or 'dvsl' FOURCCs in the fccHandler member of the 'strh' stream header chunk. The frames per second of the video stream must be specified in the dwRate and dwScale members and the total number of video blocks in the 'movi' chunk in the dwLength member.

The 'dvsd' stream handler FOURCC specifies that the DV data is as defined in Part 2 of the Specification of Consumer-use Digital VCRs. Video is in the format of 525 lines at 29.97 Hz (525-60) or 625 lines at 25.00 Hz (625-50).

The 'dvhd' stream handler FOURCC specifies that the DV data is as defined in Part 3 of the Specification of Consumer-use Digital VCRs. Video is in the format of 1125 lines at 30.00 Hz (1125-60) or 1250 lines at 25.00 Hz (1250-50).

The 'dvsl' stream handler FOURCC specifies that the DV data is as defined in Part 6 of Specification of Consumer-use Digital VCRs. Video is in the format of high-compression SD (SDL).

Note The remainder of this article provides definitions for 'dvsd' streams.

The stream header chunk must be followed by DVINFO stream format chunk. The DVINFO stream format has the following data structure defined for it.

typedef struct tag_DVINFO {
    DWORD dwDVAAuxSrc;
    DWORD dwDVAAuxCtl;
    DWORD dwDVAAuxSrc1;
    DWORD dwDVAAuxCtl1;
    DWORD dwDVVAuxSrc;
    DWORD dwDVVAuxCtl;
    DWORD dwDVReserved[2];
} DVINFO, *PDVINFO;
dwDVAAuxSrc
Specifies the Audio Auxiliary Data Source Pack for the first audio block (first 5 DV DIF sequences for 525-60 systems or 6 DV DIF sequences for 625-50 systems) of a frame. A DIF sequence is a data block that contains 150 DIF blocks. A DIF block consists of 80 bytes. The Audio Auxiliary Data Source Pack is defined in section D.7.1 of Part 2, Annex D, "The Pack Header Table and Contents of Packs" of the Specification of Consumer-use Digital VCRs.
dwDVAAuxCtl
Specifies the Audio Auxiliary Data Source Control Pack for the first audio block of a frame. The Audio Auxiliary Data Control Pack is defined in section D.7.2 of Part 2, Annex D, "The Pack Header Table and Contents of Packs" of the Specification of Consumer-use Digital VCRs.
dwDVAAuxSrc1
Specifies the Audio Auxiliary Data Source Pack for the second audio block (second 5 DV DIF sequences for 525-60 systems or 6 DV DIF sequences for 625-50 systems) of a frame.
dwDVAAuxCtl1
Specifies the Audio Auxiliary Data Source Control Pack for the second audio block of a frame.
dwDVVAuxSrc
Specifies the Video Auxiliary Data Source Pack as defined in section D.8.1 of Part 2, Annex D, "The Pack Header Table and Contents of Packs" of the Specification of Consumer-use Digital VCRs.
dwDVVAuxCtl
Specifies the Video Auxiliary Data Source Control Pack as defined in section D.8.2 of Part 2, Annex D, "The Pack Header Table and Contents of Packs" of the Specification of Consumer-use Digital VCRs.
DwDVReserved[2]
Reserved. Set this array to zero.

The actual DV data is stored as '##dc' chunks in the 'movi' chunk (the ## in the format represents the stream identifier). Each chunk contains one frame of data, either 10 or 12 DV DIF sequences for 525-60 or 625-50 systems, respectively. The DV SD ('dvsd') DIF sequence format is defined in Part 2 of the Specification of Consumer-use Digital VCRs.

The following diagram illustrates the playback of an AVI file with one DV data stream using a DirectShow filter graph (the DV Splitter and DV Video Decoder filters are included in DirectShow specifically to deal with DV data). The table that follows the diagram defines the media types.

Playback of an AVI file with one DV data stream
Media | Major type | Subtype | Format structure
A | MEDIATYPE_Stream | MEDIASUBTYPE_AVI | none
B | MEDIATYPE_iavs | MEDIASUBTYPE_dvsd, MEDIASUBTYPE_dvhd, or MEDIASUBTYPE_dvsl | DVINFO
C | MEDIATYPE_VIDEO | MEDIASUBTYPE_dvsd, MEDIASUBTYPE_dvhd, or MEDIASUBTYPE_dvsl | DVINFO
D | MEDIATYPE_AUDIO | NULL | WAVEFORMATEX
E | MEDIATYPE_VIDEO | standard video types | VIDEOINFO

The following diagram illustrates the creation of an AVI file with one DV data stream by using a DirectShow filter graph (the DV Video Encoder and DV Mux filters are included in DirectShow specifically to deal with DV data). The preceding table defines the media types. Upstream filters (not shown) can be of any combination to produce the proper media types, D and E.

Creation of an AVI file with one DV data stream

The following diagram illustrates the creation of an AVI file with one DV data stream using a source filter that communicates through hardware device drivers with a DV device (such as a 1394-based DV camcorder) for DV data input, by using a DirectShow filter graph (the source filter is included in DirectShow specifically to deal with DV data). The preceding table defines the media types.

DV capture to an AVI file with one DV data stream

The following diagram illustrates the output of an AVI file with one DV data stream using a sink filter that communicates through hardware device drivers with a DV device (such as a 1394-based DV camcorder) for DV data output, by using a DirectShow filter graph (the sink filter is included in DirectShow specifically to deal with DV data). The preceding table defines the media types.

Output of an AVI file with one DV data stream

The following example shows the AIFF RIFF form for an AVI file with one DV data stream, expanded with completed header chunks.

00000000 RIFF (0FAE35D4) 'AVI '
0000000C     LIST (00000106) 'hdrl'
00000018         avih (00000038)
                     dwMicroSecPerFrame    : 33367
                     dwMaxBytesPerSec      : 3728000
                     dwPaddingGranularity  : 0
                     dwFlags               : 0x810 HASINDEX | TRUSTCKTYPE
                     dwTotalFrames         : 2192
                     dwInitialFrames       : 0
                     dwStreams             : 1
                     dwSuggestedBufferSize : 120000
                     dwWidth               : 720
                     dwHeight              : 480
                     dwReserved            : 0x0
00000058         LIST (0000006C) 'strl'
00000064             strh (00000038)
                         fccType               : 'iavs'
                         fccHandler            : 'dvsd'
                         dwFlags               : 0x0
                         wPriority             : 0
                         wLanguage             : 0x0 undefined
                         dwInitialFrames       : 0
                         dwScale               : 100 (29.970 Frames/Sec)
                         dwRate                : 2997
                         dwStart               : 0
                         dwLength              : 2192
                         dwSuggestedBufferSize : 120000
                         dwQuality             : 0
                         dwSampleSize          : 0
                         rcFrame               : 0,0,720,480
000000A4             strf (00000020)
                         dwDVAAuxSrc     : 0x........
                         dwDVAAuxCtl     : 0x........
                         dwDVAAuxSrc1    : 0x........
                         dwDVAAuxCtl1    : 0x........
                         dwDVVAuxSrc     : 0x........
                         dwDVVAuxCtl     : 0x........
                         dwDVReserved[2] : 0,0
000000CC     LIST (0FADAC00) 'movi'
0FADACD4     idx1 (00008900)

AVI Files Containing DV Video as a 'vids' Stream and DV Audio as 'auds' Streams

Interleaved DV data can be split into a video stream and one to four audio streams within an AVI RIFF file. This has the advantage of being backward-compatible with Video for Windows, because it contains a standard video 'vids' stream and at least one standard audio 'auds' stream The primary disadvantage is that this file format requires the audio data to be redundantly stored as audio streams. The "video" stream is actually the native interleaved DV data stream. However, as a standard 'vids' stream with a handler type of 'dvsd', the DV Video Decoder is used. This format also requires that "captured" files are split by using the DV Splitter filter before they are written as AVI files.

DV data can be stored as a video stream with a separate number of audio streams in an AVI RIFF file. The video stream is specified with a standard video stream header (the fccType member value is 'vids'). The fccHandler member is specified as 'dvsd', 'dvhd', or 'dvsl'. The frames per second of the video stream must be specified in the dwRate and dwScale members and the total number of video blocks in the 'movi' chunk in the dwLength member.

In this AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams form of DV, the video stream format chunk is a standard BITMAPINFOHEADER structure. The stream format chunk can be optionally extended to include the DVINFO structure, by increasing the stream format chunk size from 40 bytes (size of the BITMAPINFOHEADER structure) to 72 bytes (size of BITMAPINFOHEADER plus DVINFO structures) and immediately following the BITMAPINFOHEADER data structure with a DVINFO data structure.

The audio stream(s) is specified with a standard audio stream header (the fccType member value is 'auds'). The fccHandler member is not used for audio streams.

The DV video data is stored as '##dc' chunks, as defined in the preceding description of an AVI file with one DV data, and the audio data is stored as '##wb' chunks in the 'movi' chunk.

The following diagram illustrates the playback of an AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams, by using a DirectShow filter graph (the DV Video Decoder filter is included in DirectShow specifically to deal with DV data). The DV media types table defines the media types.

Playback of an AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams

The following diagram illustrates the creation of an AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams, using a DirectShow filter graph (the DV Video Decoder is included in DirectShow specifically to deal with DV data). The DV media types table defines the media types. Upstream filters (not shown) can be of any combination to produce the proper media types, D and E.

Creation of an AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams

The following diagram illustrates the creation of an AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams using a source filter that communicates through hardware device drivers with a DV device (such as a 1394-based DV camcorder) for DV data input, by using a DirectShow filter graph (the source and DV Splitter filters are included in DirectShow specifically to deal with DV data). The DV media types table defines the media types.

DV capture to an AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams

The following diagram illustrates the output of an AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams using a sink filter that communicates through hardware device drivers with a DV device (such as a 1394-based DV camcorder) for DV data output, by using a DirectShow filter graph (the DV Mux and sink filters are included in DirectShow specifically to deal with DV data). The DV media types table defines the media types.

Output of an AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams

The following example shows the AIFF RIFF form for an AVI file containing DV video as a 'vids' stream and DV audio as 'auds' streams expanded with completed header chunks (including optional DVINFO data following the BITMAPINFO in the 'strf' sub-chunk for the 'vids' stream).

00000000 RIFF (103E2920) 'AVI '
0000000C     LIST (00000146) 'hdrl'
00000018         avih (00000038)
                     dwMicroSecPerFrame    : 33367
                     dwMaxBytesPerSec      : 3728000
                     dwPaddingGranularity  : 0
                     dwFlags               : 0x810 HASINDEX | TRUSTCKTYPE
                     dwTotalFrames         : 2192
                     dwInitialFrames       : 0
                     dwStreams             : 2
                     dwSuggestedBufferSize : 120000
                     dwWidth               : 720
                     dwHeight              : 480
                     dwReserved            : 0x0
00000058         LIST (00000094) 'strl'
00000064             strh (00000038)
                         fccType               : 'vids'
                         fccHandler            : 'dvsd'
                         dwFlags               : 0x0
                         wPriority             : 0
                         wLanguage             : 0x0 undefined
                         dwInitialFrames       : 0
                         dwScale               : 100 (29.970 Frames/Sec)
                         dwRate                : 2997
                         dwStart               : 0
                         dwLength              : 2192
                         dwSuggestedBufferSize : 120000
                         dwQuality             : 0
                         dwSampleSize          : 0
                         rcFrame               : 0,0,720,480
000000A4             strf (00000048)
                         biSize          : 40
                         biWidth         : 720
                         biHeight        : 480
                         biPlanes        : 1
                         biBitCount      : 24
                         biCompression   : 0x64737664 'dvsd'
                         biSizeImage     : 120000
                         biXPelsPerMeter : 0
                         biYPelsPerMeter : 0
                         biClrUsed       : 0
                         biClrImportant  : 0
                         dwDVAAuxSrc     : 0x........
                         dwDVAAuxCtl     : 0x........
                         dwDVAAuxSrc1    : 0x........
                         dwDVAAuxCtl1    : 0x........
                         dwDVVAuxSrc     : 0x........
                         dwDVVAuxCtl     : 0x........
                         dwDVReserved[2] : 0,0
000000F4         LIST (0000005E) 'strl'
00000100             strh (00000038)
                         fccType               : 'auds'
                         fccHandler            : '    '
                         dwFlags               : 0x0
                         wPriority             : 0
                         wLanguage             : 0x0 undefined
                         dwInitialFrames       : 0
                         dwScale               : 1 (32000.000 Samples/Sec)
                         dwRate                : 32000
                         dwStart               : 0
                         dwLength              : 2340474
                         dwSuggestedBufferSize : 4272
                         dwQuality             : 0
                         dwSampleSize          : 4
                         rcFrame               : 0,0,0,0
00000140             strf (00000012)
                         wFormatTag      : 1 PCM
                         nChannels       : 2
                         nSamplesPerSec  : 32000
                         nAvgBytesPerSec : 128000
                         nBlockAlign     : 4
                         wBitsPerSample  : 16
                         cbSize          : 0
00000814     LIST (103D0EF4) 'movi'
103D1710     idx1 (00011210)

AVI RIFF File Reference

The Microsoft AVI file format is a RIFF file specification used with applications that capture, edit, and play back audio-video sequences. In general, AVI files contain multiple streams of different types of data. Most AVI sequences use both audio and video streams. A simple variation for an AVI sequence uses video data and does not require an audio stream.

Modifications to the original AVI file specification made in the OpenDML AVI File Format Extensions are not discussed in this section. For further information on these extensions, see version 1.02 of the OpenDML AVI File Format Extensions published by the OpenDML AVI M-JPEG File Format Subcommittee, February 28, 1996.

This section contains the following topics.

  • AVI RIFF Form
  • AVI Main Header
  • AVI Stream Headers
  • Stream Data (LIST 'movi' Chunk)
  • BITMAPINFOHEADER Structure
  • WAVEFORMATEX Structure

AVI RIFF Form

AVI files use the AVI RIFF form. The AVI RIFF form is identified by the FOURCC (four-character code) 'AVI '. All AVI files include two mandatory LIST chunks. These chunks define the format of the stream and stream data. AVI files might also include an index chunk. This optional chunk specifies the location of data chunks within the file. An AVI file with these components has the following form:

RIFF ('AVI '
      LIST ('hdrl'
              .
              .
              .
           )
      LIST ('movi'
              .
              .
              .
           )
      ['idx1'<AVI Index>]
     )

The LIST chunks and the index chunk are subchunks of the RIFF 'AVI ' chunk. The 'AVI ' chunk identifies the file as an AVI RIFF file. The LIST 'hdrl' chunk defines the format of the data and is the first required LIST chunk. The LIST 'movi' chunk contains the data for the AVI sequence and is the second required LIST chunk. The 'idx1' chunk is the index chunk. AVI files must keep these three components in the proper sequence.

The LIST 'hdrl' and LIST 'movi' chunks use subchunks for their data. The following example shows the AVI RIFF form expanded with the chunks needed to complete the LIST 'hdrl' and LIST 'movi' chunks:

RIFF ('AVI '
      LIST ('hdrl'
            'avih'(<Main AVI Header>)
            LIST ('strl'
                  'strh'(<Stream header>)
                  'strf'(<Stream format>)
                  'strd'(<additional header data>)
                  'strn'(<Stream name>)
                  ...
                 )
             .
             .
             .
           )

      LIST ('movi'
            {SubChunk | LIST ('rec '
                              SubChunk1
                              SubChunk2
                                .
                                .
                                .
                             )
               .
               .
               .
            }
            .
            .
            .
           )

      ['idx1'<AVI Index>]
     )

AVI Main Header

This and following sections describe the chunks contained in the LIST 'hdrl' and LIST 'movi' chunks. The 'idx1' chunk is not described in this document. For more information on the 'idx1' chunk and indexes in AVI files, see version 1.02 of the OpenDML AVI File Format Extensions published by the OpenDML AVI M-JPEG File Format Subcommittee, February 28, 1996.

The file begins with the main header. In the AVI file, this header is identified by the 'avih' FOURCC (four-character code). The header contains global information for the entire AVI file, such as the number of streams within the file and the width and height of the AVI sequence. The AVI main header structure is defined as follows:

typedef struct {
    DWORD dwMicroSecPerFrame;
    DWORD dwMaxBytesPerSec;
    DWORD dwReserved1;
    DWORD dwFlags;
    DWORD dwTotalFrames;
    DWORD dwInitialFrames;
    DWORD dwStreams;
    DWORD dwSuggestedBufferSize;
    DWORD dwWidth;
    DWORD dwHeight;
    DWORD dwReserved[4];
} MainAVIHeader;
dwMicroSecPerFrame
Specifies the number of microseconds between frames. This value indicates the overall timing for the file.
dwMaxBytesPerSec
Specifies the approximate maximum data rate of the file. This value indicates the number of bytes per second the system must handle to present an AVI sequence as specified by the other parameters contained in the main header and stream header chunks.
dwReserved1
Reserved. Set this to zero.
dwFlags
Contains any flags for the file. The following flags are defined.
AVIF_HASINDEX | Indicates the AVI file has an 'idx1' chunk containing an index at the end of the file. For good performance, all AVI files should contain an index.
AVIF_MUSTUSEINDEX | Indicates that the index, rather than the physical ordering of the chunks in the file, should be used to determine the order of presentation of the data. For example, you could use this to create a list of frames for editing.
AVIF_ISINTERLEAVED | Indicates the AVI file is interleaved.
AVIF_WASCAPTUREFILE | Indicates the AVI file is a specially allocated file used for capturing real-time video. Applications should warn the user before writing over a file with this flag set because the user probably defragmented this file.
AVIF_COPYRIGHTED | Indicates the AVI file contains copyrighted data and software. When this flag is used, software should not permit the data to be duplicated.
dwTotalFrames
Specifies the total number of frames of data in the file.
dwInitialFrames
Specifies the initial frame for interleaved files. Noninterleaved files should specify zero. If you are creating interleaved files, specify the number of frames in the file prior to the initial frame of the AVI sequence in this member. For more information about the contents of this member, see "Special Information for Interleaved Files" in the Video for Windows Programmer's Guide.
dwStreams
Specifies the number of streams in the file. For example, a file with audio and video has two streams.
dwSuggestedBufferSize
Specifies the suggested buffer size for reading the file. Generally, this size should be large enough to contain the largest chunk in the file. If set to zero, or if it is too small, the playback software will have to reallocate memory during playback, which will reduce performance. For an interleaved file, the buffer size should be large enough to read an entire record, and not just a chunk.
dwWidth
Specifies the width of the AVI file in pixels.
dwHeight
Specifies the height of the AVI file in pixels.
dwReserved[4]
Reserved. Set this array to zero.

AVI Stream Headers

The main header is followed by one or more 'strl' chunks. (A 'strl' chunk is required for each data stream.) These chunks contain information about the streams in the file. Each 'strl' chunk must contain a stream header and stream format chunk. Stream header chunks are identified by the FOURCC (four-character code) 'strh' and the stream format chunks are identified by the FOURCC 'strf'. In addition to the stream header and stream format chunks, the 'strl' chunk might also contain a stream-header data chunk and a stream name chunk. Stream-header data chunks are identified by the FOURCC 'strd'. Stream name chunks are identified by the FOURCC 'strn'.

The stream header structure contains header information for a single stream of a file.

typedef struct {
    FOURCC fccType;
    FOURCC fccHandler;
    DWORD  dwFlags;
    DWORD  dwPriority;
    DWORD  dwInitialFrames;
    DWORD  dwScale;
    DWORD  dwRate;
    DWORD  dwStart;
    DWORD  dwLength;
    DWORD  dwSuggestedBufferSize;
    DWORD  dwQuality;
    DWORD  dwSampleSize;
    RECT   rcFrame;
} AVIStreamHeader;

The stream header specifies the type of data the stream contains, such as audio or video, by means of a FOURCC.

fccType
Contains a FOURCC that specifies the type of the data contained in the stream. The following standard AVI values for video and audio are defined.
'vids' | Indicates the stream contains video data. The stream format chunk contains a BITMAPINFO structure that can include palette information.
'auds' | Indicates the stream contains audio data. The stream format chunk contains a WAVEFORMATEX or PCMWAVEFORMAT structure.
'txts' | Indicates the stream contains text data.
fccHandler
Optionally, contains a FOURCC that identifies a specific data handler. The data handler is the preferred handler for the stream. For audio and video streams, this specifies the installable compressor or decompressor.
dwFlags
Contains any flags for the data stream. The bits in the high-order word of these flags are specific to the type of data contained in the stream. The following standard flags are defined.
AVISF_DISABLED | Indicates this stream should not be enabled by default.
AVISF_VIDEO_PALCHANGES | Indicates this video stream contains palette changes. This flag warns the playback software that it will need to animate the palette.
dwPriority
Specifies priority of a stream type. For example, in a file with multiple audio streams, the one with the highest priority might be the default stream.
dwInitialFrames
Specifies how far audio data is skewed ahead of the video frames in interleaved files. Typically, this is about 0.75 seconds. If you are creating interleaved files, specify the number of frames in the file prior to the initial frame of the AVI sequence in this member. For more information about the contents of this member, see "Special Information for Interleaved Files" in the Video for Windows Programmer's Guide.
dwScale
Used with dwRate to specify the time scale that this stream will use. Dividing dwRate by dwScale gives the number of samples per second. For video streams, this rate should be the frame rate. For audio streams, this rate should correspond to the time needed for nBlockAlign bytes of audio, which for PCM audio simply reduces to the sample rate.
dwRate
See dwScale.
dwStart
Specifies the starting time of the AVI file. The units are defined by the dwRate and dwScale members in the main file header. Usually, this is zero, but it can specify a delay time for a stream that does not start concurrently with the file.
dwLength
Specifies the length of this stream. The units are defined by the dwRate and dwScale members of the stream's header.
dwSuggestedBufferSize
Specifies how large a buffer should be used to read this stream. Typically, this contains a value corresponding to the largest chunk present in the stream. Using the correct buffer size makes playback more efficient. Use zero if you do not know the correct buffer size.
dwQuality
Specifies an indicator of the quality of the data in the stream. Quality is represented as a number between 0 and 10,000. For compressed data, this typically represents the value of the quality parameter passed to the compression software. If set to –1, drivers use the default quality value.
dwSampleSize
Specifies the size of a single sample of data. This is set to zero if the samples can vary in size. If this number is nonzero, then multiple samples of data can be grouped into a single chunk within the file. If it is zero, each sample of data (such as a video frame) must be in a separate chunk. For video streams, this number is typically zero, although it can be nonzero if all video frames are the same size. For audio streams, this number should be the same as the nBlockAlign member of the WAVEFORMATEX structure describing the audio.
rcFrame
Specifies the destination rectangle for a text or video stream within the movie rectangle specified by the dwWidth and dwHeight members of the AVI main header structure. The rcFrame member is typically used in support of multiple video streams. Set this rectangle to the coordinates corresponding to the movie rectangle to update the whole movie rectangle. Units for this member are pixels. The upper-left corner of the destination rectangle is relative to the upper-left corner of the movie rectangle.

The last eight members describe the playback characteristics of the stream. These factors include the playback rate (dwScale and dwRate), the starting time of the sequence (dwStart), the length of the sequence (dwLength), the size of the playback buffer (dwSuggestedBuffer), an indicator of the data quality (dwQuality), and the sample size (dwSampleSize).

Some of the members in the stream header structure are also present in the main header structure. The data in the main header applies to the whole file, while the data in the stream header structure applies only to a stream.

A stream format ('strf') chunk must follow a stream header ('strh') chunk. The stream format chunk describes the format of the data in the stream. For video streams, the information in this chunk is a BITMAPINFO structure (including palette information if appropriate). For audio streams, the information in this chunk is a WAVEFORMATEX or PCMWAVEFORMAT structure. (The WAVEFORMATEX structure is an extended version of the WAVEFORMAT structure.) For more information about this structure and other stream types, see the New Multimedia Data Types and Data Techniques Standards Update.

The 'strl' chunk might also contain an additional stream-header data ('strd') chunk. If used, this chunk follows the stream format chunk. The format and content of this chunk is defined by installable compression or decompression drivers. Typically, drivers use this information for configuration. Applications that read and write RIFF files do not need to decode this information. They transfer this data to and from a driver as a memory block.

The optional 'strn' stream name chunk provides a zero-terminated text string describing the stream. (The AVI file functions can use this chunk to let applications identify the streams they want to access by their names.)

An AVI player associates the stream headers in the LIST 'hdrl' chunk with the stream data in the LIST 'movi' chunk by using the order of the 'strl' chunks. The first 'strl' chunk applies to stream 0, the second applies to stream 1, and so forth.

For example, if the first 'strl' chunk describes the wave audio data, the wave audio data is contained in stream 0. Similarly, if the second 'strl' chunk describes video data, then the video data is contained in stream 1.

Stream Data (LIST 'movi' Chunk)

Following the header information is a LIST 'movi' chunk that contains chunks of the actual data in the streams - that is, the pictures and sounds themselves. The data chunks can reside directly in the LIST 'movi' chunk or they might be grouped into 'rec' chunks. The 'rec' grouping implies that the grouped chunks should be read from disk all at once. This is used only for files specifically interleaved to play from CD-ROM.

Like any RIFF chunk, the data chunks contain a FOURCC (four-character code) to identify the chunk type. A FOURCC is a 32-bit quantity represented as a sequence of one to four ASCII alphanumeric characters, padded on the right with blank characters. The FOURCC that identifies each chunk consists of the stream number and a two-character code that defines the type of information encapsulated in the chunk. For example, a waveform chunk is identified by a two-character code of 'wb'. If a waveform chunk corresponded to the second LIST 'hdrl' stream description, it would have a FOURCC of '01wb'.

Note While two-character codes are a convenient way to describe a stream, do not expect them to be recognized by other applications. Use FOURCCs when creating a stream or transferring the information to other applications.

Because all the format information is in the header, the audio data contained in these data chunks does not contain any information about its format. An audio data chunk has the following format (the ## in the format represents the stream identifier):

WAVE Bytes '##wb'
     BYTE  abBytes[];

Video data can be compressed or uncompressed DIBs. An uncompressed DIB has BI_RGB specified for the biCompression member in its associated BITMAPINFO structure. A compressed DIB has a value other than BI_RGB specified in the biCompression member. For more information about compression formats, see the description of the BITMAPINFOHEADER data structure in the Microsoft Windows Programmer's Reference.

A data chunk for an uncompressed DIB contains RGB video data. These chunks are identified by a two-character code of 'db' (db is an abbreviation for DIB bits). Data chunks for a compressed DIB are identified by a two-character code of 'dc' (dc is an abbreviation for DIB compressed). Neither data chunk will contain any header information about the DIBs. The data chunk for an uncompressed DIB has the following form:

DIB  Bits  '##db'
     BYTE  abBits[];

The data chunk for a compressed DIB has the following form.

Compressed DIB  Bits  '##dc'
                BYTE  abBits[];

Video data chunks can also define new palette entries used to update the palette during an AVI sequence. For more information on specifying palette information, see Video for Windows Programmer's Guide.

Text streams can use arbitrary two-character codes.

BITMAPINFOHEADER Structure

The BITMAPINFOHEADER structure contains information for the video stream of an AVI RIFF file. This structure has the following members.

typedef struct tagBITMAPINFOHEADER {
    DWORD  biSize;
    LONG   biWidth;
    LONG   biHeight;
    WORD   biPlanes;
    WORD   biBitCount;
    DWORD  biCompression;
    DWORD  biSizeImage;
    LONG   biXPelsPerMeter;
    LONG   biYPelsPerMeter;
    DWORD  biClrUsed;
    DWORD  biClrImportant;
} BITMAPINFOHEADER;
biSize
Specifies the number of bytes required by the structure.
biWidth
Specifies the width of the bitmap, in pixels.
biHeight
Specifies the height of the bitmap, in pixels. If biHeight is positive, the bitmap is a bottom-up DIB (device-independent bitmap) and its origin is the lower left corner. If biHeight is negative, the bitmap is a top-down DIB and its origin is the upper left corner.
biPlanes
Specifies the number of planes for the target device. This value must be set to 1.
biBitCount
Specifies the number of bits per pixel. Some compression formats need this information to properly decode the colors in the pixel.
biCompression
Specifies the type of compression used or requested. Both existing and new compression formats use this member.
biSizeImage
Specifies the size, in bytes, of the image. This can be set to 0 for uncompressed RGB bitmaps.
biXPelsPerMeter
Specifies the horizontal resolution, in pixels per meter, of the target device for the bitmap. An application can use this value to select a bitmap from a resource group that best matches the characteristics of the current device.
biYPelsPerMeter
Specifies the vertical resolution, in pixels per meter, of the target device for the bitmap.
biClrUsed
Specifies the number of color indices in the color table that are actually used by the bitmap. If this value is zero, the bitmap uses the maximum number of colors corresponding to the value of the biBitCount member for the compression mode specified by biCompression.
biClrImportant
Specifies the number of color indices that are considered important for displaying the bitmap. If this value is zero, all colors are important.

When the value in the biBitCount member is set to greater than eight, video drivers can assume bitmaps are true color and they do not use a color table.

When the value in the biBitCount member is set to less than or equal to eight, video drivers can assume the bitmap uses a palette or color table defined in the BITMAPINFO data structure. This data structure has the following members:

typedef struct tagBITMAPINFO {
    BITMAPINFOHEADER bmiHeader;
    RGBQUAD          bmiColors[1];
} BITMAPINFO;

The BITMAPINFO bmiheader member specifies a BITMAPINFOHEADER structure. The BITMAPINFO bmiColors member specifies an array of RGBQUAD data types that define the colors in the bitmap.

WAVEFORMATEX Structure

The WAVEFORMATEX structure contains information for the audio stream(s) of an AVI RIFF file. This structure has the following members.

typedef struct waveformat_extended_tag {
    WORD  wFormatTag;
    WORD  nChannels;
    DWORD nSamplesPerSec;
    DWORD nAvgBytesPerSec;
    WORD  nBlockAlign;
    WORD  wBitsPerSample;
    WORD  cbSize;
} WAVEFORMATEX;
wFormatTag
Defines the audio waveform type of the audio stream. A complete list of format tags can be found in the Mmreg.h header file included with Microsoft® Visual C++® and other Microsoft products.
nChannels
Specifies the number of channels in the audio stream, 1 for mono, 2 for stereo.
nSamplesPerSec
Specifies the frequency of the sample rate of the audio stream in samples/second (Hz). Examples are 11,025, 22,050, or 44,100.
nAvgBytesPerSec
Specifies the average data rate. Playback software can estimate the buffer size by using this value.
nBlockAlign
Specifies the block alignment of the data, in bytes. Playback software must process a multiple of nBlockAlign bytes of data at a time, so that the value of nBlockAlign can be used for buffer alignment.
wBitsPerSample
Specifies the number of bits per sample per channel data. Each channel is assumed to have the same sample resolution. If this field is not needed, then you should set it to zero.
cbSize
Specifies the size, in bytes, of the extra information in the format header, not including the size of the WAVEFORMATEX structure. For example, in the wave format corresponding to the wFormatTag WAVE_FORMAT_IMA_ADPCM, cbSize is calculated as sizeof(IMAADPCMWAVEFORMAT) - sizeof(WAVEFORMATEX), which yields two.

AVI 2.0 File Format Extensions

DirectShow currently supports the following AVI 2.0 file format extensions.

  • Increased AVI file size (greater than 1 GB)
  • Hierarchical indexing

See the specification in version 1.02 of the OpenDML AVI File Format Extensions published by the OpenDML AVI M-JPEG File Format Subcommittee, February 28, 1996.


Registering a Custom File Type

This article describes how to register a new file type so that file-reader source filters can recognize it. The mechanism used here is taken from the Microsoft® Win32® GetClassFile function, which is used to return the CLSID associated with the given file name. Microsoft® DirectShow® media types use the same quadruple set of values in the registry that are used for GetClassFile FileType registrations, but associate a file matching this criteria with a media type rather than a file type. Also, the registry entry for a DirectShow media type provides the CLSID of a source filter that can be used to read this media type.

For both FileType and MediaType registration, a pattern in the registry contains a series of entries of the form:

regdb key = offset, cb, mask, value

The media type is defined as a CLSID pair, {Majortype clsid, Subtype clsid}. If the data in the file at the specified offset or offsets matches a pattern in HKEY_CLASSES_ROOT\Media Type\{<major type>}\{<subtype>}, the media type CLSID pair associated with that pattern is the media type of the file.

The parameters of the registry key are interpreted as follows. The value of the offset item is an offset from the beginning or end of the file, and the cb item is a length in bytes. These two decimal values represent a particular byte range in the file. (A negative value for the offset item is interpreted from the end of the file.) The mask value is a hexadecimal bit mask that is used to perform a logical AND operation, with the byte range specified by offset and cb. The result of the logical AND operation is compared with the value item. If the mask is omitted, it is assumed to be all ones. The number of hexadecimal digits in mask and value must be twice the value of cb (because cb is in bytes).

Each pattern in the registry is compared to the file in the order of the patterns in the database. The first pattern where each of the value items matches the result of the AND operation determines the media type of the file.

Note that each entry can have multiple quadruples, all of which must match the data in the file for the media type to be associated with the file. An example of using multiple quadruples in a single entry might be to match the byte sequence at the beginning and at the end of the file. The following example shows a pattern of AB CD 12 34 as the first 4 bytes in the file and AB AB 00 AB as the last 4 bytes in the file (no masks applied here). All elements must match for the pattern to match a file with a media type.

0 = REG_SZ 0, 4, , ABCD1234,  -4, 4, , ABAB00AB

Additionally, there can be multiple entries specified under a single media type, a match to any one of which will associate the file with the media type.

For example, the pattern contained in the following entries of the registry requires that the first three bytes be AB CD 12, that the fourth byte be 32, 33, 34, or 35, and that the last 4 bytes be FE FE FE FE:

HKEY_CLASSES_ROOT
    Media Type
         {12345678-0000-0001-C000-000000000095}
                {87654321-0000-0001-C000-000000000095}
                    0 = REG_SZ 0, 4, FFFFFFFE, ABCD1234, -4, 4, , FEFEFEFE
                    1 = REG_SZ 0, 4, FFFFFFFE, ABCD1232, -4, 4, , FEFEFEFE
                    Source Filter = {56781234-0000-0001-C000-000000000095}

If a file contains such a pattern, the media type {12345678-0000-0001-C000-000000000095}{87654321-0000-0001-C000-000000000095} will be associated with this file. The file source filter for the media type is identified by the CLSID of the Source Filter value under the key for the media type.

The media type can be used to find filter handlers for the file in order to render it. A handler for a type performs a more exact test of the file to be sure of the type before attempting to render the data.

Note that this scheme allows for a set of alternative masks (for instance, .wav files) that might or might not have a RIFF header.

Registering File Extensions Without Byte Extensions

As mentioned previously, you can register a particular media type/subtype pair or a source filter CLSID for a given file extension. In this case, only the type and source filter will be used to read the media type. However, if you register your own source filter, there is no requirement for the name to represent a real file because the name gets passed to the source filter for interpretation.

The registry entries are as follows.

HKEY_CLASSES_ROOT\Media Type\Extensions

If the file extension is .foo, the key has the following structure.

.foo
REG_SZ: Media Type
REG_SZ: Subtype
REG_SZ: Source Filter

Each value represents a GUID.


Debugging with DirectShow

This article provides some tips for debugging Microsoft® DirectShow® applications and filters.

This article contains the following sections:

  • Assertion Checking
  • Object Names
  • Debug Logging
  • Critical Sections
  • Pointer Validation

See also: Simulating Graph Building with GraphEdit

Assertion Checking

Use assertion checking liberally. Assertions can verify assumptions that you make in your code about preconditions and postconditions. DirectShow provides several assertion macros. For more information, see Assert and Breakpoint Macros.

For example, a pin class might contain a private method that assumes the pin is connected. You can test this assumption with an assertion, as follows:

ASSERT(IsConnected());  // Pin must be connected.

Object Names

In debug builds, there is a global list of objects that derive from the CBaseObject class. As objects are created, they are added to the list. When they are destroyed, they are removed from the list. To display a list of those objects, call the DbgDumpObjectRegister function.

The constructor method for the CBaseObject base class—and most classes derived from it—includes a parameter for the name of the object. Give your objects unique names to identify them. If you use the NAME macro when you declare the name, storage for the name is only allocated in debug builds. In retail builds, the name becomes NULL.

Debug Logging

The DbgLog function displays debugging messages as your program executes. Use this function to trace the execution of your application or filter. You can log return codes, the values of variables, and any other relevant information.

Every debug message has a type, such as LOG_TRACE or LOG_ERROR, and a debug level, which indicates the importance of the message. Messages with lower debug levels are more important than those with higher levels.

In the following example, a hypothetical filter disconnects a pin from an array of pins. If the disconnect attempt succeeds, the filter displays a LOG_TRACE message. If the attempt fails, it displays a LOG_ERROR message:

hr = m_PinArray[iPin]->Disconnect();
if (FAILED(hr))
{
    DbgLog((LOG_ERROR, 1, TEXT("Could not disconnect pin %d. HRESULT = %#x", iPin, hr));

   // Error handling code (not shown).
}
DbgLog((LOG_TRACE, 3, TEXT("Disconnected pin %d"), iPin));

When you are debugging, you can set the debug level for each message type. Also, each module (DLL or executable) maintains its own debugging levels. If you are testing a filter, raise the debug levels for the DLL that contains the filter. For more information, see Debug Output Functions.

Critical Sections

To make deadlocks easier to track, include assertions that determine whether the calling code owns a given critical section. The CritCheckIn and CritCheckOut functions indicate whether the calling thread owns a critical section. Typically, you would call these functions from inside an assert macro. For more information, see CCritSec Debug Functions.

You can also use the DbgLockTrace function to trace when critical sections are held or released.

Pointer Validation

Consider validating pointers. For example, the ValidateReadPtr macro checks whether a specified pointer points to readable memory. Currently, the DirectShow pointer validation macros use Microsoft® Win32® pointer validation functions, such as IsBadReadPtr. On some systems, these functions swap in every page in the specified range, which can greatly reduce performance. For more information, see Pointer Validation Macros.


Programming Tips

This article contains information to help you develop Microsoft® DirectShow® applications effectively.

Global Objects

A global C++ object should not create DirectShow objects in its constructor method or release them in its destructor method. Doing so can cause the application to block indefinitely, for the following reason:

Threads cannot exit while inside a DLL's entry-point function. Kernel 32 holds a global process during the entry-point function, and the lock prevents the thread from exiting. Because some DirectShow objects own threads, they can block if released from inside a DLL entry-point function. If an application has a global C++ object, the C runtime DLL calls the object's destructor when the DLL is unloaded. If the destructor releases DirectShow objects, it can block as a result.

For similar reasons, a DLL should not create or release DirectShow objects in its entry point routine.

Filter Properties

If you create a DirectShow filter, application writers can be given access to your properties in a number of ways. You can provide property pages using the IProvidePropertyPages interface, which the application can then display. To allow the application to provide its own UI, you can also support the IPropertyBag interface which allows the application to query your filter and discover the properties. If you want to provide a specialized interface for your properties, you can also tailor an interface specifically to your filter and pin information.


Decoder Development

This section contains articles covering user mode aspects of decoder development for Microsoft® DirectShow®.

  • DirectX Video Acceleration
  • DVD Decoder Development


DirectX Video Acceleration

Microsoft DirectX 8.0

Microsoft DirectX VA: Video Acceleration
API/DDI Specification (Rev 1.0)

Note: The most recent version of this specification is available for download in Microsoft® Word® format at http://www.microsoft.com/hwdev/DirectX_VA/.

Abstract: This document describes an Application Programming Interface (API) and a corresponding Device Driver Interface (DDI) for hardware acceleration of digital video decoding processing, with support of alpha blending for such purposes as DVD subpicture support. It provides an interface definition focused on support of MPEG-2 "main profile" video (formally ITU-T H.262 | ISO/IEC 13818-2), but is also intended to support other key video codecs (for example, ITU-T Recommendations H.263 and H.261, and MPEG-1 and MPEG-4).

Contents

  • 1 Overview
    • 1.1 Summary
    • 1.2 Purpose and Standards Addressed
    • 1.3 Requirements, Performance Verification, and Schedule
      • 1.3.1 Uncompressed Picture Formats
      • 1.3.2 Accelerator Sequentiality Requirements
      • 1.3.3 Software Decoder Sequentiality Requirements
        • 1.3.3.1 Using Four Uncompressed Surfaces for Decoding
        • 1.3.3.2 Using Five or More Uncompressed Surfaces for Decoding
    • 1.4 Terminology
      • 1.4.1 Abbreviations and Symbols
      • 1.4.2 Bit Numbering Convention
      • 1.4.3 Definitions
    • 1.5 Stages
    • 1.6 Frame Buffer Organization
  • 2 Operation for Current Standards
    • 2.1 ITU-T H.261
    • 2.2 MPEG-1
    • 2.3 MPEG-2 (a.k.a. H.262)
    • 2.4 ITU-T H.263
    • 2.5 MPEG-4
    • 2.6 Prediction Principles
      • 2.6.1 Stages of Prediction
      • 2.6.2 Macroblock Portions
      • 2.6.3 Prediction Planes
  • 3 DirectX VA Data Structures and Program Constructs
    • 3.1 Encryption Support
    • 3.2 Global Restricted Mode Information
    • 3.3 Probing and Locking of Configurations
    • 3.4 Buffer Description List
    • 3.5 Compressed Picture Decoding (bDXVA_Func=1)
      • 3.5.1 Connection Configuration
      • 3.5.2 Minimal Interoperability Configuration Set
      • 3.5.3 Additional Encouraged Configuration Set
      • 3.5.4 Compressed Picture Parameters
      • 3.5.5 Buffer Structure for Macroblocks of a Picture
        • 3.5.5.1 Macroblock Control Commands
        • 3.5.5.2 Inverse Quantization, Pre-IDCT Saturation, Mismatch Control, Intra DC Offset, IDCT, Picture Reconstruction, and Reconstruction Clipping
          • 3.5.5.2.1 Off-Host IDCT
            • 3.5.5.2.1.1 Single-Coefficient Data Format
            • 3.5.5.2.1.2 Four-Grouped Coefficient Data Format
          • 3.5.5.2.2 Host-Based IDCT
            • 3.5.5.2.2.1 The 16-bit Method
            • 3.5.5.2.2.2 The 8-8 Overflow Method
        • 3.5.5.3 Deblocking Filter Control
        • 3.5.5.4 Read-Back Buffers
      • 3.5.6 Off-Host VLD Bitstream Decoding Operation
        • 3.5.6.1 Inverse Quantization Matrix Buffers
        • 3.5.6.2 Slice Control Buffers
        • 3.5.6.3 Bitstream Data Buffer Contents
    • 3.6 Alpha Blend Data Loading (bDXVA_Func=2)
      • 3.6.1 Connection Configuration
      • 3.6.2 Minimal Interoperability Configuration Set
      • 3.6.3 Loading an AYUV Alpha Blending Surface
        • 3.6.3.1 Loading a 16-entry AYUV palette
        • 3.6.3.2 Loading an AYUV surface
      • 3.6.4 Loading an IA44/AI44 Alpha Blending Surface
      • 3.6.5 Loading a DPXD Alpha Blending Surface
      • 3.6.6 Loading Highlight Data
      • 3.6.7 Loading DCCMD Data
    • 3.7 Alpha Blend Combination (bDXVA_Func=3)
      • 3.7.1 Connection Configuration
      • 3.7.2 Minimal Interoperability Configuration Set
      • 3.7.3 Alpha Blend Combination Buffers
        • 3.7.3.1 Example: MPEG-2 Pan-Scan Operation
        • 3.7.3.2 Example: DVD 4:3 Pan-Scan Within 16:9 Pictures
        • 3.7.3.3 Example: DVD 704-Wide Non-Pan-Scan Picture Operation
        • 3.7.3.4 Example: DVD 352-Wide Picture Operation
        • 3.7.3.5 Example: DVD 720-Wide Picture Operation
    • 3.8 Picture Resampling Control (bDXVA_Func=4)
      • 3.8.1 Connection Configuration
      • 3.8.2 Minimal Interoperability Configuration Set
      • 3.8.3 Picture Resampling Control Buffers
  • 4 Restricted Modes
    • 4.1 Addition of New Restricted Profiles
    • 4.2 Non-Restricted Operation
    • 4.3 H261_A Restricted Profile
    • 4.4 H261_B Restricted Profile
    • 4.5 H263_A Restricted Profile
    • 4.6 H263_B Restricted Profile
    • 4.7 H263_C Restricted Profile
    • 4.8 H263_D Restricted Profile
    • 4.9 H263_E Restricted Profile
    • 4.10 H263_F Restricted Profile
    • 4.11 MPEG1_A Restricted Profile
    • 4.12 MPEG2_A Restricted Profile
    • 4.13 MPEG2_B Restricted Profile
    • 4.14 MPEG2_C Restricted Profile
    • 4.15 MPEG2_D Restricted Profile
  • 5 IAMVideoAccelerator Operation
    • 5.1 The IAMVideoAccelerator Interface Itself
    • 5.2 Mapping DirectX VA to IAMVideoAccelerator
      • 5.2.1 Restricted Mode Profile and Configuration Establishment
      • 5.2.2 DirectX VA IAMVideoAccelerator Operational Specification
      • 5.2.3 Operational Correspondence with Motion Compensation Device Driver

Overview

This document describes an Application Programming Interface (API) and a corresponding Device Driver Interface (DDI) for acceleration of digital video decoding processing, with support of alpha blending for such purposes as DVD subpicture support. It provides an interface definition focused on support of MPEG-2 "main profile" video (formally ITU-T H.262 | ISO/IEC 13818-2), but is also intended to support other key video codecs (e.g., ITU-T Recommendations H.263 and H.261, and MPEG-1 and MPEG-4). This design is limited to decoding support, but encoding features may be defined as the interface is further extended in the future. The interface is designed to extract the most basic computationally-intensive building-blocks of these various codec designs and support their acceleration in hardware.

Graphics hardware drivers should implement support for this interface to provide a generic form of access to the acceleration capabilities of their hardware implementations. Somewhat similar vendor-specific capabilities have been defined in the past by several companies for use with their graphics hardware. However, the intent of this specification is to establish a common interface to provide cross-vendor compatibility between software application programs and advanced graphics acceleration capabilities. The establishment of a common interface is expected to increase the capability of computing systems to support video, increase the demand for software applications that provide this capability, and increase the demand for high-performance graphics capabilities.

1.1 Summary

The interface defined in this specification is capable of supporting today's dominant standard motion-compensated video codecs, including the H.26x series from the ITU-T and the MPEG-x series from ISO/IEC JTC1. It is primarily designed to support the current most commercially dominant video codec known as MPEG-2, more formally known as ITU-T Recommendation H.262 or ISO/IEC 13838-2.

The syntax specified herein is designed to provide very direct support of that standard with very low "translation" requirements for converting its syntax to the format defined herein. Additional features have been added as necessary to support the other standards in a maximally consistent manner, and encryption is supported for applications which may require it. By extracting the core common basic operations of these various standards and confining some standard-specific processing to the host CPU, this interface enables support of video codec hardware acceleration with a high degree of cross-standard flexibility while requiring minimal standard-specific customization in the acceleration hardware.

1.2 Purpose and Standards Addressed

This specification defines a language of video decoder acceleration which permits one or more stages to be divided among one or more devices. Currently, this document describes a division between a Host CPU and hardware Accelerator which executes the motion-compensated prediction (MCP) and/or inverse discrete-cosine transform (IDCT) stages of ITU-T H.261, MPEG-1 (ISO/IEC 11172-2), MPEG-2 (ISO/IEC 13818-2 | ITU-T Rec. H.262), ITU-T H.263, and a subset of MPEG-4 (ISO/IEC 14496-2). The overall goal is to offload simple (yet frequently-executed) operations wasteful of CPU resources onto a low-cost accelerator designed for this specific purpose, while allowing implementations to leave the complex, less frequently-executed operations such as bitstream parsing and variable-length decoding (VLD) on the host CPU.

The specification as described herein is for the decoding of a single video stream. No support is provided within the Microsoft® DirectX® VA API to explicitly support multiple video streams. Support of multiple video streams would therefore require a separate DirectX® VA session operation for each such video stream (e.g., a separate pair of output and input pins for the video decoder and acceleration driver for use in filter graph operation).

1.3 Requirements, Performance Verification, and Schedule

A verification of compliance with the contents of this specification will be required of any accelerator driver exposing the interface described herein. This will include:

  • Verification that the operations carried out by hardware using this API will yield the intended mathematical results, and
  • Verification that the performance obtained by a software decoder using this API will be of adequate speed and reliability to justify use of this API rather than host-software implementation of its functionality.

Until such verification is conducted, Microsoft considers the implementation to be strictly for testing purposes and not suitable for deployment with a driver that exposes the interface specified herein.

Support of this interface and performance verification for that support is expected to be required for certification of implementations for decoders and graphics accelerators in the intermediate-term future. The precise test suites and performance metrics are yet to be defined. The intermediate-term future requirements as specified herein are expected to be defined as requirements applicable in mid 2001 on all Microsoft Windows® operating systems (i.e., Windows 2000, Windows Millennium Edition, and Windows 2000 "Whistler") for any graphics acceleration hardware claiming support for hardware video decoding acceleration and for any software decoders claiming to use such graphics acceleration hardware support. Any longer-term future requirements as specified herein are expected to be defined as requirements applicable approximately one year after the intermediate-term requirements. The deadline dates of these expected requirements may be adjusted as events progress.

Anticipated encryption, configuration, and restricted mode support requirements are discussed below in the sections that describe the encryption support, configurations and restricted modes. Pixel format support requirements are discussed below in this section.

1.3.1 Uncompressed Picture Formats

For applications to use the uncompressed decoded pictures produced through DirectX VA, these pictures must be produced in some known format. The list of uncompressed pixel formats supported by any DirectX VA accelerator shall contain at least one member of the following list of pixel formats. [Reference: YUV Formats]:

  1. For decoding compressed 4:2:2 video:
    1. "YUY2", in which the data can be treated as an array of unsigned char in which the first byte contains the first sample of Y, the second byte contains the first sample of Cb, the third byte contains the second sample of Y, the fourth byte contains the first sample of Cr; etc. (such that if addressed as an array of two little-endian WORD type variables, the first WORD contains Y0 in the LSBs and Cb in the MSBs and the second WORD contains Y1 in the LSBs and Cr in the MSBs). This is the preferred DirectX VA 4:2:2 pixel format, and is expected to be an intermediate-term requirement for DirectX VA accelerators supporting 4:2:2 video
    2. "UYVY", which is the same as "YUY2", except for swapping of the byte order in each word (such that if addressed as an array of two little-endian WORD type variables, the first WORD contains Cb in the LSBs and Y0 in the MSBs and the second WORD contains Cr in the LSBs and Y1 in the MSBs).
  2. For decoding compressed 4:2:0 video:
    1. "YUY2" as above, except that two lines of output Cb and Cr samples are produced for each actual line of 4:2:0 Cb and Cr samples, the second of each pair of such two lines being either a duplicate of the first or an average of the first and third. The ability to "front-end" convert from whichever format is in use to this format is expected to be an intermediate-term requirement.
    2. "UYVY" as above, except that two lines of output Cb and Cr samples are produced for each actual line of 4:2:0 Cb and Cr samples, the second of each pair of such two lines being a either a duplicate of the first or an average of the first and third.
    3. "YV12", in which all Y samples are found first in memory as an array of unsigned char (possibly with a larger stride for memory alignment), followed immediately by all Cr samples (with half the stride of the Y lines, and half the number of lines), then followed immediately by all Cb samples in a similar fashion.
    4. "IYUV", which is the same as YV12, except for swapping the order of the Cb and Cr planes.
    5. "NV12" (not found in the referenced Web page), in which all Y samples are found first in memory as an array of unsigned char with an even number of lines (possibly with a larger stride for memory alignment), followed immediately by an array of unsigned char containing interleaved Cb and Cr samples (such that if addressed as a little-endian WORD type, Cb would be in the LSBs and Cr would be in the MSBs) with the same total stride as the Y samples. This is the preferred 4:2:0 pixel format, and is expected to be an intermediate term requirement for DirectX VA accelerators supporting 4:2:0 video.
    6. "NV21" (a neologism not found on the referenced Web page), as in NV12 except that Cb and Cr samples are swapped so that the chroma array of unsigned char would have Cr followed by Cb for each sample (such that if addressed as a little-endian WORD type, Cr would be in the LSBs and Cb would be in the MSBs).
    7. "IMC1" (a neologism not found on the referenced Web page), as in YV12, except that the stride of the Cb and Cr planes is the same as the stride in the Y plane. The Cb and Cr planes are also restricted to fall on memory boundaries which are a multiple of 16 lines (a restriction which has no effect on usage for the standard formats, since the standards all use 16×16 macroblocks).
    8. "IMC2" (a neologism not found on the referenced Web page), as in IMC1, except that Cb and Cr lines are interleaved at half-stride boundaries. In other words, each full-stride line in the chrominance area starts with a line of Cb, followed by a line of Cr starts that starts at the next half-stride boundary. (This is a more address-space efficient format than IMC1, cutting the chrominance address space in half, and thus cutting the total address space by 25%.) This runs a close second in preference relative to NV12, but NV12 appears to be more popular.
    9. "IMC3" (a neologism not found on the referenced Web page), as in IMC1, except for swapping Cb and Cr.
    10. "IMC4" (a neologism not found on the referenced Web page), as in IMC2, except for swapping Cb and Cr.

Our primary goal in specifying these formats is to document the formats in use, to enable use of the decompressed video for subsequent processing which would manipulate the video as DirectDraw surface textures. Our secondary goal is to simplify software operation by cutting down the proliferation of different formats over time - eliminating the use of different formats that unnecessarily duplicate the same functionality.

1.3.2 Accelerator Sequentiality Requirements

The primary burden for ensuring that race conditions do not cause undesirable behavior in the operation of the interface is placed on the host software decoder rather than the hardware accelerator. The only requirement imposed herein on the accelerator in this regard is to be able to properly report when queried whether the display of an uncompressed surface is pending or in progress and to be able to properly report when queried whether requested operations have been completed.

1.3.3 Software Decoder Sequentiality Requirements

Certain requirements are imposed herein to provide an assurance of proper operation of sequential operations in the decoding process. These concern the handling of uncompressed surfaces for decoding and display. The examples provided herein concern the handling of picture decoding for conventional I-, B-, and P-structured video frames (without using a deblocking filter). The same principles apply in an obvious way to other scenarios.

The guiding principles are simple: Don't write over what you need for referencing or display, and avoid race conditions. This principle can be decomposed into two rules:

  • No picture can be overwritten that has been submitted for display unless it has already been shown on the display and also removed from the display (to avoid tearing artifacts on the display), and
  • No picture can be overwritten that is needed as a reference for the creation of other pictures that have not yet been created.

This results in a requirement that the software decoder must query the status of the accelerator to avoid race conditions, and also results in a requirement that the decoder must use a sufficient number of uncompressed picture surfaces to ensure that space is available for all necessary operations.

This results in a need for at least four uncompressed picture surfaces for I, B, P picture processing (more are generally encouraged, and more are necessary for some operations such as the use of front-end alpha blending).

The following two subsections describe the use of four or more uncompressed surfaces for video decoding with B pictures, concluding that at least four uncompressed surfaces are generally needed and five or more are recommended for applications without critical delay-minimization requirements. Using extra surfaces can greatly reduce the need to wait for operational dependencies to be resolved.

Note that for compressed buffers as well as uncompressed surfaces, it is generally better to cycle through using all of the available buffers that have been allocated rather than to keep re-using the same one or the same subset of the allocated buffers, possibly causing bottlenecks which require delays to be added to wait on unnecessary dependencies. In some cases the allocation of multiple buffers by a driver may be meant to indicate that cycling through use of these buffers for double or triple buffering is the proper way to operate without artifacts. (This applies to alpha blend data loading in particular.)

1.3.3.1 Using Four Uncompressed Surfaces for Decoding

We show in Figure 1 a hypothetical case of a video decoder that requires one frame time to decode each picture and is decoding a bitstream which contains a steadily-increasing number of B pictures (starting from zero B pictures after an initial I picture) between pairs of P pictures. In this example, a letter is used to show the type of each picture (I, B, or P), a subscript is used to show the temporal display order of each picture, and a superscript is used to show which buffer is used for holding the picture. Each B picture requires two prior pictures in bitstream order in order to be decoded. As a consequence, the decoder cannot begin displaying pictures with their proper timing until after the second picture has been decoded – i.e., until during the third time slice of decoding. Somewhere during this time slice, the display of pictures with their proper timing can begin.

The initiation of the display of a picture does not in general perfectly coincide with that picture appearing on the display. Instead, the display may continue to show a picture that is prior to the one that has been commanded for display (until the proper time arrives to switch to the new picture). Thus, for optimal performance, surface 0 (which holds the first I picture) should not be overwritten for use by the B picture which arrives three frame times later, even though the I picture is not needed by that B picture for referencing. Instead, a fourth surface (surface 3) should ideally be used to hold that B picture. This avoids the need to check whether the display period of the first I picture has been completed before decoding the B picture.

Application of the two rules given above imply that the first three decoded pictures must be placed in different surfaces, because none of them has been displayed until some time during the third period (period 2). Then the fourth decoded picture should ideally be placed in a fourth surface because the display of the first displayed picture may not yet be over until some time during the fourth period (period 3).

A significant bottleneck in the process illustrated in Figure 1 occurs upon encountering the 10th decoded picture (B19) as a result of having more than two B pictures in a row. When the third or subsequent B picture in a contiguous series is encountered, the time lag tolerance between the display of one B picture and the use of a surface to hold the next decoded B picture is eliminated. In this situation, the host decoder must check the display status of the B picture displayed in the previous period (in this case, B17) to ensure that it has been removed from the display (waiting for this to happen if necessary), and then must immediately use the same surface for the next B picture to be decoded (in this case, surface 1 used for B19). It cannot decode the new B picture into either of the surfaces being used to hold its reference I or P pictures (in this case, surfaces 0 and 2 used for P06 and P210), and cannot decode the new B picture into the surface being displayed during the same interval of time (in this case, surface 3 used for B38). So it must use the surface that was displayed in the immediately preceding period (in this case, surface 1).

Decoding Process | I00 | P11 | P23 | B32 | P06 | B14 | B35 | P210 | B17 | B38 | B19 | P015
Display Process |  |  | I00 | P11 | B32 | P23 | B14 | B35 | P06 | B17 | B38 | B19
Frames Decoded* | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11
Decoding Process | B311 | B112 | B313 | B114 | P221 | B316 | B117 | B318 | B119 | B320 | P028 | ...
Display Process | P210 | B311 | B112 | B313 | B114 | P221 | B316 | B117 | B318 | B119 | B320 | ...
Frames Decoded* | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | ...
* At start of interval.

Figure 1 -- Four-Frame Decoder Buffering (superscript is buffer number, subscript is frame display index)

1.3.3.2 Using Five or More Uncompressed Surfaces for Decoding

More than four buffers can be used – allowing the time lag between the start of the display of a buffer and new writes to that buffer to increase from a minimum of one display period to two or more. This can provide more of an allowance for jitter in the timing of the decoding process. This can also enable output processing on the decoded pictures to perform a three-field deinterlace operation as part of the display process (since not only the current picture would be available for display, but the prior picture would also be available and could be used to provide context and/or allow a one-field delay in the actual display process). It can also provide some immunity against badly-designed hardware drivers that may not be written with a proper awareness of whether a picture is actually still being displayed or not (although one should properly be able to depend on hardware drivers not to exhibit such behavior). Although four buffers is the minimum for effective use of DirectX VA with B pictures, using five or more buffers is encouraged – particularly in scenarios in which very low delay is not a requirement. DirectX VA decoders for I, B, P-structured video decoding are therefore expected to set their minimum and maximum requested uncompressed surface allocation counts to at least 4 and 5, respectively, when allocating uncompressed surfaces. Using one or more extra uncompressed surfaces may often be a good way to achieve smooth, reliable, tear-free operation.

1.4 Terminology

1.4.1 Abbreviations and Symbols

' ' Binary value (left bit is MSB)

" "Decimal value

0x Hexadecimal value

LSB Least Significant Bit

MSB Most Significant Bit

// Division with rounding away from zero

/ Division with truncation toward zero

1.4.2 Bit Numbering Convention

Bit numbering in this specification is done per Microsoft prevailing convention, which is to number the LSB as bit 0 and the MSB as bit N-1 for an N bit quantity.

NOTE: This numbering convention differs from the one used in some of the video coding standards, in which the lowest-numbered bit would be the MSB.

However, when a sequence of fields of less than 8 bits is shown in a structure in this document, the sequencing follows the convention used in the video coding standards, which is to say that elements listed first are considered to lie closer to the MSB. For example, if we have an array of five single-bit elements to place in sequence into a structure description, they will be listed in decreasing index order in the structure description.

The schizophrenia inherent in this approach means that the ultimate authority for exactly where each bit goes in this interface specification should be considered to be the ".h" file associated with this interface, not this document.

1.4.3 Definitions

reference block - block area extracted from reference frame buffer.

prediction block - block filtered from reference block.

prediction plane - array of samples formed prior to combining of macroblock prediction. Each plane represents a set of prediction blocks, usually collected from one frame location. Planes are combined to form a single macroblock prediction.

Prediction macroblock - macroblock prediction including all color channels

component - one of three color channels {Y, Cb, Cr }.

Host CPU - programmable processor which controls overall function of video decode (high level operations).

Accelerator - functional unit which executes simple but high rate operations such as IDCT, MCP, display format conversion.

motion vector arithmetic - operations which convert motion vectors to prediction block addresses.

prediction address - location of the prediction block within an implementation-specific design.

composite prediction block - prediction block whose attributes apply to both luminance and chrominance.

component prediction block - prediction block whose attributes apply to either luminance or chrominance.

intra - representation of picture content without prediction using any previously-decoded picture as a reference.

inter - representation of picture content by first encoding a prediction of an area of the picture using some previously-decoded picture and then optionally adding a signal representing the deviation from that prediction.

residual difference decoding - decoding of the waveform which represents the error signal which has been encoded to represent whatever signal remains after motion-compensated prediction as appropriate. This may entail simply an "intra" representation of a non-predicted waveform or an "inter" difference after prediction.

ReservedBits - Any field in this specification having the name ReservedBits as its name or part of its name is not presently used in this specification and shall have the value zero.

should - used to describe encouraged (but not required) behavior.

shall - used to describe required behavior.

1.5 Stages

The stages depicted in the figure below comprise the MCP and IDCT Accelerator.

Figure 2 -- Decoder Stages

1.6 Frame Buffer Organization

All picture buffers are assumed to have frame-organized buffers as per MPEG-2 specification. Address Units shall be given in frame coordinates unless otherwise specified. It is possible to losslessly convert prediction blocks described in frame coordinates to field coordinates via an implementation-specific translation layer. For example, a single frame motion prediction can be broken into two separate, top and bottom macroblock-portion predictions.

The three video component channels {Y, Cb, Cr} are accessed by interfaces defined in this specification. Motion vectors for the two chrominance components are derived from those sent for luminance components. Conversion of these motion vectors to different coordinate systems is a responsibility of the Accelerator.

Operation for Current Standards

Figure 3 -- Host and Accelerator System

The basic operations of H.261, MPEG-1, MPEG-2 (H.262), H.263, and MPEG-4 are listed in chronological order below with a brief description of how they can be realized using this specification.

2.1 ITU-T H.261

Formally titled "Video Codec for Audiovisual Services at px64 kbit/s," ITU-T Recommendation H.261 was the first digital video coding standard to deliver a practical design with relatively high compression (the first digital video coding standard, H.120, is largely forgotten today), and it contains the same basic design to be later used in the other video codec standards, using 8-bit samples with Y, Cb, and Cr components, 4:2:0 sampling, 16×16 "macroblock"-based motion compensation, 8×8 IDCT, zig-zag inverse scanning of coefficients, scalar quantization, and variable-length coding of coefficients based on a combination of zero-valued run-lengths and quantization index values. All H.261 prediction blocks use forward-only prediction from the previous picture. H.261 does not have half-sample accurate prediction filters, but instead uses a type of low-pass filter called the "loop filter" (Section 3.2.3 of the H.261 specification) which can be turned off or on during motion compensation prediction for each macroblock.

Annex D Graphics: H.261 later included an interesting trick mode called "Annex D Graphic Transfer." No special support is provided for this feature in this accelerator interface. This feature can be supported using this specification by reading four decoded pictures from the accelerator back onto the host and interleaving them there for display as a higher-resolution graphic picture.

2.2 MPEG-1

MPEG-1 video, formally ISO/IEC 11172-2, was developed not long after H.261 and borrowed significantly from it. It has no loop filter, and instead has a simple half-sample filter which attempts to resolve sub-pixel movement between frames. Two additional prediction modes, bi-directional and backward prediction were added which require one additional reference frame to be buffered. The bi-directional prediction averages forward- and backward-predicted prediction blocks. The arithmetic for averaging forward and backward prediction blocks is similar to that for creating a half-sampled "interpolated" prediction block. The basic structure is otherwise the same as H.261.

2.3 MPEG-2 (a.k.a. H.262)

MPEG-2, formally titled "Information Technology - Generic Coding of Moving Pictures and Associated Audio Information: Video," ITU-T Recommendation H.262 | ISO/IEC 13818-2, added only a basic 16×8 shape to the existing tools of MPEG-1 (from a very low layer perspective). From a slightly higher layer perspective, MPEG-2 added many additional ways to combine predictions referenced from multiple fields in an attempt to deal with interlaced video characteristics

MPEG-2 frame structured pictures:

  1. Frame MC: has a 16×16 prediction block shape, much the same as MPEG-1 predictions. This is the only progressive-style motion within MPEG-2 (as specified by the motion_type parameter in MPEG-2). There are either one prediction plane (forward-only or backward-only) or two (bi-directional) as determined by the macroblock_type MPEG-2 parameter. Reference blocks are formed from contiguous frame lines from the frame buffer. The frame buffer is selected by the semantics of the decoding process. Half-sample interpolation (MPEG-2 Section 7.6.4) and bi-directional interpolation (MPEG-2 Section 7.6.7.1) have identical averaging operations as in the MPEG-1 case.
  2. Field (16×8) MC: Each plane (forward and backward directions) consists of a top 16×8 prediction block, and a bottom 16×8 prediction block. The reference block corresponding to each prediction block may be extracted from the top field or bottom field of a reference frame, as determined by the MPEG-2 parameter motion_vertical_field_select[r][s]. There are either one set of two prediction blocks for one prediction plane (forward-only or backward-only, for which there would be a total of two prediction blocks per macroblock), or sets for two prediction planes (bi-directional, for which there would then be a total of four prediction blocks in a macroblock).
  3. Dual Prime: like the Field MC case above, each plane (parity) consists of a top and bottom 16×8 shape. The same and opposite parity planes are combined together via the averaging operation identical to bi-directional interpolation in (1, 2, 4, 5). Unlike the other motion types (1, 2, 4, 5), a Dual Prime macroblock always consists of two sets of prediction blocks (same and opposite parity), for a total of four prediction blocks per macroblock.

MPEG-2 field structured pictures:

  4. Field (16×16) MC: Resembles Frame MC in that each prediction has a 16×16 shape, however the reference block data is formed from sequential top or bottom lines only, not a mixture of alternating top and bottom lines (as in progressive motion). As with all motion types in field-structured pictures, the reconstructed macroblock is likewise stored in the current frame buffer as only sequential top or bottom lines. Top or bottom field destination is determined by the MPEG-2 variable picture_structure.
  5. 16×8 MC: Although the basic prediction block shapes of this type of motion are the same as for the other 16×8 shapes (2,3), it is not partitioned into the macroblock in the same manner. The two partitions correspond to upper and lower halves of a macroblock prediction plane, rather than top and bottom fields within a macroblock. (See Figure X). Particular attention should be paid to the fact that the anchor point for the lower 16×8 half is the upper left hand corner of the 16×8 lower portion, not the upper left hand corner of the whole macroblock as is the case with all other types of motion.
  6. Dual Prime: At the lowest layer there is virtually no distinction between Dual Prime and the field structured field motion compensation with bi-directional prediction. The differences are manifested in the frame buffer selections from which reference blocks are formed. Dual Prime motion type in field structured pictures always consists of two 16×16 prediction blocks (same and opposite parity predictions).

2.4 ITU-T H.263

Formally titled "Video Coding for Low Bit Rate Communication," ITU-T Recommendation H.263 is a more recent video coder with improved compression performance relative to H.261, MPEG-1, and MPEG-2. It contains a "baseline" mode of operation supporting only the most basic form of H.263. It also contains a large number of optional enhanced modes of operation for various purposes. (It originally had five optional modes in the first version approved in late 1995, but more were added in a second version technically completed in 1997, and a few more are being finalized in 2000.) Baseline H.263 prediction operates in this interface using a subset of the MPEG-1 features. The baseline mode contains no bi-directional prediction - only forward prediction.

Rounding Control: Several H.263 optional modes require rounding control. This is supported by the bRcontrol flag in this specification.

Several H.263 optional modes allow motion vectors that address locations outside the boundaries of a picture as defined in H.263 Annex D. This is supported in this specification by a bPicExtrapolation flag indicating whether the accelerator needs to support such motion. There are two basic ways of supporting such motion: 1) clipping the value of the address on each sample fetch to ensure that it stays within picture boundaries, and 2) padding the picture by duplicated samples to widen the actual memory area used by one macroblock width and height across each border of the picture. The accelerator can use either method, as the result is the same.

Bi-directional motion prediction: The bi-directional motion prediction used in some optional H.263 prediction operations uses a different rounding operator than MPEG-1 - using division with truncation rather than rounding. This is supported by the bBidirectionalAveragingMode flag in this specification.

Four-MV motion compensation (4MV): Although each macroblock in H.263 is 16×16 in size, some optional modes (e.g., Annexes F and J) of H.263 allow four motion vectors to be sent for a single macroblock, with one macroblock for each 8×8 luminance block within the macroblock. The corresponding 8×8 chrominance area uses a single derived motion vector.

Overlapped Block Motion Compensation (OBMC): ): H.263 Annex F contains Overlapped Block Motion Compensation (OBMC) for luminance samples in addition to 4MV support. OBMC prediction is supported in this specification by allowing sending twelve motion vectors for forward prediction of a macroblock.

OBMC prediction blocks can be realized in hardware with the tools given in this specification as a combination of predictions organized into three planes: a current plane ("0"), an upper/lower plane ("1"), and a left/right plane ("2"). The three planes can serve as temporary storage for the blocks q(x,y), r(x,y), and s(x,y) defined in H.263 Section F.3. After each of the three planes have been filled out for all four blocks, they would then be combined according to the formula in H.263 Section F.3 and weighted by their respective H matrices given in H.263 Figures F.2, F.3, and F.4.

As an example, an OBMC luminance macroblock prediction may be comprised of eight top/bottom prediction blocks of 8×4 shape, eight left/right blocks of 4x8 shape, and four current blocks of 8×8 shape. If all four of the plane 0 motion vectors have the same motion vector (i.e., when not in a 4MV macroblock), a single 16×16 macroblock prediction can be used to fill the entire 16×16 plane 0.

In terms of the representation of the OBMC process in this specification, ten motion vectors are sent for the macroblock. The first four are for the Y0, Y1, Y2, and Y3 blocks in the current macroblock, remote vectors for the left and right halves of the top of the macroblock are then sent, then remote vectors for the top and bottom halves of the left side of the macroblock, and finally the remote vectors for the top and bottom halves of the right side of the macroblock. (H.263 does not use distinct remote vectors for the left and right halves of the bottom of the macroblock - it instead reuses the vectors for the current macroblock.)

Figure 4: H.263 Registration of One 8×8 Block in the OBMC Prediction Planes

P-B frames (Annex G & M):

In this mode, macroblocks for a P frame and a pseudo B-frame are multiplexed together into the unique "PB-frame" picture coding type. The B-frame portion of each macroblock borrows from information encoded for the P-frame portion of the macroblock: the B-portion forward and backward motion vectors are scaled from the P-portion vector, and the reconstructed P-portion macroblock serves as backward reference for the B-portion. The PB includes only a pseudo B-frame since the backward macroblock can only refer to the reconstructed P macroblock contained within the same PB macroblock. However, as with traditional B-frame semantics, the B macroblock within a PB-frame can refer to any location within the forward reference frame.

This limitation of the backward reference creates smaller size backward prediction block shapes as depicted in H.263 Figure G.2. This specification supports PB frames by labeling them as a distinct macroblock type with two motion vectors.

Deblocking Filter (Annex J): Special commands are defined in this specification to accelerate deblocking filters, whether used in the loop as with Annex J or used outside of the loop as would be the case for deblocking H.261 pictures or H.263 baseline pictures. The Host CPU shall create deblocking commands which observe GOB or slice segments if necessary.

Reference Picture Selection (Annexes N and U): Multiple reference frames are supported by the Accelerator using the picture index selection field of each prediction block.

Scalability (Annex O): Temporal, SNR, and Spatial scalability are supported by the tools of this specification. H.263 Spatial scalability B frames are very similar in this interface to MPEG-1 B-frames. Spatial scalability requires upsampling the lower-layer reference picture and then using the upsampled picture as the reference (in all other aspects it is essentially the same as SNR and Temporal scalability). The appropriate bi-directional averaging rounding control should be set to truncation for H.263 (MPEG-1 and MPEG-2 use upward-biased averaging, and H.263 uses downward truncation averaging).

Reference Picture Resampling (Annex P): The simple form of this annex is supported by reference buffer resampling. For fancier forms of Annex P resampling, the reconstructed frames which serve as reference frames must be resampled by external means and stored as reference frame buffers addressable by the Accelerator.

Reduced-Resolution Update mode (Annex Q): The H.263 Reduced-Resolution Update mode is not currently supported by this specification, as it has unusual residual upsampling requirements, a different form of deblocking filter, and a different form of Advanced Prediction OBMC. However, its operation with the Deblocking Filter mode active and the Advanced Prediction mode inactive could perhaps be supported in this interface with host-based IDCT processing.

Independent Segment Decoding (Annex R): There is no low-level or accelerator awareness of independent segment borders. Some forms of Annex R can be supported without any special handling (e.g., baseline plus Annex R is trivial). Forms of Annex R which require picture segment extrapolation can be supported by decoding each segment as a picture and then constructing the complete output picture from these smaller pictures.

Other H.263 Optional Features: Other H.263 optional features can be supported without any impact on the accelerator interface. For example, Annexes I, K, S, and T can be handled easily by altering the host side of the processing without any impact on the accelerator.

Specific IDCT: This interface allows specification of support of a specific IDCT which is expected to be added as a new H.263 optional feature in the near future.

2.5 MPEG-4

MPEG-4 was based heavily on H.263 for progressive-scan coding and MPEG-2 for support of interlace and color sampling formats other than 4:2:0. The features in this specification which support H.263 and MPEG-2 can be used to support MPEG-4. A parameter BPP is provided to support more than eight bits per pixel. The features most unique to MPEG-4 such as shape coding, object orientation, face modeling, mesh objects, sprites, etc. are not supported in the current interface, although they may be added in some future variation on the theme.

2.6 Prediction Principles

Block motion-compensated prediction (MCP) is the basic tool which gives MPEG and the H.26x family of codecs a gain over pure still-frame coding methods such as JPEG. Generic instances of prediction exist at many stages of the codec, but MCP is the most processing intensive. Motion vectors, DCT coefficients, and other elements not directly part of the MCP process also employ prediction to make the transmitted form of those elements more compact. These instances of prediction are not covered by this specification, and are considered to be executed on the Host CPU processor or bitstream parser/variable-length-decoding unit.

In a generic prediction coding scheme, previously transmitted and decoded elements serve as the prediction for current elements, and differences between the prediction and the actual current element values are sent as prediction error. The transmitted difference information updates the prediction to the correct value, or in the case of MCP, to a value which is a close enough approximation to a desired value. Previously decoded frames are used to predict or "guess" what future frames should look like. The difference data (known prediction error) then corrects the guess, attempting to bring the combined prediction + prediction error (reconstructed) image as close to the original (prior to compression) future frame as possible.

The reconstructed current elements are in turn stored to serve as prediction for future elements. This recursive loop is occasionally broken by various types of resets specific to the element being predicted. The resets are described by the semantics of the decoding process. For example, motion vectors and DC coefficient predictions are reset at slices, while the whole temporal frame prediction chain is reset by an intra refresh frame. The temporal basic prediction loop fits this description, but works with modified data taken from whole frames which serve as prediction. Data from the reference frames which serve as prediction are modified in order to account for movement or other types of change which occur over time.

Figure 5 -- Generic MCP Signal Flow

2.6.1 Stages of Prediction

For purposes of this specification, the formation of a macroblock prediction (via MCP) shall be described as a series of discrete phases. This realization will help explain why this specification models the MCP process in the way that it does.

Figure 6 -- Signal Flow of MoComp3 Prediction Blocks

Stage 1. Form reference frame.

NOTE: This may include resampling the input picture as necessary.

Figure 7 -- Evolution of Prediction Data within MCP

Stage 2. Reference block

A reference block is not necessarily the same as a prediction block. It most likely consists of extra samples which are needed in the prediction filtering stages. The reference block is not defined in this specification since it is likely to have properties which reflect implementation-specific means of maintaining picture buffers. Unless half-sample filtering is executed in the memory unit, the reference block for a 16×16 half-sample filtered macroblock will have a 17x17 shape. The size of the reference block is both a function of the prediction block dimensions and filter attributes of the prediction block. In this specification, a reference block shall refer to a block of data extracted from a reference frame buffer for use in motion compensated prediction (MCP).

Stage 3. Prediction block

The outcome of a filtered reference block.

Stage 4. Combined macroblock prediction

The outcome of an averaging process between one or more prediction blocks.

2.6.2 Macroblock Portions

Macroblocks are broken into regular segments in an attempt compartmentalize areas with different characteristics.

Figure 8 -- Basic Macroblock Portioning Schemes

In the MPEG-2 case, the top and bottom portion of a macroblock represent lines from two different fields captured at different instances in time, as much as 1/50-th of a second apart. Thus the top and bottom portion could have totally non-correlated content if significant movement has taken place between the two fields for the frame area covered by the macroblock. An additional 16×8 scheme is added in field-structured pictures to provide finer vertical granularity of prediction.

Figure 9 - The Two MPEG-2 Macroblock 16×8 Portions

In the MPEG-2 case, the top and bottom portion of a macroblock represent lines from two different fields captured at different instances in time, as much as 1/50-th of a second apart. Thus the top and bottom portion could have totally non-correlated content if significant movement has taken place between the two fields for the frame area covered by the macroblock. An additional 16×8 scheme is added in field-structured pictures to provide finer vertical granularity of prediction.

Partitioning of macroblocks also provides finer granularity of prediction, to better accommodate edges and smaller objects with divergent motion velocities. The prediction block itself is a crude approximation of shape, and represents a kind of average motion vector for all samples which belong to the portion of the macroblock which the prediction block represents. Ideally, each sample (or subsample) would have its own motion vector, but this would consume considerable bits and extra overhead in processing. The prediction block remains a reasonable approximation.

Prediction blocks contribute to only one portion of a macroblock. A whole prediction block covers the 16×16 area of a macroblock. This is the case with all H.261 and MPEG-1 predictions. MPEG-2 introduced the 16×8 prediction shape to address the dual field/frame nature of macroblocks. The 16×8 shape was also borrowed for use in MPEG-2 field-structured pictures to create a finer-granularity of prediction. The 8×8 shape is deployed in H.263 (Advanced Prediction), H.264, and MPEG-4. The finest granularity to date is the draft of the future "H.26L"'s 4x4 prediction block shape.

Chrominance prediction blocks usually have half the size in both horizontal and vertical directions as their corresponding luminance prediction blocks, and share the same vector used for luminance since the standards addressed by this specification always model motion as component planar co-located. Chrominance vectors are therefore scaled from luminance vectors by some means, to account for the difference in the respective luminance and chrominance sample dimensions. MPEG-2's 16×8 luminance prediction blocks have corresponding 8×4 chrominance shapes. Exceptions are often made when the luminance prediction block becomes too small. For example, in the H.263 Advanced Prediction mode, the chrominance prediction block remains 8×8 in shape, and the chrominance motion vector is derived from a scaled average of the four 8×8 luminance motion vectors. In most contexts of this document, we shall only refer to the luminance dimensions of a prediction block, plane, or macroblock - the chrominance dimensions shall be inferred unless explicitly stated.

2.6.3 Prediction Planes

Figure 10 MPEG-2 Macroblock Prediction Planes

The above figure illustrates the conceptual macroblock prediction planes which exist prior to forming the final macroblock prediction. MPEG-2 has two planes: forward & backward (bi-directional prediction), or same-parity & opposite-parity (Dual Prime). In the MPEG-1 and MPEG-2 case, planes are combined together via the simple averaging operation. More sophisticated prediction schemes such as H.263's Overlapped Block Motion Compensated Prediction have three planes. Future coding methods may employ up to eight or more prediction planes which can be combined with more sophisticated filters.

DirectX VA Data Structures and Program Constructs

3.1 Encryption Support

The security needs of some applications may require encryption of some of the data used in video decoding. To support such applications, this specification allows for encryption of DirectX VA data to be applied to three of the data structures defined for its operation:

  • The macroblock control command data structures,
  • The residual difference block data structures, and
  • Bitstream buffer contents

However, encryption is an optional aspect of DirectX VA operation for the intermediate-term future. All accelerators shall be capable of operation without encryption in use. Some encryption protocol is expected to be made a requirement in the longer-term future.

Good obfuscation of host-based software and data for processing clear-text data and performing the encryption process is essential to protecting the content. Such protection is equally important for the accelerator-side decryption process (although the decryption may be a hardware-based operation).

In order for the host decoder software to be able to use encryption, it must determine what types of encryption are supported by the accelerator. The basic information regarding what types of encryption are supported by the accelerator is contained in a list of encryption-type GUIDs supplied to the host as video accelerator type GUIDs. (The "no encryption" GUID DXVA_NoEncrypt shall not be sent in this list, as support for it is required and therefore implicit.)

The host chooses the type of encryption protocol to apply and indicates this choice to the accelerator via GUIDs as described in Section 3.2. In a typical encryption scenario, two more steps need to take place before encrypted data can be successfully transferred:

  • The host decoder may require verification that the accelerator is authorized to receive the data. This may be done by having the accelerator pass a signed data structure to the host to prove that it holds an authorized public key, private key pair.
  • The host decoder would then send an encrypted "content key" to the accelerator.

The precise number of steps for initializing the encryption protocol may depend on the particular type of encryption to be used. Each data set exchanged between the host and accelerator for the initialization of the encryption process shall be prefixed by the encryption protocol type GUID, to distinguish data for one type of encryption from data for another (in the event of the use of one type of encryption for one type of DirectX VA buffer, and some other type of encryption for another type of DirectX VA buffer).

The encryption data sets are exchanged with an indication that the operation being performed is an encryption protocol, as specified by:

DXVA_EncryptProtocolFunc {
            EncryptProtocolFlag,     // 24b
            bDXVA_Func              //  8b
            }

EncryptProtocolFlag: This is a 24-bit indication that the operation being performed is an encryption protocol transaction. EncryptProtocolFlag shall be 0xFFFF00 when sent by the host software decoder and shall be 0xFFFF08 when sent by the accelerator.

bDXVA_Func: This is an indication of the bDXVA_Func DirectX VA function to which the encryption protocol applies. As currently defined herein, the only value of bDXVA_Func that requires encryption support is "1".

The actual data set that is passed between the host and accelerator shall contain the following header information:

DXVA_EncryptProtocolHeader {
                dwFunction,              // Operation Indicated
                dwReservedBits[3],       // 3 * 32b alignment
                guidEncryptProtocol     // 128b
                }

dwFunction: Contains a DXVA_EncryptProtocolFunction indicating that the contents pertain to the encryption protocol.

guidEncryptProtocol: Contains the GUID associated with the encryption protocol.

3.2 Global Restricted Mode Information

In order for a decoder to operate using this API, an understanding must be reached between the decoder and the video accelerator for two distinct aspects of operation:

  1. What type of video data format is to be decoded. This is codified herein using the DXVA_ConnectMode data structure.
  2. How the API will be configured to operate, as to what intermediate data formats are used and which aspects of the processing are to reside on the host and which on the accelerator. This established by the negotiation of a connection configuration for each DXVA function to be used.

The DirectX VA global connection parameter is the connection restricted mode:

DXVA_ConnectMode {
            guidMode,        // 128b
            wRestrictedMode // 16b
            }

guidMode: A GUID associated with the restricted mode profile to be used.

wRestrictedMode: The numeric identifier of the connection restricted mode (see Section 4).

3.3 Probing and Locking of Configurations

TThe process of establishing the configuration for each DirectX VA function (a specific value of bDXVA_Func) that needs configuration is performed by:

  1. Optionally probing to determine whether a configuration is accepted by the accelerator, and
  2. Locking in a specific configuration if it is supported.

Probing for support of a specific configuration is performed by sending a probing command to the accelerator for the particular bDXVA_Func to be probed with a configuration. Along with the probing command is sent a configuration data structure (specific to the DXVA_Func value) which describes the configuration being probed to determine support. The accelerator then returns a S_OK or S_FALSE indication for whether the specified configuration is supported by the accelerator or not. The accelerator may also return a suggested alternative configuration.

Locking in a specific configuration is performed by sending a locking command to the accelerator for the particular bDXVA_Func to be locked into a specific configuration. Along with the locking command is sent a configuration data structure (specific to the bDXVA_Func value) which describes the configuration to be locked in if supported. The accelerator then returns a S_OK or S_FALSE indication for whether the specified configuration is supported by the accelerator. If the indication is S_OK, the specified configuration is locked in for use. If the indication is S_FALSE, a suggested alternative configuration is returned.

The decoder may send a locking command without first sending a probing command for the specified configuration. If the accelerator has returned a S_OK in a probing command for a specific configuration, it shall return a S_OK to a locking command for that same configuration, unless otherwise noted herein.

Once a locking command has been sent and acknowledged for use with a returned Yes indication, the specified configuration is locked in, and no further probing or locking commands shall be sent by the decoder for the same value of bDXVA_Func.

In order to ensure that all DirectX VA software decoders shall be capable of operation with all DirectX VA accelerators, a minimal interoperability configuration set, is defined as a set of configurations that must all be supported by any software decoder that wishes to use a particular bDXVA_Func. At least one member of that minimal interoperability configuration set shall be supported by every accelerator that indicates support for the bDXVA_Func by exposing an associated video accelerator GUID. In some cases an additional encouraged configuration set may also be defined.

Probing and locking are controlled by DXVA_ConfigQueryOrReplyFunc, which is passed as the first member of the data structure sent in a probing or locking command.

DXVA_ConfigQueryOrReplyFunc {
                QueryOrReplyFlag,        // 24b
                bDXVA_Func              //  8b
                }

QueryOrReplyFlag: The type of query or response indicated, defined as follows:

  • 0xFFFFF1 : Sent by the software decoder as a probing command,
  • 0xFFFFF5 : Sent by the software decoder as a locking command,
  • 0xFFFFF8 : Sent by the accelerator with a S_OK response to a probing command with a copy of the probed configuration,
  • 0xFFFFF9 : Sent by the accelerator with a S_OK response to a probing command, but also suggesting an alternative configuration,
  • 0xFFFFFC : Sent by the accelerator with a S_OK response to a locking command with a copy of the locked configuration,
  • 0xFFFFFB : Sent by the accelerator with a S_FALSE response to a probing command with a suggested alternative configuration, or
  • 0xFFFFFF : Sent by the accelerator with a S_FALSE response to a locking command with a suggested alternative configuration.
The least significant four bits of QueryOrReplyFlag can be interpreted as follows:

  • Bit 3: Sent by host decoder = "0", by accelerator = "1",
  • Associated with a probe = "0", with a lock = "1",
  • Bit 1: Success = "0", failure = "1", and
  • Bit 0: Duplicate configuration structure = "0", new structure = "1".

bDXVA_Func: The bDXVA_Func function to which the accompanying configuration applies.

3.4 Buffer Description List

DirectX VA primarily operates by passing buffers of data from the host to the accelerator. The DXVA function parameter (bDXVA_Func) determines what types of buffers may be passed and what specific DXVA task is to be performed. A variety of enumerated buffer types are defined herein, specifically the types are:

  1. Picture decoding parameter buffers
  2. Macroblock control command buffers (closely associated with and having a 1:1 correspondence with residual difference block data buffers)
  3. Residual difference block data buffers
  4. Deblocking Filter control command buffers (with or without a restriction on the effect of the filter)
  5. Inverse quantization matrix buffers (only used with off-host VLD processing)
  6. Slice control buffers (closely associated with and having a 1:1 correspondence with bitstream data buffers)
  7. Bitstream data buffers
  8. AYUV alpha blending sample buffers
  9. IA44/AI44 alpha blending surface buffers
  10. DPXD alpha blending surface buffers
  11. Highlight data buffers
  12. DCCMD data buffers
  13. Alpha blend combination buffers
  14. Picture resampling control buffers
  15. Read-back buffers containing commands to read macroblocks of the resulting picture back to the host.

When a set of buffers is passed from the host to the accelerator, some additional data about these buffers is also passed. This additional data is termed buffer description list. A buffer description list consists of an ordered list, starting from the first buffer of the first type as enumerated above, proceeding to the next buffer of the same type, and so on, then proceeding to the first buffer of the next type, etc. Each member of the list consists of a data structure defined as follows:

DXVA_BufferDescription {
             dwTypeIndex,       // 32b
             dwBufferIndex,     // 32b
             dwDataOffset,      // 32b
             dwDataSize,        // 32b
             dwFirstMBaddress,  // 32b
             dwNumMBsInBuffer,  // 32b
             dwWidth,           // 32b
             dwHeight,          // 32b
             dwStride,          // 32b
             dwReservedBits     // 32b
            }

dwTypeIndex: The type number of the relevant buffer from the list above in this section.

dwBufferIndex: The sequence number of the buffer within the buffers of the same type passed in the same buffer description list.

dwDataOffset: The offset of the relevant data from the beginning of the buffer (in bytes). Shall be zero.

dwDataSize: The amount of relevant data in the buffer (in bytes). Thus the location of the last byte of content in the buffer is given by dwDataOffset + dwDataSize - 1.

dwFirstMBaddress: The macroblock address of the first macroblock in the buffer in raster scan order (0 being the address of the top left macroblock, PicWidthInMBminus1 being the address of the top right macroblock, and PicHeightInMBminus1 * PicWidthInMB being the address of the bottom left macroblock, and PicHeightInMBminus1 * PicWidthInMB + PicWidthInMBminus1 being the address of the bottom right macroblock). Shall be zero if the data buffer is among the following types: picture decoding parameters, inverse quantization matrix, slice control, bitstream data, AYUV, IA44/AI44, DPXD, Highlight, or DCCMD. If the data buffer is a residual difference block data buffer, dwFirstMBaddress shall have the same value as for the corresponding macroblock control command buffer.

dwNumMBsInBuffer: The number of macroblocks of data in the buffer. This count includes skipped macroblocks. Shall be zero if the data buffer is among the following types: picture decoding parameters, inverse quantization matrix, AYUV, IA44/AI44, DPXD, Highlight, or DCCMD. If the data buffer is a macroblock control command buffer, dwNumMBsInBuffer shall be equal to the total of the values of MBskipsFollowing plus the total number of macroblock control commands in the macroblock control command buffer. If the data buffer is a residual difference block data buffer, dwNumMBsInBuffer shall have the same value as for the corresponding macroblock control command buffer. If the data buffer is a slice control command buffer, dwNumMBsInBuffer shall be equal to the total of the values of wNumberMBsInSlice in the slice control buffer. If the data buffer is a bitstream data buffer, dwNumMBsInBuffer shall have the same value as for the corresponding slice control command buffer.

dwWidth, dwHeight, dwStride: The width, height, and stride of the data in the buffer. Shall be zero unless the data buffer is among the following types: IA44/AI44, or DPXD. For the applicable buffer types, dwStride is determined from the buffer allocation setup performed by the accelerator.

NOTE: The decoder must take care to honor the stride specified for IA44/AI44 or DPXD.

3.5 Compressed Picture Decoding (bDXVA_Func=1)

The first function type defined for DirectX VA operation is the decoding of some or all of a compressed picture.

3.5.1 Connection Configuration

The DirectX VA connection configuration data structure for compressed picture decoding shall be defined as:

DXVA_ConfigPictureDecode {
    dwFunction,                      // Operation Indicated  32b
    dwReservedBits[3],               // 3 * 32b alignment
    guidConfigBitstreamEncryption,   // Encryption type GUIDs 128b
    guidConfigMBcontrolEncryption,
    guidConfigResidDiffEncryption,
    bConfigBitstreamRaw,             // Bitstream Processing  8b
    bConfigMBcontrolRasterOrder,     // Macroblock Control   8b
    bConfigResidDiffHost,            // Host Resid Diff  8b
    bConfigSpatialResid8,            // 8b
    bConfigResid8Subtraction,        // 8b
    bConfigSpatialHost8or9Clipping,  // 8b
    bConfigSpatialResidInterleaved,  // 8b
    bConfigIntraResidUnsigned,       // 8b
    bConfigResidDiffAccelerator,     // Accelerator Resid Diff  8b
    bConfigHostInverseScan,          // 8b
    bConfigSpecificIDCT,             // 8b
    bConfig4GroupedCoefs             // 8b
}

dwFunction: Contains a DXVA_ConfigQueryOrReplyFunc describing the configuration data structure.

guidConfigBitstreamEncryption: Indicates a GUID associated with the encryption protocol type for bitstream data buffers. The value DXVA_NoEncrypt (a GUID name defined in the associated header file) indicates that encryption is not applied. Shall be DXVA_NoEncrypt if bConfigBitstreamRaw is "0".

guidConfigMBcontrolEncryption: Indicates a GUID associated with the encryption protocol type for macroblock control data buffers. The value DXVA_NoEncrypt (a GUID name defined in the associated header file) indicates that encryption is not applied. Shall be DXVA_NoEncrypt if bConfigBitstreamRaw is "1".

guidConfigResidDiffEncryption: Indicates a GUID associated with the encryption protocol type for residual difference decoding data buffers (buffers containing spatial-domain data or sets of transform-domain coefficients for accelerator-based IDCT). The value DXVA_NoEncrypt (a GUID name defined in the associated header file) indicates that encryption is not applied. Shall be DXVA_NoEncrypt if bConfigBitstreamRaw is "1".

bConfigBitstreamRaw: A value of "1" specifies that the data for the pictures will be sent in bitstream buffers as raw bitstream content, and a value of "0" specifies that picture data will be sent using macroblock control command buffers. Shall be "0" if bConfigResidDiffHost is "1" or if bConfigResidDiffAccelerator is "1". An intermediate-term requirement is to support "0". Additional support of "1" is desired.

bConfigMBcontrolRasterOrder: A value of "1" specifies that the macroblock control commands within each macroblock control command buffer shall be in raster-scan order, and a value of "0" indicates arbitrary order. For some types of bitstreams, forcing raster order will either greatly increase the number of required macroblock control buffers that must be processed or will require host reordering of the control information. Support of arbitrary order can thus be advantageous for the decoding process. For example, H.261 CIF-resolution decoding can require 36 macroblock control buffers per picture if raster-scan order is necessary within each buffer (H.263 Annex K's arbitrary slice ordering and rectangular slice modes have similar repercussions.) An intermediate-term requirement is to support "0". Support of "1" is allowed in the near term, but is considered a less preferred lower level of capability.

bConfigResidDiffHost: A value of "1" specifies that some residual difference decoding data may be sent as blocks in the spatial domain from the host, and a value of "0" specifies that spatial domain data will not be sent. Shall be "0" if bConfigBitstreamRaw is "1". An intermediate-term requirement is to support "1", which is the preferred value.

bConfigSpatialResid8: Indicates the word size used for representing residual difference spatial-domain blocks for predicted (i.e., non-intra) pictures when using host-based residual difference decoding (i.e. when bConfigResidDiffHost is equal to "1").

If bConfigSpatialResid8 is "1" and bConfigResidDiffHost is "1", this indicates that the host will send residual difference spatial-domain blocks for non-intra macroblocks using 8 bit signed samples and for intra macroblocks in predicted (i.e. non-intra) pictures in a format depending on bConfigIntraResidUnsigned as follows:

  • If bConfigIntraResidUnsigned is "0", spatial-domain blocks for intra macroblocks are sent as 8 bit signed integer values relative to a constant reference value of 2(BPP-1), and
  • If bConfigIntraResidUnsigned is "1", spatial-domain blocks for intra macroblocks are sent as 8 bit unsigned integer values relative to a constant reference value of 0.

If bConfigSpatialResid8 is "0" and bConfigResidDiffHost is "1", this indicates that the host will send residual difference spatial-domain blocks of data for non-intra macroblocks using 16 bit signed samples and for intra macroblocks in predicted (i.e. non-intra) pictures in a format depending on bConfigIntraResidUnsigned as follows:

  • If bConfigIntraResidUnsigned is "0", spatial domain blocks for intra macroblocks are sent as 16 bit signed integer values relative to a constant reference value of 2(BPP-1), and
  • If bConfigIntraResidUnsigned is "1", spatial domain blocks for intra macroblocks are sent as 16 bit unsigned integer values relative to a constant reference value of 0.

bConfigSpatialResid8 shall be "0" if bConfigResidDiffHost is "0". This specification does not contain a preference for one particular value of bConfigSpatialResid8 when bConfigResidDiffHost is "1".

NOTE: For intra pictures, spatial-domain blocks shall always be sent using 8-bit samples if BPP is "8" and using 16-bit samples if BPP > 8. If bConfigIntraResidUnsigned is "0", these samples are sent as signed integer values relative to a constant reference value of 2(BPP-1), and if bConfigIntraResidUnsigned is "1", these samples are sent as unsigned integer values relative to a constant reference value of 0.

bConfigResid8Subtraction: A value of "1" when bConfigSpatialResid8 is "1" indicates that 8-bit difference overflow blocks are subtracted rather than added. Shall be "0" unless bConfigSpatialResid8 is "1". If "1", this indicates that any overflow blocks will be subtracted rather than added. An intermediate-term requirement is to support "1" if bConfigSpatialResid8 is "1". This ability to subtract differences rather than add them allows 8-bit difference decoding to be fully compliant with the full ±255 range of values required in video decoder specifications, since +255 cannot be represented as the addition of two signed 8-bit numbers but any number in the range ±255 can be represented as the difference between two signed 8-bit numbers (+255 = +127 minus -128).

bConfigSpatialHost8or9Clipping: A value of "1" with bConfigSpatialResid8 equal to "0" and bConfigResidDiffHost equal to "1" indicates that spatial-domain blocks for intra macroblocks shall be clipped to an 8-bit range on the host and that spatial-domain blocks for non-intra macroblocks shall be clipped to a 9-bit range on the host, and a value of "0" indicates that no such clipping is necessary by the host. Shall be "0" unless bConfigSpatialResid8 is equal to "0" and bConfigResidDiffHost is equal to "1". An intermediate-term requirement is to support "0". Nearer-term support of "1" is allowed but less preferred, and is considered a lower level of accelerator capability.

bConfigSpatialResidInterleaved: A value of "1" when bConfigResidDiffHost is "1" and the YUV format is "NV12" or "NV21" indicates that any spatial-domain residual difference data shall be sent in a chrominance-interleaved form matching the YUV format chrominance interleaving pattern. Shall be "0" unless bConfigResidDiffHost is "1" and the YUV format is "NV12" or "NV21". An intermediate-term requirement is to support "0". Nearer-term support of "1" is allowed but less preferred, and is considered a lower level of accelerator capability.

bConfigIntraResidUnsigned: Indicates the method of representation of spatial-domain blocks of residual difference data for intra blocks when using host-based difference decoding (i.e. when bConfigResidDiffHost is equal to "1").

If bConfigIntraResidUnsigned is equal to "0" with bConfigResidDiffHost equal to "1", this indicates that spatial-domain residual difference data blocks for intra macroblocks shall be sent as follows:

  • In a non-intra picture if bConfigSpatialResid8 is "0", the spatial-domain residual difference data blocks for intra macroblocks shall be sent as 16-bit signed integer values relative to a constant reference value of 2(BPP-1).
  • In a non-intra picture if bConfigSpatialResid8 is "1" and in an intra picture if BPP is equal to "8" (regardless of the value of bConfigSpatialResid8), the spatial-domain residual difference data blocks for intra macroblocks shall be sent as 8-bit signed integer values relative to a constant reference value of 2(BPP-1).

If bConfigIntraResidUnsigned is equal to "1" with bConfigResidDiffHost equal to "1", this indicates that spatial-domain residual difference data blocks for intra macroblocks shall be sent as follows:

  • In a non-intra picture if bConfigSpatialResid8 is "0", the spatial-domain residual difference data blocks for intra macroblocks shall be sent as 16-bit unsigned integer values relative to a constant reference value of 0.
  • In a non-intra picture if bConfigSpatialResid8 is "1" and in an intra picture if BPP is equal to "8" (regardless of the value of bConfigSpatialResid8), the spatial-domain residual difference data blocks for intra macroblocks shall be sent as 8-bit unsigned integer values relative to a constant reference value of 0.

bConfigIntraResidUnsigned shall be "0" unless bConfigResidDiffHost is "1". Nearer-term support of bConfigIntraResidUnsigned equal to "1" is allowed but less preferred than bConfigIntraResidUnsigned equal to "0", and is considered a lower level of accelerator capability.

bConfigResidDiffAccelerator: A value of "1" indicates that transform-domain blocks of coefficient data may be sent from the host for accelerator-based IDCT, and a value of "0" specifies that accelerator-based IDCT will not be used. If both bConfigResidDiffHost and bConfigResidDiffAccelerator are "1", this indicates that some residual difference decoding will be done on the host and some on the accelerator, as indicated by macroblock-level control commands. Shall be "0" if bConfigBitstreamRaw is "1". Support for bConfigResidDiffAccelerator equal to "1" is desired, but there is not expected to be an intermediate-term requirement for this support. Support for bConfigResidDiffAccelerator equal to "1" with bConfigResidDiffHost also equal to "1" indicates that the residual difference decoding can be shared between the host and accelerator on a macroblock basis, and is considered an even higher level of accelerator capability than bConfigResidDiffAccelerator equal to "1" with bConfigResidDiffHost equal to "0".

bConfigHostInverseScan: A value of "1" indicates that the inverse scan for transform-domain block processing will be performed on the host, and absolute indices will be sent instead for any transform coefficients, and a value of "0" indicates that inverse scan will be performed on the accelerator. Shall be "0" if bConfigResidDiffAccelerator is "0". Shall be "1" if bConfig4GroupedCoefs is "0". An intermediate-term expected requirement is to support "1" if bConfigResidDiffAccelerator is "1". Nearer-term support of "0" with bConfig4GroupedCoefs equal to "1" is allowed but less preferred (due to its lack of flexibility to support arbitrary scan patterns and our perception that host inverse scan adds little burden to the host software decoder processing), and is considered a lower level of accelerator capability.

bConfigSpecificIDCT: A value of "1" indicates use of the IDCT specified in Annex W of ITU-T Recommendation H.263, and a value of "0" indicates that any compliant IDCT can be used for off-host IDCT. (NOTE: The referenced draft annex does not yet have final approval in the ITU-T. If a change takes place in the ITU, this bit will refer to the final version, not the earlier draft versions. It should also be noted that the referenced draft does not comply with the IDCT requirements of MPEG-2 corrigendum 2 and thus bConfigSpecificIDCT shall not be "1" for use with MPEG-2 video.) Shall be zero if bConfigResidDiffAccelerator is "0" (indicating purely host-based residual difference decoding). An intermediate-term expected requirement is to support "0" if bConfigResidDiffAccelerator is "1". Additional support of "1" is desired. Additional values may be defined in the future.

bConfig4GroupedCoefs: A value of "1" indicates that transform coefficients for off-host IDCT will be sent using the DXVA_TCoef4Group data structure rather than the DXVA_TCoefSingle data structure. Shall be "0" if bConfigResidDiffAccelerator is "0" or if bConfigHostInverseScan is "1". An intermediate-term expected requirement is to support "0" if bConfigResidDiffAccelerator is "1". Nearer-term support of "1" with bConfigHostInverseScan equal to "0" is allowed but less preferred, and is considered a lower level of accelerator capability.

3.5.2 Minimal Interoperability Configuration Set

It is a design requirement for all DirectX VA decoders to interoperate with all DirectX VA accelerators. This requires that every DirectX VA decoder be capable of operation with any member of a set of connection configurations, and that every DirectX VA accelerator be capable of operation with at least one connection configuration member of that set. That minimal interoperability set is defined as follows:

  1. All members of this most basic set have the following aspects in common:
    1. guidConfigBitstreamEncryption = DXVA_NoEncrypt
    2. guidConfigMBcontrolEncryption = DXVA_NoEncrypt
    3. guidConfigResidDiffEncryption = DXVA_NoEncrypt
    4. bConfigBitstreamRaw = 0
    5. bConfigHostInverseScan = 0
    6. bConfigSpecificIDCT = 0
  2. The first two members of this set (among which accelerators are encouraged to support the variation with bConfigSpatialHost8or9Clipping = 0) are defined by:
    1. bConfigMBcontrolRasterOrder = 1
    2. bConfigResidDiffHost = 1
    3. bConfigSpatialResid8 = 0
    4. bConfigResid8Subtraction = 0
    5. bConfigSpatialHost8or9Clipping = 0 or 1
    6. bConfigSpatialResidInterleaved = 0
    7. bConfigIntraResidUnsigned = 0
    8. bConfigResidDiffAccelerator = 0
  3. The third member of the set (not particularly encouraged for accelerator implementation) is defined by:
    1. bConfigMBcontrolRasterOrder = 1
    2. bConfigResidDiffHost = 1
    3. bConfigSpatialResid8 = 1
    4. bConfigResid8Subtraction = 0
    5. bConfigSpatialHost8or9Clipping = 0
    6. bConfigSpatialResidInterleaved = 1
    7. bConfigIntraResidUnsigned = 0
    8. bConfigResidDiffAccelerator = 0
  4. The fourth member of this set (not particularly encouraged for accelerator implementation) is defined by:
    1. bConfigMBcontrolRasterOrder = 1
    2. bConfigResidDiffHost = 1
    3. bConfigSpatialResid8 = 0
    4. bConfigResid8Subtraction = 0
    5. bConfigSpatialHost8or9Clipping = 1
    6. bConfigSpatialResidInterleaved = 0
    7. bConfigIntraResidUnsigned = 1
    8. bConfigResidDiffAccelerator = 0
  5. Two additional members of this set (among which accelerators are encouraged to support the variation with bConfigResid8Subtraction = 1) are defined by:
    1. bConfigMBcontrolRasterOrder = 1
    2. bConfigResidDiffHost = 1
    3. bConfigSpatialResid8 = 1
    4. bConfigResid8Subtraction = 0 or 1
    5. bConfigSpatialHost8or9Clipping = 0
    6. bConfigSpatialResidInterleaved = 0
    7. bConfigIntraResidUnsigned = 0
    8. bConfigResidDiffAccelerator = 0
  6. One additional member of this set is defined only for the MPEG2_C and MPEG2_D restricted mode profiles as defined in Section 4 and indicated in DXVA_ConnectMode. No other profiles include this configuration in their minimal interoperability set. This additional member is defined by:
    1. bConfigMBcontrolRasterOrder = 1
    2. bConfigResidDiffHost = 0
    3. bConfigResidDiffAccelerator = 1
    4. bConfigHostInverseScan = 0
    5. bConfig4GroupedCoefs = 1

3.5.3 Additional Encouraged Configuration Set

Some additional configurations are encouraged to be supported in software decoders, as we believe these configurations will exist in hardware shipping in large quantities and as we believe that these configurations can provide a significant performance benefit relative to those in the minimal configuration set. These include:

  1. All members of this set have the following aspects in common:
    1. guidConfigBitstreamEncryption = DXVA_NoEncrypt
    2. guidConfigMBcontrolEncryption = DXVA_NoEncrypt
    3. guidConfigResidDiffEncryption = DXVA_NoEncrypt
    4. bConfigMBcontrolRasterOrder = 0
    5. bConfigResidDiffHost = 0
    6. bConfigSpatialResid8 = 0
    7. bConfigResid8Subtraction = 0
    8. bConfigSpatialHost8or9Clipping = 0
    9. bConfigSpatialResidInterleaved = 0
    10. bConfigSpecificIDCT = 0
  2. For good support of off-host bitstream processing acceleration, the first member of this set is defined by:
    1. bConfigBitstreamRaw = 1
    2. bConfigResidDiffAccelerator = 0
    3. bConfigHostInverseScan = 0
    4. bConfig4GroupedCoefs = 0
  3. For good support of off-host IDCT acceleration, the second member of this set is defined by:
    1. bConfigBitstreamRaw = 0
    2. bConfigResidDiffAccelerator = 1
    3. bConfigHostInverseScan = 1
    4. bConfig4GroupedCoefs = 0
  4. For support of off-host IDCT as expected to be found in some implementations, the third member of this set (not particularly encouraged for accelerators relative to the second set member) is defined by:
    1. bConfigBitstreamRaw = 0
    2. bConfigResidDiffAccelerator = 1
    3. bConfigHostInverseScan = 0
    4. bConfig4GroupedCoefs = 1

Accelerators supporting the first of these encouraged configurations are strongly encouraged to also support the second of them, in order to provide flexibility in the manner in which their acceleration capabilities can be used.

3.5.4 Compressed Picture Parameters

The following variables shall be sent once per picture:

DXVA_PictureParameters {
    wDecodedPictureIndex        // 16b
    wDeblockedPictureIndex      // 16b

    wForwardRefPictureIndex     // 16b
    wBackwardRefPictureIndex    // 16b

    wPicWidthInMBminus1         // 16b
    wPicHeightInMBminus1        // 16b

    bMacroblockWidthMinus1      // 8b
    bMacroblockHeightMinus1     // 8b

    bBlockWidthMinus1           // 8b
    bBlockHeightMinus1          // 8b

    bBPPminus1                  // 8b

    bPicStructure               // 8b
    bSecondField                // 8b
    bPicIntra                   // 8b
    bPicBackwardPrediction      // 8b

    bBidirectionalAveragingMode     // 8b
    bMVprecisionAndChromaRelation   // 8b
    bChromaFormat                   // 8b
    bPicScanFixed                   // 8b
    bPicScanMethod                  // 8b
    bPicReadbackRequests            // 8b

    bRcontrol                       // 8b
    bPicSpatialResid8               // 8b
    bPicOverflowBlocks              // 8b
    bPicExtrapolation               // 8b

    bPicDeblocked                   // 8b
    bPicDeblockConfined             // 8b
    bPic4MVallowed                  // 8b
    bPicOBMC                        // 8b
    bPicBinPB                       // 8b
    bMV_RPS                         // 8b
    bReservedBits                   // 8b (alignment)

    wBitstreamFcodes                // 16b
    wBitstreamPCEelements           // 16b
    bBitstreamConcealmentNeed       // 8b
    bBitstreamConcealmentMethod     // 8b
}

wDecodedPictureIndex: Specifies destination frame buffer for the decoded macroblocks.

wDeblockedPictureIndex: Specifies destination frame buffer for the deblocked output picture when bPicDeblocked is "1". Has no meaning and shall be "0" if bPicDeblocked is "0". May be the same as wDecodedPictureIndex.

wForwardRefPictureIndex: Specifies the frame buffer index of the picture to be used as a reference picture for "forward prediction" of the current picture. Shall not be the same as wDecodedPictureIndex. Shall be 0xFFFF if bPicIntra is "1".

wBackwardRefPictureIndex: Specifies the frame buffer index of the picture to be used as a reference picture for "backward prediction" of the current picture. Shall not be the same as wDecodedPictureIndex if backward reference motion prediction is used. Shall be 0xFFFF if bPicBackwardPrediction is "0".

wPicWidthInMBminus1: Specifies the width of the current picture in units of macroblocks, minus 1. A derived term called PicWidthInMB is formed by adding one to PicWidthInMBminus1.

wPicHeightInMBminus1: Specifies the height of the current picture in units of macroblocks, minus 1. A derived term called PicHeightInMB is formed by adding one to PicHeightInMBminus1.

bMacroblockWidthMinus1: Specifies the destination luminance sample width of a macroblock. This is equal to "15" for MPEG-1, MPEG-2, H.263, and MPEG-4. A derived term called MacroblockWidth is formed by adding one to bMacroblockWidthMinus1.

bMacroblockHeightMinus1: Specifies the destination luminance sample height of a macroblock. This is equal to "15" for MPEG-1, MPEG-2, H.261, H.263, and MPEG-4. A derived term called MacroblockHeight is formed by adding one to bMacroblockHeightMinus1.

bBlockWidthMinus1: Specifies the block width of an residual difference block. This is equal to "7" for MPEG-1, MPEG-2, H.261, H.263, and MPEG-4. Shall be "7" if bConfig4GroupedCoefs is "1". Residual difference blocks within a macroblock are sent in the order specified as in MPEG-2 Figures 6-10, 6-11, and 6-12 (raster-scan order for Y, followed by all 4:2:0 blocks of Cb in raster-scan order, followed by 4:2:0 blocks of Cr, followed by 4:2:2 blocks of Cb, followed by 4:2:2 blocks of Cr, followed by 4:4:4 blocks of Cb, followed by 4:4:4 blocks of Cr). A derived term called WT is formed by adding one to BlockWidthMinus1.

bBlockHeightMinus1: Specifies the block height of an IDCT block. This is equal to "7" for MPEG-1, MPEG-2, H.261, H.263, and MPEG-4. Shall be "7" if bConfig4GroupedCoefs is "1". A derived term called HT is formed by adding one to BlockHeightMinus1.

bBPPminus1: Specifies the number of bits per pixel for the video sample values. This shall be at least "7" (indicating 8-bit pixels). It is equal to "7" for MPEG-1, MPEG-2, H.261, and H.263. A larger number of bits per pixel is supported in some operational modes of MPEG-4. A derived term called BPP is formed by adding one to bBPPminus1.

bPicStructure: This parameter has the same meaning as the picture_structure parameter defined in Section 6.3.10 and Table 6-14 of MPEG-2, and indicates whether the current picture is a top-field picture (value '01'), a bottom-field picture (value '10'), or a frame picture (value '11'). In progressive-scan frame-structured coding such as in H.261, bPicStructure shall be '11'. A derived parameter PicCurrentField is defined as "0" unless bPicStructure is '10' (bottom field), in which case it is "1".

bSecondField: Indicates whether, in the case of field-structured coding (when bPicStructure is '01' or '10'), the current field is the second field of a picture. This is used to determine whether the opposite-parity field used as a reference for the opposite-parity lines for motion compensation prediction is the opposite-parity field of the reference picture or the opposite-parity field of the current picture. If bSecondField is "1", the current field is the second field of a picture and the field used as a reference for the opposite-parity lines for motion compensation are the opposite-parity lines of the current picture. (In both cases the field used as a reference for the same-parity lines for motion compensation are the same-parity lines of the reference picture.) Otherwise, bSecondField shall be "0".

bPicIntra: Indicates whether motion compensated prediction is needed for this picture. If bPicIntra is "1", all macroblocks are sent with IntraMacroblock equal to "1" (i.e. no motion compensated prediction is performed for the picture). Otherwise, some macroblocks of the picture may have IntraMacroblock equal to "0".

bPicBackwardPrediction: Indicates whether any macroblocks of the current picture include backward prediction. If bPicIntra is "1", bPicBackwardPrediction shall be "0". If bPicBackwardPrediction is "0", MotionBackward shall be "0" in all macroblocks of the picture. If bPicBackwardPrediction is "1", some macroblocks of the picture may have MotionBackward equal to "1".

bBidirectionalAveragingMode: This flag indicates the rounding method for combining prediction planes in bi-directional motion compensation (used for B pictures and Dual-Prime motion). The value "0" indicates MPEG-1 and MPEG-2 rounded averaging (//2), and the value "1" indicates H.263 truncated averaging (/2). bBidirectionalAveragingMode shall be "0" if no bidirectional averaging is needed.

bMVprecisionAndChromaRelation: This two-bit field indicates the precision of luminance motion vectors and how chrominance motion vectors shall be derived from luminance motion vectors:
'00' indicates that luminance motion vectors have half-sample precision and that chrominance motion vectors are derived from luminance motion vectors according to the rules in MPEG-2,
'01' indicates that luminance motion vectors have half-sample precision and that chrominance motion vectors are derived from luminance motion vectors according to the rules in H.263,
'10' indicates that luminance motion vectors have full-sample precision and that chrominance motion vectors are derived from luminance motion vectors according to the rules in H.261 Section 3.2.2 (dividing by two and truncating toward zero to full-sample values), and
'11' is reserved.

bChromaFormat: Affects number of prediction error blocks expected by the Accelerator. This variable is defined in Section 6.3.5 and Table 6-5 of MPEG-2. For MPEG-1, MPEG-2 "Main Profile," H.261 and H.263 bitstreams, this value shall always be set to '01', indicating "4:2:0" format. If '10' this indicates "4:2:2", and "11" indicates "4:4:4" sampling. Shall be equal '01' if bConfig4GroupedCoefs is "1" (since bConfig4GroupedCoefs does not include the EOB indication needed within coefficient data in 4:2:2 and 4:4:4 formats).

NOTE: Horizontal chroma siting differs slightly between H.261, H.263, MPEG-1 versus MPEG-2 and MPEG-4. This difference is assumed to be small enough to ignore.

bPicScanFixed: When using accelerator-based IDCT processing of residual difference blocks, a value of "1" for this flag indicates that the inverse-scan method is the same for all macroblocks in the picture, and a value of "0" indicates that it is not. Shall be "1" if bConfigHostInverseScan is "1" or if bConfigResidDiffAccelerator is "0".

bPicScanMethod: When bPicScanFixed is "1", this field indicates the fixed inverse scan method for the picture. When bPicScanFixed is "0", this field has no meaning and shall be '00'. If bPicScanFixed is "1" this field shall have one of the following values:

  • If bConfigHostInverseScan is "0", bPicScanMethod shall be as follows:
    • '00' = Zig-zag scan (MPEG-2 Figure 7-2),
    • '01' = Alternate-vertical (MPEG-2 Figure 7-3),
    • '10' = Alternate-horizontal (H.263 Figure I.2 Part a),
  • If bConfigHostInverseScan is "1", bPicScanMethod shall be as follows:
    • '11' = Arbitrary scan with absolute coefficient address.

bPicReadbackRequests: Indicates whether read-back control requests are issued for the current picture to read back the values of macroblocks in the final decoded (ad deblocked, if deblocking is applied with wDeblockedPictureIndex equal to wDecodedPictureIndex) picture. A value of "1" indicates that read-back requests are present, and "0" indicates that they are not.

bRcontrol: This flag is defined in H.263 Section 6.1.2. It defines the rounding method to be used for half-sample motion compensation. A value of "0" indicates the half-sample rounding method found in MPEG-1, MPEG-2, and the first version of H.263. A value of "1" indicates the rounding method which includes a downward averaging bias which can be selected in some optional modes of H.263 and MPEG-4. It is meaningless for H.261, since H.261 has no half-sample motion compensation. It shall be set to "0" for all MPEG-1, and MPEG-2 bitstreams in order to conform with the rounding operator defined by those standards.

bPicSpatialResid8: A value of "1" indicates that spatial-domain difference blocks for host-based residual difference decoding can be sent using 8-bit samples, and a value of "0" indicates that they cannot. Shall be "0" if bConfigResidDiffHost is "0" or if BPP > 8. Shall be "1" if BPP is "8" and bPicIntra is "1" and bConfigResidDiffHost is "1". Shall be "1" if bConfigSpatialResid8 is "1". If equal to "1", bPicSpatialResid8 indicates that spatial-domain intra macroblocks are sent as 8-bit values (which are either signed or unsigned as determined by bConfigIntraResidUnsigned) and that spatial-domain non-intra macroblock differences are sent as signed 8-bit difference values relative to some motion compensated prediction. bPicSpatialResid8 differs from bConfigSpatialResid8 in that it is an indication for a particular picture, not a global indication for the entire video sequence. In some cases such as in an intra picture with BPP equal to "8", bPicSpatialResid8 will be "1" even though bConfigSpatialResid8 may be "0".

bPicOverflowBlocks: A value of "1" indicates that spatial-domain difference blocks for host-based residual difference decoding of a picture may be sent using "overflow" blocks, and a value of "0" indicates that they are not. Shall be "0" if bConfigResidDiffHost is "0" or if bConfigSpatialResid8 is "0" or if BPP > 8. bPicOverflowBlocks is an indication of whether any overflow blocks may be present for the particular picture. In an intra picture with BPP equal to "8", bPicOverflowBlocks shall be "0" as no overflow blocks are needed in this case.

bPicExtrapolation: This flag indicates whether motion vectors over picture boundaries are allowed as specified by H.263 Annex D and MPEG-4. This requires either allocation of picture planes which are two macroblocks wider (one extra macroblock at the left and another at the right) and two macroblocks taller (one extra macroblock at the top and another at the bottom) than the decoded picture size, or clipping of the address of each individual pixel access to within the picture boundaries. Macroblock addresses in this specification are for macroblocks in the interior of the picture, not including padding.

bPicDeblocked: Indicates whether deblocking commands are sent for this picture for creating a deblocked output picture in the picture buffer indicated in wDeblockedPictureIndex. If bPicDeblocked is "1", deblocking commands are sent and the deblocked frame shall be generated, and if bPicDeblocked is "0", no deblocking commands are sent and no deblocked picture shall be generated.

bPicDeblockConfined: Indicates whether deblocking filter command buffers contain commands which confine the effect of the deblocking filter operations to within the same set of macroblocks as are contained in the buffer.

bPic4MVallowed: Specifies whether four forward-reference motion vectors per macroblock are allowed as used in H.263 Annexes F and J.

bPicOBMC: Specifies whether motion compensation for the current picture operates using overlapped block motion compensation (OBMC) as specified in H.263 Annex F. Shall be zero if bPic4MVallowed is "0".

bPicBinPB: Specifies whether bi-directionally-predicted macroblocks in the picture use "B in PB" motion compensation, which restricts the bi-directionally predicted area for each macroblock to the region of the corresponding macroblock in the backward reference picture, as specified in Annexes G and M of H.263.

bMV_RPS: Specifies use of motion vector reference picture selection. If "1", this indicates that a reference picture index is sent for each motion vector rather than just forward and possibly backward motion picture indexes for the picture as a whole. If bMV_RPS is "1", the parameters wForwardRefPictureIndex and wBackwardRefPictureIndex have no meaning and shall be zero.

wBitstreamFcodes: When bConfigBitstreamRaw is "1", this parameter contains four motion vector f_code values as defined in MPEG-2. Each f_code value takes four bits. These values are packed into a sixteen bit word as in MPEG-2 as follows:
Bits 12-15 (the MSBs): f_code[0][0]: The forward horizontal f_code
Bits 8-11: f_code[0][1]: The forward vertical f_code
Bits 7-4: f_code[1][0]: The backward horizontal f_code
Bits 0-3 (the LSBs): f_code[1][1]: The backward vertical f_code

If any f_code value is unnecessary or irrelevant due to the structure of the bitstream data, due to bConfigBitstreamRaw being "0", or due to the f_code parameter not being needed in the relevant video coding bitstream syntax (such as in H.261 or H.263), then f_code value shall be 0xF.

NOTE: MPEG-1 bitstreams provide this information in a different form. Therefore for MPEG-1 bitstreams, f_code[0][0] and f_code[0][1] shall be equal to MPEG-1's forward_f_code and f_code[1][0] and f_code[1][1] shall be equal to MPEG-1's backward_f_code.

wBitstreamPCEelements: When bConfigBitstreamRaw is "1", this parameter contains a set of flags necessary for the bitstream decoding process of MPEG-2 video. It is not used and shall be "0" when bConfigBitstreamRaw is "0" and for non-MPEG-2 video. The bits in this parameter are defined by their correspondence with bitstream elements of the MPEG-2 picture coding extension as follows:
Bits 14 and 15: IntraDCprecision = intra_dc_precision Bits 12 and 13: AnotherPicStructure = picture_structure. Shall be equal to bPicStructure.
Bit 11: TopFieldFirst = top_field_first
Bit 10: FrameDCTprediction = frame_pred_frame_dct
Bit 9: ConcealmentMVs = concealment_motion_vectors
Bit 8: QuantScaleType = q_scale_type
Bit 7: IntraVLCformat = intra_vlc_format
Bit 6: AlternateScan = alternate_scan
Bit 5: RepeatFirstField = repeat_first_field (not needed by the accelerator)
Bit 4: Chroma420type = chroma_420_type (not needed by the accelerator and restricted by MPEG-2 to be equal to progressive_frame)
Bit 3: ProgressiveFrame = progressive_frame
Bits 0, 1, and 2 (the LSBs): ReservedBits

bBitstreamConcealmentNeed: Specifies, when bConfigBitstreamRaw is "1", whether there is a significant likelihood of the bitstream data containing errors. Shall be "0" if bConfigBitstreamRaw is "0". Video accelerators must be designed not to crash or lock up, regardless of the content of the data given to them. However, it may be helpful for a video accelerator to have information about the host's assessment of the likelihood of syntactical errors in order to determine whether there is a need to be able to invoke some more complex error concealment algorithms which might slow down the bitstream decoding process. Allowed values for this parameter are as follows (all other values are reserved):
"0": indicates that the bitstream is unlikely to contain any significant amount of errors in its syntactical format.
"1": indicates that the bitstream may contain some errors, but these errors are likely to be infrequent (e.g., some error once or twice per hour).
"2": indicates that the bitstream is likely to contain some errors, and that these errors are likely to occur with a frequency that could have some impact on the user experience (e.g., some error every five to ten minutes), but that these errors are not likely to be a constant presence.
"3": indicates that the bitstream is likely to contain relatively significant, serious, and frequent syntactical format errors (e.g., one per minute or more frequent errors).

bBitstreamConcealmentMethod: Specifies, when bConfigBitstreamRaw is "1", a preferred default method for error concealment processing. Shall be "0" if bConfigBitstreamRaw is "0". Allowed values for this parameter are as follows (all other values are reserved):
0: Preferred concealment method unknown or unspecified.
1: Preferred concealment method is to use spatial intra-picture concealment within the picture.
2: Preferred concealment method is to use the forward-motion reference picture for inter-picture concealment (to be used most typically in a P picture or in a B picture that is temporally closer to its forward-motion reference picture than to its backward-motion reference picture).
3: Preferred concealment method is to use the backward-motion reference picture for inter-picture concealment (to be used most typically in a B picture that is temporally closer to its backward-motion reference picture than to its forward-motion reference picture).

3.5.5 Buffer Structure for Macroblocks of a Picture

A decoded picture shall contain one or more macroblock control command buffers if it does not contain bitstream data buffers. The decoding process for every macroblock shall be addressed (only once) in some buffer of each type that is used. For every macroblock control command buffer, there shall be a corresponding IDCT residual coding buffer containing the same set of macroblocks. If one or more deblocking filter control buffers are sent, the set of macroblocks in each deblocking filter control buffer shall be the same as the set of macroblocks in corresponding macroblock control and IDCT residual coding buffers.

The processing of the picture requires that the motion prediction for each macroblock must precede the addition of the IDCT residual data. This can be accomplished either by processing the motion prediction commands first and then reading this data back in from the destination picture buffer while processing the IDCT residual coding commands, or by processing these two buffers in a coordinated fashion - adding the residual data to the prediction before writing the result to the destination picture buffer. The motion prediction command and IDCT residual coding command for each macroblock affect only the rectangular region within that macroblock.

A deblocking filter command for a macroblock may require access to read the reconstructed values of two rows and two columns of samples neighboring the current macroblock at the top and left as well as reconstructed values within the current macroblock. It can result in modification of one row and one column of samples neighboring the current macroblock at the top and left as well as up to three rows and three columns within the current macroblock. The filtering process for a given macroblock may therefore require the prior reconstruction of other macroblocks. Two different types of deblocking filter buffers are defined herein: 1) a buffer type which requires access and modification of the value of reconstructed samples for macroblocks outside the current buffer (when bPicDeblockConfined is "0"), and 2) a buffer type which does not (when bPicDeblockConfined is "1"). To process the first of these two types of deblocking command buffer, the accelerator must ensure that the reconstruction has been completed for all buffers which affect macroblocks to the left and top of the macroblocks in the current buffer before processing the deblocking commands in the current buffer. Processing the second of these two types requires only prior reconstruction values within the current buffer. The deblocking post-processing can be conducted either by processing the motion prediction and IDCT residual coding commands for the entire buffer or frame first, followed by reading back in the values of some of the samples and modifying them as a result of the deblocking filter operations, or by processing the deblocking command buffer in a coordinated fashion with the IDCT residual coding bufer - performing the deblocking before writing the final output values to the destination picture buffer. Note also that the destination picture buffer for the deblocked picture may differ from that of the reconstructed picture prior to deblocking, in order to support "outside the loop" deblocking as a post-processing operation which does not affect the sample values used for prediction of the next picture.

3.5.5.1 Macroblock Control Commands

if (bPicIntra)
    NumMV = 0;
else if (PicOBMC) {
    NumMV = 10;
    if (bPicBinPB)
        NumMV++;
}
else {
    NumMV = 4;
    if (bPicBinPB && bPic4MVallowed)
        NumMV++;
}

DXVA_MB_Control {                     // Alignment to 16 Bytes

// General Macroblock Info
    wMBaddress                        // 16b Which macroblock
    wMBtype                           // 16b Control bits
    MBskipsFollowing                  //  8b

// Residual Difference Info
    MBdataLocation                    // 24b Where in buffer
    wPatternCode                      // 16b Which blocks coded

    if (bPicOverflowBlocks == 1 && IntraMacroblock == 0)
    {

        wPC_Overflow                  // 16b Which blocks overflow
        dwReservedBits1               // 32b
    }
    else if (HostResidDiff)
        ReservedBits2                 // 48b
    else if (bChromaFormat == '01')
        for (i = 0; i < 6; i++)
            bNumCoef[i]               //  8b * 6 blocks = 48b
    else {
        wTotalNumCoef                 // 16b
        ReservedBits3                 // 32b
    }

    if (bPicIntra != 0) {
        // Motion Prediction Info
        for (i=0; i < NumMV; i++) {
            MVector[i].horz           // 16b * NumMV vectors
            MVector[i].vert           // 16b * NumMV vectors
        }
        if(bMV_RPS)
            for (i = 0; i < NumMV; i++)
                bRefPicSelect[i]      //  8b * NumMV vectors
        ReservedBits4                 //  16 Byte Align
    }
}

wMBaddress: Specifies the macroblock address of the current macroblock in raster scan order (0 being the address of the top left macroblock, PicWidthInMBminus1 being the address of the top right macroblock, and PicHeightInMBminus1 * PicWidthInMB being the address of the bottom left macroblock, and PicHeightInMBminus1 * PicWidthInMB + PicWidthInMBminus1 being the address of the bottom right macroblock).

wMBtype: Specifies the type of macroblock being processed as described below:

  • bit 15: MvertFieldSel[3] (The MSB)
  • bit 14: MvertFieldSel[2]
  • bit 13: MvertFieldSel[1]
  • bit 12: MvertFieldSel[0]: Specifies vertical field selection for corresponding motion vectors sent later in the macroblock control command, as specified in further detail below. For frame-based motion with a frame picture structure (e.g., for H.261 and H.263), these bits shall all be zero. The use of these bits is the same as that specified for the corresponding bits in Section 6.3.17.2 of MPEG-2.
  • bit 11: ReservedBits.
  • bit 10: HostResidDiff: Specifies whether spatial-domain residual difference decoded blocks are sent or whether transform coefficients are sent for off-host IDCT for the current macroblock. Shall be "0" if bConfigResidDiffHost is "0". Shall be "1" if bConfigResidDiffAccelerator is "0".
  • bits 9 and 8: MotionType: Specifies the motion type in the picture, as specified in further detail below. For frame-based motion with a frame picture structure (e.g., for H.261), these bits shall be '10' (frame motion). The use of these bits is defined in Table 1 below and corresponds directly to the use of frame_motion_type or field_motion_type bits in Section 6.3.17.1 and Tables 6-17 and 6-18 of MPEG-2 when these bits are present in MPEG-2.
  • bits 7 and 6: MBscanMethod: Shall equal bPicScanMethod if bPicScanFixed is "1". If bConfigHostInverseScan is "0", MBscanMethod shall be as follows:
    • '00' = Zig-zag scan (MPEG-2 Figure 7-2),
    • '01' = Alternate-vertical (MPEG-2 Figure 7-3),
    • '10' = Alternate-horizontal (H.263 Figure I.2 Part a),
    If bConfigHostInverseScan is "1", MBscanMethod shall be equal to:
    • '11' = Arbitrary scan with absolute coefficient address.
  • bit 5: FieldResidual: A flag indicating whether the IDCT blocks use a field IDCT structure as specified in MPEG-2.
  • bit 4: H261LoopFilter: A flag specifying whether the H.261 loop filter (Section 3.2.3 of H.261) is active for the current macroblock prediction. The H.261 loop filter is a separable ¼, ½, ¼ filter applied both horizontally and vertically to all six blocks in an H.261 macroblock except at block edges where one of the taps would fall outside the block. In such cases the filter is changed to have coefficients 0, 1, 0. Full arithmetic precision is retained with rounding to 8-bit integers at the output of the 2-D filter process (half-integer or higher values being rounded up).
  • bit 3: Motion4MV: A flag indicating that forward motion uses a distinct motion vector for each of the four luminance blocks in the macroblock, as used in H.263 Annexes F and J. Motion4MV shall be "0" if MotionForward is "0" or bPic4MVallowed is "0".
  • bit 2: MotionBackward: A flag used as specified for the corresponding macroblock_motion_backward parameter in MPEG-2. If bPicBackwardPrediction is "0", MotionBackward shall be "0". Further information on the use of this flag is given below.
  • bit 1: MotionForward: A flag used as specified for the corresponding macroblock_motion_forward in MPEG-2. Further information on the use of this flag is given below.
  • bit 0: IntraMacroblock: (The LSB) A flag indicating that the macroblock is coded as "intra", and no motion vectors are used for the current macroblock. Corresponds to macroblock_intra in MPEG-2. Further information on the use of this flag is given below.

MBskipsFollowing: Specifies the number of "skipped macroblocks" to be generated following the current macroblock. Each skipped macroblock shall be generated in a manner mathematically equivalent to incrementing the value of wMBaddress and then repeating the same macroblock control command.

Any macroblock control command with a non-zero value for MBskipsFollowing contains the explicit specification of how motion-compensated prediction is to be performed for each macroblock to be skipped, and is equivalent (except for the value of MBskipsFollowing) to an explicit "non-skip" specification of the generation of the first of the series of skipped macroblocks. Thus, whenever MBskipsFollowing is not "0", the following parameters shall all be equal to "0":

  • Motion4MV,
  • IntraMacroblock,
  • wPatternCode,
  • wPCOverflow (if present)
  • bNumCoef[i] (if present)

Furthermore, the generation of following skipped macroblocks shall be restricted by the decoder to not include a "wrap" to a new row of macroblocks in the picture. In other words, a separate macroblock control command must be sent to generate the first (but not necessarily the last) macroblock of each row of macroblocks.

NOTES:

  1. The generation of a skipped macroblock in this context differs somewhat from that in MPEG-2 Section 7.6.6. In this specification, the manner in which the skipped macroblocks are generated is specified in a separate macroblock control command, rather than being inferred from the type of the preceding non-skipped macroblock and the type of picture (e.g., in MPEG-2 the method of generating skipped macroblocks depends on whether the picture is a P picture or B picture). To illustrate this point, we provide the following example. Suppose that in an MPEG-2 bitstream, macroblock 0 is coded with a residual difference, macroblock 1 is skipped, macroblock 2 is coded with a residual difference, macroblocks 3, 4, and 5 are skipped, and then macroblock 6 is coded with a residual difference. These seven macroblocks would require the generation of (at least) five DirectX VA macroblock control commands. The minimal five control commands would be characterized by the folllowing:
    1. the first would have wMBaddress = "0" and MBskipsFollowing = "0",
    2. the second would have wMBaddress = "1" and MBskipsFollowing = "0",
    3. the third would have wMBaddress = "2" and MBskipsFollowing = "0",
    4. the fourth would have wMBaddress = "3" and MBskipsFollowing = "2", and
    5. the fifth would have wMBaddress = "6" and MBskipsFollowing = "0".
  2. The following conditions are required as specified above:
    1. skipped macroblocks have no residual differences,
    2. skipped macroblocks can be generated by repeating the operation of a macroblock control command with an incremented wMBaddress, and
    3. macroblock skipping is restricted to not wrap to a new row of macroblocks,
  3. Because of the three conditions listed in note 2, an accelerator may actually implement motion compensation (when Motion4MV is "0") as the application of the specified motion vectors to a rectangle of width equal to MacroblockWidth·(MBskipsFollowing+1) in the luminance component (and to a similarly-specified rectangle in the chrominance components), rather than as MBskipsFollowing+1 repetitions of the same macroblock control operation.
  4. The generation of macroblocks indicated as skipped in H.263 with Advanced Prediction mode (Annex F) active requires coding some "skipped" macroblocks as non-skipped macroblocks using this specification - in order to specify the OBMC effect within these macroblocks.

MBdataLocation: An index into the IDCT residual coding block data buffer, indicating the location of the residual difference data for the blocks of the current macroblock, expressed as a multiple of 32 bits. Shall be "0" for the first macroblock in the macroblock control command buffer.

wPatternCode: When using host-based residual difference decoding, bit 11-i of wPatternCode (where bit 0 is the LSB) indicates whether a residual difference block is sent for block i, where i is the index of the block within the macroblock as specified in MPEG-2 Figures 6-10, 6-11, and 6-12 (raster-scan order for Y, followed by 4:2:0 blocks of Cb in raster-scan order, followed by 4:2:0 blocks of Cr, followed by 4:2:2 blocks of Cb, followed by 4:2:2 blocks of Cr, followed by 4:4:4 blocks of Cb, followed by 4:4:4 blocks of Cr). The data for the coded blocks (those blocks having bit 11-i equal to 1) is found in the residual coding buffer in the same indexing order (increasing i). For 4:2:0 MPEG-2 data, the value of wPatternCode corresponds to shifting the decoded value of CBP left by six bit positions (those lower bit positions being for the use of 4:2:2 and 4:4:4 chroma formats).

If bConfigSpatialResidInterleaved is "1", host-based residual differences are sent in a chroma-interleaved form matching that of the YUV pixel format in use. In this case each Cb and spatially-corresponding Cr pair of blocks is treated as a single residual difference data structure unit. This does not alter the value or meaning of wPatternCode, but it implies that both members of each pair of Cb and Cr data blocks are sent whenever either of these data blocks has the corresponding bit set in wPatternCode. If the bit in wPatternCode for a particular data block is zero, the corresponding residual difference data values shall be sent as zero whenever this pairing necessitates sending a residual difference data block for a block with a wPatternCode bit equal to zero.

wPC_Overflow: When using host-based residual difference decoding with bPicOverflowBlocks equal to "1" and IntraMacroblock equal to "0" (the 8-8 overflow method), wPC_Overflow contains the pattern code of the overflow blocks as specified in the same manner as for wPatternCode. The data for the coded overflow blocks (those blocks having bit 11-i equal to 1) is found in the residual coding buffer in the same indexing order (increasing i).

bNumCoef[i]: Indicates the number of coefficients in the residual difference data buffer for each block i of the macroblock, where i is the index of the block within the macroblock as specified in MPEG-2 Figures 6-10, 6-11, and 6-12 (raster-scan order for Y, followed by Cb, followed by Cr). Used only when HostResidDiff is "0" and bChromaFormat is '01' (4:2:0). (If used in 4:2:2 or 4:4:4 formats, it would increase the size of typical macroblock control commands past a critical memory alignment boundary, so only EOB is used for determining the number of coefficients in each block in non-4:2:0 cases.) The data for these coefficients is found in the residual difference buffer in the same order.

wTotalNumCoef: Indicates the total number of coefficients in the residual difference data buffer for the entire macroblock. Used only when HostResidDiff is "0" and bChromaFormat is not '01' (4:2:0).

MVector[i].horz, MVector[i].vert: Specifies the value of a motion vector in horizontal and vertical dimensions. The two-dimensional union of these two values is referred to as MVvalue[i]. Each dimension of each motion vector contains a signed integer motion offset in half-sample units. Both elements shall be even if bMVprecisionAndChromaRelation is '10' (H.261-style motion supporting only integer-sample offsets).

bRefPicSelect[i]: Specifies the reference picture buffer used in prediction for MVvalue[i] when motion vector reference picture selection is in use.

Valid combinations of IntraMacroblock, MotionForward, MotionBackward, PicMotionType, MvertFieldSel, and MVector[i] are shown in Table 1 below. The values specified in the table are for when H261LoopFilter, Motion4MV and bPicOBMC are all zero.

Table 1 - Use of Macroblock Parameters for Various Motion Types

IntraMacroblock, MotionForward, MotionBackward | MotionType (Meaning depends on picture type.) | MVector[0] MvertFieldSel[0] (1st, dir1) | MVector[1] MvertFieldSel[1] (1st, dir2) | MVector[2] MvertFieldSel[2] (2nd, dir1) | MVector[3] MvertFieldSel[3] (2nd, dir2)
Frame Structured Pictures (bPicStructure = '11')
1,0,0 (intra) | '00' (intra) | - - | - - | - - | - -
0,0,0 (no motion) | '10' (no motion) | 0 - | - - | - - | - -
0,1,0 | '10' (frame MC) | PMV[0][0] - | - - | - - | - -
0,0,1 | '10' (frame MC) | - - | PMV[0][1] - | - - | - -
0,1,1 | '10' (frame MC) | PMV[0][0] - | PMV[0][1] - | - - | - -
0,1,0 | '01' (field MC) | PMV[0][0] sel[0][0] | - - | PMV[1][0] sel[1][0] | - -
0,0,1 | '01' (field MC) | - - | PMV[0][1] sel[0][1] | - - | PMV[1][1] sel[1][1]
0,1,1 | '01' (field MC) | PMV[0][0] sel[0][0] | PMV[0][1] sel[0][1] | PMV[1][0] sel[1][0] | PMV[1][1] sel[1][1]
0,1,0 | '11' (dual-prime) | PMV[0][0] 0 (top) | vector'[2][0][0], vector'[2][0][1]<<1 1 (bot) | PMV[0][0] 1 | vector'[3][0][0], vector'[3][0][1]<<1 0
Field Structured Pictures (bPicStructure == '01' or '10')
1,0,0 (intra) | '00' (intra) | - - | - - | - - | - -
0,0,0 (no motion) | '01' (no motion) | 0 PicCurrentField | - - | - - | - -
0,1,0 | '01' (field MC) | PMV[0][0] sel[0][0] | - - | - - | - -
0,0,1 | '01' (field MC) | - - | PMV[0][1] sel[0][1] | - - | - -
0,1,1 | '01' (field MC) | PMV[0][0] sel[0][0] | PMV[0][1] sel[0][1] | - - | - -
0,1,0 | '10' (16×8 MC) | PMV[0][0] sel[0][0] | - - | PMV[1][0] sel[1][0] | - -
0,0,1 | '10' (16×8 MC) | - - | PMV[0][1] sel[0][1] | - - | PMV[1][1] sel[1][1]
0,1,1 | '10' (16×8 MC) | PMV[0][0] sel[0][0] | PMV[0][1] sel[0][1] | PMV[1][0] sel[1][0] | PMV[1][1] sel[1][1]
0,1,0 | '11' (dual-prime) | PMV[0][0] PicCurrentField | vector'[2][0] !PicCurrentField | - - | - -

NOTES:

  1. This is an extremely important table. It must be inspected very closely and fully understood. Experience has shown that there will be bugs in any implementation that fails to properly account for every utilized macroblock type in the table (especially for field-structured pictures or dual-prime motion).
  2. In a number of places in the above table the variable PMV is used rather than the raw motion vector value. This is to distinguish between PMV, which is in frame coordinates, from a motion vector which may be in field coordinates (i.e., at half-vertical resolution). In all such cases above, PMV refers to the value of PMV after updating by the current motion vector.
  3. The definitions of vector'[2][0] and vector'[3][0] are found in MPEG-2 Section 7.6.3.6. The shift operation shown indicates that the vertical component is modified to frame coordinates.
  4. In both "no motion" cases (0,0,0) above, the macroblock parameters emulate a forward prediction macroblock (0,1,0) with a zero-valued motion vector. (See also MPEG-2 Section 7.6.3.5.)

The remaining allowed cases are as follows:

H261LoopFilter == 1 && bPicOBMC == 0 && Motion4MV == 0: This indicates that one forward motion vector is sent in MVector[0] and the H.261 loop filter as specified in Section 3.2.3 of H.261 is active for the forward prediction in the macroblock. MotionForward shall be "1" in this case and IntraMacroblock and MotionBackward shall both be "0".

bPicOBMC == 0 && Motion4MV == 1: This indicates that four forward motion vectors are sent in MVector[0, 1, 2, 3]. MotionForward shall be "1" in this case and IntraMacroblock shall be "0". If MotionBackward is "1", a fifth motion vector is sent for backward prediction in MVector[4].

bPicOBMC == 1 && Motion4MV == 0: This indicates that ten forward motion vectors are sent in MVector[0, 1, 2, ..., 9] for specification of OBMC motion, and that the values of the first four such motion vectors are all equal. If MotionBackward is "1", an eleventh motion vector is sent for backward prediction in MVvalue[10].

bPicOBMC == 1 && Motion4MV == 1: This indicates that ten forward motion vectors are sent in MVvalue[0, 1, 2, ..., 9] for specification of OBMC motion, and that the values of the first four such motion vectors may differ from each other. If MotionBackward is "1", an eleventh motion vector is sent for backward prediction in MVvalue[10].

NOTE: No current configuration of the H.263 standard would exercise the case in which bPicOBMC == 1, Motion4MV == 1, and MotionBackward == 1.

Some details about the interactions between H.263's OBMC, 4MV, B, EP, and B in PB may be helpful:
a) OBMC cannot be used in a H.263 B or EP picture (H.263 Section 5.1.4.5 item 2)
b) OBMC cannot be used in the B part of a H.263 PB picture (H.263 Section F.1 paragraph 1)
c) 4MV cannot be transmitted in a H.263 B or EP picture (Only one MVFW and MVBW in syntax diagrams, and no 4MV macroblock types in H.263 Tables O.1 and O.2)
d) If 4MV is used in the macroblock of a H.263 P picture which is used as the future reference macroblock for "direct" prediction in a H.263 B picture, the OBMC is not used in the direct prediction, because four motion vectors are used according to H.263 Annex M which uses them like H.263 Annex G which doesn't apply the OBMC (H.263 Section O.4 paragraph 2 and item 2 above it). Thus, H.263 would never require both OBMC and backward prediction at the same time, and never uses 4MV in a backward direction.

NOTE: The average operator is mathematically identical ((s1+s2)//2) for MPEG-1, MPEG-2 half-sample prediction filtering, bi-directional averaging, and Dual Prime same-opposite parity combining. This operator is the same as the C-language expression: (s1+s2+1)>>1. The H.263 bi-directional averaging operator does not seed with an offset of "+1" prior to downshifting. The bBidirectionalAveragingMode parameter determines which of these methods is used.

3.5.5.2 Inverse Quantization, Pre-IDCT Saturation, Mismatch Control, Intra DC Offset, IDCT, Picture Reconstruction, and Reconstruction Clipping

The interface supports three low-level methods of handling IDCT. In all cases the basic inverse quantization process, pre-IDCT range saturation, MPEG-2 mismatch control (if necessary), and intra DC offset (if necessary) are performed on the host, and the final picture reconstruction and reconstruction clipping is done on the accelerator. The first method is to pass macroblocks of transform coefficients to the accelerator for external IDCT, picture reconstruction, and reconstruction clipping. The second and third involve performing an IDCT on the host and passing blocks of spatial-domain results for external picture reconstruction and reconstruction clipping.

The inverse quantization, pre-IDCT saturation, mismatch control, intra DC offset, IDCT, picture reconstruction, and reconstruction clipping processes are defined as the following:

  1. Performing inverse quantization as necessary (including application of any inverse quantization weighting matrices) to create a set of IDCT coefficient values [image] from entropy-coded quantization indices (performed by the host).
  2. Saturating each reconstructed coefficient value [image] of the transform coefficient block to obtain a value [image] within the restricted allowable range (performed by the host):

    Mismatch control (described as needed for MPEG-2 only, and performed by the host) is performed by adding up the saturated values of all coefficients in the macroblock (equivalent to XORing their LSBs). If the sum is even, then the saturated value of the last coefficient [image] shall be modified by subtracting one if [image] is odd and adding one if [image] is even (equivalent to toggling its LSB). (If the sum is odd, the saturated value of [image] is used without alteration.) The coefficient values subsequent to the saturation and mismatch control are then denoted herein as [image].

  3. NOTE: MPEG-1 has a different form of mismatch control that consists of altering the value by plus or minus 1 for each coefficient that would otherwise be even after inverse quantization. H.263 does not require mismatch control in the sense described herein. In any case, where applicable, mismatch control is the host's responsibility.
  4. Adding an intra DC offset if necessary (performed by the host) so that all intra blocks correspond to adding a difference to a spatial reference prediction value of 2(BPP-1). Such an offset is necessary for all of the referenced video coding standards (H.261&3 and MPEG-1&2&4), except when HostResidDiff is "1" and bConfigIntraResidUnsigned is "1", and has the value [image] in all of these cases (this value being 1024 in all such cases except MPEG-4, which allows BPP>8).
  5. Performing the unitary separable transformation (either on the host or the accelerator):

    where:

    C(u) = 1 for u = 0, otherwise [image],

    C(v) = 1 for v = 0, otherwise [image],

    x and y are the horizontal and vertical spatial coordinates in the pixel domain,

    u and v are the transform-domain horizontal and vertical frequency coordinates, and

    WT and HT are the width and height of the transform block (normally both are eight).

    NOTE: The accuracy of this IDCT process shall conform to that required in the H.261&3 and MPEG-1&2&4 video coding standards (all have very similar requirements).

  6. Adding the spatial-domain residual information to the motion-compensated prediction value for non-intra blocks or to the constant reference value for intra blocks (this constant being 2(BPP-1) except when HostResidDiff is "1" and bConfigIntraResidUnsigned is "1", in which case it is "0") to perform picture reconstruction (on the accelerator), and finally
  7. Clipping the picture reconstruction to a range of [0, (2BPP)-1] to store as the final resulting picture sample values (on the accelerator).

3.5.5.2.1 Off-Host IDCT

The transfer of macroblock IDCT coefficient data for off-host IDCT processing consists of a buffer of index and value information. Index information is sent as 16 bit words (although only 6 bit quantities are really needed for 8×8 transform blocks), and transform coefficient value information is sent as signed 16 bit words (although only 12 bits are needed for the usual case of 8×8 transform blocks and BPP=8).

Transform coefficients are sent in either DXVA_TCoefSingle or DXVA_TCoef4Group data structures. If bConfig4GroupedCoefs is "0", coefficients are sent singly using DXVA_TCoefSingle structures. If bConfig4GroupedCoefs is "1", coefficients are sent in groups of four using DXVA_TCoef4Group structures. These two alternative data structures contain two similar basic elements which are defined below.

TCoefIDX: specifies the index of the coefficient in the block, as determined from bConfigHostInverseScan. There are two basic ways that TCoefIDX can be used:

  1. Run-length ordering: When bConfigHostInverseScan is "0", MBscanMethod indicates a zig-zag, alternate-vertical, or alternate-horizontal inverse scan. In this case, TCoefIDX contains the number of zero-valued coefficients which precede the current coefficient in the specified scan order, subsequent to the last transmitted coefficient for the block (or relative to the start of the block if none preceding).
  2. Arbitrary ordering: When bConfigHostInverseScan is "1", MBscanMethod indicates arbitrary ordering. In this case, TCoefIDX simply contains the raster index of the coefficient within the block (i.e., TCoefIDX = u + v·WT)

TCoefIDX shall never be greater than or equal to WT·HT.

TCoefValue: The value of the coefficient in the block. TCoefValue shall be clipped to the appropriate range as specified in Section 3.4.2 above by the host prior to passing the coefficient value to the accelerator for inverse DCT operation. MPEG-2 mismatch control, if necessary, is also the responsibility of the host, not the accelerator (this may require the creation of extra "phantom" nonzero coefficients).

3.5.5.2.1.1 Single-Coefficient Data Format

The DXVA_TCoefSingle data structure, used whenever bConfig4GroupedCoefs is "0", is defined as:

DXVA_TCoefSingle {
  TCoefIDX        15 /* really need only 6 for 8×8 */
  TCoefEOB         1
  TCoefValue    16 /* saturated on host */
}

TCoefEOB: Indicates whether the current coefficient is the last one associated with the current block of transform coefficients. A value of 1 is indicates that the current coefficient is the last one for the block, and a value of "0" indicates that it is not.

3.5.5.2.1.2 Four-Grouped Coefficient Data Format

The DXVA_TCoef4Group data structure, used only when bConfig4GroupedCoefs is 1 and bConfigHostInverseScan is "0", is defined as:

DXVA_TCoef4Group {
  TCoefIDX[4]    4*8  /* really need only 6 for 8×8 */
  TCoefValue[4]  4*16
}

In the DXVA_TCoef4Group data structure, groups of four transform coefficients are sent together at a time along with run-length values. The ith element of each array in DXVA_TCoef4Group contains element 3-i of the actual coefficient or run-length list (so the first coefficient or index goes into element 3, the next in element 2, etc.). If only NC<4 nonzero coefficients need to be sent, then TCoefIDX[i] shall be 63 (hexadecimal 0x3F) and TCoefValue[i] shall be equal to TCoefValue[4-NC] for i=0 to 3-NC.

3.5.5.2.2 Host-Based IDCT

IDCT may be performed on the host, with the result passed through the API. There are two supported schemes for sending the results - the 16-bit method and the 8-8 overflow method. An indication of which is used is sent in bConfigSpatialResid8.

3.5.5.2.2.1 The 16-bit Method

When sending data using the 16-bit method, blocks of 16-bit data are sent sequentially. Each block of spatial-domain data consists of WT·HT values of DXVA_Sample16.

A DXVA_Sample16 is a 16-bit signed integer. If BPP is greater than 8, only the 16-bit method is allowed. If bPicIntra is "1" and BPP is "8," the 16-bit method is not allowed. If IntraMacroblock is "0", the 16-bit samples are sent as signed quantities relative to the motion-compensated prediction values. If IntraMacroblock is "1", the 16-bit samples are sent as follows:

  • If bConfigIntraResidUnsigned is "1", the samples are sent as unsigned quantities relative to the constant reference value of "0",
  • If bConfigIntraResidUnsigned is "0", the samples are sent as signed quantities relative to the constant reference value of 2(BPP-1).

Blocks of data are sent sequentially, in the order specified by scanning wPatternCode for 1-valued bits from MSB to LSB.

NOTES:

  1. No clipping of these values can be assumed to have been performed on the host, unless bConfigSpatialHost8or9Clipping is "1". Although only a BPP+1 bit range is needed to adequately represent the spatial-domain difference data, the output of some IDCTs will produce numbers beyond this range unless they are clipped. The accelerator shall work properly with at least a 15-bit range of values.
  2. Although video coding standards typically specify clipping of a difference value prior to adding it to a prediction value (e.g., 9 bit clipping in 8 bit-per-sample video), this clipping stage is actually unnecessary since it has no effect on the resulting decoded output picture. We therefore do not assume that this clipping occurs herein unless necessary for the accelerator hardware as indicated by bConfigSpatialHost8or9Clipping being set to "1".

3.5.5.2.2.2 The 8-8 Overflow Method

If BPP is "8", the 8-bit difference method may be used. Its use is required if bPicIntra is "1" and BPP is "8". In this case, each spatial-domain difference value is represented using only eight bits. When sending data using the 8-bit method, blocks of 8-bit data are sent sequentially. Each block of 8-bit spatial-domain residual difference data consists of WT×HT values of DXVA_Sample8. Each block of 8-bit spatial-domain residual difference data consists of WT×HT values of DXVA_Sample8.

If IntraMacroblock is "0" the 8-bit samples are signed differences to be added or subtracted (as determined from bConfigResid8Subtraction and whether the sample is in a first pass block or overflow block) relative to a motion compensation prediction. If IntraMacroblock is "0" and the difference to be represented for some pixel in a block is too large to represent using only eight bits, a second "overflow" block of samples can be sent.

If IntraMacroblock is "1", the 8-bit samples are set as follows:

  • If bConfigIntraResidUnsigned is "1", the 8-bit samples are sent as unsigned quantities relative to the constant reference value of "0",
  • If bConfigIntraResidUnsigned is "0", the 8-bit samples are sent as signed quantities relative to the constant reference value of 2(BPP-1).
Overflow blocks shall not be sent if IntraMacroblock is "1".

Blocks of data are sent sequentially, in the order specified by scanning wPatternCode for 1-valued bits from MSB to LSB, and then all necessary 8-bit overflow blocks are sent as specified by wPC_Overflow. Such overflow blocks are subtracted rather than added if bConfigResid8Subtraction is "1".

The first pass of 8-bit differences for each non-intra macroblock is added. If bPicOverflowBlocks is "0" or IntraMacroblock is "1", there is no second pass. If bPicOverflowBlocks is "1", IntraMacroblock is "0", and bConfigResid8Subtraction is "1", the second pass of 8-bit differences for each non-intra macroblock is subtracted. If bPicOverflowBlocks is "1", IntraMacroblock is "0", and bConfigResid8Subtraction is "0", the second pass of 8-bit differences for each non-intra macroblock is added.

If any sample is non-zero in both an original 8-bit block and in a corresponding 8-bit overflow block, then:

  • If bConfigResid8Subtraction is "0", the sign of the sample shall be the same in both blocks.
  • If bConfigResid8Subtraction is "1", the sign of the sample in the original 8-bit block shall be the same as the sign of minus one times the value of the sample in the corresponding overflow block.
This allows the sample to be added to the prediction picture with 8-bit clipping of the result after each of the two passes.

NOTE: The 8+8 method (using 8-bit differences with overflow blocks with bConfigResid8Subtraction equal to "0") cannot represent a residual difference value of +255 if IntraMacroblock is "0", which makes it not strictly compliant with video coding standards. However, this format is supported herein as it is 1) used in some existing implementations, 2) more efficient than 16-bit sample use in terms of the amount of data needed to represent a picture, and 3) not considered to normally result in any meaningful degradation of video quality.

3.5.5.3 Deblocking Filter Control

Deblocking filter control commands, if present, are sent for each luminance block in a macroblock and are sent once for each pair of chrominance blocks. The commands are sent in raster scan order within the macroblock, with all blocks for luminance sent before any blocks for chrominance, then one chrominance 4:2:0 command, then one chrominance 4:2:2 command if needed, then two chrominance 4:4:4 commands if needed (the same filtering is applied to both chrominance components). The filtering for each block is specified by specification of the deblocking to occur across its top edge, followed by specification of the deblocking to occur across its left edge. Deblocking is specified for chrominance only once - and the same deblocking commands are used for both the Cb and Cr components. For example, deblocking of a 16×16 macroblock which contains 4:2:0 data using 8×8 blocks is specified by sending four sets of two (top and left) edge filtering commands for the luminance blocks, followed by one set of two edge filtering commands for the chrominance. The data structure for specification of each deblocking edge is as follows:

DXVA_DeblockingEdgeControl {
    EdgeFilterStrength    7 /* need only 4b for H.263 */
    EdgeFilterOn        1
}

EdgeFilterStrength: This parameter specifies the strength of the filtering to be performed as specified in H.263 Annex J.

EdgeFilterOn: This flag shall be "1" if the edge is to be filtered, and "0" if not.

The actual edge filtering for the edges with EdgeFilterOn equal to "1" shall be performed precisely as specified in H.263 Annex J with the specified value of EdgeFilterStrength and with clipping at the output to the range of [0, (2BPP)-1]. As specified in H.263 Annex J, all top-edge filtering for all blocks shall be performed "prior" to any left edge filtering for any blocks (in the sense that the values of the samples used for top-edge filtering shall be those reconstructed values prior to any deblocking filtering for left-edge filtering).

If the buffer type indicates that sample values of macroblocks outside of the current deblocking filter command buffer are not affected, the EdgeFilterOn parameter shall be zero for all edges at the left and top of the region covered by the macroblocks with deblocking filter commands in the buffer.

3.5.5.4 Read-Back Buffers

One read-back command buffer is present when bPicReadbackRequests is "1" and this commands the accelerator to return resulting final (after deblocking if applicable) picture macroblock data to the host. If an encryption protocol is in use, the accelerator may respond to read-back requests by returning an error indication, returning garbage data, or returning encrypted data (as may be specified by the encryption protocol).

The buffer passed to the accelerator shall contain read-back commands containing a single parameter per macroblock to be read:

wMBaddress: (16 bits) Specifies the macroblock address of the current macroblock in raster scan order ("0" being the address of the top left macroblock, PicWidthInMBminus1 being the address of the top right macroblock, and PicHeightInMBminus1 * PicWidthInMB being the address of the bottom left macroblock, and PicHeightInMBminus1 * PicWidthInMB + PicWidthInMBminus1 being the address of the bottom right macroblock).

If BPP is "8", the data shall be returned in the form of 8 bit unsigned values (thus Black is nominally Y=16, Cb=Cr=128 and White is nominally Y=235, Cb=Cr=128), and if BPP is greater than 8, the data shall be returned in the form of 16-bit unsigned values.

The data is returned from the accelerator to the host in the form of:

  1. First, a copy of the read-back command buffer itself, followed by padding to the next 32 Byte alignment boundary, and then
  2. The macroblock data values, returned in the order sent in the read-back command buffer, in the form of WT·HT samples per block for each block in each macroblock. Residual difference blocks within a macroblock shall be returned in the order specified as in MPEG-2 Figures 6-10, 6-11, and 6-12 (raster-scan order for Y, followed by all 4:2:0 blocks of Cb in raster scan order, followed by 4:2:0 blocks of Cr, followed by 4:2:2 blocks of Cb, followed by 4:2:2 blocks of Cr, followed by 4:4:4 blocks of Cb, followed by 4:4:4 blocks of Cr).

3.5.6 Off-Host VLD Bitstream Decoding Operation

When variable-length decoding of raw bitstream data is performed on the accelerator, the data sent by the host for the decoding of the picture is divided into three types of buffers:

  1. Inverse quantization matrix buffers, which provide information about how to perform inverse quantization of the bitstream data,
  2. Slice control buffers, each of which provides information about the location of start codes and data within a corresponding bitstream data buffer, and
  3. Bitstream data buffers, which contain raw streams of data encoded according to a specific video coding specification.

3.5.6.1 Inverse Quantization Matrix Buffers

An inverse quantization matrix buffer is sent to initialize inverse quantization matrices for off-host bitstream decoding. Inverse quantization matrix buffers provide information about how to decode all current and subsequent video in the bitstream, until a new inverse quantization matrix buffer is provided. (Thus, inverse quantization matrices are persistent.) No more than one inverse quantization matrix buffer shall be sent from the host to the accelerator at a time.

DXVA_QmatrixData {
  for(i=0; i<4; i++)
    bNewQmatrix[i]      // 8b
  for(i=0; i<4; i++)
    if(bNewQmatrix[i] == 1)
      Qmatrix[i]        // WT·HT·16b
}

bNewQmatrix[i]: Indicates whether a new inverse quantization matrix of type i is present in the buffer. If bNewQmatrix[i] is "1", a new inverse quantization matrix of type i follows in the inverse quantization matrix buffer. Type i=0 is for intra luminance quantization, i=1 is for inter luminance quantization, i=2 is for intra chrominance quantization, and i=3 is for inter chrominance quantization. No default values of inverse quantization matrices may be assumed by the accelerator in the absence of any prior value sent by the host. The value of bNewQmatrix[i] shall not be zero for both i=0 and i=1.

If the value of bNewQmatrix[i] is "0" for i=2 or i=3, then:

  1. If bNewQmatrix[i-2] is "0", the previous inverse quantization matrix for i shall continue to be used by the accelerator, and
  2. If bNewQmatrix[i-2] is "1", the inverse quantization matrix for i shall be set equal to the new inverse quantization matrix for i-2.

If the relevant video coding specification does not need inverse quantization matrices (e.g., H.261 and H.263), no inverse quantization matrix buffer shall be sent. If the relevant video coding specification does need inverse quantization matrices, some value must be provided for these inverse quantization matrices by the host prior to, or in conjunction with, the transferal of any bitstream data buffers at the start of the video decoding process.

NOTE: No default value is assumed for quantization matrices in the absence of any prior value sent from the host. The quantization matrix values must be sent explicitly, even if they contain values that are available by default in the relevant video coding specification.

Qmatrix[i]: An inverse quantization matrix. Present only when bNewQmatrix[i] is equal to "1". The matrix consists of WT·HT unsigned words (in which only the lower eight bits of each word are used for the dominant video coding standards). The order of the data values within the inverse quantization matrix shall be as specified in the relevant video coding specification.

NOTE: For MPEG-2 bitstreams, the data values within Qmatrix[i] are in zig-zag inverse scan order, as specified in subclause 7.3.1 and Figure 7-2 of MPEG-2.

3.5.6.2 Slice Control Buffers

Slice control buffers shall be provided to guide the operation of off-host VLD bitstream processing. The host software decoder shall determine the location of "slice-level" resynchronization points in the bitstream. A slice is defined to be a multi-macroblock layer which includes a resynchronization point in the bitstream data. In H.261 bitstreams, a GOB shall be considered a slice. In H.263 bitstreams, a sequence of one or more GOBs starting with a GOB start code and containing no additional GOB start codes shall be considered a slice. A slice control buffer shall contain one or more DXVA_SliceInfo data structures, according to the contents of a corresponding bitstream data buffer.

DXVA_SliceInfo {
              wHorizontalPosition       //16b
              wVerticalPosition         //16b
              dwSliceBitsInBuffer       //32b
              dwSliceDataLocation       //32b
              bStartCodeBitOffset       // 8b
              bReservedBits             // 8b
              wMBbitOffset              //16b
              wNumberMBsInSlice         //16b
              wQuantizerScaleCode       //16b
              wBadSliceChopping         //16b
            }

wHorizontalPosition, wVerticalPosition: The horizontal and vertical position of the first macroblock of the slice, expressed in units of macroblocks with zero indicating the left-most or top-most macroblock of the picture, respectively.

dwSliceBitsInBuffer: The total number of bits in the corresponding bitstream data buffer which contain data for the current slice. This shall be a multiple of eight for MPEG-1, MPEG-2, and MPEG-4, and in the slice structured mode of H.263, since slice start codes in these cases are byte aligned.

dwSliceDataLocation: The location of the first byte containing data for the slice (e.g., the location of a slice start code) in the bitstream data buffer. Shall be zero if the start of the slice is not within the corresponding bitstream data buffer.

bStartCodeBitOffset: The number of MSBs of the byte at dwSliceDataLocation which do not contain data for the slice (zero for MPEG-1, MPEG-2, and MPEG-4 since slice start codes in these specifications are byte aligned, but possibly nonzero for H.261 and H.263 which do not force byte alignment of GOB start codes). Shall be in the range of 0...7. Shall be zero if the start of the slice is not within the corresponding bitstream data buffer. MSBs marked irrelevant for the current slice by bStartCodeBitOffset may contain data for a previous slice in the case of start codes which are not byte aligned, as may occur for example in H.263 baseline mode.

wMBbitOffset: The number of bits of slice header data prior to the first bit of macroblock layer data in the bitstream buffer. For example, if wMBbitOffset is 83, the macroblock layer data for the slice starts after 83 bits slice header data. Shall be zero if the start of the slice is not within the corresponding bitstream data buffer.

wNumberMBsInSlice: The number of macroblocks of data in the slice, including skipped macroblocks. May be zero if this number cannot be readily determined from the header of the picture and the headers and initial macroblock data of the current and next slice in the bitstream, such as in the rectangular slice and arbitrary slice ordering submodes of the slice mode of H.263. Shall not be zero for H.261, MPEG-1, MPEG-2, MPEG-4, or when not using the rectangular slice or arbitrary slice submodes of the slice structured mode in H.263.

wQuantizerScaleCode: The quantizer scaling code from the slice level of the bitstream, as specified in the particular video coding specification (ranging from "1" to "31" for H.261, H.262/MPEG-2, H.263, MPEG-1, and MPEG-4).

wBadSliceChopping: A parameter containing a value defined as follows:

"0" : All bits for the slice are located within the corresponding bitstream data buffer.

"1" : The bits for the start of the slice are within the corresponding bitstream data buffer, and the bits for the end of the slice are not (because the bitstream data buffer is full).

"2" : The bits for the start of the slice are not within the corresponding bitstream data buffer (because the previous bitstream data buffer was full), but the bits for the end of the slice are within the corresponding bitstream data buffer.

"3" : The bits for the start of the slice are not within the corresponding bitstream data buffer (because the previous bitstream data buffer was full), and the bits for the end of the slice are also not within the corresponding bitstream data buffer (because the corresponding bitstream data buffer is also full).

Nonzero values of wBadSliceChopping should generally be avoided by the host software decoder.

3.5.6.3 Bitstream Data Buffer Contents

If a bitstream buffer is used, the buffer simply contains raw bytes from a video bitstream to support off-host decoding including low-level bitstream parsing with variable-length decoding.

Certain restrictions are imposed on the contents of bitstream data buffers, in order to ensure that they are used in a manner consistent with the intended design:

  1. Except for MPEG-1 and MPEG-2 use, the first bitstream data buffer for each picture shall start with all data if any (subsequent to the end of all data for any prior picture) that precedes the first slice for the current picture in the bitstream (sequence header, picture header, etc.).
  2. For MPEG-1 and MPEG-2 use, the first bitstream data buffer for each picture shall start with the slice start code of the first slice of the picture (no sequence header, picture header, etc., since all relevant data is provided elsewhere in parameters of this specification).
  3. If the start of a slice of bitstream data is located within a particular bitstream data buffer, the end of that slice shall also be located within that same data buffer unless the buffer which contains the start of the slice is completely full to its allocated size.

The decoder should manage the filling of the bitstream data buffers in a manner to generally avoid the straddling of slices across different buffers.

3.6 Alpha Blend Data Loading (bDXVA_Func=2)

The second type of DirectX VA function is the loading of information for specifying an alpha blending surface to be blended with video data.

3.6.1 Connection Configuration

The DirectX VA connection configuration data structure for alpha blend data loading shall be defined as:

DXVA_ConfigAlphaLoad {
           // Operation Indicated
          dwFunction         //32b
          dwReservedBits[3] // 3 * 32b alignment
          bConfigDataType //8b
}

dwFunction: Contains a DXVA_ConfigQueryOrReplyFunc describing the configuration data structure.

bConfigDataType: Specifies the type of alpha blend data to be used, as defined by:

"0": 16-entry AYUV palette with IA44 alpha blending surface,

"1": 16-entry AYUV palette with AI44 alpha blending surface,

"2": 16-entry AYUV palette with DPXD, Highlight, and DCCMD data,

"3": AYUV graphic surface.

Support for bConfigDataType being "0" or "2" are allowed for near-term accelerator implementations, but other formats are preferred and both formats "1" and "3" are expected to be required in the intermediate term unless otherwise indicated by the restricted mode profile.

3.6.2 Minimal Interoperability Configuration Set

It is a design requirement for all DirectX VA decoders to interoperate with all DirectX VA accelerators. This requires that every DirectX VA decoder be capable of operation with any member of a set of connection configurations, and that every DirectX VA accelerator be capable of operation with at least one connection configuration member of that set. The minimal interoperability configuration set for alpha blend data loading consists of all defined values of bConfigDataType.

3.6.3 Loading an AYUV Alpha Blending Surface

An AYUV alpha blending surface is defined as an array of samples of 32 bits each. This surface can be used as the source for blending a graphic with decoded video pictures.

Each AYUV sample is structured as follows:

DXVA_AYUVsample{
            bSampleAlpha8   // 8b (the MSBs)
            bY_Value        // 8b
            bCbValue        // 8b
            bCrValue        // 8b (the LSBs)
}

bSampleAlpha8: The opacity of the sample. The value "0" indicates that the sample is transparent (so that the other entries have no effect on the resulting blended picture) and the value "255" indicates that the sample is opaque (so that the other entries completely determine the value of the resulting blended picture sample). For non-zero values of SampleAlpha8, the blend specified is to add (SampleAlpha8+1) times the graphic value to (255-SampleAlpha8) times the picture value and to the constant 128, and right-shift the result by eight places. For a zero value of SampleAlpha8, the blend specified is to use the picture value without alteration.

bY_Value, bCbValue, bCrValue: A color in Y, Cb, Cr color space (per ITU-T Rec. 601) as an unsigned quantity. Thus with BPP=8, the color Black is nominally specified by Y=16, Cb=Cr=128, and the color White is nominally specified by Y=235, Cb=Cr=128.

The width and height of the AYUV alpha blending surface are specified in the associated buffer description list.

3.6.3.1 Loading a 16-entry AYUV palette

A 16-entry YUV palette is defined as an array of 16 DXVA_AYUVsamples. In this case the SampleAlpha8 for each sample has no meaning and shall be "0".

The palette can be used to create the source for blending a graphic with decoded video pictures. This palette can be used to create the graphic source along with either:

  1. an IA44/AI44 alpha blending surface or
  2. a DPXD alpha blending surface, a highlight buffer, and DCCMD data.

3.6.3.2 Loading an AYUV surface

Rather than loading just a 16-entry palette, an entire image graphic can simply be loaded directly as an AYUV image to specify the graphic content.

3.6.4 Loading an IA44/AI44 Alpha Blending Surface

An index-alpha 4-4 (IA44) alpha blending surface is defined as an array of 8-bit samples, each of which is structured as follows:

DXVA_IA44sample{
        SampleIndex4        // 4b (the MSBs)
        SampleAlpha4        // 4b (the LSBs)
        }

An alpha-index 4-4 (AI44) alpha blending surface is defined as an array of 8-bit samples, each of which is structured as follows:

DXVA_AI44sample{
    SampleAlpha4        // 4b (the MSBs)
    SampleIndex4        // 4b (the LSBs)
    }

SampleIndex4: The index into the 16-entry palette for the sample.

SampleAlpha4: The opacity of the sample. The value "0" indicates that the sample is transparent (so that the palette entry for SampleIndex4 has no effect on the resulting blended picture) and the value "15" indicates that the sample is opaque (so that the palette entry for SampleIndex4 completely determines the resulting blended picture). For non-zero values of SampleAlpha4, the blend specified is to add (SampleAlpha4+1) times the graphic value to (15-SampleAlpha4) times the picture value and to the constant 8, and right-shift the result by four places. For a zero value of SampleAlpha4, the blend specified is to use the picture value without alteration.

The width and height of the IA44 alpha blending surface are specified in the associated buffer description list.

3.6.5 Loading a DPXD Alpha Blending Surface

A decoded PXD (DPXD) alpha blending surface is defined as a packed frame-structured array of two-bit samples, each of which is to be used as an index into a four-color table determined by highlight and DCCMD data. The result of the combination of DPXD, highlight, and DCCMD is equivalent to an IA44 surface, and is used with a 16-entry YUV palette for blending. If treated as an array of bytes, the index of the first two-bit sample shall be placed in the MSBs of the first byte of DPXD data, the next sample in the next two bits, the third sample in the next two bits, the fourth sample in the LSBs, the fifth sample in the MSBs of the next byte, and so on.

The DPXD alpha blending surface may be created from the PXD information on a DVD, which is in a run-length encoded format. The creation of DPXD for DirectX VA from PXD on a DVD thus requires the host to perform the run-length decoding of the raw data from the disk.

The stride of the surface shall be interpreted as the stride in bytes, not in two-bit sample units. However, the width and height shall be in two-bit sample units.

NOTE: The PXD on a DVD is in a field-structured interlaced format. The DPXD alpha blending surface defined herein is not. The host is therefore responsible for interleaving the data from the two fields if forming DPXD from DVD PXD data.

NOTE: For further clarification of DVD subpicture definition and data field interpretation, see DVD Specifications for Read-Only Disk: Part 3 - Video Specification (v. 1.11, May '99).

3.6.6 Loading Highlight Data

The Highlight data is formatted in a manner compatible with the DVD ROM specification, and is to be applied along with DCCMD data to a DPXD surface to create an alpha blending surface. The Highlight data buffer contents shall be as follows:

DXVA_Highlight {
    wHighlightActive    // 16b
    wHighlightIndices   // 16b
    wHighlightAlphas    // 16b
    HighlightRect       // 128b
}

wHighlightActive: Indicates whether or not a rectangular highlight area is currently activated ("0" indicates inactive, and "1" indicates active). If inactive, the highlight data shall have no effect on the content of the blended picture.

wHighlightIndices: Contains the four-bit palette index of the highlighted rectangular area on the subpicture for each of the two-bit indices in the DPXD. The four MSBs shall be for index 3, the next four bits shall be for index 2, the next four bits shall be for index 1, and the four LSBs shall be for index 0.

wHighlightAlphas: Contains the four-bit opacity of the highlighted rectangular area on the subpicture for each of the two-bit indices used by the DPXD. The four MSBs shall be for index 3, the next four bits shall be for index 2, the next four bits shall be for index 1, and the four LSBs shall be for index "0". The interpretation of the four-bit opacity values shall be as described above for SampleAlpha4.

wHighlightRect: Contains the definition of the area of the highlight rectangle as a RECT data type.

The following restrictions apply to the RECT parameters:

  • "left" and "top" shall be greater than or equal to zero,
  • "right" and "bottom" shall be greater than "left" and "top", respectively, and
  • "right" shall not exceed 720, and "bottom" shall not exceed 576.

NOTE: There appears to be a difference between the way the DVD specification defines a subpicture rectangular area and the convention typically used in Microsoft applications. We follow the Microsoft convention for this specification, which is to say that a rectangle of width 10 and height 10 in the upper left corner of the picture is defined by Top = 0, Left = 0, Right = 10, Bottom = 10. The convention in the DVD specification appears to instead use Right = 9 and Bottom = 9.

3.6.7 Loading DCCMD Data

The DCCMD (display control command) data is formatted in a manner compatible with the DVD ROM specification, and is to be applied along with Highlight data to a DPXD surface to create an alpha blending surface. The DCCMD data buffer contents shall consist of data formatted as a list of DVD display control commands (DCCMDs).

NOTE: For further clarification of DVD subpicture definition and data field interpretation, see DVD Specifications for Read-Only Disk: Part 3 - Video Specification (v. 1.11, May '99).

3.7 Alpha Blend Combination (bDXVA_Func=3)

Alpha blend combination takes the last loaded alpha blend source information and combines it with a reference picture to create a blended picture for display. It uses an alpha blend combination data buffer to control this process.

3.7.1 Connection Configuration

The DirectX VA connection configuration data structure for alpha blend combination shall be defined as:

DXVA_ConfigAlphaCombine {
  // Operation Indicated
  dwFunction                 // 32b
  dwReservedBits[3]         // 3 * 32b alignment

  bConfigBlendType          // 8b
  bConfigPictureResizing    // 8b
  bConfigOnlyUsePicDestRectArea  //8b
  bConfigGraphicResizing    // 8b
  bConfigWholePlaneAlpha    // 8b
}

dwFunction: Contains a DXVA_ConfigQueryOrReplyFunc describing the configuration data structure.

bConfigBlendType: Specifies the type of alpha blend combinations to be performed, as defined by:

"0": Front-end buffer-to-buffer blend,

"1": Back-end hardware blend.

Support for bConfigBlendType equal to "1" is allowed for near-term accelerator implementations, but support of bConfigBlendType being "0" is expected to be required in the intermediate term.

bConfigPictureResizing: Specifies whether the PictureSourceRect16thPel for subpicture blending may differ in ,width and height from the PictureDestinationRect (adjusted for the 1/16th-sample scaling of PictureSourceRect16thPel) and whether the parameters in PictureSourceRect16thPel may not be multiples of 16, thus requiring the source picture to be resampled by the accelerator. "1" indicates that resampling (whether for resizing and/or for sub-pixel accuracy) is supported and "0" indicates that it is not.

bConfigOnlyUsePicDestRectArea: Specifies whether the decoder can command operations which specify values for areas of an output generated destination picture that fall outside of the PictureDestinationRect. "0" indicates that areas outside of the PictureDestinationRect can be specified by the blend combination commands. "1" indicates that the host decoder cannot rely on the values of and cannot display any region of the blended surface outside of the area specified by PictureDestinationRect.

bConfigGraphicResizing: Specifies whether the GraphicSourceRect for subpicture blending may differ in size from the GraphicDestinationRect, thus requiring the alpha blending graphic to be resampled by the accelerator. "1" indicates that resizing is supported and "0" indicates that it is not.

bConfigWholePlaneAlpha: Specifies whether a whole-plane alpha parameter can be applied to the graphic data. "1" indicates that a whole-plane alpha can be applied, and "0" indicates that it cannot.

3.7.2 Minimal Interoperability Configuration Set

It is a design requirement for all DirectX VA decoders to interoperate with all DirectX VA accelerators. This requires that every DirectX VA decoder be capable of operation with any member of a set of connection configurations, and that every DirectX VA accelerator be capable of operation with at least one connection configuration member of that set. The minimal interoperability configuration set for alpha blend data loading consists of bConfigBlendType having a choice of values as determined by the DirectX VA restricted mode profile.

3.7.3 Alpha Blend Combination Buffers

An alpha blend combination buffer governs the generation of a blended picture from a source picture and a graphic image with accompanying alpha blending information. In the event that the source and destination pictures are not in 4:4:4 format, every second sample of the graphic blending information (i.e., the first, third, fifth, etc.) shall be applied to the subsampled source chrominance information in the vertical or horizontal direction as applicable to produce the blended result.

DXVA_BlendCombination {
          wPictureSourceIndex           //16b
          wBlendedDestinationIndex      //16b
          PictureSourceRect16thPel      //128b
          PictureDestinationRect        //128b
          GraphicSourceRect             //128b
          GraphicDestinationRect        //128b
          wBlendDelay                   //16b
          bBlendOn                      //8b
          bWholePlaneAlpha              //8b
          OutsideYUVcolor               //32b
        }

wPictureSourceIndex: The index of the picture to be combined with the graphic. Shall be 0xFFFF if back-end hardware alpha blending is in use.

wBlendedDestinationIndex: The index of the combined picture to be created. Shall be 0xFFFF if back-end hardware alpha blending is in use. Shall not be equal to wPictureSourceIndex.

PictureSourceRect16thPel: The area of the source picture to be combined with the graphic, specified as a RECT data structure in units of 1/16th sample in the luminance component. In other words, the parameters in the RECT data structure are fixed-point representations which each have 28 bits before and 4 bits after the binary point. (This 1/16th sample accuracy allows PictureSourceRect16thPel to contain the same accuracy as the frame_centre_horizontal_offset and frame_centre_vertical_offset pan-scan parameters in MPEG-2.) If bConfigPictureResizing is "0", all parameters in PictureSourceRect16thPel shall be integer multiples of 16.

The following restrictions apply to the RECT parameters of PictureSourceRect16thPel:

  • "left" and "top" shall be greater than or equal to zero,
  • "right" and "bottom" shall be greater than or equal to "left" and "top", respectively,
  • if "right" is equal to "left" or "top" is equal to "bottom", a case only allowed if bConfigOnlyUsePicDestRectArea is "0", all of the RECT parameters shall have the value "0", indicating no use of the source picture, and
  • "right" and "bottom" shall not exceed 16 times the allocated width and height, respectively, of the uncompressed source picture surface.

For example, if PictureSourceRect16thPel is used to select an entire MPEG-2 decoded picture, the PictureSourceRect16thPel parameters can be computed as follows:

  • left = 0
  • top = 0
  • right = 16·horizontal_size
  • bottom = 16·vertical_size

PictureDestinationRect: The area of the destination picture to hold the area from the source picture, specified as a RECT data structure. If bConfigPictureResizing is "0", shall have the same width and height as the area specified by PictureSourceRect16thPel. If PictureDestinationRect differs in size from PictureSourceRect16thPel, the resampling method to be applied is not specified, but should have a quality at least equivalent to that of bilinear resampling.

The following restrictions apply to the RECT parameters:

  • "left" and "top" shall be greater than or equal to zero,
  • "right" and "bottom" shall be greater than or equal to "left" and "top", respectively,
  • if "right" is equal to "left" or "top" is equal to "bottom", a case only allowed if bConfigOnlyUsePicDestRectArea is "0", all of the RECT parameters shall have the value "0" and PictureSourceRect16thPel shall also specify all parameters having the value "0",
  • if bConfigBlendType = 0, "right" and "bottom" shall not exceed the allocated width and height, respectively, of the uncompressed destination picture surface, and
  • if bConfigBlendType = 1, "right" and "bottom" shall not exceed the allocated width and height, respectively, of the source graphic surface.

GraphicSourceRect: The area of the graphic picture to be combined with the source picture, specified as a RECT data structure. If alpha blend data loading uses bConfigDataType equal to "2", the following restrictions on GraphicSourceRect apply:

  1. The "top" and "left" parameters of GraphicSourceRect shall be zero.
  2. The "right" parameter of GraphicSourceRect shall be equal to the "End X-coordinate" minus the "Start X-coordinate" of the last preceding DVD SET_DAREA DCCMD, plus 1 to adjust for the differing rectangle interpretations as described in the note below.
  3. The "bottom" parameter of GraphicSourceRect shall be equal to the "End Y-coordinate" minus the "Start Y-coordinate" of the last preceding DVD SET_DAREA DCCMD, plus 1 to adjust for the differing rectangle interpretations as described in the note below.

The following restrictions apply to the RECT parameters:

  1. "left" and "top" shall be greater than or equal to zero,
  2. "right" and "bottom" shall be greater than or equal to "left" and "top", respectively,
  3. if "right" is equal to "left" or "top" is equal to "bottom", all of the RECT parameters shall have the value "0", indicating no use of the graphic picture, and
  4. "right" and "bottom" shall not exceed the allocated width and height, respectively, of the graphic source surface. The allocated width and height are defined as 720 and 576, respectively, when bConfigDataType = "2".

GraphicDestinationRect: The area of the destination picture to hold the area from the graphic picture, specified as a RECT data structure. If bConfigGraphicResizing is "0", shall have the same width and height as the area specified by GraphicSourceRect. If GraphicDestinationRect differs in size from GraphicSourceRect, the resampling method to be applied to the graphic is not specified, but should have a quality at least equivalent to that of bilinear resampling of an AYUV surface representing the blending information.

The following restrictions apply to the RECT parameters of GraphicDestinationRect:

  1. "left" and "top" shall be greater than or equal to zero, unless this requirement conflicts with the need to offset the graphic by 8 samples as described in the next paragraph and in Sections 3.7.3.3 and 3.7.3.4,
  2. "right" and "bottom" shall be greater than or equal to "left" and "top", respectively,
  3. if "right" is equal to "left" or "top" is equal to "bottom", then all of the RECT parameters shall have the value "0" and GraphicSourceRect shall also specify all parameters having the value "0",
  4. if bConfigBlendType = 0, "right" and "bottom" shall not exceed the allocated width and height, respectively, of the uncompressed destination picture surface, and
  5. if bConfigBlendType = 1, "right" and "bottom" shall not exceed the allocated width and height, respectively, of the source graphic surface, and

If alpha blend data loading uses bConfigDataType equal to "2" and if bConfigGraphicResizing is "0", the following additional restrictions on GraphicDestinationRect apply:

  1. "top" shall be equal to the "Start Y-coordinate" of the last preceding DVD SET_DAREA DCCMD.
  2. "left" shall be equal to either the "Start X-coordinate" of the last preceding DVD SET_DAREA DCCMD or to that value minus 8 (see Sections 3.7.3.3 and 3.7.3.4).
  3. The "right" parameter of GraphicDestinationRect shall be equal to the value of "left" plus the "End X-coordinate" minus the "Start X-coordinate" of the last preceding DVD SET_DAREA DCCMD, plus 1 to adjust for the differing rectangle interpretations as described in the note below.
  4. The "bottom" parameter of GraphicDestinationRect shall be equal to the value of "top" plus the "End Y-coordinate" minus the "Start Y-coordinate" of the last preceding DVD SET_DAREA DCCMD, plus 1 to adjust for the differing rectangle interpretations as described in the note below.

NOTE: There appears to be a difference between the way the DVD specification defines a subpicture rectangular area and the convention typically used in Microsoft applications. We follow the Microsoft convention for this specification, which is to say that a rectangle of width 10 and height 10 in the upper left corner of the picture is defined by Top = 0, Left = 0, Right = 10, Bottom = 10. The convention in the DVD specification appears to instead use an equivalent of Right = 9 and Bottom = 9.

wBlendDelay: If back-end hardware blending is in use, wBlendDelay contains a number of milliseconds of delay prior to the combination operation going into effect. Has no meaning and shall be "0" if front-end blending is in use.

bBlendOn: If back-end hardware blending is in use, the specified blending shall be applied from the time specified in a blending combination function with bBlendOn being "1" until the specified execution time of a new blending combination with bBlendOn being "1" or until the blending is disabled by a blending combination function with bBlendOn being "0". Has no meaning and shall be zero if front-end blending is in use.

If back-end hardware blending is in use and bBlendOn is "0", the only other parameter in the alpha blend combination buffer that has meaning is wBlendDelay.

bWholePlaneAlpha: Contains an opacity multiplier for the alpha channel of the graphic. The value "0" indicates that the graphic is transparent (so that the graphic content has no effect on the resulting blended picture) and the value "255" indicates that the graphic content uses its full sample opacity. For non-zero values of bWholePlaneAlpha, the blend specified is to multiply the opacity of each location in the graphic content by (bWholePlaneAlpha+1)/256. For a zero value of bWholePlaneAlpha, the blend specified is to use the opacity specified in the graphic content without alteration. Shall be zero if bConfigWholePlaneAlpha is "0".

OutsideYUVcolor: Contains an indication of whether the areas outside of the PictureDestinationRect are to be generated as having a constant color for blending, and contains that constant color if so indicated. OutsideYUVcolor is formatted as a DXVA_AYUVsample and shall follow the following convention:

  1. The value of bSampleAlpha8 in OutsideYUVcolor shall be "255" if the areas outside of the PictureDestinationRect are to be generated as a constant color for blending.
  2. The value of bSampleAlpha8 in OutsideYUVcolor shall be "0" if either of the following two cases applies:
    1. if the areas outside of the PictureDestinationRect are to be unaffected by the blend or
    2. if the areas outside of the PictureDestinationRect cannot be used (as indicated by bConfigStayInPicDestRectArea having the value "1").
  3. All other values for bSampleAlpha8 in OutsideYUVcolor are reserved for future use.

The value of bSampleAlpha8 in OutsideYUVcolor shall be "0" if bConfigStayInPicDestRectArea is "1".

If bSampleAlpha8 in OutsideYUVcolor is "0", the only area of the destination surface that will be affected by the blend is the part within the PictureDestinationRect. If bSampleAlpha8 in OutsideYUVcolor is "255", any area of the destination surface that is outside of the PictureDestinationRect but within the GraphicDestinationRect shall be generated by blending the graphic with the color specified in the non-alpha parameters of OutsideYUVcolor and the entire allocated area of the destination surface that falls outside of both PictureDestinationRect and GraphicDestinationRect shall be set to the color specified in the non-alpha parameters of OutsideYUVcolor. If bConfigBlendType is "1", the OutsideYUVcolor parameters shall be set to indicate blending with black by specifying bSampleAlpha8 = 255, bY_Value = 16, bCbValue = bCrValue = 128.

NOTE: When bConfigBlendType is "1" (back-end hardware blend), the actual blending operations may differ somewhat in method from what is described herein. However, the visual result shall be equivalent. For example, some resizing specified to map a video picture from a source to a destination size may instead be applied in an inverse manner map the graphic content to its proper location relative to the source video picture, with the blended result then displayed in a manner compensating for this difference in operation - but the ultimate visual effect of the result shall be as specified by the blend combination command.

3.7.3.1 Example: MPEG-2 Pan-Scan Operation

For example, if PictureSourceRect16thPel is used to select an area specified by MPEG-2 video pan-scan parameters, the PictureSourceRect16thPel parameters can be computed as follows (provided that the values computed do not violate the restrictions above, as could be the case with some MPEG-2 pan-scan parameters and in particular can be the case with some MPEG-2 DVD content):

  1. left = 8·(horizontal_size - display_horizontal_size) - frame_centre_horizontal_offset
  2. top = 8·(vertical_size - display_vertical_size) - frame_centre_vertical_offset
  3. right = left + 16·display_horizontal_size
  4. bottom = top + 16·display_vertical_size

And the PictureDestinationRect would normally then be created as:

  1. left = 0 or 8 (per Section 3.7.3.3 below)
  2. top = 0
  3. right = left + display_horizontal_size
  4. bottom = top + display_vertical_size

3.7.3.2 Example: DVD 4:3 Pan-Scan Within 16:9 Pictures

For example, in DVD's use of MPEG-2 for 4:3 pan-scan within 16:9 pictures, the pan-scan parameters are restricted such that they will not violate the restrictions given above, and further such that in this case the pan-scan parameters follow the following restrictions:

  1. horizontal_size = 720 or 704
  2. vertical_size = 480 or 576
  3. display_horizontal_size = 540
  4. display_vertical_size = vertical_size
  5. frame_centre_vertical_offset = 0
  6. frame_centre_horizontal_offset has an absolute value that is
    1. less than or equal to 1440 for horizontal_size = 720 and
    2. less than or equal to 1312 for horizontal_size = 704

The formulation described in Section 3.7.3.1 can then be applied directly in this case.

3.7.3.3 Example: DVD 704-Wide Non-Pan-Scan Picture Operation

As an alternative example, the use of MPEG-2 on DVD for 704-wide pictures would specify a source rectangle if using Section 3.7.3.1 that exceeds the boundaries of the decoded picture (it specifies a display_horizontal_size of 720 that exceeds the decoded picture's horizontal_size of 704). In such a case, the host software decoder is responsible for cropping the source rectangle to keep it from reaching outside the allocated source area and for managing the destination rectangle to adjust for the cropping. In this case there are two basic alternatives. Both cases involve specifying a picture source rectangle (in 1/16th sample resolution) such that:

  • left = 0
  • right = 16·(left + horizontal_size) = 11264

The two alternatives are:

  1. Either the picture destination rectangle can be set as:
    • left = (display_horizontal_size – horizontal_size) / 2 = 8
    • right = left + horizontal_size = 712
    with the graphic used in a straightforward fashion.
  2. Or the picture destination rectangle can be set as:
    • left = 0
    • right = left + horizontal_size = 704
    with the graphic destination rectangle being displaced to the left by 8 samples to compensate for the shifted picture destination.

The second of these two alternatives is presumably the preferred one.

3.7.3.4 Example: DVD 352-Wide Picture Operation

Another example is DVD's use of 352-wide pictures, which can be stretched to a width of 704 by use of a picture source rectangle (in 1/16th sample resolution) having:

  1. left = 0
  2. right = 16·(left + horizontal_size) = 5632
and a picture destination rectangle having two alternative formulations:
  1. Either the picture destination rectangle can be set as:
    1. left = 8
    2. right = left + 2·horizontal_size = 712
    3. with the graphic used in a straightforward fashion
  2. Or the picture destination rectangle can be set as:
    1. left = 0
    2. right = left + 2·horizontal_size = 704
    3. with the graphic destination rectangle being displaced to the left by 8 to compensate for the shifted picture destination

The second of these two alternatives is presumably the preferred one.

3.7.3.5 Example: DVD 720-Wide Picture Operation

A rather trivial example is the use of MPEG-2 on DVD with 720-wide pictures, in which case the picture source rectangle (in 1/16th sample resolution) would have:

  1. left = 0
  2. right = left + 16·horizontal_size = 11520
and the destination rectangle would normally have:
  1. left = 0
  2. right = left + horizontal_size = 720

3.7.3.6 Example: DVD 16:9 Letterbox Height in 4:3 Picture Operation

Another example is DVD's use of 16:9 video for 4:3 displays with letterbox framing. This can be supported by using a picture source rectangle having:

  1. top = 0
  2. bottom = top + 16·vertical_size = 7680 or 9216
and a picture destination rectangle having:
  1. top = vertical_size / 8 = 60 or 72
  2. bottom = 7 · vertical_size / 8 = 420 or 504

3.8 Picture Resampling Control (bDXVA_Func=4)

The picture resampling function is specified for such purposes as spatial scalable video coding, reference picture resampling, or resampling for use as an upsampled or display picture.

The resampling shall be performed as specified for H.263 Annex O Spatial Scalability or for H.263 Annex P with "clipping" at the picture edges, which is the same as in some forms of Spatial Scalability in MPEG-2 and MPEG-4. This uses simple two-tap separable filtering.

3.8.1 Connection Configuration

Picture resampling control does not require a connection configuration. Its operation requires only support of the appropriate restricted mode GUID.

3.8.2 Minimal Interoperability Configuration Set

As no connection configuration is needed for picture resampling control, no minimal interoperability set needs to be defined for its operation.

3.8.3 Picture Resampling Control Buffers

A single buffer type is defined for controlling the resampling process.

DXVA_PicResample {

  wPicResampleSourcePicIndex    // 16b
  wPicResampleDestPicIndex      // 16b

  wPicResampleRcontrol          // 8b
  bPicResampleExtrapWidth       // 8b
  bPicResampleExtrapHeight

  dwPicResampleSourceWidth      // 32b
  dwPicResampleSourceHeight     // 32b

  dwPicResampleDestWidth        // 32b
  dwPicResampleDestHeight       // 32b

  dwPicResampleFullDestWidth    // 32b
  dwPicResampleFullDestHeight   // 32b
}

wPicResampleRcontrol: Specifies the averaging rounding mode of the resampling operation. In the case of H.263 Annex O Spatial Scalability, this parameter shall be 1. (This corresponds to the value of RCRPR in H.263 Annex P which is equivalent to the upsampling needed for H.263 Annex O spatial scalability.) In the case of H.263 Annex P Reference Picture Resampling, this parameter shall be equal to the H.263 parameter RCRPR.

bPicResampleExtrapWidth, bPicResampleExtrapHeight: If nonzero and the padding method of using motion vectors over picture boundaries is used on the accelerator, any resampling shall include padding of the resampled picture as well - and this padding shall cover at least the specified width and height around each edge of the resampled picture regardless of the resampling operation which is performed.

dwPicResampleSourcePicIndex: Specifies the reference buffer to be resampled.

dwPicResampleDestPicIndex: Specifies the buffer to be used for the output of the reference picture resampling operation.

dwPicResampleSourceWidth, dwPicResampleSourceHeight: The width and height of the area of the source picture to be resampled to the destination picture.

dwPicResampleDestWidth, dwPicResampleDestHeight: The width and height of the area of the destination picture to contain the resampled data from the source picture.

dwPicResampleFullDestWidth, dwPicResampleFullDestHeight: The full width and height of the area of the destination picture to contain the resampled data from the source picture. Clipping shall be used to generate any samples outside the source resampling area. (This parameter is necessary for H.263 Annex P support of custom source formats in which the luminance width or height is not divisible by 16.)

4 Restricted Modes

A number of restricted mode profiles are defined in this section. The definition of these restricted mode profiles allows a decoder to determine the capabilities of an accelerator by obtaining an indication of which restricted mode profiles it supports.

Some of the restricted mode profiles defined herein are defined by simple subsets of the capabilities of other restricted mode profiles also defined herein (for example, the MPEG2_A profile is a subset of the capabilities of the MPEG2_B profile). In order to enforce a logical structure to the accelerator capability determination, it is a requirement that all accelerators that support some particular restricted mode profile shall also expose support of all other restricted mode profiles that are defined as subsets of the capabilities of the particular profile in question. For example, since the MPEG2_A profile is defined as a subset of the capabilities of the MPEG2_B profile, all accelerators that support the MPEG2_B profile shall also expose support of the MPEG2_A profile.

4.1 Addition of New Restricted Profiles

The restricted-mode profiles below are defined in anticipation of the combinations of features which might be likely to find widespread support. Microsoft is open to suggestions as to the addition of new profiles containing different combinations of features as are identified as practical and necessary. The restricted mode profile is defined herein to establish the set of video coding "tools" necessary for decoding - essentially to determine whether a given video data format can be decoded in some fashion using the API. In addition to establishing the set of "tools", the decoder must also know how to drive those tools through the API. That issue is discussed in the following section on configuration information.

4.2 Non-Restricted Operation

If this API/DDI is operated without strict conformance to a restricted-mode profile as specified below, the wRestrictedMode field shall be set to a specific value to indicate this lack of restriction.

  1. Connection mode and functions:
    1. wRestrictedMode = 0xFFFF
    2. All defined values of bDXVA_Func allowed

4.3 H261_A Restricted Profile

The H261_A restricted profile contains the set of features required for minimal support of ITU-T Rec. H.261 without acceleration support for H.261 Annex D graphics. Support of this profile is expected to be a longer-term requirement. This set of features is defined by the following set of restrictions:

  1. Connection mode and functions:
    1. wRestrictedMode = "1"
    2. bDXVA_Func = 1
  2. bDXVA_Func = 1 (picture decoding) restrictions:
    1. Frame-level restrictions:
      • BPP = 8
      • bSecondField = 0
      • (MacroblockWidth, MacroblockHeight) = (16, 16)
      • (WT, HT) = (8, 8)
      • bChromaFormat = '01' (4:2:0)
      • bPicStructure = '11' (frame structured)
      • bMVprecisionAndChromaRelation = '10' (H.261 integer-sample motion)
      • bPicExtrapolation = 0
      • bPicDeblocked = 0
      • bPic4MVallowed = 0
      • bPicOBMC = 0
      • bMV_RPS = 0
      • bPicScanFixed = 1
    2. Macroblock-level restrictions:
      • MotionType = '10' (frame motion) if MotionForward = 1
      • MBscanMethod = '00' (zig-zag) if bConfigHostInverseScan = 0
      • FieldResidual = 0 (frame residual)
      • MotionBackward = 0 (no backward prediction)
    3. Bitstream buffer restrictions:
      • The contents of any bitstream buffers shall contain data in the H.261 video format.

    3. 4.4 H261_B Restricted Profile

    The H261_B restricted profile contains the set of features required for support of ITU-T Rec. H.261 without acceleration support for H.261 Annex D graphics but with deblocking filter post-processing support. Support of this profile is not intermediate-term requirement. This set of features is defined by the restrictions listed above for the H261_A restricted profile, except:

    1. Connection mode and functions:
      1. wRestrictedMode = "2"
    2. bDXVA_Func = 1 (picture decoding) restrictions:
      1. bPicDeblocked may be either 0 or 1
      2. wDeblockedPictureIndex shall not be equal to wDecodedPictureIndex when bPicDeblocked is 1

    4.5 H263_A Restricted Profile

The H263_A restricted profile contains the set of features required for support of ITU-T Rec. H.263 and a small specific set of enhanced optional capabilities. Support of this profile is an intermediate-term requirement. This set of features is defined by the following set of restrictions:

  1. Connection mode and functions:
    1. wRestrictedMode = "3"
    4. bDXVA_Func = 1
  2. bDXVA_Func = 1 (picture decoding) restrictions:
    1. Frame-level restrictions:
      • BPP = 8
      • bSecondField = 0
      • (MacroblockWidth, MacroblockHeight) = (16, 16)
      • (WT, HT) = (8, 8)
      • bChromaFormat = '01' (4:2:0)
      • bPicStructure = '11' (frame structured)
      • bRcontrol = 0
      • bMVprecisionAndChromaRelation = '01' (H.263 half-sample motion)
      • bPicExtrapolation = 0
      • bPicDeblocked = 0
      • bPic4MVallowed = 0
      • bPicOBMC = 0
      • bMV_RPS = 0
      • bPicScanFixed = 1
    2. Macroblock-level restrictions:
      • MotionType = '10' (frame motion) if MotionForward = 1
      • MBscanMethod = '00' (zig-zag) if bConfigHostInverseScan = 0
      • FieldResidual = 0 (frame residual)
      • H261LoopFilter = 0 (no H.261 loop filter)
      • MotionBackward = 0 (no backward or bidirectional motion)
    3. Bitstream buffer restrictions:
      • The contents of any bitstream buffers shall contain data in the H.263 video format in "baseline" mode (no options, no PLUSPTYPE) or with Annex L information (to be ignored).

4.6 H263_B Restricted Profile

The H263_B restricted profile contains the set of features required for support of ITU-T Rec. H.263 and a specific set of enhanced optional capabilities. Support of this profile is expected to be a longer-term requirement. This set of features is specified by the restrictions listed above for the H263_A restricted profile, except:

  1. Connection mode and functions:
    1. wRestrictedMode = "4"
  2. bDXVA_Func = 1 (picture decoding) restrictions):
    1. Frame-level restrictions:
      • bPicDeblocked may be either 0 or 1
      • wDeblockedPictureIndex may or may not be equal to wDecodedPictureIndex when bPicDeblocked = 1
      • bRcontrol may be either 0 or 1
      • bPicExtrapolation may be either 0 or 1
      • Pic4MV may be either 0 or 1
      • Motion4MV may be either 0 or 1
      • bPicScanFixed may be either 0 or 1
    2. Macroblock-level restrictions:
      • MBscanMethod may be '00' (zig-zag), '01' (alternate vertical) or '10' (alternate horizontal) if bConfigHostInverseScan = 0
    3. Bitstream buffer restrictions:
      • The contents of any bitstream buffers may also contain data in the H.263 video format with any subset of CPCF, CPFMT and Annexes D, I, N (single forward reference picture per output picture), and T.

4.7 H263_C Restricted Profile

The H263_C restricted profile contains the set of features required for support of ITU-T Rec. H.263 and a specific set of enhanced optional capabilities. Support of this profile is expected to be a longer-term requirement. This set of features is specified by the restrictions listed above for the H263_B restricted profile, except:

  1. Connection mode and functions:
    1. wRestrictedMode = "5"
  2. bDXVA_Func = 1 (picture decoding) restrictions):
    1. Frame-level restrictions:
      • bPicDeblocked may be 1
      • wDeblockedPictureIndex may or may not be equal to wDecodedPictureIndex when bPicDeblocked = 1
    2. Bitstream buffer restrictions:
      • The contents of any bitstream buffers may also contain data in the H.263 video format with any subset of CPCF, CPFMT and Annexes D, I, J, N (single forward reference picture per output picture), and T.

4.8 H263_D Restricted Profile

The H263_D restricted profile contains the set of features required for support of ITU-T Rec. H.263 and a specific set of enhanced optional capabilities. Support of this profile is an intermediate-term requirement. This set of features is specified by the restrictions listed above for the H263_C restricted profile, except:

  1. Connection mode and functions:
    1. wRestrictedMode = "6"
    2. bDXVA_Func may be either 1 (picture decoding) or 4 (picture resampling)
  2. bDXVA_Func = 1 (picture decoding) restrictions):
    1. Frame-level restrictions:
      • bBidirectionalAveragingMode = 1 (H.263 bidirectional averaging) or 0 (MPEG-2 bidirectional averaging)
      • bMV_RPS may be either 0 or 1
    2. Macroblock-level restrictions:
      • MotionBackward may be either 0 or 1
    3. Bitstream buffer restrictions:
      • The contents of any bitstream buffers may also contain data in the H.263 video format with any subset of Annexes K, O, P (factor-of-two resizing with clipping only in one or both dimensions), S, and U.
  3. bDXVA_Func = 4 (picture resampling) restrictions:
    1. PicResampleSourceWidth and PicResampleDestWidth shall be equal or related by a multiplicative factor of 2 (or 1/2).
    2. PicResampleSourceHeight and PicResampleDestHeight shall be equal or related by a multiplicative factor of 2 (or 1/2).
    3. If PicResampleSourceHeight and PicResampleDestHeight are equal, PicResampleSourceWidth and PicResampleDestWidth shall be related by a multiplicative factor of 2 (or 1/2). If PicResampleSourceHeight and PicResampleDestHeight indicate an upsampling operation, PicResampleSourceWidth and PicResampleDestWidth shall not indicate a downsampling operation, and vice versa.

NOTE: Although H.263 requires only support of bBidirectionalAveragingMode equal to "1" when MotionForward is "1" and MotionBackward is "1", the H263_C restricted profile also allows bBidirectionalAveragingMode being "0". This is intended to allow the H263_C restricted profile to support MPEG-4 video as well as H.263 video - and MPEG-4 uses the MPEG-1/MPEG-2 style of bidirectional averaging.

4.9 H263_E Restricted Profile

The H263_D restricted profile contains the set of features required for support of ITU-T Rec. H.263 and a specific set of enhanced optional capabilities. Support of this profile is not an intermediate-term requirement. This set of features is specified by the restrictions listed above for the H263_D restricted profile, except:

  1. Connection mode and functions:
    1. wRestrictedMode = "7"
  2. bDXVA_Func = 1 (picture decoding) restrictions):
    1. Frame-level restrictions:
      • bPicOBMC may be either 0 or 1
    2. Macroblock-level restrictions:
      • if bPicOBMC is 1 and Motion4MV is 1, MotionBackward shall be "0"
    3. Bitstream buffer restrictions:
      • The contents of any bitstream buffers may also contain data in the H.263 video format with Annex F.

4.10 H263_F Restricted Profile

The H263_E restricted profile contains the set of features required for support of ITU-T Rec. H.263 and a specific set of enhanced optional capabilities. Support of this profile is not an intermediate-term requirement. This set of features is specified by the restrictions listed above for the H263_E restricted profile, except:

  1. Connection mode and functions:
    1. wRestrictedMode = "8"
  2. bDXVA_Func = 1 (picture decoding) restrictions):
    4. Frame-level restrictions:
      • bPicBinPB may be either "0" or 1
    5. Bitstream buffer restrictions:
      • The contents of any bitstream buffers may also contain data in the H.263 video format with any subset of Annexes G, M, V and W.

4.11 MPEG1_A Restricted Profile

The MPEG1_A restricted profile contains a set of features required for support of MPEG-1 video. Support of this profile is an intermediate-term requirement. This set of features is defined by the following set of restrictions:

  1. Connection mode and functions:
    1. wRestrictedMode = "9"
    2. bDXVA_Func = 1
  2. bDXVA_Func = 1 (picture decoding) restrictions):
    1. Frame-level restrictions:
      • BPP = 8
      • bSecondField = 0
      • (MacroblockWidth, MacroblockHeight) = (16, 16)
      • (WT, HT) = (8, 8)
      • bChromaFormat = '01' (4:2:0)
      • bPicStructure = '11' (frame structured)
      • bRcontrol = 0
      • bBidirectionalAveragingMode = 0 (MPEG-2 bidirectional averaging)
      • bMVprecisionAndChromaRelation = '00' (MPEG-2 half-sample motion)
      • bPicExtrapolation = 0
      • bPicDeblocked = 0
      • bPic4MVallowed = 0
      • bPicOBMC = 0
      • bMV_RPS = 0
      • SpecificIDCT = 0
      • bPicScanFixed = 1
    2. Macroblock-level restrictions:
      • MotionType = '10' (frame motion)
      • MBscanMethod = '00' (zig-zag) if bConfigHostInverseScan = 0
      • FieldResidual = 0 (frame residual)
      • H261LoopFilter = 0 (no H.261 loop filter)
    3. Bitstream buffer restrictions:
      • The contents of any bitstream buffers shall contain data in the MPEG-1 main profile video format.

4.12 MPEG2_A Restricted Profile

The MPEG2_A restricted profile contains a set of features required for support of MPEG-2 video Main Profile. Support of this profile is an intermediate-term requirement. This set of features is defined by the following set of restrictions:

  1. Connection mode and functions:
    1. wRestrictedMode = 0xA
    2. bDXVA_Func = 1
  2. bDXVA_Func = 1 (picture decoding) restrictions):
    1. Frame-level restrictions:
      • wRestrictedMode = 0xA
      • BPP = 8
      • (MacroblockWidth, MacroblockHeight) = (16, 16)
      • (WT, HT) = (8, 8)
      • bChromaFormat = '01' (4:2:0)
      • bRcontrol = 0
      • bBidirectionalAveragingMode = 0 (MPEG-2 bidirectional averaging)
      • bMVprecisionAndChromaRelation = '00' (MPEG-2 half-sample motion)
      • bPicExtrapolation = 0
      • bPicDeblocked = 0
      • bPic4MVallowed = 0
      • bPicOBMC = 0
      • bMV_RPS = 0
      • SpecificIDCT = 0
      • bPicScanFixed = 1
    2. Macroblock-level restrictions
      • MBscanMethod may be '00' (zig-zag) or '01' (alternate vertical) if bConfigHostInverseScan = 0
      • H261LoopFilter = 0
    3. Bitstream buffer restrictions:
      • The contents of any bitstream buffers shall contain data in the MPEG-2 main profile video format.
      • bNewQmatrix[i] = 0, for i = 2 and 3

4.13 MPEG2_B Restricted Profile

The MPEG2_B restricted profile contains a set of features required for support of MPEG-2 video Main Profile and an associated DVD subpicture using front-end buffer-to-buffer sub-picture blending. Support of this profile is not an intermediate-term requirement. This set of features is defined by the restrictions listed above for the MPEG2_A restricted profile, except:

  3. Connection mode and functions:
    1. wRestrictedMode = 0xB
    2. bDXVA_Func = 1 (picture decoding) or 2 (alpha blend data loading) or 3 (alpha blend combination) (all of these values shall be supported)
    3. bConfigBlendType = 0 (front-end buffer-to-buffer blending)
    4. bConfigDataType = 0, 1, or 3 (at the accelerator's discretion)
    5. Alpha blending source and destination surfaces are supported with width and height of at least 720 and 576, respectively.

4.14 MPEG2_C Restricted Profile

The MPEG2_C restricted profile contains a set of features required for support of MPEG-2 video Main Profile. Support of this profile is an intermediate-term requirement. This set of features is defined by the restrictions listed above for the MPEG2_A restricted profile, except:

  1. Connection mode and functions:
    1. wRestrictedMode = 0xC
    2. one additional member having bConfigResidDiffHost=0 and bConfigResidDiffAccelerator=1 is added to the minimal interoperability set as described in Section 3.5.2.

Since the MPEG2_C restricted profile is defined by a relaxation of the accelerator requirements of the MPEG2_A profile (by allowing an accelerator to not support any of the members of the minimal interoperability set for MPEG2_A), all accelerators that support the MPEG2_A profile shall support the MPEG2_C profile. Similarly, all accelerators that support the MPEG2_D profile shall support the MPEG2_C profile.

4.15 MPEG2_D Restricted Profile

The MPEG2_D restricted profile contains a set of features required for support of MPEG-2 video Main Profile and an associated DVD subpicture using back-end hardware sub-picture blending. Support of this profile is not an intermediate-term requirement. This set of features is defined by the restrictions listed above for the MPEG2_B restricted profile, except:

  1. Connection mode and functions:
    1. wRestrictedMode = 0xD
    2. one additional member having bConfigResidDiffHost=0 and bConfigResidDiffAccelerator=1 is added to the minimal interoperability set as described in Section 3.5.2.
    3. bConfigBlendType may be either 0 or 1 (at the accelerator's discretion)
    4. bConfigDataType may support any value (at the accelerator's discretion)

Since the MPEG2_D restricted profile is defined by a relaxation of the accelerator requirements of the MPEG2_B profile (by allowing an accelerator to not support any of the members of the minimal interoperability set for MPEG2_B), all drivers that support the MPEG2_B profile shall support the MPEG2_D profile.

5 IAMVideoAccelerator Operation

The IAMVideoAccelerator interface provides the mechanism for DirectX VA operation within Windows 2000. This section describes how the DirectX VA data formats shall be sent through this interface.

5.1 The IAMVideoAccelerator Interface Itself

The following is intended as an expansion upon (and potentially an improvement of) the overview description of the use of IAMVideoAccelerator in the current Microsoft DirectShow® documentation set.

NOTE: This interface is available in Microsoft Windows® 2000.

The overlay mixer's input pin supports the IAMVideoAccelerator interface, and the decoder's output pin supports the IAMVideoAcceleratorNotify interface. The sequence of events for connecting the filter pins is as follows:

  1. The filter graph manager calls decoder's output pin's IPin::Connect. An AM_MEDIA_TYPE is an optional parameter.
    • AM_MEDIA_TYPE is a data structure that describes a type of media. It contains a majortype GUID (which in our case should be MEDIATYPE_Video), a subtype GUID (which in our case should be a video accelerator GUID), and a variety of other things. One of those things is a format type GUID containing information about the media, including in our case the width and height of an uncompressed video picture - most likely in an MPEG1VIDEOINFO, VIDEOINFOHEADER, MPEG2VIDEOINFO, or VIDEOINFOHEADER2 structure.
    • The AM_MEDIA_TYPE structure, if present, tells the decoder to operate using the specified media type, which may be "fully specified" or "partially specified". If "fully specified," the decoder would normally simply attempt to operate with that media type. If "partially specified," it will attempt to find a "fully-specified" compatible mode of operation that it can use to connect in a manner consistent with the "partially-specified" media type.
    • The ordinary manner for attempting to find a "fully-specified" media type to use for a connection is to simply run through a list of every "fully-specified" media type that the output pin supports which is compatible with the "partially-specified" media type and attempt to connect with each of them until successful. The process would normally be similar if no AM_MEDIA_TYPE is contained in the IPin::Connect call, but with the output pin needing to check all of its media types.
  2. If the decoder wants to check whether a specific AM_MEDIA_TYPE (including a video accelerator GUID) is supported by the downstream input pin, it can call that pin's IPin::QueryAccept (with the video accelerator GUID as the subtype of the AM_MEDIA_TYPE) or it can simply attempt to connect to that pin as described in item 5 below.
  3. If the decoder does not know which video accelerator GUIDs the downstream input pin supports and does not wish to propose just some particular candidate video accelerator GUID by calling the downstream input pin's IPin::QueryAccept, the decoder can call IAMVideoAccelerator::GetVideoAcceleratorGUIDs to get a list of the video accelerator GUIDs the pin supports.
  4. For some particular video accelerator GUID, the decoder can call the downstream input pin's IAMVideoAccelerator::GetUncompFormatsSupported to get a list of the DDPIXELFORMATs that can be used to render a specific video accelerator GUID. The list returned should be considered to be in decreasing preference order (i.e., with the most preferred format listed first).
  5. The decoder calls the downstream input pin's IPin::ReceiveConnection, passing it an AM_MEDIA_TYPE with the proper video accelerator GUID as the subtype of the media type. This sets up the connection for operation, including the creation of the uncompressed output surfaces (which are allocated using the width and height found in AM_MEDIA_TYPE, and the number of surfaces to allocate found by a call described below, and whatever other information the video accelerator has available and wishes to use for that purpose - such as the video accelerator GUID itself). If the downstream input pin rejects the video accelerator GUID or some other aspect of the connection, this can cause the IPin::ReceiveConnection to fail. If the IPin::ReceiveConnection fails, this is indicated in a returned HRESULT, and the decoder can try to make the call again, e.g., with a new video accelerator GUID in the AM_MEDIA_TYPE structure.
    • NOTE: This is another way (and the most definitive way) for the decoder to determine what is supported by the downstream input pin - simply calling IPin::ReceiveConnection and trying to connect, and then check whether the connection attempt was successful.
  6. During the IPin::ReceiveConnection, the overlay mixer calls the decoder's IAMVideoAcceleratorNotify::GetUncompSurfacesInfo, passing it the video accelerator GUID and an AMVAUncompBufferInfo structure, in order to figure out how many uncompressed surfaces to allocate. The decoder returns an AMVAUncompBufferInfo structure.
    • The AMVAUncompBufferInfo data structure contains the minimum and maximum number of surfaces to be allocated of the particular type, and a DDPIXELFORMAT structure describing the pixel format of the surfaces to be allocated.
    • MINOR NOTE: Nothing is actually passed in to the decoder in the call to IAMVideoAcceleratorNotify::GetUncompSurfacesInfo other than the video accelerator GUID.
  7. The overlay mixer calls the decoder's IAMVideoAcceleratorNotify::SetUncompSurfacesInfo, passing to the decoder the actual number of uncompressed surfaces that were allocated.
  8. The overlay mixer calls the decoder's IAMVideoAcceleratorNotify::GetCreateVideoAcceleratorData to get any data needed to initialize the video accelerator.
  9. The decoder calls IAMVideoAccelerator::GetCompBufferInfo, passing it a video accelerator GUID, an AMVAUncompDataInfo structure, and the number of compressed buffer types, to get in return a set of AMVACompBufferInfo data structures, one corresponding to each type of compressed data buffer used by the video accelerator GUID.
    • The AMVAUncompDataInfo structure contains the width and height of the decoded uncompressed data (in pixels) and the DDPIXELFORMAT of the uncompressed picture.
    • The AMVACompBufferInfo data structures returned each contain:
      • The number of compressed buffers needed of the specific type,
      • The width and height of the surface to create (fields which may or may not have any actual meaning):

        NOTE: The DirectDraw surface allocation operation for the compressed buffers does not currently provide for the width or height of these surfaces to be greater than or equal to 215, although the surface allocation call may not overtly fail if this limit is violated. Therefore, the driver could structure its requests for compressed buffer memory to avoid such extreme sizes. For example, rather than requesting a buffer with width="1" and height="65536", the driver should request a buffer of width="1024" and height="64".
      • The total number of bytes to be used by the surface,
      • A structure of type DDSCAPS2 defining a DirectDrawSurface object, describing the capabilities to create surfaces to store compressed data,
      • A DDPIXELFORMAT, describing the pixel format used to create surfaces to store compressed data (a field which may or may not have any actual meaning).
  10. NOTE: The overlay mixer's calls to some of the decoder's IAMVideoAcceleratorNotify interface methods may (and normally would) occur inside of the decoder's call to the overlay mixer's IPin::ReceiveConnection. Specifically, this applies to the following:
    • IAMVideoAcceleratorNotify::GetUncompSurfacesInfo,
    • IAMVideoAcceleratorNotify::SetUncompSurfacesInfo, and
    • IAMVideoAcceleratorNotify::GetCreateVideoAcceleratorData.
  11. NOTE: To support dynamic format changes, the decoder may also call IPin::ReceiveConnection and other methods per above while the filters are connected and running. This capability is provided in order to support dynamic format changes (although not in the H.263 sense - as all data sets are started up again from scratch and any reference picture information is therefore lost).

The following is a description of IAMVideoAccelerator use during operation after initialization:

  1. For each uncompressed surface, the decoder calls IAMVideoAccelerator::BeginFrame to begin the processing to create the output picture. When it does this, the decoder sends an AMVABeginFrameInfo structure.
    • The AMVABeginFrameInfo structure contains an index for a destination buffer, a pointer to some data to send downstream, and a pointer to a place where the accelerator can put some data for the decoder to read.
    • NOTE 1: The accelerator does not actually receive the destination buffer index, as it is translated by the overlay mixer before going downstream.
    • NOTE 2: IAMVideoAccelerator::BeginFrame can be called more than once between calls to IAMVideoAccelerator::EndFrame.
    • NOTE 3: There is no assumption within the interface operation that IAMVideoAccelerator::BeginFrame and IAMVideoAccelerator::EndFrame need to be called for the processing of every individual picture in the bitstream. The only real things that IAMVideoAccelerator::BeginFrame does, as far as the interface is concerned, is:
      • Create an association within the overlay mixer between an index and an uncompressed surface, and
      • Provide a means to call a specific function in a device driver (with support of a means of passing arbitrary data back and forth between the decoder and the device driver).

    2. (However, in DirectX VA operation there is a requirement described below that IAMVideoAccelerator::BeginFrame and IAMVideoAccelerator::EndFrame do need to be called for the processing of every individual picture in the bitstream.)

  2. For sending uncompressed data to the accelerator, the decoder calls:
    • IAMVideoAccelerator::GetBuffer to lock and obtain access to a specified buffer (if it has not previously called this to get that access). IAMVideoAccelerator::GetBuffer can also be used to get a copy of the contents of the last uncompressed output picture for which IAMVideoAccelerator::BeginFrame was called, providing IAMVideoAccelerator::EndFrame has not been called for that destination buffer index. If the DDI returns a render status of DDERR_WASSTILLDRAWING for the requested buffer, a sleep loop will be operated within IAMVideoAccelerator::GetBuffer until this condition is cleared. In order to call IAMVideoAccelerator::GetBuffer, the decoder will need some information from an AMVACompBufferInfo data structure which is obtained by calling IAMVideoAccelerator::GetCompBufferInfo.
    • IAMVideoAccelerator::Execute to indicate that the data in a set of compressed buffers as indicated in an array of AMVABUFFERINFO data structures should be processed. A function code dwFunction is passed to the driver in this call. A lpPrivateInputData pointer is also passed to some data to send downstream, and a lpPrivateOutputData pointer is passed to a place where the downstream process can put some data for the decoder to read.
    • IAMVideoAccelerator::ReleaseBuffer to indicate that the decoder has completed use of a specified buffer for the moment and no longer needs locked access to the buffer. (If the decoder wishes to continue to use the buffer, it can simply not call IAMVideoAccelerator::ReleaseBuffer for the moment, thus avoiding the need to call IAMVideoAccelerator::GetBuffer until it really intends to not use the buffer anymore.
    • IAMVideoAccelerator::QueryRenderStatus to check on whether a buffer is safe for reading from or writing to.
  3. To complete output processing for a destination buffer, the decoder calls IAMVideoAccelerator::EndFrame. It can pass some arbitrary data downstream with this call, and that's essentially all that happens as a result of this call. It doesn't send a destination buffer index in this call, so it can't indicate to the accelerator precisely what destination buffer is completed unless this indication is contained in the arbitrary data that is passed.
  4. To display a frame, the decoder calls IAMVideoAccelerator::DisplayFrame with the index of the frame to display and a IMediaSample structure containing start and stop time stamps.
  5. Finally, the decoder should, upon completion of all processing, indicate completion of all remaining begun output frames by calling IAMVideoAccelerator::EndFrame and release all of its locked buffers by calling IAMVideoAccelerator::ReleaseBuffer for each unreleased buffer.

5.2 Mapping DirectX VA to IAMVideoAccelerator

5.2.1 Restricted Mode Profile and Configuration Establishment

Due to the variety of types of data that can be decoded by DirectX VA, and the multiple decoding configurations supported within DirectX VA for each of these types of data (e.g., using bitstream buffers vs. host residual difference decoding vs. accelerator-based IDCT with and without encryption of each relevant type of buffer, etc.), we believe it would be somewhat ungainly to simply specify a unique GUID for every unique data type and decoding configuration. This would create a large number of GUIDs (e.g., hypothetically if there were 16 profiles of DirectX VA and 16 configurations possible for each, there would need to be 256 defined GUIDs - requiring 4k bytes of memory just to hold them all. This issue is the most difficult part of determining how to map DirectX VA into IAMVideoAccelerator, with the remainder of the operational definition mostly being quite straightforward. As a result, we specify a unique GUID only for each type of data (i.e., for each restricted mode profile) and allow an additional GUID to be associated with each type of encryption. The decoding configuration is then established between the decoder and accelerator by a lower-level subordinate negotiation using probing and locking operations to establish configurations for each type of DirectX VA function.

5.2.2 DirectX VA IAMVideoAccelerator Operational Specification

The precise mechanism of operation is as follows:

  1. Each restricted mode profile defined herein has an associated DirectX VA GUID which can be supported by a downstream input pin's IPin::QueryAccept and IPin::ReceiveConnection and listed in IAMVideoAccelerator::GetVideoAcceleratorGUIDs.
  2. Similarly, each encryption protocol type for use with DirectX VA shall have an associated encryption protocol type GUID which can be supported by a downstream input pin's IPin::QueryAccept and IPin::ReceiveConnection and listed in IAMVideoAccelerator::GetVideoAcceleratorGUIDs. The "no encryption" GUID DXVA_NoEncrypt shall not be sent in this list, as support for it is required and therefore implicit.
  3. After calling IPin::ReceiveConnection to attempt a connection to the downstream input pin, the decoder's IAMVideoAcceleratorNotify::GetCreateVideoAcceleratorData shall return a pointer to a DXVA_ConnectMode data structure containing the connection mode information for the connection. IAMVideoAccelerator::GetCompBufferInfo shall be called with *pdwNumTypesCompBuffers = 16 and shall return compressed buffer information based on the convention that the type number of each buffer as defined in Section 3.4 can be used directly as the zero-based index into the array of AMVACompBufferInfo data structures that is returned. This requires that for any buffer types that will not be used (including buffer type 0, since there is no defined use of that buffer type), the accelerator driver will provide AMVACompBufferInfo data structures with some form of "dummy" parameter values (e.g., dwNumCompBuffers=0, dwWidthToCreate=0, dwHeightToCreate=0, and dwBytesToAllocate=0).
  4. DXVA function indications and associated data buffers are sent using IAMVideoAccelerator::Execute. The DXVA function is indicated in the dwFunction parameter of the call. The only DXVA functions that are relevant for initialization are DXVA_ConfigQueryOrReplyFunc and DXVA_EncryptProtocolFunc.
    • If dwFunction contains a DXVA_ConfigQueryOrReplyFunc, the lpPrivateInputData pointer for passing data to the accelerator in this call shall point to a configuration data structure, the lpPrivateOutputData pointer for receiving information from the accelerator shall point to an area where an alternative or duplicate configuration data structure can be placed, the pamvaBufferInfo pointer for an array of AMVABUFFERINFO shall be NULL, and dwNumBuffers shall be zero. The returned HRESULT contains the S_OK or S_FALSE indication, or E_FAIL or E_INVALIDARG or some other error indication HRESULT in the event of a severe problem in protocol execution (such as an invalid configuration parameter). All calls to IAMVideoAccelerator::Execute for all uses of DXVA_ConfigQueryOrReplyFunc shall precede all other calls to IAMVideoAccelerator::Execute.
    • If dwFunction contains a DXVA_EncryptProtocolFunc, the lpPrivateInputData pointer for passing data to the accelerator in this call shall point to an encryption protocol data structure that begins with DXVA_EncryptProtocolHeader, the lpPrivateOutputData pointer for receiving information from the accelerator shall point to an area where the data to be returned (such as a certificate) by the encryption protocol (which will begin with DXVA_EncryptProtocolHeader) can be placed, the pamvaBufferInfo pointer for an array of AMVABUFFERINFO shall be NULL, and dwNumBuffers shall be zero. The returned HRESULT contains S_OK as long as the encryption protocol is functioning normally and contains E_FAIL or E_INVALIDARG or some other error indication HRESULT in the event of a severe problem in protocol execution.
    After initialization of operation in the above fashion, the actual operation of the decoder proceeds as follows:
  5. IAMVideoAccelerator::BeginFrame shall be called prior to sending any bDXVA_Func with compressed buffer parameters which cause writes to an uncompressed destination surface. The purpose of IAMVideoAccelerator::BeginFrame in DirectX VA is to associate destination surfaces with index values and to notify the video accelerator driver of the intent to initiate writes a surface so that the driver can respond with an indication of whether the surface is ready to be overwritten. The AMVABeginFrameInfo structure passed in IAMVideoAccelerator::BeginFrame shall contain a pInputData pointer to single WORD wBeginPictureIndex parameter matching the frame index passed into IAMVideoAccelerator::BeginFrame (and dwSizeInputData shall be 2). This is the index to be used in a compressed buffer to command a write to the surface (i.e., to be used as wDecodedPictureIndex, wDeblockedPictureIndex, wBlendedDestinationIndex, or wPicResampleDestPicIndex). The pointer pOutputData in AMVABeginFrameInfo shall be NULL (and dwSizeOutputData shall be "0"). The HRESULT that is returned by IAMVideoAccelerator::BeginFrame shall be:
    • S_OK if the uncompressed surface is available and ready for use.
    • E_PENDING if the uncompressed surface is not yet available for use but will become available soon (i.e., if the uncompressed surface is being read for display and the reading/display of the surface has not yet been completed).
    • E_FAIL or E_INVALIDARG some other error indication only if a data format or protocol error is detected (such as an incorrect value of dwSizeInputData or a non-NULL pOutputData).
  6. DXVA function indications and assocated data buffers are sent using IAMVideoAccelerator::Execute. More than one bDXVA_Func value may be indicated in the same call to IAMVideoAccelerator::Execute. The bDXVA_Func values shall be packed into the dwFunction parameter of the call, with the first function command in the eight MSBs, the next command in the next eight bits, etc., and with any remaining bits padded out with zeros. The value 0xFF for bDXVA_Func indicates that the bDXVA_Func is extended to two or four bytes. If the second byte is also 0xFF, this indicates that bDXVA_Func is extended to four bytes. If the upper four bits of the third byte are 0xF or 0x0, this indicates that bDXVA_Func contains a DXVA_ConfigQueryOrReplyFunc or DXVA_EncryptProtocolFunc. Multi-byte commands shall not indicate continuation past the end of dwFunction. Care must be taken by the decoder to ensure that no sequential dependencies are present between different bDXVA_Func values specified in the same call to IAMVideoAccelerator::Execute and that all potential race conditions (such as between picture decoding and sub-picture blending, between sub-picture loading and sub-picture blending, etc.) are prevented by appropriate calls to IAMVideoAccelerator::BeginFrame and IAMVideoAccelerator::QueryRenderStatus before subsequent calls to IAMVideoAccelerator::Execute.
    • If dwFunction contains a DXVA_ConfigQueryOrReplyFunc, the lpPrivateInputData pointer for passing data to the accelerator in this call shall point to a configuration data structure, the lpPrivateOutputData pointer for receiving information from the accelerator shall point to an area where an alternative or duplicate configuration data structure can be placed, the pamvaBufferInfo pointer for an array of AMVABUFFERINFO shall be NULL, and dwNumBuffers shall be zero. The returned HRESULT contains the S_OK or S_FALSE indication in response to the query, or E_FAIL or E_INVALIDARG some other error indication HRESULT in the event of a severe problem in protocol execution (such as an invalid.configuration parameter). All calls to IAMVideoAccelerator::Execute for all uses of DXVA_ConfigQueryOrReplyFunc shall precede all other calls to IAMVideoAccelerator::Execute.
    • If dwFunction contains a DXVA_EncryptProtocolFunc, the lpPrivateInputData pointer for passing data to the accelerator in this call shall point to an encryption protocol data structure that begins with DXVA_EncryptProtocolHeader, the lpPrivateOutputData pointer for receiving information from the accelerator shall point to an area where the data to be returned (such as a certificate) by the encryption protocol (which will begin with DXVA_EncryptProtocolHeader) can be placed, the pamvaBufferInfo pointer for an array of AMVABUFFERINFO shall be NULL, and dwNumBuffers shall be zero. The returned HRESULT contains S_OK as long as the encryption protocol is functioning normally and contains E_FAIL or E_INVALIDARG or some other error indication HRESULT in the event of a severe problem in protocol execution.
    • If dwFunction does not contain a DXVA_ConfigQueryOrReplyFunc or DXVA_EncryptProtocolFunc, the lpPrivateInputData pointer for passing data to the accelerator shall point to a buffer description list. The first four entries in the buffer description list structure for each buffer (dwTypeIndex, dwBufferIndex, dwDataOffset, and dwDataSize) shall be equal to those in the AMVABUFFERINFO data structure for the same buffer. If bDXVA_Func is equal to "1" is specified within dwFunction and bPicReadbackRequests is "1", the lpPrivateOutputData pointer for receiving information from the accelerator shall point to an area of persistent memory (e.g., heap) to be filled in with read-back macroblock data from the accelerator (such data not guaranteed to be present until IAMVideoAccelerator::QueryRenderStatus for writing to the same picture parameters buffer indicates S_OK as described in item 10 below). Otherwise, the lpPrivateOutputData pointer for receiving information from the accelerator shall point to a single DWORD to be set to one of the following indication values (particularly useful for reporting bitstream errors in off-host VLD operation):
      • "0": Execution OK,
      • "1": Minor problem in data format encountered,
      • "2": Significant problem in data format encountered,
      • "3": Severe problem in data format encountered,
      • "4": Other severe problem encountered.
      If either type of "severe" problem is indicated, the software decoder should cease to operate the function(s) unless corrective action can be taken. This data returned from the accelerator shall not be read by the host until after the buffer rendering for the picture has completed, as can be tested by IAMVideoAccelerator::QueryRenderStatus. The returned HRESULT contains S_OK as long as the interface operation is functioning normally and may return E_FAIL or E_INVALIDARG or some other error indication HRESULT in the event of a severe problem.
  7. The picture decoding parameters buffer shall be among the first buffers sent for the decoding of each picture when using IAMVideoAccelerator::Execute with bDXVA_Func equal to "1", and all the buffers for decoding a picture in a bitstream shall be sent before any buffers for decoding subsequent pictures. If a macroblock control command buffer is sent, a corresponding residual difference data buffer shall be sent (containing data for the same macroblocks) with the same IAMVideoAccelerator::Execute call.
  8. IAMVideoAccelerator::EndFrame shall be called after all compressed buffers have been sent that will cause the creation of the output content in a specified uncompressed surface (i.e., a result of operations specified for wDecodedPictureIndex, wDeblockedPictureIndex, wBlendedDestinationIndex, or wPicResampleDestPicIndex). The purpose of this call to IAMVideoAccelerator::EndFrame is to notify the video accelerator hardware that all data needed for the specified operation has been sent. The pointer to data to send downstream through IAMVideoAccelerator::EndFrame shall point to a single WORD wEndPictureIndex containing the index of the frame that is ending. This parameter shall match the wBeginPictureIndex value specified in athe prior call to IAMVideoAccelerator::BeginFrame before the sending of the relevant compressed buffers. Subsequent to a call to IAMVideoAccelerator::EndFrame, the uncompressed surface with index wEndPictureIndex shall not be found in any picture's wDecodedPictureIndex, wDeblockedPictureIndex, wBlendedDestinationIndex, or wPicResampleDestPicIndex until after another call to IAMVideoAccelerator::BeginFrame is issued to announce that this.will occur and an S_OK has been returned as a result. However, that destination surface index may occur in subsequent read access commands such as wForwardRefPictureIndex, wBackwardRefPictureIndex, wPicResampleSourcePicIndex, or bRefPicSelect[i]. The HRESULT returned by IAMVideoAccelerator::EndFrame shall be S_OK unless there is some kind of data format or protocol error, in which case it can be E_FAIL or E_INVALIDARG or some other error indication.
  9. In the case of field based decoding (e.g. in MPEG-2 bitstreams) there will not be a one-to-one mapping of functional pictures in the bitstream to uncompressed surfaces in the accelerator interface. When decoding field pictures in an MPEG-2 bitstream, there will be two "pictures" decoded to produce one complete output uncompressed surface. In the DirectX VA interface definition, each frame corresponds to each use of wDecodedPictureIndex, wDeblockedPictureIndex, wBlendedDestinationIndex, or wPicResampleDestPicIndex. Thus two pairs of calls to IAMVideoAccelerator::BeginFrame and IAMVideoAccelerator::EndFrame are required for the decoding of field pictures into output uncompressed surfaces.
  10. A call to IAMVideoAccelerator::QueryRenderStatus with dwFlags equal to zero which occurs sometime after a call to IAMVideoAccelerator::EndFrame with a particular wEndPictureIndex and checks the status of a buffer that was sent that contained the wEndPictureIndex in wDecodedPictureIndex, wDeblockedPictureIndex, wBlendedDestinationIndex, or wPicResampleDestPicIndex will return an S_OK indication if all of the operations to write the data to the uncompressed surface have completed and will return E_PENDING if the operation has not yet completed. E_FAIL or E_INVALIDARG or some other error indication may be returned in the event of a protocol error.

5.2.3 Operational Correspondence with Motion Compensation Device Driver

This section contains a description of the Motion Compensation device driver side of the DirectX VA interface [Reference: Windows 2000 DDK - Graphics Drivers - Design Guide - 3.0 DirectDraw DDI - 3.12 Motion Compensation]. The following items refer to entries accessed through the DD_MOTIONCOMPCALLBACKS structure:

  1. At the start of the relevant processing, the device driver's DdMoCompCreate is used to notify the driver that the software decoder will start using a video acceleration object.
  2. GUIDs received from IAMVideoAccelerator::GetVideoAcceleratorGUIDs originate from the device driver's DdMoCompGetGUIDs.
  3. A call to the downstream input pin's IAMVideoAccelerator::GetUncompFormatsSupported returns data from the device driver's DdMoCompGetFormats.
  4. The DXVA_ConnectMode data structure from the decoder's IAMVideoAcceleratorNotify::GetCreateVideoAcceleratorData is passed to the device driver's DdMoCompCreate.
  5. Data returned from IAMVideoAccelerator::GetCompBufferInfo originates from the device driver's DdMoCompGetBuffInfo.
  6. Buffers sent using IAMVideoAccelerator::Execute are received by the device driver's DdMoCompRender.
  7. Use of IAMVideoAccelerator::QueryRenderStatus invokes the device driver's DdMoCompQueryStatus. A return code of DDERR_WASSTILLDRAWING from DdMoCompQueryStatus will be seen by the host decoder as a return code of E_PENDING from IAMVideoAccelerator::QueryRenderStatus.
  8. Data sent to IAMVideoAccelerator::BeginFrame are received by the device driver's DdMoCompBeginFrame. A return code of E_PENDING is needed from DdMoCompBeginFrame in order for E_PENDING to be seen by the host decoder in response to IAMVideoAccelerator::BeginFrame.
  9. Data sent to IAMVideoAccelerator::EndFrame are received by the device driver's DdMoCompEndFrame.
  10. At the end of the relevant processing, the device driver's DdMoCompDestroy is used to notify the driver that the current video acceleration object will no longer be used, so that the driver can perform any necessary cleanup.


DVD Decoder Development

Microsoft DirectX 8.0

DVD Decoder Development in DirectShow

This section contains pointers to the reference pages for all the DirectShow property sets and interfaces that are either DVD-specific or else used extensively in DVD decoding. In addition to what is listed here, a decoder and its pins must also support the generic DirectShow filter interfaces as described in Writing DirectShow Filters.

This section contains the following topics.

  • Decoder Volume Control
  • DVD Region Change Support in Windows

See also:

  • DVD Karaoke Property Set
  • DVD Copy Protection Property Set
  • DVD Subpicture Property Set
  • Pin Property Set
  • IKsPropertySet Interface
  • IVideoFrameStep Interface (hardware decoders only)
  • IVPConfig Interface (hardware decoders only)


Decoder Volume Control

Applications control audio volume through the IBasicAudio interface. An IBasicAudio interface handler is provided for KSProxy. For a decoder to handle the volume commands from KSProxy, it must add several registry keys in its setup script and support the KSPROPSETID_Wave property set.

Create some new registry keys for the driver:

  HKLM\SYSTEM\
    CurrentControlSet\Control
      DeviceClasses
        (decoder guid, eg 2721AE....)
          (Pnp id, eg ##?#VDGENDEV#...)
            #GLOBAL
              Device Parameters
                CLSID		REG_SZ	{17CCA...}
                  FriendlyName	REG_SZ	WDM DVD Driver
                    Interfaces <--- create this key
                    {b9f8ac3e-0f71-11d2-b72c-00c04fb6bd3d} <-- also create this key, it is not a value)
      MediaInterfaces
        {b9f8ac3e-0f71-11d2-b72c-00c04fb6bd3d} <-- create this key
          (default)		REG_SZ	'KsProxy IBasicAudio handler' <-- set this value
          IID	REG_SZ	56 a8 68 b3 0a d4 11 ce b0 3a 00 20 af 0b a7 70	<-- create this string value

To implement volume control, the driver also must support KSPROPSETID_Wave, along with KsProperty.Id = KSPROPERTY_WAVE_VOLUME. This property is passed to the driver through the IKsPropertySet::Get and IKsPropertySet::Set methods. The LeftAttenuation and RightAttentuation fields specify the left/right speaker volumes as linear values from 0x0000 to 0xffff.


DVD Region Change Support in Windows

Introduction

This document explains how the DVD region selection process works under Microsoft® Windows® 9x and Windows 2000. The first section describes the three sources of DVD Region Information. The second section describes how PC system manufacturers can set a system's initial DVD region. The third section explains how the DVD Navigator determines region match between the drive, decoder and disc. The last section shows how application and decoder developers can implement correct DVD region selection support in their code.

Sources of DVD Region Information

There are three sources of DVD region information that work together to determine the region for DVD playback on a Windows PC.
  • DVD Title
    Most DVD titles are marked for a specific region. Some titles can be played in only one region, some can be played in multiple regions, and others can be played all regions.
  • DVD-ROM Drive
    There are two types of DVD-ROM drives: RPC Phase 1 and RPC Phase 2 (hereafter referred to as RPC1 and RPC2) drives. RPC1 drives do not have built-in hardware support for region management. For these drives, Windows maintains the region change count information and the region can be changed only once. RPC2 drives maintain the region change count information in hardware and in general the region of such drives can be changed up to 5 times.
  • DVD Decoder
    Some DVD decoders, hardware or software, are set for a specific region. In general, the user cannot change the decoder's region.

How to Set the Initial Region in Windows 98 and Windows 2000

It is the responsibility of the system manufacturer to select an initial DVD region for the DVD drive in their PCs.

  • Under Windows 98
    The system manufacturer can set a Registry key (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\DefaultDVDRegion (binary)) to set the default DVD region for the drive. The value of this key should be set to the region number for which it should be set on first playback. System manufacturers using OPK builds can add this value to the registry during an "audit mode boot," so the end user never sets the initial region. If this key is set before any DVD title is played on a DVD-enabled Windows system, then the Windows components will select that region for the drive on the first attempt to play back a DVD title.

    If the system manufacturer sets the default region in the Registry and then plays a multi-region disc that includes the default region, the region is set to the default and the disc just plays. If the disc's region does not match the default region, the user will be prompted to change to the required region. (This will be the only region change allowed for an RPC-1 drive.) If no such default region is specified by the system manufacturer, Windows picks a region based on the Operating System locale, time zone, and other factors. If the first disc played is a multi-region disc, then Windows picks the region based on the locale, time zone, and other factors and looks for a match with the lowest region number. If no region on the multi-region disc matches the region picked by Windows, then the region with the lowest number on disc is selected.

    If the manufacturer does not set a region, on first boot the Windows 98 Operating System base components will pick a region based on the Operating System language and the time zone and set the drive to that region. The system manufacturer is free to set the region on the drive and if that is not done during the manufacturing process, it is up to Windows to select the drive's region based on the best guess it can make.

  • Under Windows 2000
    In Windows 2000, the default DVD region is selected based upon the locale that the machine is set up for. Windows 2000 will always set the initial region for a DVD drive using this default region as well as the disc's region, if there is a disc is in the drive. The system manufacturer does not have to do anything to set the initial region for Windows 2000 DVD drives.

    For RPC1 drives, if there is no disc in the drive during boot up then the default region is set based only on the locale of the machine. If there is a DVD disc in the drive during boot up, the default region is selected to be the drive's region, provided it matches a region of the disc; otherwise the lowest region on the disc is picked as the initial region of the drive. The user (or system manufacturer) has one remaining change allowed, in case the default was not correct.

    For RPC2 drives, if during the setup process Windows 2000 finds that the drive does not have any region set (i.e., fresh drive), it will try to pick a region as above, but only if there is a disc in the drive. (RPC1 drives will choose the region without any disc in drive). Once a region is set for RPC2 drives, it is not auto-changed by either a re-installation or a clean installation of the Operating System.

What Microsoft DVD Navigator Does

The Microsoft DVD Navigator uses the following method to determine region match while playing DVD discs on a PC:

The DVD Navigator gets the disc's region, drive's region and decoder's region. If the disc region is "all regions" then the DVD Navigator plays the disc. If the disc is not marked for all regions, the DVD Navigator checks whether the decoder has a preset region. If the decoder has a preset region and it does not match the disc's region, the DVD Navigator will return an error indicating that it cannot play the disc on the current DVD configuration. If the decoder's region is the same as the disc's region, the DVD Navigator will then check whether the drive's region is the same as the disc's region. If they are the same, the DVD Navigator will play the title. If they are not the same, then the DVD Navigator invokes the code to change the drive's region. If the allowed number of region changes has been exhausted, then the region change attempt fails and the title can't be played on that system.

Subsequent DVD region change

On Windows 9x, when the DVD Navigator detects that a region change on the DVD drive is necessary, it uses DVDRgn.exe to request a region change on the drive. This application is regionalized along with other components of the operating system. This application is not installed by default under Windows 98. A method of installing it on the target system is demonstrated below.

In Windows 2000, the DVD Navigator invokes a property page on the DVD-ROM drive device in the Device Manager. This property page is also brought up by the DVDPlay.exe application when a region needs to be changed. The UI of this property page is very similar to that of DVDRgn.exe and it is regionalized in the operating system.

For RPC1 drives, the Windows Operating System components manage region changes. RPC2 drives maintain the region setting in their own hardware. When the number of allowed changes are exhausted on a RPC2 drive, the drive will fail the call to change the region and the region-change component in the operating system will indicate that to the user.

Installing the Windows Region Change Support Components

Application developers can utilize the DVD region change support built into Windows to change region inside the DVD playback applications. There are two different ways of doing this for the Windows 9x and Windows 2000 platforms.
  • Under Windows 9x
    Under Windows 9x platforms, the region-change application, DVDRgn.exe, is installed only when a hardware decoder with a WDM stream class minidriver is installed using the standard INF file. For other software decoders and the upgrade market, insert the following lines into an INF file used by an installation program to add DVDRgn.exe to the target system.
    [Version]
Signature=$CHICAGO$
LayoutFile=layout.inf

[DestinationDirs]
DvdRgnCopy=25       ; Windows
DefaultDestDir=25   ; Windows

[DefaultInstall]
CopyFiles=DvdRgnCopy

[DvdRgnCopy]
dvdrgn.exe
  • Under Windows 2000
    On Windows 2000 systems the component that provides the DVD region change support is in the DLL storprop.dll (available in %windir%\system32). This DLL is installed by default and no extra steps are required to ensure that this DLL is available.

Integrating Region-Change Support into an Application

The following functions are provided for developers who wish to integrate region-change support into their decoders or DVD applications.
/////////////////////////////////////////////////////////////////////
// ChangeDVDRegion :  Function to change the DVD drive region.
//
// Parameters:
//  In:  hWnd - window handle of the application
//              that calls this function
//  Out: none.
//
// Returns:
//    TRUE: if the drive region change is successful
//    FALSE: if drive region change fails (probably because
//           no drive was found with a valid DVD-V disc).
/////////////////////////////////////////////////////////////////////
BOOL ChangeDVDRegion(HWND hWnd)
{
  typedef BOOL (APIENTRY *DVDPPLAUNCHER) (HWND hWnd, CHAR DriveLetter);
  BOOL   bRegionChanged = FALSE;
  TCHAR   szCmdLine[MAX_PATH];

  // First find out which drive is a DVD drive with a valid DVD-V disc.

  TCHAR     szDVDDrive[4];
  if (! GetDriveLetter (szDVDDrive) )
  {
    MessageBox(hWnd,
    TEXT("No DVD drive was found with DVD-V disc.")
    TEXT("\nCannot change DVD region of the drive."),
    TEXT("Error"), MB_OK | MB_INFORMATION) ;
    return FALSE;
  }

  // Detect which OS we are running on. For Windows NT, use the storprop.dll,
  // while for Windows 9x use the DVDRgn.exe application to change the region.

  OSVERSIONINFO   ver;
  ver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
  GetVersionEx(&ver);
  if (VER_PLATFORM_WIN32_NT  == ver.dwPlatformId)
  {
    // Windows NT platform
    HINSTANCE       hInstDLL;
    DVDPPLAUNCHER    dvdPPLauncher;
    CHAR         szDVDDriveA[4];

  #ifdef UNICODE
    WideCharToMultiByte(0, 0, szDVDDrive, -1,
              szDVDDriveA, sizeof(szDVDDriveA),
              NULL, NULL );
  #else
    strcpy(szDVDDriveA, szDVDDrive);
  #endif  // UNICODE

    GetSystemDirectory(szCmdLine, MAX_PATH);
    lstrcat(szCmdLine, TEXT("\\storprop.dll"));

    hInstDLL = LoadLibrary (szCmdLine);
    if (hInstDLL)
    {
      dvdPPLauncher = (DVDPPLAUNCHER) GetProcAddress(hInstDLL,
                                            "DvdLauncher");
      if (dvdPPLauncher)
      {
        bRegionChanged = dvdPPLauncher(hWnd, szDVDDriveA[0]);
      }
      FreeLibrary(hInstDLL);
    }
  }  // end of region change code for Windows NT platform
  else   // Windows 9x platform
  {
    // Get path of \windows\dvdrgn.exe for command line string
    GetWindowsDirectory(szCmdLine, MAX_PATH);
    lstrcat(szCmdLine, TEXT("\\DVDRgn.exe "));

    // Add only the drive letter as command line parameter
    lstrncat(szCmdLine, szDVDDrive, 1);

    // Prepare to execute DVDRgn.exe
    STARTUPINFO               StartupInfo;
    PROCESS_INFORMATION       ProcessInfo;
    StartupInfo.cb            = sizeof(StartupInfo);
    StartupInfo.dwFlags       = STARTF_USESHOWWINDOW;
    StartupInfo.wShowWindow   = SW_SHOWNORMAL;
    StartupInfo.lpReserved    = NULL;
    StartupInfo.lpDesktop     = NULL;
    StartupInfo.lpTitle       = NULL;
    StartupInfo.cbReserved2   = 0;
    StartupInfo.lpReserved2   = NULL;
    if (CreateProcess(csModuleName, szCmdLine,
                    NULL, NULL, TRUE,
                    NORMAL_PRIORITY_CLASS,
                    NULL, NULL, &StartupInfo, &ProcessInfo) )
    {
      // Wait until DVDRgn.exe finishes
      WaitForSingleObject(ProcessInfo.hProcess, INFINITE);
      DWORD dwRet = 1;
      BOOL bRet = GetExitCodeProcess(ProcessInfo.hProcess,
                           &dwRet);
      // If the user changed the drive region
      // successfully, the exit code of DVDRgn.exe is 0.
      if (bRet && 0 == dwRet)
      {
        bRegionChanged = TRUE;
      }
    }
  }  // end of region change code for Windows 9x platform

  if (bRegionChanged)   // if region changed successfully
  {
    // Delete old filter graph and create new filter graph
    // via IDvdGraphBuilder::RenderDvdVideoVolume().
  }
  else   // DVD region didn't happen
  {
    MessageBox(hWnd,
    TEXT("DVD drive region could not be changed.")
    TEXT("Error"), MB_OK | MB_INFORMATION) ;
  }
} //End function ChangeDVDRegion

/////////////////////////////////////////////////////////////////////
// GetDriveLetter :  Function to get the drive letter of the currently
//           active DVD drive
// Parameters:
//  In:    pDvdC - pointer to IDvdControl interface of
//                DVDNavigator filter..
//  Out:   pszDrive - the first DVD drive that is found
//                   to have a valid DVD-V disc.
//
// Returns:
//     TRUE:   if a DVD drive is found (with valid disc)
//    FALSE:   if no DVD drive was found with valid DVD-V disc.
/////////////////////////////////////////////////////////////////////
BOOL GetDriveLetter(IDvdControl *pDvdC, TCHAR *pszDrive)
{
  CHAR   szPathA[MAX_PATH];
  TCHAR   szPath[MAX_PATH];
  ULONG   ulActualSize;
  pszDrive[0] = pszDrive[3] = 0;

  // Get the current root directory
  if (pDvdC ->GetRoot(szPathA, MAX_PATH, &ulActualSize))
  {
    #ifdef UNICODE
      MultiByteToWideChar(CP_ACP, 0, szPathA, 0, szPath, MAX_PATH);
    #else
      lstrcpy(szPath, szPathA);
    #endif  // UNICODE
    lstrcpyn(pszDrive, szPath, 3);
    if (DRIVE_CDROM == GetDriveType(pszDrive)) // could be a DVD drive
      return TRUE;
  }

  // Now loop through all the valid drives to detect which one
  // is a DVD drive with a valid DVD-V disc in it.

  // Get all valid drives
  DWORD dwLeng = GetLogicalDriveStrings(MAX_PATH, szPath);
  TCHAR  *pszTemp = szPath;
  // Try all drives one by one
  for (DWORD dw = 0; dw < dwLeng; dw += 4)
  {
    // Look only for CD-ROM drives that has a disc with required (.ifo) files
    if (DRIVE_CDROM  == GetDriveType(pszTemp))
      {
        TCHAR   szDVDPath1[MAX_PATH]
        TCHAR   szDVDPath2[MAX_PATH];
        lstrcpyn(szDVDPath1, pszTemp, 4);
        lstrcpyn(szDVDPath 2, pszTemp, 4);
        lstrcat(szDVDPath1, TEXT("Video_ts\\Video_ts.ifo"));
        lstrcat(szDVDPath2, TEXT("Video_ts\\Vts_01_0.ifo"));

        // If the .ifo files exist on this drive then it has a valid DVD-V disc
        if (DoesFileExist(achDVDPath1) && DoesFileExist(achDVDPath2))
        {
          lstrcpyn(pszDrive, pszTemp, 3);
          return TRUE;   // return the first drive that has a valid DVD-V disc
        }
      }
    pszTemp += 4;
  }

  return FALSE ;   // didn't find any DVD drive (with DVD-V content)
} //End function GetDriveLetter

/////////////////////////////////////////////////////////////////////
// DoesFileExist : Function to determine if the given filename is an existing file.
//
// Parameters:
//  In:    pszFile - filename string to check for existence.
//  Out:   none.
//
// Returns:
//     TRUE:   if the specified file is found.
//      FALSE:   if the specified file is not found.
/////////////////////////////////////////////////////////////////////
BOOL DoesFileExist(LPTSTR pszFile)
{
  HANDLE    hFile = NULL ;
  // We don't want any error message box to pop up when we try to test
  // if the required file is available to open for read.

  UINT uErrorMode = SetErrorMode(SEM_FAILCRITICALERRORS |
  SEM_NOOPENFILEERRORBOX);
  hFile = CreateFile(pszFile, GENERIC_READ,
                    FILE_SHARE_READ, NULL,
                    OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN,
                    NULL);
  SetErrorMode(uErrorMode);  // restore error mode
  If (INVALID_HANDLE_VALUE  == hFile)
    return FALSE ;

  CloseHandle(hFile);
  return TRUE;
} //End function DoesFileExist


DirectShow Tutorials

This section contains tutorials for Microsoft® DirectShow®.

  • Enumerating Devices and Filters
  • Enumerating Objects in a Filter Graph
  • Seeking Within a Stream
  • Displaying a Filter's Property Pages
  • Grabbing Media Samples
  • Recompressing an AVI File


Enumerating Devices and Filters

Sometimes an application needs to locate a particular filter on the user's system. For example, a video capture application might display a list of available capture devices. Because Microsoft® DirectShow® uses a component-based architecture, it is not always possible to know until run time what filters are installed on the system. This is particularly true for filters that represent hardware devices. Two components in DirectShow make it easier to locate registered filters:

  • The system device enumerator finds filters by their category.
  • The filter mapper finds filters according to search criteria supplied by the application.

The enumerators discussed in this section follow the standard form used by COM enumeration interfaces. For more information, see the IEnumXXXX topic in the Microsoft Platform Software Development Kit (SDK). This section contains the following topics:

  • Using the System Device Enumerator
  • Using the Filter Mapper

Using the System Device Enumerator

The system device enumerator provides a uniform way to enumerate, by category, the filters registered on a user's system. Moreover, it differentiates between individual hardware devices, even if the same filter supports them. This is particularly useful for devices that use the Windows Driver Model (WDM) and the KSProxy filter. For example, the user might have several WDM video capture devices, all supported by the same filter. The system device enumerator treats them as separate device instances.

The system device enumerator works by creating an enumerator for a specific category, such as audio capture or video compression. The category enumerator returns a unique moniker for each device in the category. The category enumerator automatically includes any relevant Plug and Play devices in the category. For a list of categories, see Filter Categories.

To create the system device enumerator, call CoCreateInstance with a class identifier (CLSID) of CLSID_SystemDeviceEnum. To retrieve the category enumerator, call ICreateDevEnum::CreateClassEnumerator with the CLSID of the desired category. The category enumerator supports the IEnumMoniker interface, which you can use to enumerate the individual monikers. Call IMoniker::BindToObject on a moniker to create and initialize the device object, or IMoniker::BindToStorage to retrieve the friendly name of the device (for example, to populate a list box in a user interface). The following diagram illustrates this process.

The following example shows how to create an instance of the system device enumerator and then use it to enumerate video compressor devices. For brevity, the example omits any error checking.

ICreateDevEnum *pSysDevEnum = NULL;
CoCreateInstance(CLSID_SystemDeviceEnum,
    NULL, CLSCTX_INPROC, IID_ICreateDevEnum,
    (void **)&pSysDevEnum);

IEnumMoniker *pEnumCat = NULL;
pSysDevEnum->CreateClassEnumerator(CLSID_VideoCompressorCategory, &pEnumCat, 0);

IMoniker *pMoniker;
ULONG cFetched;
while(pEnumCat->Next(1, &pMoniker, &cFetched) == S_OK)
{
    IPropertyBag *pPropBag;
    pMoniker->BindToStorage(0, 0, IID_IPropertyBag, (void **)&pPropBag);

    VARIANT varName;
    varName.vt = VT_BSTR;
    pPropBag->Read(L"FriendlyName", &varName, 0);

    // Do something with the name.

    SysFreeString(varName.bstrVal);
    pPropBag->Release();
    pMoniker->Release();
}
pEnumCat->Release();
pSysDevEnum->Release();

Using the Filter Mapper

The filter mapper is a COM object that enumerates filters based on various search criteria. The filter mapper is less efficient than the system device enumerator, so if you need filters from a particular category, use the system device enumerator. But if you need to locate a filter that supports a certain combination of media types, but does not fall into a clear-cut category, you might need to use the filter mapper. An example would be a renderer filter or a decoder filter.

The filter mapper supports the IFilterMapper2 interface. To search for a filter, call IFilterMapper2::EnumMatchingFilters. This method takes several parameters that define the search criteria, and returns with an enumerator for the matching filters. The enumerator supports IEnumMoniker, and supplies a unique moniker for each matching filter.

The following example enumerates filters that accept digital video (DV) input and have at least one output pin, of any media type. (The DV Video Decoder filter matches these criteria.)

IFilterMapper2 *pMapper = NULL;
IEnumMoniker *pEnum = NULL;

CoCreateInstance(CLSID_FilterMapper2,
    NULL, CLSCTX_INPROC, IID_IFilterMapper2,
    (void **) &pMapper);

GUID arrayInTypes[2];
arrayInTypes[0] = MEDIATYPE_Video;
arrayInTypes[1] = MEDIASUBTYPE_dvsd;

hr = pMapper->EnumMatchingFilters(
        &pEnum,
        0,                  // Reserved.
        TRUE,               // Use exact match?
        MERIT_DO_NOT_USE+1, // Minimum merit.
        TRUE,               // At least one input pin?
        1,                  // Number of major type/subtype pairs for input.
        arrayInTypes,       // Array of major type/subtype pairs for input.
        NULL,               // Input medium.
        NULL,               // Input pin category.
        FALSE,              // Must be a renderer?
        TRUE,               // At least one output pin?
        0,                  // Number of major type/subtype pairs for output.
        NULL,               // Array of major type/subtype pairs for output.
        NULL,               // Output medium.
        NULL);              // Output pin category.

// Enumerate using pEnum, as in the previous example.

The EnumMatchingFilters method has a fairly large number of parameters, which are commented in the example. The significant ones for this example include:

  • Minimum merit value: The filter must have a merit value above MERIT_DO_NOT_USE.
  • Input types: The caller passes an array containing pairs of major types and subtypes. Only filters that support at least one of these pairs will match.
  • Exact match: A filter can register NULL values for major type, subtype, pin category, or medium. Unless you specify exact matching, a NULL value acts as a wildcard, matching any value that you specify. With exact matching, the filter must exactly match your criteria. However, if you give a NULL parameter in the search criteria, it always acts as a wildcard or "don't care" value, matching any filter.


Enumerating Objects in a Filter Graph

Most of the time, you don't have to worry about individual filters and pins, because a Microsoft® DirectShow® application can simply call methods on the filter graph. Occasionally, however, you will need to locate a particular filter in the graph or even a particular pin on a filter. For example, your application might use a custom interface that a filter exposes, in order to set properties on the filter. Or, you might construct a specialized filter graph by hand and need to call methods on individual pins to connect the filters. For this purpose, DirectShow provides several methods for enumerating objects in a filter graph.

The enumerators discussed in this section follow the standard form used by COM enumeration interfaces. For more information, see the IEnumXXXX topic in the Platform SDK. For information on enumerating filters that are registered on the user's computer, but aren't yet in the filter graph, see Enumerating Devices and Filters.

This article contains the following topics:

  • Enumerating Filters
  • Enumerating Pins
  • Enumerating Media Types

Enumerating Filters

The filter graph manager supports the IFilterGraph::EnumFilters method, which enumerates all the filters in the filter graph. It returns a pointer to the IEnumFilters interface. The IEnumFilters::Next method retrieves IBaseFilter interface pointers.

The following example shows a function that enumerates the filters in a graph and displays a message box with each filter's name. It uses the IBaseFilter::QueryFilterInfo method to retrieve the name of the filter. Note the places where the function calls IUnknown::Release on an interface to decrement the reference count.

void EnumFilters (IFilterGraph *pGraph)
{
    IEnumFilters *pEnum = NULL;
    IBaseFilter *pFilter;
    ULONG cFetched;

    pGraph->EnumFilters(&pEnum);
    while(pEnum->Next(1, &pFilter, &cFetched) == S_OK)
    {
        FILTER_INFO FilterInfo;
        char szName[256];

        pFilter->QueryFilterInfo(&FilterInfo);
        WideCharToMultiByte(CP_ACP, 0, FilterInfo.achName, -1, szName, 256, 0, 0);
        MessageBox(NULL, szName, "Filter name", MB_OK);

        FilterInfo.pGraph->Release();
        pFilter->Release();
    }
    pEnum->Release();
}

Enumerating Pins

Filters support the IBaseFilter::EnumPins method, which enumerates the pins available on the filter. It returns a pointer to the IEnumPins interface. The IEnumPins::Next method retrieves IPin interface pointers.

The following example shows a function that locates a pin with a given direction (input or output) on a given filter. It uses the PIN_DIRECTION enumeration to specify the pin direction, and the IPin::QueryDirection method to find the direction of each enumerated pin. If this function finds a matching pin, it returns an IPin interface pointer with an outstanding reference count. The caller is responsible for releasing the interface.

IPin *GetPin(IBaseFilter *pFilter, PIN_DIRECTION PinDir)
{
    BOOL       bFound = FALSE;
    IEnumPins  *pEnum;
    IPin       *pPin;

    pFilter->EnumPins(&pEnum);
    while(pEnum->Next(1, &pPin, 0) == S_OK)
    {
        PIN_DIRECTION PinDirThis;
        pPin->QueryDirection(&PinDirThis);
        if (bFound = (PinDir == PinDirThis))
            break;
        pPin->Release();
    }
    pEnum->Release();
    return (bFound ? pPin : 0);
}

Enumerating Media Types

Pins support the IPin::EnumMediaTypes method, which enumerates a pin's preferred media types. It returns a pointer to the IEnumMediaTypes interface. The IEnumMediaTypes::Next method retrieves pointers to AM_MEDIA_TYPE structures describing media types.

The media type enumerator exists primarily to help the filter graph make intelligent connections, and your applications will probably not use it. A pin does not necessarily return any preferred media types. Moreover, the media types it returns might depend on the filter's connection status. For example, a filter's output pin might return a different set of media types depending on which media type was set for the filter's input pin.


Seeking Within a Stream

This section describes how an application can seek to different positions within a media stream. It contains the following topics:

  • Overview
  • Seeking Capabilities
  • Time Formats
  • Setting and Retrieving the Stream Position
  • Setting the Playback Rate
  • Case Study: Implementing a Seek Bar

Overview

Microsoft® DirectShow® supports seeking through the IMediaSeeking interface. The filter graph manager exposes this interface, but the seeking functionality is always implemented by filters.

The application queries the filter graph manager for IMediaSeeking and uses it to issue seek commands. The filter graph manager distributes the seek commands to all of the renderer filters in the graph, again using the IMediaSeeking interface. Each renderer passes the commands upstream, through the output pins of the upstream filters, until they reach a filter that can execute them. Typically a source filter or a parser filter, such as the AVI Splitter, carries out the seek operation.

When a filter performs a seek operation, it flushes any pending data. The downstream filters also flush their data. For more information, see Data Flow for Filter Developers. The result is to minimize the latency of seek commands, because existing data is flushed from the graph. The following diagram illustrates the sequence of events.

If a parser filter has more than one output pin, it typically designates one of them to accept seek commands. The other pins reject or ignore any seek commands they receive. In this way, the parser keeps all of its streams synchronized.

Seeking Capabilities

Some data cannot be seeked. For example, you cannot seek a live video stream from a camera. If a stream is seekable, however, there are various types of seeking it might support. These include:

  • Seeking to an arbitrary position in the stream.
  • Retrieving the duration of the stream.
  • Retrieving the current position within the stream.
  • Playing backwards.

The IMediaSeeking interface defines a set of flags, AM_SEEKING_SEEKING_CAPABILITIES, that describe the possible seeking capabilities. To retrieve the stream's capabilities, call the IMediaSeeking::GetCapabilities method. The method returns a bitwise combination of flags. The application can test them using the & (bitwise AND) operator. For example, the following code checks whether the graph can seek to an arbitrary position:

DWORD dwCap = 0;
HRESULT hr = pSeek->GetCapabilities(&dwCap);
if (AM_SEEKING_CanSeekAbsolute & dwCap)
{
    // Graph can seek to absolute positions.
}

An alternate method is IMediaSeeking::CheckCapabilities, which tests a subset of the seeking capabilities. The caller passes a bitwise combination of flags, as follows:

// Set flags for the capabilities you want to check.
DWORD dwCaps = AM_SEEKING_CanSeekAbsolute |
               AM_SEEKING_CanSeekForwards |
               AM_SEEKING_CanSeekBackwards;

HRESULT hr = pMediaSeeking->CheckCapabilities(&dwCaps);

If the stream supports all of the indicated capabilities, the return value is S_OK. If it supports none of them, the method returns an error code. If the stream supports a subset of them, the return value is S_FALSE. When the method returns, the input parameter contains a bitwise combination of the supported capabilities, from the original set that was passed in. You can test the result as follows:

if (hr == S_FALSE) // Some requested capabilities are not supported.
{
    if (dwCaps & AM_SEEKING_CanSeekAbsolute)
        // This capability is supported.
        ...
}

Time Formats

The IMediaSeeking interface supports several time formats, including media time (in 100-nanosecond units), video frames, and byte offsets within the stream. Each time format is defined by a globally unique identifier (GUID). For a list of the time formats that DirectShow defines, see Time Format GUIDs. Third parties can also define GUIDs for custom time formats.

The filter graph manager defaults to media time. To use another time format, call the IMediaSeeking::SetTimeFormat method. If the method succeeds, all subsequent seek commands use the new format. To determine whether the media stream supports a given time format, call the IMediaSeeking::IsFormatSupported method. The following example sets the time format to frames and stores the result in a Boolean flag, for later use:

hr = pSeek->SetTimeFormat(&TIME_FORMAT_FRAME);
BOOL bTimeInFrames = SUCCEEDED(hr);

Setting and Retrieving the Stream Position

The filter graph maintains two position values: the current position and the stop position:

  • In a running graph, the current position reflects the data now being rendered. In a stopped or paused graph, it defines the point where streaming will begin on the next run command.
  • The stop position is the point where the stream will end. When the graph reaches the stop position, no more data is streamed, and the filter graph manager posts an EC_COMPLETE event. (The graph does not automatically switch to a stopped state, however. For more information, see Responding to Events.)

To retrieve the current position, call the IMediaSeeking::GetCurrentPosition method. To retrieve the stop position, call the IMediaSeeking::GetStopPosition method. The returned values are in units of the current time format (see preceding section). They are always relative to the original media source.

To seek to a new position, or to set a new stop position, call the IMediaSeeking::SetPositions method. The following code shows an example:

#define ONE_SECOND 10000000
REFERENCE_TIME rtNow = 2 * ONE_SECOND, rtStop = 5 * ONE_SECOND;

hr = pSeek->SetPositions(
    &rtNow,  AM_SEEKING_AbsolutePositioning,
    &rtStop, AM_SEEKING_AbsolutePositioning
    );

This example assumes that the current time format is media time, which has units of 100 nanoseconds. One second is 10,000,000 units. For convenience, the example defines this value as ONE_SECOND.

Note If you are using the DirectShow base classes, the constant UNITS is defined, which has the same value. For more information, see Base Classes.

The rtNow parameter specifies the new position. The second parameter is a flag that defines how to interpret rtNow. The flag in this example indicates that rtNow is defined as an absolute position in the source. When the call returns, the filter graph seeks to a position that is two seconds from the start of the stream. The rtStop parameter gives the stop time. The last parameter is another flag, indicating that the stop time is also an absolute position.

To specify a position relative to the previous position value, use the AM_SEEKING_RelativePositioning flag. To leave one of the position values unchanged, use the AM_SEEKING_NoPositioning flag. The corresponding time parameter can be NULL in that case. The following example seeks forward by 10 seconds, leaving the stop position unchanged:

REFERENCE_TIME rtNow = 10 * ONE_SECOND;
hr = pSeek->SetPositions(
    &rtNow, AM_SEEKING_RelativePositioning,
    NULL, AM_SEEKING_NoPositioning
    );

When the filter graph is stopped, the video renderer does not update its image after a seek operation. To the user, it will appear as if the seek did not happen. To update the image, pause the graph after the seek operation. Pausing the graph cues a new video frame for the video renderer. The IMediaControl::StopWhenReady method pauses the graph and then returns it to a stopped state.

Setting the Playback Rate

To change the playback rate, call the IMediaSeeking::SetRate method. Specify the new rate as a fraction of the original rate. For example, to play at twice-normal speed, use the following:

pSeek->SetRate(2.0)

The rate must be greater than zero. Rates greater than one are faster than normal. Rates between zero and one are slower than normal.

Regardless of the playback rate, the current position and the stop position are always expressed relative to the original source. For example, if a source file is 20 seconds long (at normal playback rate), setting the current position to 10 seconds seeks to the middle of the file. If the stop position is 20 seconds (the end of the file) and the playback rate is 2.0, the file will play for another 5 seconds of real time: 10 seconds of source file, at twice the normal playback speed.

Case Study: Implementing a Seek Bar

This section describes how to implement a seek bar for a media-player application. The seek bar is implemented as a trackbar control.

When the application starts, initialize the trackbar:

HWND hTrack = GetDlgItem(hwnd, IDC_SLIDER1);
EnableWindow(hTrack, FALSE);
SendMessage(hTrack, TBM_SETRANGE, TRUE, MAKELONG(0, 100));

The trackbar is disabled until the user opens a media file. The trackbar range is from 0 to 100. The application converts from media time to a percentage of the file duration. For example, trackbar position "50" always corresponds to the middle of the file. (An alternate approach would be setting the trackbar's maximum range to the duration of the file. However, media time is a 64-bit integer, and trackbar ranges are limited to 32 bits.)

When the user opens a file, the application builds a file-playback graph. It queries the filter graph manager for the IMediaSeeking interface (not shown). The application then checks whether the graph can seek and whether it can retrieve the file duration. If the graph supports both of these capabilities, the application retrieves the duration and enables the trackbar:

REFERENCE_TIME g_rtTotalTime;
DWORD caps = AM_SEEKING_CanSeekAbsolute | AM_SEEKING_CanGetDuration;

if (pSeek && S_OK == pSeek->CheckCapabilities(&caps))
{
    pSeek->GetDuration(&g_rtTotalTime);
    EnableWindow(hTrack, TRUE);
}

When the user issues a "Play" command, the application runs the graph. It also starts a timer event that periodically updates the trackbar position. As each timer event is activated, the timer callback retrieves the current playback position and sets the trackbar accordingly:

#define TICKLEN 100   // Tick length (frequency of trackbar update).
MMRESULT wTimerID;

void CALLBACK MediaTimer(UINT wTimerID, UINT msg,
    DWORD dwUser, DWORD dw1, DWORD dw2)
{
    REFERENCE_TIME rtNow;
    pSeek->GetCurrentPosition(&rtNow);
    long sliderTick = (long)((rtNow * 100) / g_rtTotalTime);
    SendMessage( hScroll, TBM_SETPOS, TRUE, sliderTick );
}

void OnUserPlay()
{
    pGraph->Run();
    if(wTimerID)        // Is timer event pending?
    {
        timeKillEvent(wTimerID);  // Cancel the timer.
        wTimerID = 0;
    }
    wTimerID = timeSetEvent(TICKLEN, 50, MediaTimer, NULL, TIME_PERIODIC);
}

When the user stops or pauses the graph, the application cancels the timer event.

When the user drags or clicks the trackbar control, the application receives a WM_HSCROLL event. The low word of the wParam parameter is the trackbar notification message. The relevant messages are TB_ENDTRACK, which is sent at the end of the trackbar action, and TB_THUMBTRACK, which is sent continuously while the user drags the trackbar.

The following function handles both messages:

void HandleTrackbar(HWND hTrackbar, short int userReq)
{
// If the file is not seekable, the trackbar is disabled.
// Therefore, seeking is valid here.

    static OAFilterState state;
    static BOOL bStartOfScroll = TRUE;

    if (userReq == TB_ENDTRACK || userReq == TB_THUMBTRACK)
    {
        DWORD Position  = SendMessage(hTrackbar, TBM_GETPOS, 0, 0);

        // Pause when the scroll action begins.
        if (bStartOfScroll)
        {
            pControl->GetState(10, &state);
            bStartOfScroll = FALSE;
            pControl->Pause();
        }

        // Update the position continuously.
        REFERENCE_TIME newTime = (g_rtTotalTime * Position) / 100;
        pSeek->SetPositions(&newTime, AM_SEEKING_AbsolutePositioning,
            NULL, AM_SEEKING_NoPositioning);

        // Restore the state at the end.
        if (userReq == TB_ENDTRACK)
        {
            if (state == State_Stopped)
                pControl->Stop();
            else if (state == State_Running)
                pControl->Run();
            bStartOfScroll = TRUE;
        }
    }
}

In order to seek smoothly while the user drags the trackbar, the function pauses the graph until the user releases the trackbar. If the graph was running, paused mode prevents the graph from continuing to play while the user is dragging the control. If the graph was stopped, paused mode ensures that the video window is updated. On receiving the TB_ENDTRACK message, the function restores the graph to its original state.


Displaying a Filter's Property Pages

A property page is one way for a filter to support properties that the user can set. This article describes how to display a filter's property pages in an application. It presents a sample console application that builds a file playback graph, displays any property pages defined by the filters in the graph, and then plays a file.

This article contains the following sections:

  • How to Display Property Pages
  • Sample Code

For more information about property pages, see the Platform SDK documentation.

How to Display Property Pages

Filters with property pages expose the ISpecifyPropertyPages interface. To determine whether a filter defines a property page, query the filter for this interface using QueryInterface and test the return value using the SUCCEEDED macro. The following code example shows an outline of what to do:

IBaseFilter *pFilter;
// Obtain the filter's IBaseFilter interface. (Not shown)

ISpecifyPropertyPages *pSpecify;
HRESULT hr = pFilter->QueryInterface(IID_ISpecifyPropertyPages, (void **)&pSpecify);
if (SUCCEEDED(hr)) {
    // Show the page.
}

If you directly created an instance of a filter (by calling CoCreateInstance), you already have a pointer to the filter. If not, you can do one of the following:

  • Enumerate the filters in the graph, using the IFilterGraph::EnumFilters method. The following sample code uses this approach. For more information on enumerating filters, see Enumerating Objects in a Filter Graph.
  • Call the IFilterGraph::FindFilterByName method on the filter graph.

Once you have the ISpecifyPropertyPages interface pointer, you can retrieve the filter's property pages by calling the ISpecifyPropertyPages::GetPages method. This method fills a counted array of globally unique identifiers (GUIDs) with the class identifier (CLSID) of each property page. The counted array is defined by a CAUUID structure, which you must allocate but do not have to initialize. The array itself, contained in the pElems member of the CAUUID structure, is allocated by the method.

CAUUID caGUID;
pSpecify->GetPages(&caGUID);
pSpecify->Release();

The OleCreatePropertyFrame function provides a simple way to display the property pages in a modal dialog box, as shown in the following code example:

OleCreatePropertyFrame(
    NULL,                   // Parent window
    0,                      // x (Reserved)
    0,                      // y (Reserved)
    FilterInfo.achName,     // Caption for the dialog box
    1,                      // Number of filters
    (IUnknown **)&pFilter,  // Pointer to the filter
    caGUID.cElems,          // Number of property pages
    caGUID.pElems,          // Pointer to property page CLSIDs
    0,                      // Locale identifier
    0,                      // Reserved
    NULL                    // Reserved
);

The sample code uses the name of the filter for the dialog box caption. It obtains the name by calling the IBaseFilter::QueryFilterInfo method on the filter. See the following sample code for details. When you are done, always free the GUID array by calling the CoTaskMemFree function.

CoTaskMemFree(caGUID.pElems);

Sample Code

The following sample code is a console application. It takes a file name as a command-line argument, builds a graph to play the file, displays any property pages defined by the filters in the graph, and plays the file.

#include <dshow.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    HRESULT  hr;
    WCHAR    wPath[MAX_PATH];
    IGraphBuilder *pGraph = NULL;

    if (argc < 2) {
        printf("Usage: %s movie.ext\n", argv[0]);
        exit(0);
    }
    CoInitialize(NULL);
    CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC_SERVER,
                        IID_IGraphBuilder, (LPVOID *)&pGraph);

    // Convert the file name to a wide-character string.
    MultiByteToWideChar(CP_ACP, 0, argv[1], -1, wPath, MAX_PATH);
    hr = pGraph->RenderFile(wPath, NULL);
    if (FAILED(hr)) {
        printf("Error: Could not open file named %s.\n", argv[1]);
        pGraph->Release();
        CoUninitialize();
        exit(1);
    }

    // Enumerate the filters and display their property pages.
    IEnumFilters *pEnum;
    IBaseFilter *pFilter = NULL;

    pGraph->EnumFilters(&pEnum);
    while(pEnum->Next(1, &pFilter, NULL) == S_OK)
    {
        ISpecifyPropertyPages *pSpecify;
        hr = pFilter->QueryInterface(IID_ISpecifyPropertyPages, (void **)&pSpecify);
        if (SUCCEEDED(hr)) {
            FILTER_INFO FilterInfo;
            pFilter->QueryFilterInfo(&FilterInfo);

            CAUUID caGUID;
            pSpecify->GetPages(&caGUID);
            pSpecify->Release();

            OleCreatePropertyFrame(
                NULL,                   // Parent window
                0,                      // x (Reserved)
                0,                      // y (Reserved)
                FilterInfo.achName,     // Caption for the dialog box
                1,                      // Number of filters
                (IUnknown **)&pFilter,  // Pointer to the filter
                caGUID.cElems,          // Number of property pages
                caGUID.pElems,          // Pointer to property page CLSIDs
                0,                      // Locale identifier
                0,                      // Reserved
                NULL                    // Reserved
            );
            CoTaskMemFree(caGUID.pElems);
            FilterInfo.pGraph->Release();
        }
        pFilter->Release();
    }
    pEnum->Release();

    // Run the graph.
    IMediaControl *pMediaControl = NULL;
    pGraph->QueryInterface(IID_IMediaControl, (void **)&pMediaControl);
    pMediaControl->Run();
    MessageBox(NULL, "Click to end playback.", "DirectShow", MB_OK);

    pMediaControl->Release();
    pGraph->Release();
    CoUninitialize();
    return 0;
}


Grabbing Media Samples

This article describes how to retrieve media samples, using the Sample Grabber filter.

The Microsoft® DirectShow® architecture shields applications from having to manipulate media data directly. If you need to modify media data, you should write a transform filter or a Microsoft® DirectX® Media Object (DMO) for this purpose. On the other hand, if you need to use the data without modification—for example, to display a frame from a video file—you can use the Sample Grabber filter.

This article contains the following sections:

  • Adding the Sample Grabber to the Filter Graph
  • Buffers and One-Shot Mode
  • Using a Callback Method

Adding the Sample Grabber to the Filter Graph

The Sample Grabber is a transform filter that supports the ISampleGrabber interface. It passes all samples downstream unchanged, so it can be inserted into a filter graph without altering the data stream. You can then use it to grab samples as they pass through the filter.

By default, the Sample Grabber has no preferred media types. Before you insert it into a filter graph, set the media type for the input pin by calling the ISampleGrabber::SetMediaType method. Setting a media type ensures that the filter graph manager inserts the Sample Grabber at the correct point in the graph.

The SetMediaType method takes a pointer to an AM_MEDIA_TYPE structure that describes the media type. Depending on the situation, you can set the subtype or format type to GUID_NULL, which indicates "unspecified." The following example adds the Sample Grabber to the filter graph and sets the media type to 24-bit uncompressed RGB video:

#include <dshow.h>
#include <qedit.h>

IBaseFilter     *pF = NULL;
ISampleGrabber  *pGrab = NULL;  // Be sure to release these later.
AM_MEDIA_TYPE   mt;

CoCreateInstance(CLSID_SampleGrabber, NULL, CLSCTX_INPROC_SERVER,
    IID_IBaseFilter, (LPVOID *)&pF);
pF->QueryInterface(IID_ISampleGrabber, (void **)&pGrab);

pGraph->AddFilter(pF, L"Grabber");

ZeroMemory(&mt, sizeof(AM_MEDIA_TYPE));
mt.majortype = MEDIATYPE_Video;
mt.subtype = MEDIASUBTYPE_RGB24;
mt.formattype = FORMAT_VideoInfo;
hr = pGrab->SetMediaType(&mt);

Now you can build the rest of the graph and connect the Sample Grabber filter. There are various ways to do this, including:

  • Call IGraphBuilder::RenderFile. The filter graph manager will connect the Sample Grabber according to its media type.
  • Add filters one at a time and connect them with the IGraphBuilder::Connect method.
  • Use the ICaptureGraphBuilder2 interface.

For example, the following code builds a playback graph for the file Example.avi:

pGraph->RenderFile(L"C:\\Example.avi", NULL);

Because the Sample Grabber's media type was set to uncompressed video, the filter graph manager puts it between the video decompressor and the video renderer, where it will receive uncompressed video samples.

If you want to grab samples without rendering them, connect the Sample Grabber's output pin to the Null Renderer filter, which discards incoming samples.

Buffers and One-Shot Mode

The Sample Grabber can copy the samples that it receives to an internal buffer. To enable buffering, call the ISampleGrabber::SetBufferSamples method with a value of TRUE. To retrieve a copy of the sample, call the ISampleGrabber::GetCurrentBuffer method.

Each sample overwrites the previous one in the buffer. To grab a sample from a particular point in the stream, switch the Sample Grabber to "one-shot" mode. In one-shot mode, the Sample Grabber stops the graph as soon as it receives one sample. To enable one-shot mode, call the ISampleGrabber::SetOneShot method with a value of TRUE.

Seek to the desired time, run the graph, and wait for the graph to stop. The following code shows how to do this:

// Query the filter graph manager for these interfaces (not shown).
IMediaControl   *pMediaControl = NULL;
IMediaSeeking   *pSeek = NULL;
IMediaEvent     *pEvent = NULL;

// Set up one-shot mode.
pGrab->SetBufferSamples(TRUE);
pGrab->SetOneShot(TRUE);

// Seek three seconds.
REFERENCE_TIME rtStart = 3 * 10000000;
REFERENCE_TIME rtStop = rtStart;

hr = pSeek->SetPositions(&rtStart, AM_SEEKING_AbsolutePositioning,
                         &rtStop, AM_SEEKING_AbsolutePositioning);

// Run the graph and wait for completion.
long evCode;
hr = pMediaControl->Run();
hr = pEvent->WaitForCompletion(INFINITE, &evCode);

When the WaitForCompletion method returns, the Sample Grabber's buffer holds a copy of the video frame. The buffer contains only the media data portion of the sample; it does not include the format header. To obtain the format header, call ISampleGrabber::GetConnectedMediaType. This method returns an AM_MEDIA_TYPE structure whose pbFormat member points to the format header. Be sure to release the buffer memory when you're done using it.

To illustrate, the following code creates a device-independent bitmap (DIB) from a video stream, using the format header and the sample buffer:

AM_MEDIA_TYPE MediaType;
pGrab->GetConnectedMediaType(&MediaType);

// Get a pointer to the video header.
VIDEOINFOHEADER *pVideoHeader = (VIDEOINFOHEADER*)MediaType.pbFormat;

// The video header contains the bitmap information.
// Copy it into a BITMAPINFO structure.
BITMAPINFO BitmapInfo;
ZeroMemory(&BitmapInfo, sizeof(BitmapInfo));
CopyMemory(&BitmapInfo.bmiHeader, &(pVideoHeader->bmiHeader), sizeof(BITMAPINFOHEADER));

// Create a DIB from the bitmap header, and get a pointer to the buffer.
void *buffer = NULL;
HBITMAP hBitmap =
    CreateDIBSection(0, &BitmapInfo, DIB_RGB_COLORS, &buffer, NULL, 0);

// Copy the image into the buffer.
hr = pGrab->GetCurrentBuffer(NULL, (long *)buffer);

The application can call BitBlt to display the image. For more information, see the Platform SDK. Although this example assumes a video stream, the Sample Grabber can retrieve audio samples or any other media sample. To blit the image, use code such as the following:

long Width = pVideoHeader->bmiHeader.biWidth;
long Height = pVideoHeader->bmiHeader.biHeight;

HDC hdcDest = GetDC(hwnd);
HDC hdcSrc = CreateCompatibleDC(NULL);
SelectObject(hdcSrc, hBitmap);
BitBlt(hdcDest, 0, 0, Width, Height, hdcSrc, 0, 0, SRCCOPY);

Using a Callback Method

Instead of working in one-shot mode, the Sample Grabber can invoke a callback method for each sample that it receives. The application must implement the ISampleGrabberCB interface. It contains the following methods:

  • SampleCB: Receives a pointer to the sample's IMediaSample interface.
  • BufferCB: Receives a buffer that contains the media data.

Typically, you would implement only one of these methods. To set the callback, call the ISampleGrabber::SetCallback method. It takes an index value that specifies which callback method to use. If you specify the BufferCB method, also call ISampleGrabber::SetBufferSamples to enable buffering, as described in the preceding section.

The following example implements the callback interface in a class named CGrabCB. The class derives from the CUnknown class, one of the base classes included with the DirectShow SDK. Using CUnknown is not required, but it makes the code somewhat shorter. For more information on using CUnknown, see How to Implement IUnknown.

In this example, the SampleCB method prints the start time of each sample in the console window. The BufferCB method is not implemented and returns E_NOTIMPL.

#include <streams.h>
// Link to Strmbase.lib

class CGrabCB: public CUnknown, public ISampleGrabberCB
{
public:
    DECLARE_IUNKNOWN;

    STDMETHODIMP NonDelegatingQueryInterface(REFIID riid, void **ppv)
    {
        if( riid == IID_ISampleGrabberCB )
        {
            return GetInterface((ISampleGrabberCB*)this, ppv);
        }
        return CUnknown::NonDelegatingQueryInterface(riid, ppv);
    }

    // ISampleGrabberCB methods
    STDMETHODIMP SampleCB(double SampleTime, IMediaSample *pSample)
    {
        printf("Sample time: %f\n", SampleTime);
        return S_OK;
    }

    STDMETHODIMP BufferCB(double SampleTime, BYTE *pBuffer, long BufferLen)
    {
        return E_NOTIMPL;
    }

    // Constructor
    CGrabCB( ) : CUnknown("SGCB", NULL)
    { }
};

To use the callback, create a new instance of the CGrabCB class and pass it to the ISampleGrabber::SetCallback method. Then run the filter graph:

pGrab->SetOneShot(FALSE);
pGrab->SetBufferSamples(FALSE);

CGrabCB *cb = new CGrabCB();
pGrab->SetCallback(cb, 0);


Recompressing an AVI File

This article describes how to recompress an Audio-Video Interleaved (AVI) file using the capture graph builder, a COM object that constructs capture graphs and other custom filter graphs.

Note Two versions of the capture graph builder ship with Microsoft® DirectShow®. They have different class identifiers and expose different interfaces. The earlier version has the class identifier CLSID_CaptureGraphBuilder and exposes the ICaptureGraphBuilder interface. It is supported for compatibility with existing applications. The new version has the class identifier CLSID_CaptureGraphBuilder2 and exposes the newer ICaptureGraphBuilder2 interface, which is more flexible than the earlier version.

For information on using ICaptureGraphBuilder2 in a video capture application, see How to Write a Capture Application. In this article, ICaptureGraphBuilder2 is used to copy media data from a source file to an output file, recompressing it along the way.

This article contains the following sections:

  • Creating the Graph
  • Building the Rendering Section
  • Connecting the Source Filter
  • Writing the File
  • Sample Code

Creating the Graph

Start by creating an instance of the capture graph builder, as shown in the following example:

ICaptureGraphBuilder2   *pBuild = NULL;
CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC,
        IID_ICaptureGraphBuilder2, (void **)&pBuild);

The capture graph builder automatically creates a filter graph manager. Initially, the filter graph is empty, with no filters. Building the filter graph is a two-stage process:

  1. Build the rendering section of the graph, which includes the AVI MUX filter and the File Writer. The MUX filter combines video and audio streams into a single AVI stream for the file writer.
  2. Add the file source filter to the graph and connect it to the MUX filter. The capture graph builder inserts any splitter filters and decoder filters needed to parse the file format. The audio and video streams can also be routed through audio and video compression filters, if desired.

Building the Rendering Section

To build the rendering section of the graph, call the ICaptureGraphBuilder2::SetOutputFileName method. This method takes input parameters that specify the media subtype for the output, and the name of the output file. It returns with output parameters that contain pointers to the MUX filter and the file writer. The pointer to the MUX filter is needed during the next stage of building the graph. The pointer to the file writer is not needed for this example, so that parameter can be NULL. To keep the example short, the following code example uses a literal string for the file name:

IBaseFilter *pMux = NULL;
pBuild->SetOutputFileName(
        &MEDIASUBTYPE_Avi,  // File type.
        L"Output.avi",      // File name.
        &pMux,              // Receives a pointer to the multiplexer.
        NULL);              // Receives a pointer to the file writer.

After the method returns, the pointer to the MUX filter has an outstanding reference count, so the application must release the pointer when it is done. The MUX filter exposes interfaces for controlling the AVI format:

  • IConfigInterleaving contains methods for setting the interleaving mode.
  • IConfigAviMux contains methods for setting the master stream and the AVI compatibility index.

The following diagram shows the filter graph at this point.

Rendering Section of the Filter Graph

Connecting the Source Filter

The next stage is to connect a source filter to the rest of the graph. First, call the ICaptureGraphBuilder2::GetFiltergraph method to retrieve a pointer to the filter graph's IGraphBuilder interface. Then call the IGraphBuilder::AddSourceFilter method, which loads a file and retrieves a pointer to the file source filter.

IGraphBuilder   *pGraph = NULL;
IBaseFilter     *pSrc = NULL;

pBuild->GetFiltergraph(&pGraph);
pGraph->AddSourceFilter(L"C:\\Input.avi", L"Source Filter", &pSrc);

Next, create instances of the video and audio compression filters that you will use to recompress the file. One approach is to enumerate the compression devices on the user's system and allow the user to select one. For information on how to do this, see Enumerating Devices and Filters. As an alternative, if you have a compression filter that you want to use, you can directly create an instance of it, through a call to CoCreateInstance. After creating an instance of a compression filter, add it to the filter graph by calling IFilterGraph::AddFilter.

The following code example create an instance of the AVI Compressor filter, which compresses video. In this example, the audio is left uncompressed.

CoCreateInstance(CLSID_AVICo, NULL, CLSCTX_INPROC,
        IID_IBaseFilter, (void **)&pVComp);
pGraph->AddFilter(pVComp, L"Compressor");

At this point, the source filter and the compression filter are not connected to anything else in the graph, as shown in the following illustration.

Filter Graph with Source and Compression Filters

The final step in building the graph is to render the video and audio streams, using the ICaptureGraphBuilder2::RenderStream method. This method connects an output pin on the source filter to the rendering section of the graph, optionally through a compression filter.

The methods in ICaptureGraphBuilder2 are designed to work with live capture sources, such as video cameras, which can have separate output pins for preview and capture. In that situation, the first two parameters of RenderStream specify which pin to connect, by designating a pin category and a media type. With a file source filter, there is only one output pin, so it is not necessary to specify these parameters.

The next three parameters are pointers to the source filter (or a pin on the source filter), the compression filter, and the sink filter. For writing to a file, the last of these should be a pointer to the multiplexer.

The following code example renders the video stream through the video compressor:

pBuild->RenderStream(
        NULL,       // Output pin category
        NULL,       // Media type
        pSrc,       // Source filter
        pVComp,     // Compressor filter
        pMux);      // Sink filter (the AVI Mux)

The following diagram shows the filter graph so far.

Rendered Video Stream

The diagram assumes that the source file has two streams, one audio and one video. If so, the AVI Splitter filter has an output pin for the audio stream, but the pin is not yet connected to anything in the graph. To render the audio stream, call RenderStream again.

pBuild->RenderStream(NULL, NULL, pSrc, NULL, pMux);

The source filter's only output pin is already connected, so the RenderStream method searches for an unconnected output pin on the splitter filter. It finds the audio output pin and connects it directly to the MUX filter. If the source file has a video stream but no audio stream, the second call to RenderStream fails. This is expected behavior. The graph is complete after the first call to RenderStream, so the failure in the second call is harmless; the graph will still run.

The following diagram shows the completed filter graph.

Rendered Audio and Video Streams

The order of the two calls is important in this example, because the video stream is recompressed but the audio stream is not. The first call includes a video compressor, and therefore it specifies the video stream. The second call does not include a compressor, so it could apply to any stream. The audio stream is the only one that remains, so the call works.

However, suppose the order were switched:

pBuild->RenderStream(NULL, NULL, pSrc, NULL, pMux);
// WRONG! This might render the video stream...

pBuild->RenderStream(NULL, NULL, pSrc, pVComp, pMux);
// ... causing this to fail.

Here, the second call specifies the compressor. It is indeterminate whether the first call will render the video stream or the audio stream. If it renders the video stream, the second call fails.

On the other hand, if the example used both a video compressor and an audio compressor, the order would not matter. Each call would fully specify one stream or the other. For similar reasons, the order would not matter if the example used no compression filters. (In that case, the two calls would be identical.)

If the source file has more than two streams, the resulting filter graph is incorrect and will exhibit unexpected behaviors. This situation is uncommon, but to be safe you can enumerate the output pins on the splitter filter after you render the first stream. For more information, see Enumerating Objects in a Filter Graph.

Writing the File

Before writing the file, you can set properties on the compression filter. The example code shows how to set the bit rate and the key frame rate. For details, see the example code in the following section.

To write the file, simply run the filter graph. Call the IMediaControl::Run method, wait for playback to complete, and then explicitly stop the graph by calling IMediaControl::Stop. Otherwise, the file is not written correctly. For more information, see Responding to Events.

To display the progress of the file-writing operation, query the MUX filter for the IMediaSeeking interface. Call the IMediaSeeking::GetDuration method to retrieve the duration of the file. Periodically while the graph is running, call the IMediaSeeking::GetCurrentPosition method to retrieve the graph's current position in the stream. Current position divided by duration gives the percentage complete.

Note: Usually, an application should query the filter graph manager for IMediaSeeking, and not query an individual filter. File writing is an exception to this rule. The filter graph manager does not retrieve the current position from the filters. Instead, it calculates the position based on the starting postion and how long the graph has been running. For file writing, this can give the wrong result, because writing the file can take longer than the file duration. Retrieving the position from the MUX filter produces an accurate result.

Sample Code

For brevity, the following code does not perform any error checking:

#include <dshow.h>
#include <stdio.h>

void __cdecl main(void)
{
    ICaptureGraphBuilder2   *pBuild = NULL;
    IGraphBuilder           *pGraph = NULL;
    IBaseFilter             *pSrc = NULL;       // Source filter
    IBaseFilter             *pMux = NULL;       // MUX filter
    IBaseFilter             *pVComp = NULL;     // Video compressor filter

    CoInitialize(NULL);

    // Create the capture graph builder.
    CoCreateInstance(CLSID_CaptureGraphBuilder2, NULL, CLSCTX_INPROC,
            IID_ICaptureGraphBuilder2, (void **)&pBuild);

    // Make the rendering section of the graph.
    pBuild->SetOutputFileName(
            &MEDIASUBTYPE_Avi,  // File type.
            L"C:\\Output.avi",  // File name.
            &pMux,              // Receives a pointer to the multiplexer.
            NULL);              // Receives a pointer to the file writer.

    // Load the source file.
    pBuild->GetFiltergraph(&pGraph);
    pGraph->AddSourceFilter(L"C:\\Input.avi", L"Source Filter", &pSrc);

    // Add the compressor filter.
    CoCreateInstance(CLSID_AVICo, NULL, CLSCTX_INPROC,
            IID_IBaseFilter, (void **)&pVComp);
    pGraph->AddFilter(pVComp, L"Compressor");

    // Render the video stream, through the compressor.
    pBuild->RenderStream(
            NULL,       // Output pin category
            NULL,       // Media type
            pSrc,       // Source filter
            pVComp,     // Compressor filter
            pMux);      // Sink filter (the AVI Mux)

    // Render the audio stream.
    pBuild->RenderStream(NULL, NULL, pSrc, NULL, pMux);

    // Set video compression properties.
    IAMStreamConfig         *pStreamConfig = NULL;
    IAMVideoCompression     *pCompress = NULL;

    // Compress at 100k/second data rate.
    AM_MEDIA_TYPE *pmt;
    pBuild->FindInterface(NULL, NULL, pVComp, IID_IAMStreamConfig, (void **)&pStreamConfig);
    pStreamConfig->GetFormat(&pmt);
    if (pmt->formattype == FORMAT_VideoInfo)
    {
        ((VIDEOINFOHEADER *)(pmt->pbFormat))->dwBitRate = 100000;
        pStreamConfig->SetFormat(pmt);
    }
    DeleteMediaType(pmt);

    // Request key frames every four frames.
    pStreamConfig->QueryInterface(IID_IAMVideoCompression, (void **)&pCompress);
    pCompress->put_KeyFrameRate(4);
    pCompress->Release();
    pStreamConfig->Release();

    // Run the graph.
    IMediaControl   *pControl = NULL;
    IMediaSeeking   *pSeek = NULL;
    IMediaEvent     *pEvent = NULL;
    pGraph->QueryInterface(IID_IMediaControl, (void **)&pControl);
    pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);

    HRESULT hr = pMux->QueryInterface(IID_IMediaSeeking, (void**)&pSeek);

    pControl->Run();
    printf("Recompressing... \n");

    long evCode;
    if (SUCCEEDED(hr))  // IMediaSeeking is supported
    {
        REFERENCE_TIME rtTotal, rtNow = 0;
        pSeek->GetDuration(&rtTotal);
        while ((pEvent->WaitForCompletion(1000, &evCode)) == E_ABORT)
        {
            pSeek->GetCurrentPosition(&rtNow);
            printf("%d%%\n", (rtNow * 100)/rtTotal);
        }
        pSeek->Release();
    }
    else  // Cannot update the progress.
    {
        pEvent->WaitForCompletion(INFINITE, &evCode);
    }
    pControl->Stop();
    printf("All done\n");

    pSrc->Release();
    pMux->Release();
    pVComp->Release();
    pControl->Release();
    pEvent->Release();
    pBuild->Release();
    pGraph->Release();
    CoUninitialize();
}


DirectShow Reference

This section contains all the Microsoft® DirectShow® reference information.

  • Filters
  • Interfaces
  • Structures
  • Enumerated Types
  • Constants and GUIDs
  • Functions
  • MSWebDVD ActiveX Control
  • Property Sets
  • DirectShow Components
  • DirectShow Base Classes


Filters

Microsoft® DirectShow® provides a set of default filters that install automatically with Microsoft® Windows®. These filters support many data formats while providing a high degree of hardware independence. An application can also register and install custom filters on the target system.

  • ACM Wrapper
  • Analog Video Crossbar
  • ASF Writer
  • ASF Reader
  • Audio Capture
  • Audio Renderer
  • AVI Compressor
  • AVI Decompressor
  • AVI Draw
  • AVI Mux
  • AVI Splitter
  • BDA IP Sink
  • BDA MPE Filter
  • BDA Network Provider
  • BDA SLIP Deframer
  • BDA Transport Information Filter
  • CC Decoder
  • Color Space Converter
  • Default DirectSound Device
  • DMO Wrapper
  • DV Muxer
  • DV Splitter
  • DV Video Decoder
  • DV Video Encoder
  • DVD Navigator
  • File Source (Async)
  • File Source (URL)
  • File Writer
  • Full Screen Renderer
  • Infinite Pin Tee
  • Internal Script Command Renderer
  • Line 21 Decoder
  • MIDI Parser
  • MIDI Renderer
  • MJPEG Compressor
  • MJPEG Decompressor
  • MPEG-1 Audio Decoder
  • MPEG-1 Stream Splitter
  • MPEG-1 Video Decoder
  • MPEG-2 Demultiplexer
  • MPEG-2 Splitter
  • MSYUV Color Space Converter Codec
  • NABTS/FEC Codec Filter
  • Null Renderer
  • Overlay Mixer
  • Overlay Mixer2
  • QT Decompressor
  • QuickTime Movie Parser
  • SAMI (CC) Parser
  • Sample Grabber
  • Smart Tee
  • Tee/Sink-to-Sink Converter
  • TV Audio
  • TV Tuner
  • VBI Surface Allocator
  • VFW Capture Filter
  • VGA 16 Color Ditherer
  • Video Renderer
  • WAVE Parser
  • WDM Video Capture
  • WST Codec
  • WST Decoder


ACM Wrapper Filter

The ACM Wrapper filter enables codecs that use the Audio Compression Manager (ACM) to join a Microsoft® DirectShow® filter graph. Decompression is only to PCM audio. When wrapping a compressor, this filter appears in the audio compressor category and can support additional interfaces. There should never be any need to add it manually to a graph; it is pulled in automatically by the filter graph manager. It is used only for playback or sample rate conversion.

Filter interfaces | IBaseFilter, IPersistPropertyBag
Input pin media types | MEDIATYPE_Audio, MEDIASUBTYPE_NULL, FORMAT_WaveFormatEx
Input pin interfaces | IMemInputPin, IPin, IQualityControl
Output pin media types MEDIATYPE_Audio, MEDIASUBTYPE_PCM, FORMAT_WaveFormatEx.

Any combination of the following are possible.

  • Samples per second (kHz): 44.1, 22.05, 11.025, or 8.0.
  • Channels: Stereo or mono.
  • Bits per sample: 8 or 16.
Output pin interfaces | IAMStreamConfig, IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_ACMWrapper
Property Page CLSID | No property page.
Executable | Quartz.dll
Merit | MERIT_NORMAL
Category | CLSID_AudioCompressorCategory


Analog Video Crossbar Filter

The Analog Video Crossbar filter represents a video crossbar on a video capture device that supports the Windows® Driver Model (WDM). The single output stream represents a hardware path for analog baseband video. One of the input pins comes from a TV Tuner (the TV Tuner Filter). Other input pins support video or audio streams. The filter supports any media subtypes and formats that are supported on the downstream connections.

The Analog Video Crossbar filter exposes the IAMCrossbar interface, which is used for routine source selection.

This filter is available through Windows 98 and Windows® 2000.
Filter interfaces | IAMCrossbar, ISpecifyPropertyPages, IPersistPropertyBag, IPersistStream
Input pin media types | MEDIATYPE_AnalogAudio, MEDIATYPE_AnalogVideo
Input pin interfaces | IKsPropertySet
Output pin media types | MEDIATYPE_AnalogAudio, MEDIATYPE_AnalogVideo
Output pin interfaces | IKsPropertySet
Filter CLSID | CLSID_CrossbarFilter
Property Page CLSID | CLSID_CrossbarFilterPropertyPage
Executable | ksxbar.ax
Merit | Driver-dependent.
Category | AM_KSCATEGORY_CROSSBAR


ASF Writer Filter

The ASF Writer accepts a variable number of input streams and creates an Advanced Streaming Format (ASF) file. The filter handles all compression and multiplexing (although the compression mechanism can be bypassed). You can use the ASF Writer in various scenarios including digital video (DV) capture, audio recompression, and conversion of Audio-Video Interleaved (AVI) or MPEG multimedia files for network streaming. This filter provides the only way to create Microsoft® Windows Media™ Audio and Windows Media Video files in Microsoft® DirectShow®.

For more information on how to write ASF files, see Creating ASF Files in DirectShow.

Filter interfaces | IAMFilterMiscFlags, IConfigAsfWriter, IFileSinkFilter2, IMediaSeeking, IPersistStream, ISpecifyPropertyPages
Input pin media types | Dependent on the ASF profile, typically uncompressed types like MEDIATYPE_Audio or MEDIATYPE_Video, although compressed types can be accepted if they match the ASF profile.
Input pin interfaces | IPin, IMemInputPin, IAMStreamConfig
Output pin media types | Not applicable.
Output pin interfaces | Not applicable.
Filter CLSID | CLSID_WMAsfWriter
Property page CLSID | CLSID_AsfWriterProperties
Executable | Qasf.dll
Merit | MERIT_DO_NOT_USE
Category | Not specified

Remarks

The filter requires a valid install of the Windows Media Format Software Development Kit (SDK) and its underlying dependencies.

The number of input pins varies depending on the profile or profile identifier of the ASF stream.

On the input pins, only one method of IAMStreamConfig is supported: IAMStreamConfig::GetFormat. All other methods return E_NOTIMPL. Call GetFormat to determine the stream's format based on the ASF profile that has been used to configure the filter (see IConfigAsfWriter).


ASF Reader Filter

When given the name of an ASF file, the ASF Reader reads the file from disk, parses the compressed streams, and exposes an output pin for each one. This filter typically connects to audio and/or video codec filters, which do the decompression. Seeking is supported if the ASF file is seekable. The ASF Reader time stamps the samples before sending them downstream.

This filter depends on the Microsoft® Windows Media™ Software Development Kit (SDK). This filter is not the default source filter for ASF files. You must explicitly add it to the graph by its class identifier (CLSID). This filter exposes the Microsoft® DirectShow® IFileSourceFilter interface, and the Windows Media SDK IWMHeaderInfo interface.

This is a typical ASF filter graph for file playback:

Filter interfaces | IFileSourceFilter, IWMHeaderInfo
Input pin media types | Not applicable.
Input pin interfaces | Not applicable.
Output pin media types | Varies depending on the streams within the ASF file.
Output pin interfaces | IMediaSeeking
Filter CLSID | CLSID_WMAsfReader {187463A0-5BB7-11d3-ACBE-0080C75E246E}
Property Page CLSID | No property page.
Executable | Qasf.dll
Merit | MERIT_UNLIKELY
Category | CLSID_LegacyAmFilterCategory


Audio Capture Filter

The Audio Capture filter represents an audio capture device. It has one capture output pin and several input pins (one for each type of input on the card, such as LineIn, Mic, CD, and MIDI).

This filter can work with more than one hardware device. The system device enumerator will return a unique moniker for each device that can be used with this filter. The friendly name corresponds to the name of the device. (This is the name that appears in GraphEdit.) For more information, see Enumerating Devices and Filters.

Filter Interfaces | IAMAudioInputMixer, IAMFilterMiscFlags, IAMResourceControl, IBaseFilter, IPersistPropertyBag, ISpecifyPropertyPages
Input Pin Media Types | MEDIATYPE_AnalogAudio, MEDIASUBTYPE_NULL
Input Pin Interfaces | IAMAudioInputMixer, IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Audio, MEDIASUBTYPE_NULL
Output Pin Interfaces | IAMBufferNegotiation, IAMPushSource, IAMStreamConfig, IAMStreamControl, IKsPropertySet, IPin, IQualityControl
Filter CLSID | CLSID_AudioRecord
Property Page CLSID | CLSID_AudioInputMixerProperties
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_AudioInputDeviceCategory

Remarks

The input pins represent physical hardware connections and are never connected to other filters in DirectShow.


Audio Renderer Filter

The Audio Renderer filter is a generic audio rendering filter that you can connect to the output of any of the following filters, if they contain WAV audio: Async File Source, URL File Source, MPEG-1 Stream Splitter, AVI Splitter, WAVE Parser, or any audio transform filter. This filter does not check the audio stream's subtype; the WAVEFORMAT or WAVEFORMATEX structure passed in the format block contains the information needed to connect to this filter.

This filter supports a range of sample rates that depends on the audio driver.

Filter Interfaces | IAMDirectSound, IAMResourceControl, IBaseFilter, IBasicAudio, IMediaPosition, IMediaSeeking, IPersistPropertyBag, IPersistStream, IQualityControl, IReferenceClock
Input Pin Media Types | MEDIATYPE_Audio
Input Pin Interfaces | IMemInputPin, IPin, IPinConnection, IQualityControl
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_AudioRender
Property Page CLSID | CLSID_AudioProperties, CLSID_AudioRendererAdvancedProperties
Executable | quartz.dll
Merit | MERIT_PREFERRED
Category | CLSID_AudioRendererCategory


AVI Compressor Filter

The AVI Compressor is a wrapper filter for installable video compressors that support the Video Compression Manager (VCM) interface. The VCM interface is not a part of the DirectShow architecture, so a "wrapper filter" is required to enable these compressors to function in the context of a filter graph. The AVI Compressor is used in graphs that create new compressed AVI files or recompress existing AVI files. The Capture Graph Builder can be instructed to add this filter to a capture graph.

The AVI Compressor's input pin connects upstream to a filter that sends it uncompressed video data. This can include VFW Capture filter or WDM Video Capture filter (each of which wraps a hardware video source), the AVI Splitter, the Color Space Converter or any other filter that can handle uncompressed video data. The AVI Compressor's downstream pin typically connects to the AVI MUX filter, which interleaves the compressed video with a compressed audio stream from the ACM Wrapper filter. The ACM Wrapper works with the Audio Compression Manager in the same way that the AVI Compressor works with the VCM.

If the compressor has a property page that allows the user to configure various compression parameters, an application can display it using the AVI Compressor's IAMVfwCompressDialogs interface.

Note: MPEG compressors and decompressors are never implemented as VCM codecs, but only as native DirectShow filters. Also, the Intel® Indeo® compressors and decompressors provided with DirectShow are implemented as native filters, not as VCM codecs.

Filter Interfaces | IAMVfwCompressDialogs, IBaseFilter, IPersistPropertyBag, ISpecifyPropertyPages
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL
Output Pin Interfaces | IAMStreamConfig, IAMVideoCompression, IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_AVICo
Property Page CLSID | No property page.
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_VideoCompressorCategory


AVI Decompressor Filter

The AVI Decompressor is a wrapper filter for installable decompressors that support the Video Compression Manager (VCM) interface. The VCM interface is not a part of the DirectShow architecture, so a "wrapper filter" is required to enable these compressors to function in the context of a filter graph.

When the Filter Graph Manager is building a graph to render an AVI file, it checks the FOURCC in the file's AVI header to determine whether the video stream is compressed. If it is, the Filter Graph Manager adds the AVI Decompressor, which then searches the registry for an installed decompressor that can handle the file. (But if the AVI file was compressed with the Intel® Indeo® compression scheme, then the native Indeo DirectShow filter will be pulled into the graph instead of the AVI Decompressor.) All this happens automatically; your application is not responsible for these details.

On its upstream pin the AVI Decompressor typically connects to the AVI Splitter. On its output pin it typically connects to the Video Renderer.
Filter Interfaces | IBaseFilter
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_VideoInfo The subtype must correspond to an old-style FOURCC. (For more information, see FOURCCMap Class.)
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_VideoInfo
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_AVIDec
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Category | CLSID_LegacyAmFilterCategory

Remarks

The media subtype on the pins is built from the FourCC code in the AVI file.


AVI Draw Filter

AVI Draw is pulled automatically into a playback graph instead of the AVI Decompressor when video is being output to an external NTSC television monitor.

Filter Interfaces | IBaseFilter
Input Pin Media Types MEDIATYPE_Video, FORMAT_VideoInfo.

The following subtypes are valid:
  • MEDIASUBTYPE_MJPG
  • MEDIASUBTYPE_TVMJ
  • MEDIASUBTYPE_WAKE
  • MEDIASUBTYPE_CFCC
  • MEDIASUBTYPE_IJPG
  • MEDIASUBTYPE_Plum
  • MEDIASUBTYPE_DVCS
  • MEDIASUBTYPE_DVSD
  • MEDIASUBTYPE_MDVF
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IOverlayNotify, IPin, IQualityControl
Filter CLSID | CLSID_AVIDraw
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL + 100
Category | CLSID_LegacyAmFilterCategory

Remarks

Since the AVI Draw filter and the VFW Capture filter both connect to the same hardware, they cannot be in the same filter graph.


AVI Mux Filter

The AVI Mux accepts multiple input streams and interleaves them into AVI format. Video capture or authoring applications can use the AVI Mux filter to save files to disc in AVI format. This filter is typically connected to the File Writer filter, but it can connect to any filter that supports IStream and IMemInputPin on its input pin. The AVI Mux filter creates a separate input pin for each input stream.

Filter Interfaces | IBaseFilter, IConfigAviMux, IConfigInterleaving, IMediaSeeking, IPersistMediaPropertyBag, ISpecifyPropertyPages
Input Pin Media Types Any major type that corresponds to an old-style FOURCC, or MEDIATYPE_AUXLine21Data. (For more information, see FOURCCMap Class.)
  • If the major type is MEDIATYPE_Audio, the format must be FORMAT_WaveFormatEx.
  • If the major type is MEDIATYPE_Video, the format must be FORMAT_VideoInfo or FORMAT_DvInfo.
  • If the major type is MEDIATYPE_Interleaved, the format must be FORMAT_DvInfo.
Input Pin Interfaces | IAMStreamControl, IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Stream, MEDIASUBTYPE_avi
Output Pin Interfaces | IPin, IPinFlowControl, IQualityControl
Filter CLSID | CLSID_AviDest
Property Page CLSID | CLSID_AviMuxProptyPage, CLSID_AviMuxProptyPage1
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory

Remarks

This filter has multiple input pins and one output pin.


AVI Splitter Filter

The AVI Splitter Filter is used for playback of AVI files. It accepts data in AVI format and splits it into its constitutent streams for further procecessing and/or rendering. This filter is typically connected to the Async File Source filter on its input pin, although it can connect to any filter that has an output pin that supports IAsyncReader. (Note that the AVI Mux filter does not support IAsyncReader.)

Filter Interfaces | IAMMediaContent, IBaseFilter, IPersistMediaPropertyBag
Input Pin Media Types | MEDIATYPE_stream, MEDIASUBTYPE_avi.
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIATYPE_audio, or other types depending on the content of the file, whether the file is compressed, and what codec was used.
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_AviSplitter
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Category | CLSID_LegacyAmFilterCategory

Remarks

This filter is considered a source filter because it pushes data through an AVI playback filter graph and implements seeking.


BDA IP Sink

BDA IP Sink is a kernel-mode filter that can be used in either BDA or non-BDA, analog or digital, television graphs to deliver IP data (such as that found in the NABTS VBI scan lines) to Winsock. In analog graphs it connects upstream to the BDA SLIP Deframer. In digital graphs it connects upstream to the BDA MPE Filter. There is no downstream connection supported on DirectX® 8.0; application developers must implement their own components for receiving and processing the IP data from Winsock. There are no application-callable interfaces on BDA IP Sink.

BDA IP Sink appears in GraphEdit under the "BDA Rendering Filters" category. Because this is a kernel-mode filter, applications cannot co-create it directly, but must use the System Device Enumerator to instantiate it, as described in Enumerating Devices and Filters. This filter must be added to the graph manually using the IFilterGraph::AddFilter method; the Capture Graph Builder cannot be used to add this filter to the graph.


BDA MPE Filter

Multi-Protocol Encapsulation (MPE) is the protocol by which IP data is transmitted over digital television networks. The BDA MPE Filter is a kernel-mode filter that extracts the IP packets from the MPE frames and delivers them to BDA IP Sink and ultimately on to Winsock, where interested applications can listen for and process the data. The BDA SLIP Deframer performs the same function on analog television graphs, where the SLIP framing protocol is used.

The BDA MPE Filter appears in GraphEdit under the "BDA Receiver Component" category. Because this is a kernel-mode filter, applications cannot co-create it directly, but must use the System Device Enumerator to instantiate it, as described in Enumerating Devices and Filters. This filter must be added to the graph manually using the IFilterGraph::AddFilter method; the Capture Graph Builder cannot be used to add this filter to the graph.


BDA Network Provider

Microsoft provides two Network Provider filters, one for ATSC networks and one for DVB networks. The Network Provider is the source filter in a digital television filter graph based on Microsoft® Broadcast Driver Architecture (BDA). This filter functions as the default tuner in a BDA filter graph through its support for ITuner. It performs essential graph-configuration tasks that enable the downstream filters such as the Tranport Information Filter and the MPEG-2 Demultiplexer.

A television receiver on a personal computer can be comprised of one or more pieces of hardware, working in conjunction with one or more pieces of software. BDA provides a uniform way to configure and control this hardware and software. The BDA Network Provider uses these interfaces to configure the hardware and software components of the receiver to acquire television transmissions. In the case of digital transmissions, the BDA Network Provider obtains program information from the BDA Transport Information Filter. It uses this information to configure the receiver components to acquire the elementary streams (for example, Video, Audio, and Data) that make up the program to be rendered.

The Microsoft ATSC Network Provider and Microsoft DVB Network Provider filters appear in GraphEdit under the "BDA Network Providers" category. This filter must be added to the graph manually using the IFilterGraph::AddFilter method; the capture graph builder cannot be used to add this filter to the graph.


BDA SLIP Deframer

The BDA SLIP Deframer is a kernel-mode filter that can be used in either BDA or non-BDA analog television graphs where SLIP de-framing of IP data (such as that found on the NABTS VBI scan lines) is required. It connects upstream to the NABTS/FEC VBI Codec and downstream to BDA IP Sink, which makes the IP packets available to interested applications via Winsock. There are no application-callable interfaces on the BDA SLIP Deframer. In digital television graphs, the BDA MPE Filter is used to extract the IP packets from the data stream.

The BDA SLIP Deframer appears in GraphEdit under the "BDA Receiver Component" category. Because this is a kernel-mode filter, applications cannot co-create it directly, but must use the System Device Enumerator to instantiate it, as described in Enumerating Devices and Filters. This filter must be added to the graph manually using the IFilterGraph::AddFilter method; the Capture Graph Builder cannot be used to add this filter to the graph.


BDA MPEG2 Transport Information Filter

Digital TV transmissions multiplex many programs and their related elementary streams (e.g. audio, video, ATVEF data) in a single transport stream. So that a receiver can properly acquire all the elementary streams related to a specific program and so that a receiver can tell what programs are contained in the stream, the transport stream will also contain many sets of tables that act as a catalog of information contained in the transport stream. Under direction of the Network Provider, the MPEG-2 Demultiplexer delivers these tables to the Transport Information Filter. The Transport Information Filter then parses these tables and provides the information to the Network Provider so that it can control the other receiver filters and nodes in the graph.

BDA IP Sink appears in GraphEdit under the "BDA Transport Information Renderers" category. This filter must be added to the graph manually using the IFilterGraph::AddFilter method; the capture graph builder cannot be used to add this filter to the graph.


CC Decoder

Microsoft DirectX 8.0

CC Decoder Filter

The CC VBI decoder is a kernel-mode stream class filter. It appears in GraphEdit under the "WDM Streaming VBI Codecs" category. It processes captured VBI lines and delivers decoded closed-captioning data to the Line 21 Decoder and/or to interested applications.

This filter has two input pins, VBI and HWCC. The VBI pin is used for raw VBI data, and the HWCC pin is used when the VBI decoding is performed in hardware by the capture filter. When the data is received on the HWCC pin, the CC Decoder operates in "pass-through" mode, and sends the data directly to the Line 21 Decoder without processing it in any way.

The CC Decoder has up to eight output pins, each of which can select their own lines and substreams. The first output pin is connected to the Line-21 decoder.

Because this is a kernel-mode filter, applications cannot co-create it directly, but must use the System Device Enumerator to instantiate it, as described in Enumerating Devices and Filters.


Color Space Converter Filter

This transform filter converts from one RGB color type to another RGB type, such as between 24-bit and 8-bit RGB color. Since this type of conversion is generally handled more efficiently within a video decompressor, the main use of the Color Space Converter is when the stream source consists of uncompressed RGB frames.

Filter Interfaces | IBaseFilter
Input Pin Media Types MEDIATYPE_Video, FORMAT_VideoInfo.

The following subtypes are valid:
  • MEDIASUBTYPE_RGB8
  • MEDIASUBTYPE_RGB555
  • MEDIASUBTYPE_RGB565
  • MEDIASUBTYPE_RGB24
  • MEDIASUBTYPE_RGB32
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types MEDIATYPE_Video, FORMAT_VideoInfo.

The following subtypes are valid:
  • MEDIASUBTYPE_RGB8
  • MEDIASUBTYPE_RGB555
  • MEDIASUBTYPE_RGB565
  • MEDIASUBTYPE_RGB24
  • MEDIASUBTYPE_RGB32
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_Colour
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Category | CLSID_LegacyAmFilterCategory


Default DirectSound Device Filter

This filter is a generic audio rendering filter that you can connect to the output of any of the following filters, if they contain WAV audio: Async File Source, URL File Source, MPEG-1 Stream Splitter, AVI Splitter, WAVE Parser, or any audio transform filter. In addition to its basic sound-rendering capabilities, this filter can process Microsoft® DirectSound® API calls; use the IAMDirectSound methods to set and retrieve the window that will handle the sound playback. The DirectSound Audio Renderer is the default audio rendering filter for Microsoft® DirectShow®.

This filter supports sample rates between 100 and 100,000 Hz, regardless of the audio driver.

Filter Interfaces | IAMDirectSound, IAMResourceControl, IBaseFilter, IBasicAudio, IDirectSound3DBuffer, IDirectSound3dListener, IMediaPosition, IMediaSeeking, IQualityControl, IReferenceClock
Input Pin Media Types | MEDIATYPE_Audio, MEDIASUBTYPE_NULL, FORMAT_WaveFormatEx
Input Pin Interfaces | IMemInputPin, IPin, IPinConnection, IQualityControl
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_DSoundRender
Property Page CLSID | CLSID_AudioProperties, CLSID_AudioRendererAdvancedProperties
Executable | quartz.dll
Merit | MERIT_PREFERRED - 1
Category | CLSID_AudioRendererCategory


DMO Wrapper Filter

The DMO Wrapper filter enables a Microsoft® DirectShow® application to use a Microsoft® DirectX® Media Object (DMO) within a filter graph. The filter wraps the DMO and handles all the details of using the DMO, such as passing data to and from the DMO. Also, the filter aggregates the DMO, so the application can query the filter for any COM interfaces that the DMO exposes.

For information on using this filter, see Using DMOs in a DirectShow Application.

Filter Interfaces | IBaseFilter, IDMOWrapperFilter, IPersistStream
Input Pin Media Types | See Remarks
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | See Remarks
Output Pin Interfaces | IAMStreamConfig, IAMVideoCompression, IPin, IQualityControl
Filter CLSID | CLSID_DMOWrapperFilter
Property Page CLSID | No property page
Executable | Qasf.dll
Merit | See Remarks
Category | See Remarks

Remarks

For each input stream on the DMO, the filter creates a corresponding input pin. For each output stream, it creates a corresponding output pin. The media types depend on the DMO.

If the DMO is a video encoder or an audio encoder, the filter's output pin exposes the IAMStreamConfig interface. If the DMO is a video encoder, the output pin also exposes the IAMVideoCompression interface. The pin queries the DMO for the interface; if the DMO supports the interface, the pin delegates to the DMO. Otherwise, the pin provides its own implementation.

DirectShow assigns all DMOs a default merit value of MERIT_NORMAL + 0x800. This value falls between MERIT_NORMAL and MERIT_PREFERRED. Decoder filters generally have a merit value of MERIT_NORMAL. Therefore, the filter graph manager will usually select a DMO decoder over a decoder filter. To override the default merit value, add a registry entry to the DMO's registry key in HKEY_CLASSES_ROOT\CLSID. Include a DWORD value named Merit whose value specifies the merit.

The DMO Wrapper filter does not appear by itself in any category. When it wraps a DMO, it appears in the DirectShow category that corresponds to the DMO's category, under the name of the DMO. For more information, see Using DMOs in a DirectShow Application.


DV Muxer Filter

This filter combines a digital video (DV)–encoded video stream with one or two audio streams to produce an interleaved DV stream. To write the stream to an AVI file, connect this filter to the AVI Mux filter and connect the AVI Mux to the File Writer filter. For more information, see Digital Video in DirectShow.

Filter Interfaces | IBaseFilter, IMediaSeeking
Input Pin Media Types | Video: MEDIATYPE_Video, MEDIASUBTYPE_dvsd, FORMAT_VideoInfo Audio: MEDIATYPE_Audio, MEDIASUBTYPE_PCM, FORMAT_WaveFormatEx
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Interleaved, MEDIASUBTYPE_dvsd, FORMAT_DvInfo
Output Pin Interfaces | IPin, IQualityControl
Filter CLSID | CLSID_DVMux
Property Page CLSID | No property page
Executable | qdv.dll
Merit | MERIT_UNLIKELY
Category | CLSID_LegacyAmFilterCategory

Remarks

The DV Muxer can create two audio input pins. It supports the audio formats shown in the following table.

Audio Pin 1 | Audio Pin 2 | Output Format
Sample Rate (kHz) | Bits/Sample | Channels | Sample Rate | Bits/Sample | Channels
32 | 16 | Mono | Unconnected | SD 2 Channel
32 | 16 | Stereo | Unconnected | SD 4 Channel
44.1 or 48 | 16 | Stereo or Mono | Unconnected | SD 2 Channel
Unconnected | 32 | 16 | Stereo or Mono | Disallowed
Unconnected | 44.1 or 48 | 16 | Mono | Disallowed
Unconnected | 44.1 or 48 | 16 | Stereo | SD 2 Channel
32 | 16 | Mono | 32 | 16 | Mono | SD 2 Channel
32 | 16 | Stereo or Mono* | 32 | 16 | Stereo or Mono* | SD 4 Channel
44.1 | 16 | Mono | 44.1 | 16 | Mono | SD 2 Channel
48 | 16 | Mono | 48 | 16 | Mono | SD 2 Channel
* If at least one input pin is stereo.

For the purpose of this table, audio pin 1 is defined as the first input pin connected to an audio source, and audio pin 2 is defined as the second input pin connected to an audio source. Once an audio pin is connected, this numbering scheme remains in effect unless both audio pins are disconnected. For example, if you connect both audio pins and then disconnect audio pin 1, the remaining pin is still considered pin 2.

Audio supplied to pin 1 is recorded to the first audio block of the DV frames (CH1), and audio supplied to pin 2 is recorded to the second audio block (CH2). Exception: If the filter has a single stereo input at 44.1 kHz or 48 kHz, the left audio channel is recorded to the first audio block, and the right audio channel is recorded to the second audio block.

For SD 4-channel output: If the input is stereo, the left track is recorded to CHa or CHc, and the right track is recorded to CHb or CHd. If the input is mono, the audio is recorded to CHa or CHc, and CHb and CHd are silent.

By connecting and disconnecting audio pin 1, it is possible to reach a disallowed format. In that case, the filter's IMediaFilter::Pause method returns VFW_E_NOT_CONNECTED. This limitation prevents a situation in which the first audio block has no audio, but the second audio block does have audio. The second block should have audio only if the first block also has audio.

The DV Muxer does not permit audio inputs with different sampling rates. However, graph-building methods such as IGraphBuilder::Connect will typically add the ACM Wrapper filter, which will convert the second audio stream to match the first stream's sampling rate.

If the audio input is 48 kHz or 32 kHz, the audio output is locked. (It is not possible to lock 44.1-kHz audio.)

If no audio pins are connected, the filter produces DV frames with no audio.


DV Splitter Filter

This filter splits an interleaved digital video (DV) stream into its component video and audio streams.

Filter Interfaces | IBaseFilter, IDVSplitter
Input Pin Media Types | MEDIATYPE_Interleaved, MEDIASUBTYPE_dvsd, FORMAT_DvInfo
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Video: MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_DvInfo Audio: MEDIATYPE_Audio, MEDIASUBTYPE_PCM, FORMAT_WaveFormatEx
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_DVSplitter
Property Page CLSID | No property page.
Executable | qdv.dll
Merit | MERIT_NORMAL
Category | CLSID_LegacyAmFilterCategory

Remarks

Only one output pin at a time exposes the IMediaPosition and IMediaSeeking interfaces.

The DV Splitter filter can accept dynamic format changes in the audio stream. However, if the AVI Mux filter is downstream, it will reject the format change. If this happens, the DV Splitter stops producing an audio stream.

Note: This limitation affects type-2 file capture only. For preview, there is no AVI Mux filter downstream. For type-1 file capture, the interleaved stream is not split in the first place. If the DV source is a live camera, there is normally no reason for the audio format to change. However, it might happen if you transmit from a VCR tape that contains heterogeneous sources edited together.


DV Video Decoder Filter

This filter decodes a digital video (DV) stream into uncompressed video. It provides a custom interface, IIPDVDec, for setting the decoding resolution.

Filter Interfaces | IBaseFilter, IIPDVDec, IPersistStream, ISpecifyPropertyPages
Input Pin Media Types
  • MEDIATYPE_Video
  • MEDIASUBTYPE_dvsd or MEDIASUBTYPE_dvc
  • FORMAT_VideoInfo or FORMAT_DvInfo
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types MEDIATYPE_Video, FORMAT_VideoInfo.

The following subtypes are possible:
  • MEDIASUBTYPE_RGB24
  • MEDIASUBTYPE_RGB565
  • MEDIASUBTYPE_RGB555
  • MEDIASUBTYPE_RGB8
  • MEDIASUBTYPE_UYVY
  • MEDIASUBTYPE_YUY2
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_DVVideoCodec
Property Page CLSID | CLSID_DVDecPropertiesPage
Executable | qdv.dll
Merit | MERIT_NORMAL
Category | CLSID_LegacyAmFilterCategory


DV Video Encoder Filter

This filter encodes an uncompressed video stream into digital video (DV). It provides a custom interface, IDVEnc, for setting the encoding resolution and format.

Filter Interfaces | IAMVideoCompression, IBaseFilter, IDVEnc, IPersistStream, ISpecifyPropertyPages
Input Pin Media Types MEDIATYPE_Video, FORMAT_VideoInfo

The following subtypes are valid:
  • MEDIASUBTYPE_RGB24
  • MEDIASUBTYPE_RGB565
  • MEDIASUBTYPE_RGB555
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_dvsd, FORMAT_VideoInfo
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_DVVideoEnc
Property Page CLSID | CLSID_DVEncPropertiesPage
Executable | qdv.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_VideoCompressorCategory

Remarks

For 16-bit video (MEDIASUBTYPE_RGB555 or MEDIASUBTYPE_RGB565), the input must be 720 x 480 pixels for NTSC, or 720 x 576 pixels for PAL. For 24-bit video, there are no size constraints on the input.

The output is always 720 x 480 for NTSC or 720 x 576 for PAL; 24-bit video is scaled to fit these dimensions.


DVD Navigator Filter

The DVD Navigator filter is the source filter for a DVD-Video playback filter graph. It opens all necessary files in a DVD-Video volume, navigates through the linear DVD-Video .vob files, and parses the resulting MPEG-2 program stream, splitting the stream into three (video, audio, subpicture) output pins.

The DVD Navigator filter also implements the IDvdControl2 and IDvdInfo2 interfaces that enable a DVD playback application to control DVD-Video playback. The older interfaces IDvdControl and IDvdInfo are deprecated in favor of the newer interfaces. The new interfaces do not inherit from the old ones; they represent completely new implementations.

Filter Interfaces | IBaseFilter, IDvdControl, IDvdControl2, IDvdCmd, IDvdInfo, IDvdInfo2, IDvdState IFileSourceFilter, ISpecifyPropertyPages
Input Pin Media Types | MEDIATYPE_Stream; MEDIASUBTYPE_MPEG2_PROGRAM
Input Pin Interfaces | Not applicable.
Output Pin Media Types
  • MEDIATYPE_Audio, MEDIASUBTYPE_MPEG1AudioPayload
  • MEDIATYPE_Video, MEDIASUBTYPE_MPEG2_VIDEO
Output Pin Interfaces | IPin, IQualityControl
Filter CLSID | CLSID_DVDNavigator
Property Page CLSID | No property page.
Executable | qdvd.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory


File Source (Async) Filter

The Async File Source filter opens and reads local files of many different data formats and passes the data to a parser filter. For downloading data from the web, use the URL File Source filter.

Filter Interfaces | IBaseFilter, IFileSourceFilter
Input Pin Media Types | Not applicable.
Input Pin Interfaces | Not applicable.
Output Pin Media Types | MEDIATYPE_Stream. The subtype depends on the media format. (MEDIASUBTYPE_NULL if the filter doesn’t recognize the format.)
Output Pin Interfaces | IAsyncReader
Filter CLSID | CLSID_AsyncReader
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Category | CLSID_LegacyAmFilterCategory


File Source (URL) Filter

The URL File Source filter is a generic asynchronous source filter that works with any source file that can be identified by a Uniform Resource Locator (URL) and whose media major type is stream. This includes AVI, MOV, MPEG, and WAV files. It requires the downstream filter to be a parser, such as the MPEG-1 Stream Splitter, the AVI Splitter, or the QuickTime Movie Parser.

Filter Interfaces | IAMOpenProgress, IBaseFilter, IFileSourceFilter
Input Pin Media Types | Not applicable.
Input Pin Interfaces | Not applicable.
Output Pin Media Types | MEDIATYPE_Stream. The subtype depends on the media format. (MEDIASUBTYPE_NULL if the filter doesn’t recognize the format.)
Output Pin Interfaces | IAsyncReader, IPin
Filter CLSID | CLSID_URLReader
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Category | CLSID_LegacyAmFilterCategory

Remarks

This filter uses Microsoft® Internet Explorer's URLMon and supports code pages.


File Writer Filter

The File Writer filter can be used to write files to disc regardless of format. The filter simply writes to disc whatever it receives on its input pin, so it must be connected upstream to a multiplexer that can format the file correctly. You can create a new output file with the File Writer or specify an existing file; if the file already exists, it will be completely overwritten with the new data.

The time stamps on samples delivered to the file writer are byte offsets in the file. The input pin exposes the IStream interface and supports a subset of the interface. This enables the upstream filter to write data when the graph is stopped.

Note: If you are writing ASF files using the Microsoft® Windows Media™ Software Development Kit, use the ASF Writer filter. The ASF Writer provides the only way to create Microsoft Windows Media Audio (WMA) files in Microsoft DirectShow.

Filter Interfaces | IAMFilterMiscFlags, IBaseFilter, IFileSinkFilter, IFileSinkFilter2, IPersistStream
Input Pin Media Types | MEDIATYPE_Stream, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl, IStream
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_FileWriter
Property Page CLSID | No property page.
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory


Full Screen Renderer Filter

The Full Screen Renderer filter uses Microsoft® DirectDraw® to render full-screen video on older graphics cards that can not quickly stretch a 320x240 video to 1024x768. To overcome this hardware limitation, the Full Screen Renderer simply switches the graphics display card into 320x240 mode. Newer video cards can stretch the display quickly enough to permit the Video Renderer filter to be used for both windowed and full-screen modes. The Filter Graph Manager calls the Full Screen Renderer into a graph automatically. The newer the video card, the less likely it is that this filter will be used. Do not manually add this filter to a graph; let the filter graph manager select the video renderer.

Filter Interfaces | IBaseFilter, IFullScreenVideo, IFullScreenVideoEx, IMediaPosition, IMediaSeeking, IQualityControl, IQualProp
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_Null
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_ModexRenderer
Property Page CLSID | CLSID_ModexProperties
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Category | CLSID_LegacyAmFilterCategory


Infinite Pin Tee Filter

This filter delivers samples delivered to its input pin to a variable number of output pins. When an instance of the filter is created, it has one output pin. Each time an output pin is connected, the filter creates another output pin. All output pins share the same media type as the input pin.

Filter Interfaces | IBaseFilter
Input Pin Media Types | Any media type.
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Any media type; matched the media type of the input pin.
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_InfTee
Property Page CLSID | No property page.
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory


Internal Script Command Renderer Filter

Receives script commands and dispatches them to the application.

This filter accepts script commands in one of two formats:

  • MEDIATYPE_Text: Each media sample contains an ANSI text string.
  • MEDIATYPE_ScriptCommand: Each media sample contains two NULL-terminated Unicode™ strings, concatenated together. The first string describes the command type and the second string is the script command.

When the filter receives a sample, it sends an EC_OLE_EVENT event notification. The first event parameter is a BSTR with the command type, or Text if the format is MEDIATYPE_Text. The second event parameter is a BSTR with the script command. The application can retrieve the event and respond to the script command.

For an example of how to use this filter, see SAMI (CC) Parser.

Filter Interfaces | IBaseFilter, IMediaPosition, IMediaSeeking
Input Pin Media Types
  • MEDIATYPE_ScriptCommand, MEDIASUBTYPE_NULL
  • MEDIATYPE_Text, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Not applicable
Output Pin Interfaces | Not applicable
Filter CLSID | {48025243-2D39-11CE-875D-00608CB78066}
Property Page CLSID | No property page
Executable | Quartz.dll
Merit | MERIT_PREFERRED + 1
Category | CLSID_LegacyAmFilterCategory


Line 21 Decoder Filter

The Line 21 Decoder filter accepts line21 data in either the standard byte pair format or, in the case of DVD, as a packet for the whole group of pictures (GOP). For every GOP in the DVD video stream, there can be a user data packet that has that particular GOP's header information and line 21 data.

On the input pin the filter connects to any line21 data provider, e.g., a DVD video decoder that has a line21 data output pin, or the CC Decoder WDM filter (via KsProxy) that provides line21 data from the VBI stream coming into a TVTuner/video capture card.

The filter decodes the line 21 data into bitmaps and passes them to the downstream filter, either to a secondary pin on the Overlay Mixer or to the Video Renderer. (The Overlay Mixer's primary pin always takes the main video stream.)

The following diagram shows a typical DVD filter graph using the Line 21 Decoder.

DVD Filter Graph Using Line21 Decoder

Filter Interfaces | IAMLine21Decoder
Input Pin Media Types Major Type: MEDIATYPE_AUXLine21Data
Subtype:
  • MEDIASUBTYPE_Line21_BytePair [standard line 21]
  • MEDIASUBTYPE_Line21_GOPPacket [DVD line 21]
Format Type: FORMAT_VideoInfo or none.
Input Pin Interfaces | None.
Output Pin Media Types Major type: MEDIATYPE_Video
Subtype:
  • MEDIASUBTYPE_RGB8
  • MEDIASUBTYPE_RGB555
  • MEDIASUBTYPE_RGB565
  • MEDIASUBTYPE_RGB24
  • MEDIASUBTYPE_RGB32
Format Type: FORMAT_VideoInfo
Output Pin Interfaces | None.
Filter CLSID | CLSID_Line21Decoder
Property Page CLSID | None
Executable | qdvd.dll
Merit | MERIT_NORMAL
Category | CLSID_LegacyAmFilterCategory


MIDI Parser Filter

The MIDI Parser filter reads MIDI data that is found in .MID and .RMI files. The filter accepts a stream from the Async File Source or URL File Source filters and outputs MIDI samples to the MIDI Renderer for playback.

Filter Interfaces | IAMMediaContent, IBaseFilter
Input Pin Media Types | MEDIATYPE_Stream, MEDIASUBTYPE_Midi
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Midi, MEDIASUBTYPE_NULL
Output Pin Interfaces | IMediaSeeking, IQualityControl, IPin
Filter CLSID | CLSID_MIDIParser {D51BD5A2-7548-11cf-A520-0080C77EF58A}
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Category | CLSID_LegacyAmFilterCategory

Remarks

For more information, see MIDI Renderer.


MIDI Renderer Filter

The MIDI Renderer filter renders MIDI data from the MIDI Parser filter.

Filter Interfaces | IAMDirectSound, IAMResourceControl, IBaseFilter, IBasicAudio, IMediaPosition, IMediaSeeking, IQualityControl, IReferenceClock
Input Pin Media Types | MEDIATYPE_Midi, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | Not applicable
Output Pin Interfaces | Not applicable
Filter CLSID | CLSID_AVIMIDIRender
Property Page CLSID | No property page
Executable | quartz.dll
Merit | MERIT_PREFERRED
Category | CLSID_MidiRendererCategory

Remarks

The GUID for the format type is NULL, but the format block contains the following structure:

typedef struct _MIDIFORMAT {
    DWORD       dwDivision;
    DWORD       dwReserved[7];
} MIDIFORMAT, FAR * LPMIDIFORMAT;

The dwDivision member specifies the time division of the file. The time division is given in the header of any standard MIDI file (SMF), in the MThd chunk. The MIDI Renderer sets this property on the MIDI data stream by calling the midiStreamProperty function.

Samples from the MIDI Parser filter contain one second of MIDI data. The MIDI Renderer uses the midiStreamOut function to render the MIDI data. Each sample is a synchronization point: the start of the buffer contains all of the commands necessary to set the correct state for rendering that buffer.


MJPEG Compressor Filter

This filter compresses an uncompressed video stream, using motion JPEG compression.

Filter Interfaces | IBaseFilter, IPersistStream
Input Pin Media Types | MEDIATYPE_VIDEO, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_MJPG
Output Pin Interfaces | IAMStreamConfig, IAMVideoCompression, IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_MJPGEnc
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_VideoCompressorCategory

Remarks

This filter encodes using the media subtype MEDIASUBTYPE_MJPG, which corresponds to the FOURCC code 'MJPG'.


MJPEG Decompressor Filter

This filter decodes a video stream from motion JPEG to uncompressed video. Some digital video cameras produce a motion JPEG video stream.

Filter Interfaces | IBaseFilter
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_MJPG
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_VIDEO, MEDIASUBTYPE_NULL
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_MjpegDec
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Category | CLSID_LegacyAmFilterCategory

Remarks

This filter is compatible with motion JPEG video that uses the FOURCC code 'MJPG'. It cannot decode other varieties of motion JPEG. For these, you will need to use a third-party decoder filter.


MPEG-1 Audio Decoder Filter

Decodes MPEG-1 Layer I and Layer II audio to PCM.

Filter Interfaces | IBaseFilter, ISpecifyPropertyPages
Input Pin Media Types MEDIATYPE_Audio, FORMAT_WaveFormatEx

The following subtypes are valid:
  • MEDIASUBTYPE_MPEG1Packet
  • MEDIASUBTYPE_MPEG1Payload
  • MEDIASUBTYPE_MPEG1AudioPayload
  • GUID_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Audio, MEDIASUBTYPE_PCM
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_CMpegAudioCodec
Property Page CLSID | CLSID_MpegAudioDecoderPropertyPage
Executable | quartz.dll
Merit | 0x03680001
Category | CLSID_LegacyAmFilterCategory


MPEG-1 Stream Splitter Filter

This filter splits an MPEG-1 system stream into its component audio and video streams.

Filter Interfaces | IAMMediaContent, IAMStreamSelect, IBaseFilter
Input Pin Media Types MEDIATYPE_Stream

The following subtypes are valid:
  • MEDIASUBTYPE_MPEG1System
  • MEDIASUBTYPE_MPEG1VideoCD
  • MEDIASUBTYPE_Audio
  • MEDIASUBTYPE_Video
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types
  • MEDIATYPE_Video, MEDIASUBTYPE_MPEG1Packet
  • MEDIATYPE_Video, MEDIASUBTYPE_MPEG1Payload
  • MEDIATYPE_Audio, MEDIASUBTYPE_MPEG1Packet
  • MEDIATYPE_Audio, MEDIASUBTYPE_MPEG1Payload
Output Pin Interfaces | IPin, IMediaSeeking
Filter CLSID | CLSID_MPEG1Splitter
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Category | CLSID_LegacyAmFilterCategory

Remarks

Because MPEG-1 content is not indexed, seeking can be very approximate. It is usually good for a fixed bitrate MPEG-1 system stream (which is usually hardware generated for video CD). IAMMediaContent is exposed for MP3 ID3 content.


MPEG-1 Video Decoder Filter

Decodes MPEG-1 video.

Filter Interfaces | IBaseFilter, IMpegVideoDecoder, ISpecifyPropertyPages
Input Pin Media Types MEDIATYPE_Video, FORMAT_MPEGVideo

The following subtypes are valid:
  • MEDIASUBTYPE_MPEG1Packet
  • MEDIASUBTYPE_MPEG1Payload
Input Pin Interfaces | IPin, IMemInputPin
Output Pin Media Types MEDIATYPE_Video, FORMAT_VideoInfo or FORMAT_VideoInfo2

The following subtypes are possible:
  • MEDIASUBTYPE_RGB24
  • MEDIASUBTYPE_RGB32
  • MEDIASUBTYPE_RGB8
  • MEDIASUBTYPE_RGB555
  • MEDIASUBTYPE_RGB565
  • MEDIASUBTYPE_UYVY
  • MEDIASUBTYPE_Y41P
  • MEDIASUBTYPE_YUY2
  • MEDIASUBTYPE_YV12
Output Pin Interfaces | IPin, IQualityControl
Filter CLSID | CLSID_CMPEGVideoCodec
Property Page CLSID | CLSID_MpegVideoDecodePropertyPage
Executable | quartz.dll
Merit | 0x40000001
Category | CLSID_LegacyAmFilterCategory

Remarks

This filter can decode into a DirectDraw Surface. The filter uses MMX if the machine supports MMX.


MPEG-2 Demultiplexer

The MPEG-2 Demultiplexer (Demux) operates on MPEG-2 transport and program streams that are delivered in push-mode. (For demultiplexing MPEG-2 program streams that are delivered in pull-mode, such as in file-playback scenarios, use the MPEG-2 Splitter filter.) When operating on a transport stream, the Demux is said to be in transport stream mode. When operating on a program stream, the Demux is said to be in program stream mode. In transport stream mode, the demultiplexing is based on a mapping of one or more packet IDs (PID) to an output pin. In program stream mode, the mapping is between one stream ID and one output pin. If a PID or stream ID is not mapped to an output pin, it is simply discarded by the Demux.

The Demux can also operate in pass-though mode on transport streams. For example, an application can map all the PIDs it is interested in to a single output pin, and create a stream of PID packets that can be written to file, re-broadcast, or processed in some other way. No re-multiplexing of the packets is performed in pass-through mode, and the output stream is not a compliant MPEG-2 transport stream. Packets with errors are not filtered out.

The following illustration shows possible data flows when the Demux is in transport stream mode.

Demux in Transport Stream Mode

Configuring the Filter

When the Demux is first instantiated and added to the filter graph, it has a single input pin and no output pins. In filter graphs that render digital television transmissions and are based on Microsoft® Broadcast Driver Architecture (BDA), the BDA Network Provider filter is responsible for creating the output pins on the Demux and mapping the pins to PIDs. In other filter graphs, it is the responsibility of the application to create and configure the output pins by setting the pin's media type when the pin is created and mapping the stream IDs (program stream mode) or PIDs (transport stream mode) to each pin.

The Demux configures itself internally for either transport or program streams only after some triggering event occurs that indicates which type of stream the filter should expect. The typical triggering event occurs when the first output pin is configured. For example, in program stream mode, an application will create a new output pin using the filter's IMpeg2Demultiplexer::CreateOutputPin method. This method returns an IPin interface pointer to the pin that was created. The application then uses this pointer in a call to QueryInterface to obtain the IMPEG2StreamIDMap interface. At this point the Demux will configure itself for program stream mode, because IMPEG2StreamIDMap is specific to program streams. The same process occurs for transport mode when the application calls QueryInterface on the first output pin and requests the IMPEG2PIDMap interface. Another triggering event is when the input pin of the Demux is connected; the connection media type will indicate to the Demux whether the incoming stream is a program stream or a transport stream.

The Demux must be configured before it can be put into the Run state. Once the Demux has configured itself for one type of stream, it cannot be reconfigured to operate on the other type of stream. To switch the Demux between program stream mode and transport stream mode, you must start over with a newly instantiated filter.

Configuring the Pins for Program Stream Mode

As described in the preceding section, after creating an output pin, the application queries the pin for the IMPEG2StreamIDMap interface. The application then calls the IMPEG2StreamIDMap::MapStreamId method to associate the pin with a specified elementary stream, and to indicate whether substream filtering is required. In MPEG-2 program streams (but not transport streams) the audio elementary stream may itself be further divided into multiple substreams. This is often done to provide multiple audio tracks. The application is responsible for providing the pin with the necessary substream filtering information so that the pin knows which substream to pass to the audio decoder. See the IMPEG2StreamIDMap::MapStreamID reference page for more information.

Configuring the Pins for Transport Stream Mode

If the filter graph contains a BDA Network Provider source filter, this filter will automatically create all the necessary output pins on the Demux and map the PIDs for each pin. For audio and video streams there is generally one PID mapped per pin. For the Program Service Information (PSI) stream, several PIDs may be mapped to the output pin that connects to the Transport Information Filter (TIF). The BDA Network Provider works behind the scenes with the TIF to obtain PIDs for the various tables in the PSI stream, and configure the output pins on the Demux accordingly. If you are providing a transport stream through a custom filter that is not based on BDA, then either the filter or the application must do this work.

Clock Behavior

The Demux functions as the reference clock for the filter graph by implementing the IReferenceClock interface. With transport streams, this clock is slaved to the PCR stream corresponding to the last-mapped audio or video stream. If more PCR streams exist, they are tracked, but not used. With program streams, the Demux slaves its clock to the SCR stream. Slaving the clock to the PCR or SCR stream prevents overflow and underflow conditions in downstream buffers that would otherwise occur due to variations between the local system clock and the stream clock.

The Demux also guarantees monotonically increasing presentation time stamps to the downstream filters. This means, for example, that if a transport stream includes a segment such as a commercial that was created with a different clock than the main program, the Demux will adjust the presentation time stamps to hide the discontinuity from the downstream decoders and renderers.

Filter Interfaces | IMpeg2Demultiplexer, IBaseFilter, IReferenceClock, ISpecifyPropertyPages
Input Pin Media Types | MEDIATYPE_Stream, MEDIASUBTYPE_MPEG2_TRANSPORT, Format_None MEDIATYPE_Stream, MEDIASUBTYPE_MPEG2_PROGRAM, Format_None
Input Pin Interfaces | IPin
Output Pin Media Types | Audio and video elementary stream must have a major type of audio or video. The Demux sets no limitations on the media subtype.
Output Pin Interfaces | IMPEG2StreamIDMap, IMPEG2PIDMap, IPin
Filter CLSID | CLSID_MPEG2Demultiplexer
Property Page CLSID | Use the ISpecifyPropertyPages interface to access the propery pages.
Executable | mpg2splt.ax
Merit | MERIT_NORMAL
Category | CLSID_LegacyAmFilterCategory


MPEG-2 Splitter

The MPEG-2 Splitter filter accepts as input MPEG-2 program streams delivered in pull-mode (file playback) that contain at least one of the following stream types: MPEG-2 video; MPEG-2 audio; AC3 audio encoded as defined for DVD video; PCM audio encoded as defined for DVD video. It parses the streams, creates an output pin for each one, and outputs the compressed audio and/or video MPEG packets to an MPEG-2 decoder filter.

Note that Microsoft DirectShow does not provide an MPEG-2 decoder.

For MPEG-2 program and transport streams delivered in push-mode (live source), use the MPEG-2 Demultiplexer.

Filter Interfaces | IBaseFilter, ISpecifyPropertyPages, IAMParse, IAMStreamSelect
Input Pin Media Types
  • MEDIATYPE_Stream, MEDIASUBTYPE_MPEG2_PROGRAM
  • MEDIATYPE_Stream, MEDIASUBTYPE_MPEG2_TRANSPORT
  • MEDIATYPE_Stream, MEDIASUBTYPE_MPEG1_Video
  • MEDIATYPE_Stream, MEDIASUBTYPE_NULL
Input Pin Interfaces | IPin, IMemInputPin
Output Pin Media Types
Output Pin Interfaces | IPin, IMediaSeeking
Filter CLSID | CLSID_MMSPLITTER
Property Page CLSID | N/A
Executable | mpg2splt.ax
Merit | MERIT_NORMAL + 1
Category | CLSID_AudioInputDeviceCategory


MSYUV Codec

Microsoft DirectX 8.0

MSYUV Color Space Converter Codec

MSYUV is a YUV-to-RGB color space converter codec. It enables playback of video source data in YUV formats on clients whose video display adapter cannot be used for YUV-to-RGB conversions in hardware. The codec participates in filter graphs through the AVI Decompressor wrapper filter.

Digital conferencing cameras with 1394 or USB interfaces can produce image data in various YUV formats. If the display hardware does not support on-board YUV-to-RGB conversion, or if the hardware conversion capability cannot be used for some other reason, then the YUV image data must be converted to RGB format before it is sent to the Video Renderer.

When building the filter graph, if the Graph Builder detects a YUV format in an output pin's media type, it will insert the AVI Decompressor into the graph and the AVI Decompressor will then load the MSYUV codec and configure it initially to perform the conversion to RGB. After the graph first transitions to a run or paused state, the Video Renderer filter can detect whether the video display adapter can perform the conversion in hardware. If it can, then the AVI Decompressor is notified and it reconfigures MSYUV to operate in "pass-through mode," which causes the codec to skip the conversion and copy the YUV image data directly onto a DirectDraw overlay surface in video memory.

MSYUV converts packed YUV formats to RGB, as shown in the following list:
  • UYVY -> RGB16, RGB8
  • YUY2 -> RGB16, RGB8
  • YVYU -> RGB16, RGB8

For filter details, see AVI Decompressor.


NABTS/FEC VBI Codec Filter

The NABTS/FEC VBI Codec is a kernel-mode stream class filter used in analog television filter graphs. It processes captured VBI lines and distributes decoded and/or forward-error-corrected SLIP packets containing NABTS data downstream to the BDA SLIP Deframer, BDA IP Sink and ultimately to Winsock. There are no application-callable interfaces on this filter.

The NABTS/FEC VBI Codec has two input pins, VBI and HWNABTS. The VBI pin is used if the capture filter is delivering raw VBI data, and the HWNABTS pin is used if the capture filter is delivering decoded VBI data; in this case, the NABTS/FEC VBI Codec simply passes the data through to the BDA SLIP Deframer.

The NABTS/FEC VBI Codec appears in GraphEdit under the "WDM Streaming VBI Codecs" category. Because this is a kernel-mode filter, applications cannot co-create it directly, but must use the System Device Enumerator to instantiate it, as described in Enumerating Devices and Filters. This filter must be added to the graph manually using the IFilterGraph::AddFilter method; the Capture Graph Builder cannot be used to add this filter to the graph.


Null Renderer Filter

This filter is a renderer that discards every sample it receives, without displaying or rendering the sample data.

Use the Null Renderer when an output pin in the graph requires a downstream connection, but you do not wish to render the data from that pin. By connecting the output pin to the Null Renderer, you complete the connection without rendering the data.

Filter interfaces | IBaseFilter
Input pin media types | Any media type
Input pin interfaces | IMemInputPin, IPin, IQualityControl
Output pin media types | Not applicable.
Output pin interfaces | Not applicable.
Filter CLSID | CLSID_NullRenderer
Property Page CLSID | No property page.
Executable | Qedit.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory


Overlay Mixer Filter

The Overlay Mixer filter is essentially a Microsoft® DirectDraw®-based video renderer. It uses destination color keying to mix video surfaces with overlays in scenarios such as line 21 closed captioning or digital video disc (DVD) subpicture data. This filter is used primarily in DVD playback and video capture applications, but you can use it in any scenario where you need to apply an overlay to a video surface.

It is added to the filter graph automatically when applications use the IDVDGraphBuilder and ICaptureGraphBuilder2 interfaces to create the graph. The Overlay Mixer will never be pulled into a graph automatically by the filter graph manager when rendering a file, since its merit is MERIT_DO_NOT_USE. Game applications can use the Overlay Mixer in limited ways to add video to the game screen.

(Note: The Overlay Mixer2 filter is identical to the Overlay Mixer except for two important distinctions: the Overlay Mixer supports the VIDEOINFO and VIDEOINFO2 format types, while the Overlay Mixer2 supports only the VIDEOINFO2 format type, and Overlay Mixer2 has a merit of MERIT_UNLIKELY, meaning it may in some situations be pulled into a graph automatically when the filter graph manager renders a file. This filter is primarily used in TV preview/capture graphs.)

Applications can control certain behavior on the Overlay Mixer through its IMixerPinConfig2 interface, but application developers should never be concerned with the details of the mixer's internal workings as described in this article. The following information is provided for the benefit of filter developers, and game developers who want to use the Overlay Mixer's DirectDraw Exclusive Mode.

Internal Operations

The Overlay Mixer exposes an input pin for each incoming stream. Typically, there are three input pins: Pin 0 for video data and Pins 1 and 2 for line 21 and DVD subpicture data. Internally, the Overlay Mixer uses DirectDraw to render video. It creates a DirectDraw object with a primary surface comprising the entire desktop, and an overlay surface whose rectangle is defined by the size of the video stream connected to Pin 0. If the decoder does not specify a color key, the Overlay Mixer uses default color keys: dark gray for more recent graphics cards and magenta for older 256-color cards.

Note In the current version of the Overlay Mixer, the results are undefined if the decoder passes in two video streams to be rendered simultaneously in the same place on the overlay surface, as sometimes occurs with DVDs that contain both subpicture and line 21 streams. The video might flicker, or display only one of the streams.

Upstream Connection with the Video Decoder

The Overlay Mixer's input pins typically connect to an upstream video decoder (or decoders if a separate decoder is handling the line 21 or DVD subpicture data). The incoming video data must always connect to the Overlay Mixer's Pin 0. The line 21 or subpicture data streams, whether they come from the same video decoder or not, connect on Pin 1 or greater. If the decoder is a software decoder that uses the host CPU exclusively, then the connection between the decoder and the Overlay Mixer's Pin 0 is a standard IMemInputPin interface connection. If the decoder uses hardware acceleration, then its connection to Pin 0 on the Overlay Mixer must be an IAMVideoAccelerator connection. These two types of connections are mutually exclusive.

Filters that wrap a hardware decoder and connect to the Overlay Mixer through a video port must implement IVPConfig. The Overlay Mixer implements the IVPNotify interface, which calls into IVPConfig on the decoder to set and retrieve various control information. This mechanism enables the decoder to specify information about the overlay surfaces it requires, and it enables the Overlay Mixer to inform the decoder of the location of those surfaces in the video memory. The Overlay Mixer is also responsible for ensuring that the video rectangle is scaled correctly. Video capture scenarios present certain issues with respect to scaling of the preview image and the capture of interleaved video frames. If you are developing a filter or WDM driver for a hardware video capture device, refer to the IVPConfig and IVPNotify reference pages for more information on these topics.

The Overlay Mixer is not used in 1394 or USB capture scenarios. It is used in video capture over the PCI bus.

Downstream Communication with the Video Renderer

When connected to the Overlay Mixer, the Microsoft® DirectShow® Video Renderer filter does not actually render the video at all. The connection is an IOverlay connection rather than an IMemInputPin connection. This enables the Overlay Mixer to do the actual rendering, so that the Video Renderer is responsible only for creating the window and controlling its size and location on the desktop. This window can be a top-level window, or a child window within an application. The Overlay Mixer and Video Renderer hold a continual conversation during graph operation by means of IOverlay on the video renderer and IOverlayNotify on the Overlay Mixer. In addition to window size and position information, the Video Renderer passes its window handle through the Overlay Mixer to DirectDraw, which manages the rectangle clipping. Applications can control the Video Renderer through its IVideoWindow and IBasicVideo2 interfaces.

DirectDraw Exclusive Mode

The Overlay Mixer's DirectDraw exclusive mode enables games to display video on some part of the screen. In this mode, the Overlay Mixer renders the video directly to a DirectDraw surface created by the game application, rather than to a window provided by the Video Renderer. This enables games to control the color key. To use the Overlay Mixer in DirectDraw exclusive mode, create an instance of the Overlay Mixer and obtain its IDDrawExclModeVideo interface before building the filter graph, and add the DirectDraw surfaces to the Overlay Mixer. The Overlay Mixer will ensure that the rendering is done into the DirectDraw surface. One significant limitation of this mode is that the game does not get access to the actual video bits. If you use IDDrawExclModeVideo, your application creates the primary surface, and the Overlay Mixer creates the overlay surface.

You can also use DirectDraw exclusive mode to perform windowless rendering—for example, in a Web page—but this is not recommended, because the Overlay Mixer does not perform any mixing in this mode. This means that no line 21 or subpicture data can be displayed. To write a DVD playback application in windowless mode, the recommended approach is to use the MSWebDVD ActiveX® control.
Filter Interfaces | IAMOverlayFX, IAMVideoDecimationProperties, IBaseFilter, IDDrawExclModeVideo, IKsPropertySet, IMediaPosition, IMediaSeeking, IQualProp
Input Pin Media Types Major Type: MEDIATYPE_Video
Subtypes:
  • MEDIASUBTYPE_Overlay (pin 0 only)
  • DirectDraw YUV formats: MEDIASUBTYPE_YUVxx (pin 0 only)
  • DirectDraw Video Acceleration formats: MEDIASUBTYPE_DVAxxx (pin 0 only)
  • Microsoft® DirectDraw® RGB formats: MEDIASUBTYPE_RGBxx (all input pins)
Format Type: Format_VIDEOINFO, Format_VIDEOINFO2
Input Pin Interfaces | IAMVideoAccelerator, IKsPropertySet, IMemInputPin, IMixerPinConfig, IMixerPinConfig2, IOverlay (pin 0 only), IPin, IPinConnection, IQualityControl, IVPNotify, IVPNotify2
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_Overlay
Output Pin Interfaces | IPin, IQualityControl
Filter CLSID | CLSID_OverlayMixer
Property Page CLSID | No property page.
Executable | qdvd.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory


Overlay Mixer2 Filter

The Overlay Mixer2 filter is identical in its functionality to the Overlay Mixer but has a higher merit, which allows it to be added to a filter graph automatically. It is provided so that the Filter Graph Manager can add the Overlay Mixer to a graph when it renders non-DVD MPEG-2 files in in TV capture/preview graphs. This is not possible with the original Overlay Mixer because its merit is MERIT_DO_NOT_USE. The only other distinction is that the Overlay Mixer supports the VIDEOINFO and VIDEOINFO2 format types, while the Overlay Mixer2 supports only the VIDEOINFO2 format type. The choice of whether to use the Overlay Mixer or the Overlay Mixer2 is handled by the component that builds the graph, either the Filter Graph Manager, the Capture Graph Builder or the DVD Graph Builder; from an application's point of view they are the same filter, with the same interfaces and functionality.

The documentation for the Overlay Mixer also applies to the Overlay Mixer2.

Filter Interfaces | IAMOverlayFX, IAMVideoDecimationProperties, IBaseFilter, IDDrawExclModeVideo, IKsPropertySet, IMediaPosition, IMediaSeeking, IQualProp
Input Pin Media Types Major Type: MEDIATYPE_Video
Subtypes:
  • MEDIASUBTYPE_Overlay (pin 0 only)
  • Microsoft® DirectDraw® RGB formats: MEDIASUBTYPE_RGBxx (all input pins)
  • DirectDraw YUV formats: MEDIASUBTYPE_YUVxx (pin 0 only)
  • DirectDraw Video Acceleration formats: MEDIASUBTYPE_DVAxxx (Pin 0 only)
Format Type: Format_VIDEOINFO2
Input Pin Interfaces | IAMVideoAccelerator, IKsPropertySet, IMemInputPin, IMixerPinConfig, IMixerPinConfig2, IOverlay (pin 0 only), IPin, IPinConnection, IQualityControl, IVPNotify, IVPNotify2
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_Overlay
Output Pin Interfaces | IPin, IQualityControl
Filter CLSID | CLSID_OverlayMixer2
Property Page CLSID | No property page.
Executable | qdvd.dll
Merit | MERIT_UNLIKELY
Category | CLSID_LegacyAmFilterCategory


QT Decompressor Filter

The QT Decompressor filter decompresses Apple® QuickTime® 2.0 video. This format is typically used in older QuickTime files.

Filter Interfaces | IBaseFilter
Input Pin Media Types MEDIATYPE_Video, FORMAT_VideoInfo

The following subtypes are valid:
  • MEDIASUBTYPE_QTRpza
  • MEDIASUBTYPE_QTSmc
  • MEDIASUBTYPE_QTRle
  • MEDIASUBTYPE_QTJpeg
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_VideoInfo
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_QTDec
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Category | CLSID_LegacyAmFilterCategory


QuickTime Movie Parser Filter

The QuickTime Movie Parser filter splits Apple® QuickTime® data into audio and video streams. It supports QuickTime 2.0 and earlier. The input pin connects to a source filter such as the Async File Source filter or the URL File Source filter. The Parser uses the AVI Decompressor or QT Decompressor filter to decompress QuickTime files. The filter creates one output pin for the video stream and one output pin for the audio stream.

Filter Interfaces | IAMMediaContent, IBaseFilter
Input Pin Media Types | MEDIATYPE_Stream, MEDIASUBTYPE_QTMovie;
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types
  • MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_VideoInfo
  • MEDIATYPE_Audio, MEDIASUBTYPE_NULL, FORMAT_WaveFormatEx
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_QuickTimeParser
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_NORMAL
Category | CLSID_LegacyAmFilterCategory


SAMI (CC) Parser Filter

Parses captioning data from Synchronized Accessible Media Interchange (SAMI) files.

SAMI is a text format similar to HTML, and is used for encoding time-based captions. This filter converts SAMI data into a text stream. Each sample in the stream contains one caption entry, along with format information. The time stamps on the samples are generated from the time information in the SAMI file.

This filter is designed to be used with the Internal Script Command Renderer filter. The Internal Script Command Renderer receives the text samples and sends them to the application, in the form of event notifications. For more information, see the Remarks section.

Filter Interfaces | IAMStreamSelect, IBaseFilter
Input Pin Media Types | MEDIATYPE_Stream
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Text, MEDIASUBTYPE_NULL
Output Pin Interfaces | IMediaSeeking, IPin, IQualityControl
Filter CLSID | {33FACFE0-A9BE-11D0-A520-00A0D10129C0}
Property Page CLSID | No property page
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Category | CLSID_LegacyAmFilterCategory

Remarks

The following is a simple SAMI file:

<SAMI>
<Head>
<STYLE TYPE="text/css"> <!--
    .ENCC {Name: English; lang:en-US; SAMI_TYPE: CC;}
    .FRCC {Name: French; lang:fr-FR; SAMI_TYPE: CC;}
    #NORMAL {Name: Normal; font-family: arial;}
    #GREENTEXT {Name: GreenText; color:green; font-family: verdana;}
-->
</STYLE>
</Head>
<BODY>
<Sync Start=1000>
    <P CLASS="ENCC">One
    <P CLASS="FRCC">Un

<Sync Start=2000>
    <P CLASS="ENCC">Two
    <P CLASS="FRCC">Deux

<Sync Start=3000>
    <P CLASS="ENCC">Three
    <P CLASS="FRCC">Trois
</BODY>
</SAMI>

The STYLE tag defines two language settings, English (.ENCC) and French (.FRCC). It also defines two styles, #NORMAL and #GREENTEXT. Each SYNC tag defines the start time for a caption, in milliseconds. The P tags contain the caption text, while the CLASS attribute specifies the language setting to which the caption applies.

For each language and style, the filter creates a logical stream. At any time, exactly one language stream and one style stream are enabled. When the filter generates a sample, it selects the caption for the current language and applies the current style. By default, the first language and style declared in the file are enabled. An application can use the IAMStreamSelect::Enable method to enable a different stream.

With the default settings, the first caption in the example file produces the following output:

<P STYLE=" Name: English; lang:en-US; SAMI_TYPE: CC; Name: Normal; font-family: arial;">One

If the output goes to the Internal Script Command Renderer, that filter sends an EC_OLE_EVENT event notification. The second event parameter is a BSTR with the caption text. The application can retrieve the event and display the caption.

The following example shows how to render a SAMI file, retrieve stream information, enable streams, and display caption text. The example assumes that the previous SAMI file is saved as C:\Sami_test_file.sami. For brevity, the example used hard-coded stream indexes when it calls the IAMStreamSelect::Enable method:

void __cdecl main()
{
    HRESULT hr;
    IGraphBuilder *pGraph;
    IMediaControl *pMediaControl;
    IMediaEventEx *pEv;
    IBaseFilter   *pSAMI;

    CoInitialize(NULL);

    // Create the filter graph manager.
    CoCreateInstance(CLSID_FilterGraph, NULL, CLSCTX_INPROC,
                        IID_IGraphBuilder, (void **)&pGraph);
    pGraph->QueryInterface(IID_IMediaControl, (void **)&pMediaControl);
    pGraph->QueryInterface(IID_IMediaEventEx, (void**)&pEv);

    // Create the graph and find the SAMI parser.
    pGraph->RenderFile(L"C:\\Sami_test_file.sami", NULL);
    hr = pGraph->FindFilterByName(L"SAMI (CC) Parser", &pSAMI);
    if (SUCCEEDED(hr))
    {
        IAMStreamSelect *pStrm = NULL;
        hr = pSAMI->QueryInterface(IID_IAMStreamSelect, (void**)&pStrm);
        if (SUCCEEDED(hr))
        {
            DWORD dwStreams = 0;
            pStrm->Count(&dwStreams);
            printf("Stream count: %d\n", dwStreams);

            // Select French and "GreenText"
            hr = pStrm->Enable(1, AMSTREAMSELECTENABLE_ENABLE);
            hr = pStrm->Enable(3, AMSTREAMSELECTENABLE_ENABLE);

            // Print the name of each logical stream.
            for (DWORD index = 0; index < dwStreams; index++)
            {
                DWORD dwFlags;
                WCHAR *wszName;
                hr = pStrm->Info(index, NULL, &dwFlags, NULL, NULL, &wszName, NULL, NULL);
                wprintf(L"Stream %d: %s [%s]\n", index, wszName,
                    (dwFlags ?  L"ENABLED" : L"DISABLED"));
                CoTaskMemFree(wszName);
            }
            pStrm->Release();
        }
        pSAMI->Release();
    }

    // Run the graph and display the captions.
    pMediaControl->Run();
    while (1)
    {
        long evCode, lParam1, lParam2;
        pEv->GetEvent(&evCode, &lParam1, &lParam2, 100);

        if (evCode == EC_OLE_EVENT) {
            wprintf(L"%s\n", (BSTR)lParam2);
        }
        pEv->FreeEventParams(evCode, lParam1, lParam2);

        if (evCode == EC_USERABORT || evCode == EC_COMPLETE || evCode == EC_ERRORABORT)
            break;
    }

    // Clean up.
    pMediaControl->Release();
    pEv->Release();
    pGraph->Release();
    CoUninitialize();
}

This filter uses the IAsyncReader interface to pull samples from the source filter. Therefore, it does not support the IMemInputPin interface on its input pin.


Sample Grabber Filter

The Sample Grabber filter provides a way to retrieve samples as they pass through the filter graph. It is a transform filter with one input pin and one output pin. It passes all samples downstream unchanged, so you can insert it into a filter graph without altering the data stream. Your application can then retrieve individual samples from the filter by calling methods on the ISampleGrabber interface.

If you want to retrieve samples without rendering the data, connect the Sample Grabber filter to the Null Renderer filter.

For more information on using this filter, see Grabbing Media Samples.

Filter interfaces | IBaseFilter, ISampleGrabber
Input pin media types | Any media type.
Input pin interfaces | IMemInputPin, IPin, IQualityControl
Output pin media types | Any media type. Matches input media type.
Output pin interfaces | IPin, IQualityControl
Filter CLSID | CLSID_SampleGrabber
Property Page CLSID | No property page.
Executable | Qedit.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory


Smart Tee Filter

The Smart Tee filter is used in video capture graphs to split the video stream into a preview stream and a capture stream. This is done without any additional data copying. The output pins support whatever media types are supported on the downstream connection.

The Smart Tee filter is useful when a video capture filter does not provide separate pins for capture and preview. The Smart Tee filter delivers preview data only if doing so does not hurt capture performance. It also removes the time stamps from the preview stream. The capture graph builder automatically inserts the Smart Tee filter when needed. For more information, see How to Write a Capture Application.

The following illustration shows a typical capture graph that uses the Smart Tee filter.

Using the Smart Tee Filter

Filter Interfaces | IBaseFilter
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_NULL
Output Pin Interfaces | IAMStreamControl, IPin, IQualityControl
Filter CLSID | CLSID_SmartTee
Property Page CLSID | No property page.
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory


Tee/Sink-to-Sink Converter

The Tee/Sink-to-Sink Converter is a kernel-mode, KsProxy-based filter. It is used in analog video television filter graphs where VBI data is being rendered or captured. The filter is connected upstream to the WDM Video Capture Filter and provides an efficient means to duplicate streams of data within kernel mode without the expensive transitions between kernel and user mode. It delivers each received data block to all output pins, and the downstream codec is responsible for finding the specific VBI data to decode.

The other important function of the Tee/Sink-to-Sink Converter is not really relevant for application programmers, but is mentioned here for completeness. The "Sink-to-Sink" capability was required for the Microsoft® Windows 98® platform to enabled the connection of two drivers that each supported only incoming IRPs. This functionality is now performed by other components in the WDM architecture.

The Tee/Sink-to-Sink Converter appears in GraphEdit under the "WDM Streaming Tee/Splitter Devices" category. Because this is a kernel-mode filter, applications cannot co-create it directly, but must use the System Device Enumerator to instantiate it, as described in Enumerating Devices and Filters.


TV Audio Filter

The TV Audio filter provides control of television audio decoding, stereo or monoaural selection, and secondary audio program (SAP) selection.

This filter is available through Microsoft® Windows® 98 and Windows 2000.

Filter Interfaces | IAMTVAudio, IPersistPropertyBag, ISpecifyPropertyPages, IKsPropertySet
Input Pin Media Types | MEDIATYPE_AnalogAudio
Input Pin Interfaces | IKsPropertySet
Output Pin Media Types | MEDIATYPE_AnalogAudio
Output Pin Interfaces | IKsPropertySet
Filter CLSID | CLSID_TVAudioFilter
Property Page CLSID | CLSID_TVAudioFilterPropertyPage
Executable |
Merit |
Category | CLSID_AudioInputDeviceCategory


TV Tuner Filter

The TV Tuner filter selects an analog broadcast or cable channel to be viewed. The single output stream is a hardware path for analog baseband video. This output should connect to the Analog Video Crossbar filter. The input pins include an input for cable and an antenna input.

This filter is available through Microsoft® Windows 98® and Windows 2000.

Filter Interfaces | IBaseFilter, IAMTVTuner, ISpecifyPropertyPages, IPersistPropertyBag, IKsObject, IKsPropertySet
Input Pin Media Types | Not applicable.
Input Pin Interfaces | Not applicable.
Output Pin Media Types | Video: MEDIATYPE_AnalogVideo, KSDATAFORMAT_SUBTYPE_NONE Audio: MEDIATYPE_AnalogAudio, MEDIASUBTYPE_NULL
Output Pin Interfaces | IPin
Filter CLSID | CLSID_CTVTunerFilter
Property Page CLSID | CLSID_TVTunerFilterPropertyPage
Executable | KSTVTune.ax
Merit |
Category | CLSID_VideoInputDeviceCategory


VBI Surface Allocator

The VBI Surface Allocator controls the allocation of VBI buffers in analog television graphs with hardware video port capture scenarios. With devices such as the Bt829 decoder, the frame buffer may contain multiple VBI capture buffers that are accessed via a proprietary hardware-based mechanism known generically as a Video Port. The VBISurf filter connects downstream from the capture filter and has no output pin. The filter works closely with the Overlay Mixer (via DirectDraw) to perform coordinated operations on the hardware video port, utilizing the same limited SVGA frame buffer memory.

Filter Interfaces | IBaseFilter, IVPVBINotify
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_VPVBI
Input Pin Interfaces | IVPVBINotify, IKsPropertySet
Output Pin Media Types | MEDIATYPE_NULL, MEDIASUBTYPE_NULL. (Nothing is ever connected to the output pin.)
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_VBISurfaces
Property Page CLSID | No property page.
Executable | vbisurf.ax
Merit | MERIT_NORMAL
Category | CLSID_LegacyAmFilterCategory


VFW Capture Filter

This filter works with older video capture hardware that uses Video For Windows.

This filter has two output pins. One is called Capture, and the other is called either Preview or Overlay.

Filter Interfaces | IPersistPropertyBag, IAMVfwCaptureDialogs, IAMFilterMiscFlags, IBaseFilter, ISpecifyPropertyPages, IVfwCaptureOptions, IOverlayNotify
Input Pin Media Types | Not applicable.
Input Pin Interfaces | Not applicable.
Output Pin Media Types | Capture: MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_VideoInfo Overlay: MEDIATYPE_Video, MEDIASUBTYPE_Overlay, FORMAT_VideoInfo Preview: MEDIATYPE_Video, MEDIASUBTYPE_NULL, FORMAT_VideoInfo
Output Pin Interfaces | Capture: IAMBufferNegotiation, IAMDroppedFrames, IAMPushSource, IAMStreamConfig, IAMStreamControl, IAMVideoCompression, IKsPropertySet, IPin, IQualityControl Overlay: IAMStreamControl, IKsPropertySet, IPin, IQualityControl Preview: IAMPushSource, IAMStreamControl, IKsPropertySet, IPin, IQualityControl
Filter CLSID | CLSID_VfwCapture
Property Page CLSID | CLSID_CaptureProperties
Executable | qcap.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_VideoInputDeviceCategory


VGA 16 Color Ditherer Filter

The VGA 16 Color Ditherer filter converts from an RGB color type to a 4-bit color display so that AVI and MPEG video streams may be displayed on older 16-color monitors. This filter is inserted in the graph between a decompressor filter and a video renderer filter.

Filter Interfaces | IBaseFilter
Input Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_RGB8
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Video, MEDIASUBTYPE_RGB4
Output Pin Interfaces | IMediaPosition, IMediaSeeking, IPin, IQualityControl
Filter CLSID | CLSID_Dither
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Category | CLSID_LegacyAmFilterCategory


Video Renderer Filter

The Video Renderer filter is a generic video renderer that you can connect to any video transform filter that produces decompressed video data.

The Video Renderer filter uses Microsoft® DirectDraw® methods, if the video card supports them. Full-screen rendering is enabled from the filter graph manager, which automatically switches between the Video Renderer and the Full Screen Renderer when appropriate for certain older graphics cards; you do not need to include the Full Screen Renderer in the filter graph beforehand. On newer cards the Video Renderer itself performs the full screen rendering.

The Video Renderer will accept YUV as well as RGB formats if the video graphics card supports YUV overlay surfaces. But it is important to note that the Video Renderer, when it is initially connected to the upstream filter, will always insist on an RGB format that matches the color depth of the current monitor settings. For example, if the user has set their monitor to 24-bit color, then the upstream filter must be capable of providing data in 24-bit RGB. When the graph goes into a run state, the Video Renderer will negotiate a dynamic format change to the appropriate YUV color space. The Video Renderer requires the initial RGB data format because in some cases it may need to dynamically switch to using GDI instead of DirectDraw to render the video; GDI does not support YUV color spaces. The Video Renderer will switch to GDI if the video memory is being used by another application, or if the video display rectangle straddles two monitors on a multi-monitor system, or if the video rectangle is completely obscured by another window on the screen.

This filter has its own plug-in distributor in the filter graph manager, which enables applications to set and retrieve properties on the filter by calling the corresponding interface methods on the filter graph manager. Most other Microsoft® DirectShow® filters are not visible to applications in this manner.

The thread that co-creates the Video Renderer is the one on which the Video Renderer's window is created. That thread must have a message loop to dispatch messages to the Video Renderer's window.

Filter Interfaces | IBaseFilter, IBasicVideo, IBasicVideo2, IDirectDrawVideo, IKsPropertySet, IMediaPosition, IMediaSeeking, IQualityControl, IQualProp, IVideoWindow
Input Pin Media Types | MEDIATYPE_Video
Input Pin Interfaces | IMemInputPin, IOverlay, IPin, IPinConnection, IQualityControl
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_VideoRenderer
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_PREFERRED
Category | CLSID_LegacyAmFilterCategory


WAVE Parser Filter

The WAVE Parser filter parses WAV-format audio data from .wav, .au, or .aif files. The upstream filter must be the Async File Source filter, URL File Source filter, or a compatible third-party asynchronous source filter that contains WAV audio data. The output stream is audio data, which you can connect directly to an audio rendering filter or to an intervening audio transform filter.

Filter Interfaces | IAMMediaContent, IBaseFilter, IPersistMediaPropertyBag
Input Pin Media Types MEDIATYPE_Stream

The following subtypes are valid:
  • MEDIASUBTYPE_AIFF
  • MEDIASUBTYPE_AU
  • MEDIASUBTYPE_WAVE
Input Pin Interfaces | IPin, IQualityControl
Output Pin Media Types | MEDIATYPE_Audio, MEDIASUBTYPE_NULL
Output Pin Interfaces | IPin, IMediaSeeking
Filter CLSID | CLSID_WAVEParser {D51BD5A1-7548-11cf-A520-0080C77EF58A}
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_UNLIKELY
Category | CLSID_LegacyAmFilterCategory


WDM Video Capture Filter

The WDM Video Capture filter is actually a kernel mode KsProxy plug-in that provides property pages and the COM interfaces for WDM drivers that control analog capture devices (also called analog video decoders). Of course, from an application's perspective, this is just another filter that can be discovered through the System Device Enumerator. As with any filter based on KsProxy, the friendly name of the filter will depend on the underlying driver. The system device enumerator will return a unique moniker for each device that uses this plug-in. For more information, see Enumerating Devices and Filters and How Hardware Devices Participate in the Filter Graph.

Not all devices that are exposed through the WDM Video Capture Filter

will implement all of the interfaces described below. It is the responsiblity of the application to determine which interfaces are supported by a particular device.

Filter Interfaces | The WDM driver for the device may support one or more of the following: IAMExtDevice, IAMExtTransport, IAMTimecodeReader, IAMCameraControl, IAMVideoProcAmp, IAMAnalogVideoDecoder, IAMVideoCompression, IAMVideoControl.
Input Pin Media Types | Driver-dependent.
Input Pin Interfaces | Driver-dependent.
Output Pin Media Types | Driver-dependent.
Output Pin Interfaces | Driver-dependent. May include IAMStreamControl, or IAMVideoCompression (if the video is compressed).
Filter CLSID | Driver-dependent.
Property Page CLSID | Driver-dependent.
Plug-in Executable | kswdmcap.ax
Merit | Driver-dependent.
Category | CLSID_VideoInputDeviceCategory


WST Codec

World Standard Teletext (WST) is the European standard for data transmission using VBI on PAL analog television signals. Both captioning and data services are provided using this standard. The WST Codec is a kernel-mode filter that receives raw VBI samples and, optionally, decoded Teletext samples from the Capture Filter via the Tee/Sink-to-Sink Converter filter. This codec decodes and/or duplicates the decoded and forward-error-corrected Teletext data for the WST Decoder filter. The WST Decoder then creates the bitmaps that are sent to the Overlay Mixer.

The WST Codec appears in GraphEdit in the "WDM Streaming VBI Codecs" category. Because this is a kernel-mode filter, applications cannot co-create it directly, but must use the System Device Enumerator to instantiate it, as described in Enumerating Devices and Filters.


WST Decoder

The WST Decoder is a kernel-mode filter that accepts decoded World Standard Teletext data from the WST Codec and delivers the bitmaps to Pin 2 on the Overlay Mixer using fonts supplied by Microsoft. Only Western European languages are supported at this time; no Unicode™ fonts are currently provided. There are no application-callable interfaces on the WST Decoder.

The WST Decoder appears in GraphEdit under the "WDM Streaming VBI Codecs" category. Because this is a kernel-mode filter, applications cannot co-create it directly, but must use the System Device Enumerator to instantiate it, as described in Enumerating Devices and Filters. This filter can be added to the graph automatically by calling ICaptureGraphBuilder2::RenderStream on the output pin of the WST Codec.


Interfaces

This topic contains reference information for the Microsoft® DirectShow® COM interfaces. To provide broad support for various types of hardware, file formats, and stream operations, DirectShow implements a large number of interfaces. Some are used by applications; others are used internally by filters and other DirectShow components.

Any particular application will use only a small subset of these interfaces. Which interfaces you need depends on the nature of the application. The following tables summarize the application-level interfaces according to their purpose:

  • Building a Filter Graph
  • Controlling a Filter Graph
  • Audio Capture and Rendering
  • DVD
  • Video Capture
  • Video Editing
  • File Encoding and Decoding
  • Video Rendering, Scaling, and Overlays
  • TV Tuning
  • External Device Control

See also:

  • Alphabetical List of DirectShow Interfaces
  • DirectShow Filters
  • DirectShow Components

Building a Filter Graph

Applications use these interfaces to build various types of filter graphs.

Interface | Purpose
ICaptureGraphBuilder2 | Build filter graphs for video capture.
ICreateDevEnum | Enumerate the available system devices.
IDvdGraphBuilder | Build filter graphs for DVD navigation and playback.
IFilterGraph2 | Add, remove, or connect filters.
IFilterMapper2 | Enumerate the filters registered on the user's system.
IGraphBuilder | Build filter graphs for file playback or for custom uses.
IGraphConfig | Dynamically reconfigure a filter graph.
IGraphVersion | Determine when the graph changes.

Controlling a Filter Graph

These interfaces provide methods for controlling a filter graph.

Interface | Purpose
IAMGraphStreams | Synchronize live streams in a filter graph.
IEnumFilters | Enumerate the filters in the graph.
IFilterChain | Control chains of filters.
IMediaControl | Run, pause, and stop the filter graph. (Also provides Automation-compatible methods for building graphs.)
IMediaEventEx | Respond to events in the graph.
IMediaSeeking | Seek within a file.
IQueueCommand | Queue commands to run at a later time.
IVideoFrameStep | Frame-step through a video stream.

Audio Capture and Rendering

These interfaces support capture and rendering of audio.

Interface | Purpose
IAMAudioInputMixer | Access the analog inputs on the system's sound card and adjust characteristics, such as mono or stereo, mix level, pan level, loudness, treble, and bass.
IAMDirectSound | On a Microsoft DirectSound®-compatible device, controls whether the application's audio output is audible when other applications have the focus, and which application window is associated with sound.
IAMResourceControl | Hold an audio device resource before it is needed.
IBasicAudio | Set audio output volume and balance.

DVD

Interface | Purpose
IDvdCmd | Block the DVD Navigator until a command starts or completes.
IDvdControl2 | Navigate and play DVD-Video titles, including karaoke titles.
IDvdGraphBuilder | Build a filter graph for DVD-Video playback from the available software and hardware on the system.
IDvdInfo2 | Query for various attributes of a DVD disc or the DVD Navigator's state.
IDvdState | Save the state of the user's session to disk, including playback location, parental level, and region.

Video Capture

These interfaces support video capture, using Microsoft® Windows® Driver Model (WDM) devices or legacy Microsoft® Video for Windows® (VFW) devices.

Interface | Purpose
IAMAnalogVideoDecoder | Control video digitization on a WDM video capture card.
IAMAnalogVideoEncoder | Control a hardware video encoder.
IAMBufferNegotiation | Control how a pin allocates buffers.
IAMCopyCaptureFileProgress | Callback interface to receive the progress of a file copy operation.
IAMCrossbar | Create a hardware connection between a WDM audio or video source and a WDM capture device.
IAMDroppedFrames | Query a capture filter about capture performance.
IAMStreamControl | Control the start and stop times of individual streams.
IAMVfwCaptureDialogs | Display the dialog boxes provided by VFW capture drivers.
IAMVideoControl | Control the picture from a capture device.
IAMVideoProcAmp | Adjust the qualities of a video signal, such as brightness, contrast, hue, saturation, gamma, and sharpness.
ICaptureGraphBuilder2 | Build filter graphs for video capture.
IFileSinkFilter2 | Specify the name and attributes of an output file.
ISampleGrabber | Retrieve media samples as they move through the filter graph.

Video Editing

DirectShow Editing Services (DES) provides the following interfaces.

Interface | Purpose
IAMErrorLog | Callback interface for error logging.
IAMSetErrorLog | Set or retrieve an error log.
IAMTimeline | Set and retrieve properties on a timeline and create timeline objects.
IAMTimelineComp | Insert or retrieve virtual tracks on a composition.
IAMTimelineEffect | Retrieve an effect's priority.
IAMTimelineEffectable | Add an effect to a timeline object.
IAMTimelineGroup | Set and retrieve properties on a group.
IAMTimelineObj | Set and retrieve properties on a timeline object.
IAMTimelineSplittable | Split a timeline object.
IAMTimelineSrc | Set and retrieve properties on a source.
IAMTimelineTrack | Set and retrieve properties on a track.
IAMTimelineTrans | Set and retrieve properties on a transition.
IAMTimelineTransable | Add a transition to a timeline object.
IAMTimelineVirtualTrack | Set and retrieve properties on a virtual track.
IMediaDet | Retrieve information about a media file.
IMediaLocator | Validate file names.
IPropertySetter | Set properties on an effect or transition.
IRenderEngine | Render a video editing project.
ISmartRenderEngine | Use smart recompression to render a video editing project.
IXml2Dex | Save and load video editing projects in Extensible Markup Language (XML).

File Encoding and Decoding

Interface | Purpose
IAMMediaContent | Retrieve meta-data from a stream, such as the author and title.
IAMOpenProgress | Determine the progress of a file-open operation.
IAMParse | Query and set the parse time for the current position in an MPEG stream.
IAMStreamSelect | Control which logical streams are played, and retrieve information about them.
IAMVfwCompressDialogs | Display dialog boxes provided by VFW codecs.
IAMVideoCompression | Set video compression parameters.
IConfigAsfWriter | Control how the ASF File Writer filter writes Advanced Streaming Format (ASF) files.
IConfigAviMux | Control how the AVI Mux filter writes AVI files.
IConfigInterleaving | Configure interleaving when the AVI Mux filter writes AVI files.
IDVEnc | Set the encoding resolution on the DV Video Encoder filter.
IDVSplitter | Downgrade the frame rate on a digital video (DV) stream
IIPDVDec | Set the decoding resolution on the DV Video Decoder filter.
IPersistMediaPropertyBag | Set and retrieve INFO and DISP chunks in AVI streams.

Video Rendering, Scaling, and Overlays

Interface | Purpose
IAMLine21Decoder | Provides access to closed-captioned information and settings.
IAMOverlayFX | Apply overlay effects to the video surface.
IAMVideoDecimationProperties | Control how DirectShow scales a video image if the video window is smaller than the native size of the video.
IBasicVideo2 | Set video properties.
IDDrawExclModeVideo | Render video in Microsoft® DirectDraw® exclusive full-screen mode.
IDDrawExclModeVideoCallback | Callback interface to receive notification about changes to the overlay position, size, and visibility.
IDirectDrawVideo | Disable specified DirectDraw capabilities.
IDirectDrawMediaSample | Access a DirectDraw surface allocated by the Overlay Mixer filter.
IFullScreenVideo | Control the Full-Screen Renderer filter.
IMixerPinConfig2 | Set video color controls on the Overlay Mixer when mixing multiple video streams.
IQualProp | Query a video renderer for performance information.
IVideoWindow | Set video window properties.

TV Tuning

Interface | Purpose
IAMTunerNotification | Callback interface to receive event notifications from the TV tuner filter.
IAMTVTuner | Control a TV tuner device.
IAMTVAudio | Control the audio from a TV tuner.
IAMTVAudioNotification | Callback interface to receive event notifications from a TV tuner card.
IAMAnalogVideoDecoder | Contains methods for selecting the digitization format, indicating the horizontal lock status, and controlling the time constant on the digitizer phase lock loop (PLL).
IAMAnalogVideoDecoder | Contains methods for selecting the digitization format, indicating the horizontal lock status, and controlling the time constant on the digitizer phase lock loop (PLL).

External Device Control

Interface | Purpose
IAMCameraControl | Control a camera.
IAMExtDevice | Control an external device such as a VCR or camcorder.
IAMExtTransport | Control VCR transport functions, such as play, pause, record, fast-forward, and rewind.
IAMTimecodeDisplay | Set properties on a device that displays SMPTE timecode.
IAMTimecodeGenerator | Set properties on a device that generates SMPTE timecode.
IAMTimecodeReader | Read SMPTE timecode from an external device.


Alphabetical List of DirectShow Interfaces

The following is an alphabetical list of all the DirectShow COM interfaces.

  • IAMAnalogVideoDecoder
  • IAMAnalogVideoEncoder
  • IAMAudioInputMixer
  • IAMBufferNegotiation
  • IAMCameraControl
  • IAMClockAdjust
  • IAMCollection
  • IAMCopyCaptureFileProgress
  • IAMCrossbar
  • IAMDirectSound
  • IAMDroppedFrames
  • IAMErrorLog
  • IAMExtDevice
  • IAMExtTransport
  • IAMFilterMiscFlags
  • IAMGraphStreams
  • IAMLatency
  • IAMLine21Decoder
  • IAMMediaContent
  • IAMOpenProgress
  • IAMOverlayFX
  • IAMParse
  • IAMPushSource
  • IAMResourceControl
  • IAMSetErrorLog
  • IAMStreamConfig
  • IAMStreamControl
  • IAMStreamSelect
  • IAMTimecodeDisplay
  • IAMTimecodeGenerator
  • IAMTimecodeReader
  • IAMTimeline
  • IAMTimelineComp
  • IAMTimelineEffect
  • IAMTimelineEffectable
  • IAMTimelineGroup
  • IAMTimelineObj
  • IAMTimelineSplittable
  • IAMTimelineSrc
  • IAMTimelineTrack
  • IAMTimelineTrans
  • IAMTimelineTransable
  • IAMTimelineVirtualTrack
  • IAMTuner
  • IAMTunerNotification
  • IAMTVAudio
  • IAMTVAudioNotification
  • IAMTVTuner
  • IAMVfwCaptureDialogs
  • IAMVfwCompressDialogs
  • IAMVideoAccelerator
  • IAMVideoAcceleratorNotify
  • IAMVideoCompression
  • IAMVideoControl
  • IAMVideoDecimationProperties
  • IAMVideoProcAmp
  • IAsyncReader
  • IBaseFilter
  • IBasicAudio
  • IBasicVideo
  • IBasicVideo2
  • ICaptureGraphBuilder2
  • IConfigAviMux
  • IConfigInterleaving
  • ICreateDevEnum
  • IDDrawExclModeVideo
  • IDDrawExclModeVideoCallback
  • IDecimateVideoImage
  • IDeferredCommand
  • IDirectDrawVideo
  • IDirectDrawMediaSample
  • IDirectDrawMediaSampleAllocator
  • IDistributorNotify
  • IDMOWrapperFilter
  • IDvdCmd
  • IDvdControl2
  • IDvdGraphBuilder
  • IDvdInfo2
  • IDvdState
  • IDVEnc
  • IDVSplitter
  • IEnumFilters
  • IEnumMediaTypes
  • IEnumPIDMap
  • IEnumPins
  • IEnumStreamIdMap
  • IFileSinkFilter
  • IFileSinkFilter2
  • IFileSourceFilter
  • IFilterChain
  • IFilterGraph
  • IFilterGraph2
  • IFilterInfo
  • IFilterMapper2
  • IFindCompressorCB
  • IFullScreenVideo
  • IGraphBuilder
  • IGraphConfig
  • IGraphConfigCallback
  • IGraphVersion
  • IIPDVDec
  • IKsPropertySet
  • IMediaControl
  • IMediaDet
  • IMediaEvent
  • IMediaEventEx
  • IMediaEventSink
  • IMediaFilter
  • IMediaLocator
  • IMediaPosition
  • IMediaPropertyBag
  • IMediaSample
  • IMediaSample2
  • IMediaSeeking
  • IMediaTypeInfo
  • IMemAllocator
  • IMemInputPin
  • IMixerPinConfig
  • IMixerPinConfig2
  • IMpeg2Demultiplexer
  • IMPEG2PIDMap
  • IMPEG2StreamIdMap
  • IOverlay
  • IOverlayNotify
  • IOverlayNotify2
  • IPersistMediaPropertyBag
  • IPin
  • IPinConnection
  • IPinFlowControl
  • IPinInfo
  • IPropertySetter
  • IQualityControl
  • IQualProp
  • IQueueCommand
  • IReferenceClock
  • IRegFilterInfo
  • IRenderEngine
  • IResourceConsumer
  • IResourceManager
  • ISampleGrabber
  • ISampleGrabberCB
  • ISeekingPassThru
  • ISmartRenderEngine
  • IStreamBuilder
  • IUnknown
  • IVideoFrameStep
  • IVideoWindow
  • IVPBaseConfig
  • IVPBaseNotify
  • IVPConfig
  • IVPNotify
  • IVPNotify2
  • IXml2Dex


IAMAnalogVideoDecoder Interface

The IAMAnalogVideoDecoder interface is implemented on the WDM Video Capture filter. This interface specifies and retrieves information about the process of video digitization on a WDM-compliant video capture card. It contains methods for selecting the digitization format, indicating the horizontal lock status, and controlling the time constant on the digitizer phase lock loop (PLL).

Applications should use this interface to select and control the various aspects of video digitization, such as getting and setting the supported analog video format, determining whether the horizontal sync is locked, and retrieving other various information about the digitization format.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMAnalogVideoDecoder methods | Description
get_AvailableTVFormats | Retrieves the currently available analog video formats.
put_TVFormat | Sets the current analog video format.
get_TVFormat | Retrieves the current analog video format.
get_HorizontalLocked | Determines whether the horizontal sync is locked.
put_VCRHorizontalLocking | Sets the condition for being connected to a VCR (changes PLL timing).
get_VCRHorizontalLocking | Determines whether horizontal locking has been set.
get_NumberOfLines | Retrieves the number of horizontal lines in the current video signal.
put_OutputEnable | Enables or disables the output bus.
get_OutputEnable | Determines whether the output bus is enabled.

IAMAnalogVideoDecoder::get_AvailableTVFormats

IAMAnalogVideoDecoder Interface

Retrieves the currently available analog video formats.

Syntax

HRESULT get_AvailableTVFormats(
    long *lAnalogVideoStandard
    );

Parameters

lAnalogVideoStandard
[out] Pointer to an integer that represents the available analog video formats. This can potentially be several values from the AnalogVideoStandard enumerated type, combined by a bitwise OR operation.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMAnalogVideoDecoder::get_HorizontalLocked

IAMAnalogVideoDecoder Interface

Determines whether the horizontal sync is locked.

Syntax

HRESULT get_HorizontalLocked(
    long *plLocked
    );

Parameters

plLocked
[out] Pointer to a value indicating whether the horizontal sync is locked; TRUE indicates the horizontal sync is locked, FALSE indicates that it is not.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMAnalogVideoDecoder::get_NumberOfLines

IAMAnalogVideoDecoder Interface

Retrieves the number of horizontal lines in a video signal.

Syntax

HRESULT get_NumberOfLines(
    long *plNumberOfLines
    );

Parameters

plNumberOfLines
[out] Pointer to the number of horizontal lines in the video signal. For NTSC, this will generally be 525, and for PAL/SECAM, it will typically be 625.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMAnalogVideoDecoder::get_OutputEnable

IAMAnalogVideoDecoder Interface

Determines whether the output bus is enabled or disabled.

Syntax

HRESULT get_OutputEnable(
    long *plOutputEnable
    );

Parameters

plOutputEnable
[out] Pointer to a value specifying whether the output bus is enabled; returns TRUE if it is enabled, FALSE if it is disabled.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMAnalogVideoDecoder::get_TVFormat

IAMAnalogVideoDecoder Interface

Retrieves the current analog video format.

Syntax

HRESULT get_TVFormat(
    long *plAnalogVideoStandard
    );

Parameters

plAnalogVideoStandard
[out] Pointer to the AnalogVideoStandard enumerated type, which contains the supported analog video formats.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMAnalogVideoDecoder::get_VCRHorizontalLocking

IAMAnalogVideoDecoder Interface

Determines whether horizontal locking has been set.

Syntax

HRESULT get_VCRHorizontalLocking(
    long *plVCRHorizontalLocking
    );

Parameters

plVCRHorizontalLocking
[out] Pointer to a value indicting whether horizontal locking is set. TRUE indicates horizontal locking is set; FALSE otherwise.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

VCRs might have bad sync timing (due to tape slips, tape noise or dropouts, and the mechanical nature of the recording mechanism). Having the horizontal locking on tells the decoder to relax its standards, which leads to a better chance of maintaining sync.

IAMAnalogVideoDecoder::put_OutputEnable

IAMAnalogVideoDecoder Interface

Enables or disables the output bus.

Syntax

HRESULT put_OutputEnable(
    long lOutputEnable
    );

Parameters

lOutputEnable
[in] Value indicating if the output bus is enabled; specify TRUE to enable it, FALSE to disable it.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMAnalogVideoDecoder::put_TVFormat

IAMAnalogVideoDecoder Interface

Sets the current format to one of the supported analog video standards.

Syntax

HRESULT put_TVFormat(
    long lAnalogVideoStandard
    );

Parameters

lAnalogVideoStandard
[in] Value from the AnalogVideoStandard enumerated type, which contains the supported analog video formats.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMAnalogVideoDecoder::put_VCRHorizontalLocking

IAMAnalogVideoDecoder Interface

Specifies whether horizontal locking is set.

Syntax

HRESULT put_VCRHorizontalLocking(
    long lVCRHorizontalLocking
    );

Parameters

lVCRHorizontalLocking
[in] Value indicating whether horizontal locking is set.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

VCRs might have bad sync timing (due to tape slips, tape noise or dropouts, and the mechanical nature of the recording mechanism). This method tells the decoder to relax its standards, which leads to a better chance of maintaining sync.


IAMAnalogVideoEncoder Interface

The IAMAnalogVideoEncoder interface might be implemented by a hardware video encoder in video capture operations when an application is streaming data to disk and sending it back out to videotape. It provides methods for setting the video standard and enabling or disabling closed captioning and copy protection.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMAnalogVideoEncoder methods | Description
get_AvailableTVFormats | Retrieves the analog video standards (NTSC/M, PAL/B, SECAM/K1, and so on) supported by the encoder.
put_TVFormat | Sets the encoder to a particular analog video standard.
get_TVFormat | Retrieves the analog video standard that the encoder is currently set to.
put_CopyProtection | Sets the level of copy protection for the encoder.
get_CopyProtection | Determines whether copy protection is currently enabled.
put_CCEnable | Enables or disables closed captioning.
get_CCEnable | Determines whether closed captioning is currently enabled.

IAMAnalogVideoEncoder::get_AvailableTVFormats

IAMAnalogVideoEncoder Interface

Retrieves the analog video standards (NTSC/M, PAL/B, SECAM/K1, and so on) supported by the encoder.

Syntax

HRESULT get_AvailableTVFormats(
    long *lAnalogVideoStandard
);

Parameters

lAnalogVideoStandard
[out] Pointer to a variable that receives any combination of the values defined in the AnalogVideoStandard enum.

Return Value

Returns an HRESULT value.

IAMAnalogVideoEncoder::get_CCEnable

IAMAnalogVideoEncoder Interface

Determines whether closed captioning is currently enabled.

Syntax

HRESULT get_CCEnable(
    long *lCCEnable
);

Parameters

lCCEnable
[out] Pointer to a variable that receives the current status of closed captioning on the encoder; 1 means closed captioning is enabled and 0 means it is disabled.

Return Value

Returns an HRESULT value.

IAMAnalogVideoEncoder::get_CopyProtection

IAMAnalogVideoEncoder Interface

Determines whether copy protection is currently enabled on the encoder.

Syntax

HRESULT get_CopyProtection(
    long *lVideoCopyProtection
);

Parameters

lVideoCopyProtection
[out] Pointer to a variable that receives the current copy protection level, as defined in the AM_COPY_MACROVISION_LEVEL enumeration.

Return Value

Returns an HRESULT value.

IAMAnalogVideoEncoder::get_TVFormat

IAMAnalogVideoEncoder Interface

Retrieves the analog video standard that the encoder is currently set to (NTSC/M, PAL/B, SECAM/K1, and so on).

Syntax

HRESULT get_TVFormat(
    long *plAnalogVideoStandard
);

Parameters

plAnalogVideoStandard
[out] Pointer to a variable that receives the encoder's current video standard.

Return Value

Returns an HRESULT value.

Remarks

Possible values and their meaning are defined in the AnalogVideoStandard enumeration.

IAMAnalogVideoEncoder::put_CCEnable

IAMAnalogVideoEncoder Interface

Enables or disables closed captioning.

Syntax

HRESULT put_CCEnable(
    long lCCEnable
);

Parameters

lCCEnable
[in] Value indicating whether to turn closed captioning on or off; 1 means "on" and 0 means "off."

Return Value

Returns an HRESULT value.

IAMAnalogVideoEncoder::put_CopyProtection

IAMAnalogVideoEncoder Interface

Sets the level of copy protection for the encoder.

Syntax

HRESULT put_CopyProtection(
    long lVideoCopyProtection
);

Parameters

lVideoCopyProtection
[in] Value indicating the level of copy protection to set, as defined in the AM_COPY_MACROVISION_LEVEL enumeration.

Return Value

Returns an HRESULT value.

IAMAnalogVideoEncoder::put_TVFormat

IAMAnalogVideoEncoder Interface

Sets the encoder to a particular analog video standard (NTSC/M, PAL/B, SECAM/K1, and so on).

Syntax

HRESULT put_TVFormat(
    long lAnalogVideoStandard
);

Parameters

lAnalogVideoStandard
[in] Video standard that the encoder will be set to. Possible values are defined in the AnalogVideoStandard enumeration.

Return Value

Returns an HRESULT value.


IAMAudioInputMixer Interface

The IAMAudioInputMixer interface is implemented on each input pin of the Audio Capture Filter and tells the filter what level, panning, and equalizer to use for each input. The name of each pin, such as "Line in" or "Microphone", reflects the type of input.

Because the capabilities of the Audio Capture filter reflect the particular hardware device it is associated with, the filter cannot support an interface method if the device does not support it.

Application developers: Use this interface to access the sound card's analog inputs, and adjust audio input characteristics on the Audio Capture filter such as mixing, use of mono or stereo, mix level, pan level, loudness, treble, and bass settings. Use the pin names to decide how to set the recording levels for each type of input.

Filter Developers: Implement this interface on each input pin of an audio capture filter. You can also implement this interface on the audio capture filter itself to control the overall record level and panning after the audio mixing occurs.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMAudioInputMixer methods | Description
put_Enable | Enables or disables an input in the mix.
get_Enable | Retrieves whether the input is enabled.
put_Mono | Combines all channels of an input into a mono signal.
get_Mono | Retrieves whether all channels of an input are combined into a mono signal.
put_MixLevel | Sets the record level for this input.
get_MixLevel | Retrieves the recording level for this input.
put_Pan | Sets the pan for this input.
get_Pan | Retrieves the pan for this input.
put_Loudness | Turns the loudness control for this input on or off.
get_Loudness | Retrieves the loudness control setting for this input.
put_Treble | Sets the treble equalization for this input.
get_Treble | Retrieves the treble equalization for this input.
get_TrebleRange | Retrieves the treble range for this input.
put_Bass | Sets the bass equalization for this input.
get_Bass | Retrieves the bass equalization for this input.
get_BassRange | Retrieves the bass range for this input.

IAMAudioInputMixer::get_Bass

IAMAudioInputMixer Interface

Retrieves the bass equalization for this input.

Syntax

HRESULT get_Bass(
  double *pBass
  );

Parameters

pBass
[in] Pointer to a variable of type double that represents the bass gain in decibels (a negative value means attenuate).

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
NOERROR | Success.

IAMAudioInputMixer::get_BassRange

IAMAudioInputMixer Interface

Retrieves the bass range for this input.

Syntax

HRESULT get_BassRange(
  double *pRange
  );

Parameters

pRange
[out, retval] pointer to a variable of type double that represents the largest value allowed in the bass range specified in put_Bass. For example, 6.0 means any value between –6.0 and 6.0 is allowed.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
NOERROR | Success.

IAMAudioInputMixer::get_Enable

IAMAudioInputMixer Interface

Retrieves whether the input is enabled.

Syntax

HRESULT get_Enable(
  BOOL *pfEnable
  );

Parameters

pfEnable
[in] Pointer to a value of type BOOL that indicates whether mixing is enabled for the input. TRUE indicates the input is enabled, FALSE indicates the input is disabled.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Couldn't retrieve information.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
NOERROR | Success.

IAMAudioInputMixer::get_Loudness

IAMAudioInputMixer Interface

Retrieves the loudness control setting for this input.

Syntax

HRESULT get_Loudness(
  int *pfLoudness
  );

Parameters

pfLoudness
[in] Pointer to a variable of type int that indicates whether loudness is on or off; 1 indicates on, 0 indicates off.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Error.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
E_OUTOFMEMORY | Out of memory.
NOERROR | Success.

IAMAudioInputMixer::get_MixLevel

IAMAudioInputMixer Interface

Retrieves the recording level for this input.

Syntax

HRESULT get_MixLevel(
  double *pLevel
  );

Parameters

[out] pLevel
Pointer to a variable of type bool that represents the recording level. Values range between 0 (off) and 1 (full volume). AMF_AUTOMATICGAIN (-0x0001), if supported, means automatic adjustment of level.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Error retrieving recording level.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
NOERROR | Success.

IAMAudioInputMixer::get_Mono

IAMAudioInputMixer Interface

Retrieves whether all channels of an input are combined into a mono signal.

Syntax

HRESULT get_Mono(
  BOOL *pfMono
  );

Parameters

pfMono
[in] Pointer to a variable of type BOOL that indicates whether mono is enabled. TRUE indicates mono is enabled, FALSE indicates mono is disabled.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Error getting mono control.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
NOERROR | Success.

IAMAudioInputMixer::get_Pan

IAMAudioInputMixer Interface

Retrieves the pan level for this input.

Syntax

HRESULT get_Pan(
  double *pPan
  );

Parameters

pPan
[in] Pointer to a variable of type double that represents the pan level. Possible levels are from –1 to 1, with specific values as follows:
–1 | Full left
0 | Center
1 | Full right

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Error retrieving pan level.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Can't pan: not stereo.
NOERROR | Success.

IAMAudioInputMixer::get_Treble

IAMAudioInputMixer Interface

Retrieves the treble equalization for this input.

Syntax

HRESULT get_Treble(
  double *pTreble
  );

Parameters

pTreble
[in] Pointer to a variable of type double that represents the treble gain in decibels (a negative value means attenuate).

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
NOERROR | Success.

IAMAudioInputMixer::get_TrebleRange

IAMAudioInputMixer Interface

Retrieves the treble range for this input.

Syntax

HRESULT get_TrebleRange(
  double *pRange
  );

Parameters

pRange
[out, retval] Pointer to a variable of type double that represents the largest value allowed in the treble range. This is the maximum value allowed in put_Treble. For example, 6.0 means any value between –6.0 and 6.0 is allowed.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
NOERROR | Success.

IAMAudioInputMixer::put_Bass

IAMAudioInputMixer Interface

Sets the bass equalization for this input.

Syntax

HRESULT put_Bass(
  double Bass
  );

Parameters

Bass
[in] Variable of type double that specifies the gain in decibels (a negative value means attenuate).

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Argument is invalid. Must be in range given by get_BassRange.
E_NOTIMPL | Method isn't supported.
NOERROR | Success.

Remarks

Boosts or cuts the signal's bass before it is recorded by the number of decibels specified by Bass.

IAMAudioInputMixer::put_Enable

IAMAudioInputMixer Interface

Enables or disables an input in the mix.

Syntax

HRESULT put_Enable(
  BOOL fEnable
  );

Parameters

fEnable
[in] Variable of type BOOL that specifies whether to enable or disable an input. TRUE enables the input, FALSE disables it.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failed to enable or disable an input.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
NOERROR | Successfully enabled or disabled an input.

Remarks

If disabled, this input will not be mixed in as part of the recorded signal.

IAMAudioInputMixer::put_Loudness

IAMAudioInputMixer Interface

Turns the loudness control for this input on or off.

Syntax

HRESULT put_Loudness(
  BOOL fLoudness
  );

Parameters

fLoudness
[in] Variable of type BOOL that specifies whether loudness is on. TRUE sets loudness on, FALSE sets loudness off.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Loudness control set.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
NOERROR | Success.

Remarks

IAMAudioInputMixer::put_Loudness boosts the bass of low volume signals before they are recorded to compensate for the fact that your ear doesn't hear quiet bass sounds as well as other sounds.

IAMAudioInputMixer::put_MixLevel

IAMAudioInputMixer Interface

Sets the record level for this input.

Syntax

HRESULT put_MixLevel(
  double Level
  );

Parameters

Level
Variable of type double that specifies the recording level. Values range between 0 (off) and 1 (full volume). AMF_AUTOMATICGAIN (-0x0001), if supported, means automatic adjustment of level.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Error setting volume.
E_POINTER | Null pointer argument.
E_INVALIDARG | Record level must be between 0 and 1.
E_NOTIMPL | Automatic gain currently not implemented.
NOERROR | Success.

IAMAudioInputMixer::put_Mono

IAMAudioInputMixer Interface

Combines all channels of an input into a mono signal.

Syntax

HRESULT put_Mono(
  BOOL fMono
  );

Parameters

fMono
[in] Variable of type BOOL that specifies a mono or multichannel signal. TRUE indicates mono, FALSE indicates multichannel.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Error setting mono control.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
NOERROR | Success.

Remarks

When set to mono mode, making a stereo recording of this input will have both channels contain the same data. The result will be a mixture of the left and right signals.

IAMAudioInputMixer::put_Pan

IAMAudioInputMixer Interface

Sets the pan for this input.

Syntax

HRESULT put_Pan(
  double Pan
  );

Parameters

Pan
[in] Variable of type double that specifies the pan level. Possible values for Pan are from -1 to 1, with specific values as follows:
-1 | Full left
0 | Center
1 | Full right

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Error setting volume.
E_POINTER | Null pointer argument.
E_INVALIDARG | Pan level must be between -1 and 1.
E_NOTIMPL | Can't pan: not stereo.
NOERROR | Success.

Remarks

Setting the pan of an input to full left makes that input's signal go only into the left channel of a stereo recording. Panning has no effect for a mono recording.

IAMAudioInputMixer::put_Treble

IAMAudioInputMixer Interface

Sets the treble equalization for this input.

Syntax

HRESULT put_Treble(
  [in] double Treble
  );

Parameters

Treble
[in] Variable of type double that specifies the gain in decibels (a negative value means attenuate).

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Argument is invalid. Must be in range given by get_TrebleRange.
E_NOTIMPL | Method isn't supported.
NOERROR | Success.

Remarks

This method boosts or cuts the signal's treble by a specified number of decibels before it is recorded.


IAMBufferNegotiation Interface

The IAMBufferNegotiation interface is implemented on pins, particularly on pins in capture filters, to enable applications to control the buffer allocation process for the pin.

Teleconferencing applications should use this interface to specify a minimal number of buffers. This tells the capture filter not to waste resources buffering information in slower capture or disk-writing scenarios.

If your application is performing audio preview (sending captured audio to an output device) and you find that the latency is too high, try specifying a smaller number of buffers.

The IAMBufferNegotiation::SuggestAllocatorProperties method accepts an ALLOCATOR_PROPERTIES structure that contains the allocator's count, size, alignment, and prefix properties that you want to use. Typically, you set only the cBuffers member of the ALLOCATOR_PROPERTIES structure, which refers to the number of buffers at the specified allocator. All other properties should indicate a negative number to enable your capture hardware to use its own default values.

If a negative value is specified for cBuffers, the allocator will try to allocate as many buffers as it needs, which depends on the available resources and capture frame rate. If you specify a higher value, the allocator will try to allocate more buffers, up to the system's available memory. Allocating a lower number of buffers can result in dropped frames. For teleconferencing applications, it may be desirable to set this number to a smaller value (for example, 2 is a reasonable setting if the network can only support transmission of 2 frames per second (fps) at a given video format and resolution).

Applications can call the IAMBufferNegotiation::GetAllocatorProperties method to retrieve the properties of the allocator being used.

Filter developers: Implement this interface when your pin will connect to another pin by using the IMemInputPin interface and you want to enable an application to allocate the buffer settings to be used for transporting media samples between filters. All capture filters should support this interface to enable applications to specify precise settings for buffers.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMBufferNegotiation methods | Description
SuggestAllocatorProperties | Asks a pin to use the allocator buffer properties set in the ALLOCATOR_PROPERTIES structure.
GetAllocatorProperties | Retrieves the properties of the allocator being used by a pin.

IAMBufferNegotiation::GetAllocatorProperties

IAMBufferNegotiation Interface

Retrieves the properties of the allocator that a pin is using.

Syntax

HRESULT GetAllocatorProperties(
  ALLOCATOR_PROPERTIES *pprop
  );

Parameters

pprop
[out] Pointer to an ALLOCATOR_PROPERTIES structure.

Return Value

Returns S_OK if successful, otherwise returns an HRESULT value indicating the cause of the failure. Possible error codes include the following:

E_FAIL | Failure.
E_POINTER | NULL pointer.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

Call this method only after the pins connect.

See Also

SuggestAllocatorProperties

IAMBufferNegotiation::SuggestAllocatorProperties

IAMBufferNegotiation Interface

Asks a pin to use the allocator buffer properties set in the ALLOCATOR_PROPERTIES structure.

Syntax

HRESULT SuggestAllocatorProperties(
  const ALLOCATOR_PROPERTIES *pprop
  );

Parameters

pprop
[in] Pointer to an ALLOCATOR_PROPERTIES structure.

Return Value

Returns S_OK if successful, otherwise returns an HRESULT value indicating the cause of the failure. Possible error codes include the following:

E_FAIL | Failure. (Could not use suggested properties.)
E_POINTER | NULL pointer.
E_UNEXPECTED | Unexpected failure.
VFW_E_ALREADY_CONNECTED | Pin is already connected.

Remarks

An application must call this function before two pins are connected. If the pins are connected before you call this method, then the filter graph will have already negotiated the buffer and it will be too late for an application to preallocate them.

Applications must call this method on both pins being connected to ensure that the other pin doesn't overrule the application's request. However, if one pin doesn't support this interface, a single call will be sufficient.

Use a negative number for any element in the ALLOCATOR_PROPERTIES structure to set properties to default values.

See Also

IAMBufferNegotiation::GetAllocatorProperties


IAMCameraControl Interface

The IAMCameraControl interface provides local or remote control over a camera.

This interface should be implemented in Microsoft® DirectShow® for filters that control camera devices that offer some form of device control such as zoom, pan, aperture adjustment, or shutter speed. Note that WDM capture drivers automatically expose this interface from KsProxy.ax if they support the associated kernel streaming property sets.

Applications should use this interface to control device settings such as zoom, pan, aperture adjustment, or shutter speed.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMCameraControl methods | Description
GetRange | Retrieves values associated with the range of a specified camera property.
Set | Sets a camera property.
Get | Retrieves the value of a specific camera control property.

IAMCameraControl::Get

IAMCameraControl Interface

Retrieves the value of a specific camera control property.

Syntax

HRESULT Get (
     long Property,
     long *lValue,
     long *Flags
    );

Parameters

Property
[in] Value that specifies which property from the CameraControlProperty enumerated type to query.
lValue
[out] Pointer to the retrieved value of the specified property. For a description of the possible ranges and values, see Remarks.
Flags
[out] Pointer to a value from the CameraControlFlags enumerated type that indicates whether the camera property is automatic or manual.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

Each property represented from the CameraControlProperty enumerated type can have an automatic or manual setting. If the Flags parameter is set to CameraControl_Flags_Auto from the CameraControlFlags enumerated type, then the lValue parameter is ignored. The lValue range and meaning depends on the property being queried. The following table describes possible values.

Property | lValue range and meaning
Pan | Value that specifies the pan setting in degrees. Values range from –180 to +180, with the default set to zero. Positive values are clockwise from the origin (the camera rotates clockwise when viewed from above), and negative values are counterclockwise from the origin. Note that a particular device might implement only a subset of this range.
Tilt | Value that specifies the tilt setting in degrees. Values range from –180 to +180, with the default set to zero. Positive values point the imaging plane up, and negative values point the imaging plane down. Note that a particular device might implement only a subset of this range.
Roll | Value that specifies the roll setting in degrees. Values range from –180 to +180, with the default being set to zero. Positive values cause a clockwise rotation of the camera along the image viewing axis, and negative values cause a counterclockwise rotation of the camera. Note that a particular device may only implement a subset of this range.
Zoom | Value that specifies the zoom setting in millimeter units. Values range from 10 to 600, and the default is device specific.
Exposure Value that specifies the exposure setting in seconds, by using the following formula. For values less than zero, the exposure time is 1/2n seconds. For positive values and zero, the exposure time is 2n seconds. Note that a particular device might implement only a subset of this range. For example, a device advertises a range of –7 to 1, with stepping set to 1. The corresponding exposure times are:
Value | -7 | -6 | -5 | -4 | -3 | -2 | -1 | 0 | 1
Seconds | 1/128 | 1/64 | 1/32 | 1/16 | 1/8 | 1/4 | 1/2 | 1 | 2
Iris | Value that specifies the iris setting expressed as fstop * 10.
Focus | Value that specifies the focus setting as the distance to the optimally focused target, in millimeters. The range and default values are device specific. Note that a particular device might implement only a subset of this range.

IAMCameraControl::GetRange

IAMCameraControl Interface

Retrieves values associated with the range of a specified camera property.

Syntax

HRESULT GetRange (
     long property,
     long *pMin,
     long *pMax,
     long *pSteppingDelta,
     long *pDefault,
     long *pCapsFlags
    );

Parameters

property
[in] Value that specifies which property from the CameraControlProperty enumerated type to query.
pMin
[out] Pointer to the minimum range for the specified property.
pMax
[out] Pointer to the maximum range for the specified property.
pSteppingDelta
[out] Pointer to the step size for the specified property. The step size is the increment by which the property can change, due to the underlying hardware. (For example, you might have a digital camera that can move in 5-degree increments.)
pDefault
[out] Pointer to the default value of the specified property.
pCapsFlags
[out] Pointer to a value from the CameraControlFlags enumerated type indicating whether the camera property is automatic or manual.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMCameraControl::Set

IAMCameraControl Interface

Sets the value of a specific camera control property.

Syntax

HRESULT Set (
     long Property,
     long lValue,
     long Flags
    );

Parameters

Property
[in] Value that specifies which property from the CameraControlProperty enumerated type to change.
lValue
[in] New value of the specified property.
Flags
[in] Value from the CameraControlFlags enumerated type specifying whether the camera property is automatic or manual.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

Each property represented from the CameraControlProperty enumerated type can have an automatic or manual setting. If the Flags parameter is set to CameraControl_Flags_Auto from the CameraControlFlags enumerated type, then the lValue parameter is ignored. The lValue range and meaning depends on the property being queried. The following table describes possible values.

Property | lValue range and meaning
Pan | Value that specifies the pan setting in degrees. Values range from –180 to +180, with the default set to zero. Positive values are clockwise from the origin (the camera rotates clockwise when viewed from above), and negative values are counterclockwise from the origin. Note that a particular device might implement only a subset of this range.
Tilt | Value that specifies the tilt setting in degrees. Values range from –180 to +180, with the default set to zero. Positive values point the imaging plane up, and negative values point the imaging plane down. Note that a particular device might implement only a subset of this range.
Roll | Value that specifies the roll setting in degrees. Values range from –180 to +180, with the default being set to zero. Positive values cause a clockwise rotation of the camera along the image viewing axis, and negative values cause a counterclockwise rotation of the camera. Note that a particular device may only implement a subset of this range.
Zoom | Value that specifies the zoom setting in millimeter units. Values range from 10 to 600, and the default is device specific.
Exposure Value that specifies the exposure setting in seconds, by using the following formula. For values less than zero, the exposure time is 1/2n seconds. For positive values and zero, the exposure time is 2n seconds. Note that a particular device might implement only a subset of this range. For example, a device advertises a range of –7 to 1, with stepping set to 1. The corresponding exposure times are:
Value | -7 | -6 | -5 | -4 | -3 | -2 | -1 | 0 | 1
Seconds | 1/128 | 1/64 | 1/32 | 1/16 | 1/8 | 1/4 | 1/2 | 1 | 2
Iris | Value that specifies the iris setting expressed as fstop * 10.
Focus | Value that specifies the focus setting as the distance to the optimally focused target, in millimeters. The range and default values are device specific. Note that a particular device might implement only a subset of this range.


IAMClockAdjust Interface

The IAMClockAdjust interface gives timing information from an external source to the filter graph. In the case of multimedia streams, if the application uses both audio and video streams outside the filter graph, it can communicate clock information to the filter graph by using this interface. You can use this to synchronize different streams.

The Microsoft® DirectShow® system reference clock object implements this interface. See IReferenceClock for more information.

Use this interface to adjust the default clock object in DirectShow.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMClockAdjust method | Description
SetClockDelta | Sets the incremental change in time so filter graphs can update their clocks from an outside source.

IAMClockAdjust::SetClockDelta

IAMClockAdjust Interface

Adjusts the clock by passing the reference time to the filter graph. The incremental time change then gets added to the system reference clock object.

Syntax

HRESULT SetClockDelta(
    REFERENCE_TIME rtDelta
);

Parameters

rtDelta
[in] Value representing the time change, in milliseconds.

Return Value

Returns S_OK if successful or E_POINTER if rtDelta is invalid.


IAMCollection Interface

This interface is implemented by the Filter Graph Manager for use by applications written in Microsoft® Visual Basic® or a scripting language.

IAMCollection allows access to collections of objects such as those exporting IPinInfo and IFilterInfo interfaces. For example, the IFilterInfo::get_Pins method retrieves an IAMCollection interface that can be used to access the IPinInfo interfaces for each pin on the filter.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether there is type information available for this dispatch interface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returned successfully.
GetIDsOfNames | Converts text names of properties and methods (including arguments) to their corresponding DISPIDs.
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IAMCollection methods | Description
get_Count | Retrieves the number of items in the collection.
get_NewEnum | Retrieves an enumerator object that implements IEnumVARIANT on this collection.
Item | Retrieves the indexed item from the collection.

IAMCollection::get_Count

IAMCollection Interface

Retrieves the number of items in the collection.

Syntax

HRESULT get_Count(
    LONG *plCount
    );

Parameters

plCount
[out, retval] Pointer to the number of items in the collection.

Return Value

Returns an HRESULT value.

IAMCollection::get_NewEnum

IAMCollection Interface

Retrieves an enumerator object that implements IEnumVARIANT on this collection.

Syntax

HRESULT get_NewEnum(
    IUnknown **ppUnk
    );

Parameters

ppUnk
[out, retval] Address of a pointer to an IUnknown interface for an object that implements IEnumVARIANT on this collection.

Return Value

Returns an HRESULT value.

IAMCollection::Item

IAMCollection Interface

Retrieves the indexed item from the collection.

Syntax

HRESULT Item(
    long lItem,
    IUnknown **ppUnk
    );

Parameters

lItem
[in] Index into the collection.
ppUnk
[out] Address of a pointer to the returned IUnknown interface for the contained item.

Return Value

Returns an HRESULT value.

Remarks

The returned ppUnk parameter represents an object corresponding to the type of objects in the container. It can be an IFilterInfo, IPinInfo, or IMediaTypeInfo object. The index is zero-based.


IAMCopyCaptureFileProgress Interface

The IAMCopyCaptureFileProgress interface contains one method, Progress, which the ICaptureGraphBuilder::CopyCaptureFile method can call to receive information on the progress of a copy operation.

Capture applications can implement this interface to receive information on the percentage complete of the copy operation on the capture file. If an application does not need to receive this information, there is no need to implement the interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMCopyCaptureFileProgress methods | Description
Progress | Called periodically by the ICaptureGraphBuilder::CopyCaptureFile method during capture operations.

IAMCopyCaptureFileProgress::Progress

IAMCopyCaptureFileProgress Interface

Called periodically by the ICaptureGraphBuilder::CopyCaptureFile method during capture operations.

Syntax

HRESULT Progress(
  int iProgress
  );

Parameters

iProgress
[in] Integer between 0 and 100 specifying the percentage of the copy operation that has completed.

Return Value

Return S_OK if successful or S_FALSE if the operation is aborted.

Remarks

Applications typically use the value of iProgress to update a progress bar on the user interface.


IAMCrossbar Interface

The IAMCrossbar interface is implemented by the DirectShow® Analog Video Crossbar filter. This filter is a wrapper filter for crossbars on WDM streaming devices, and therefore always assumes the friendly name of the device it is wrapping. For more information on wrapper filters and WDM streaming devices, see How Hardware Devices Participate in the Filter Graph.

The Analog Video Crossbar routes signals from an analog or digital audio or video source to a video capture filter. The filter is modeled after a general switching matrix, with n inputs and m outputs. Any of the input signals can be routed to one or more of the outputs. A single crossbar can route both video and audio signals. You can also use a video pin to route only the audio portion of a combined signal.

Note A number of methods on this interface take pin indexes as parameters. Pin indexes are computed by using an IEnumPins enumerator. The index values for input pins and output pins both start at zero. You can call the get_PinCounts method to retrieve the number of input and output pins.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMCrossbar methods | Description
get_PinCounts | Retrieves the number of input and output pins.
CanRoute | Determines if the crossbar filter can route the analog or digital signal.
Route | Routes an input pin to an output pin.
get_IsRoutedTo | Retrieves the input pin connected to a given output pin.
get_CrossbarPinInfo | Retrieves a pin that has audio or video data relating to a given pin.

IAMCrossbar::CanRoute

IAMCrossbar Interface

Determines if routing is possible.

Syntax

HRESULT CanRoute (
  long OutputPinIndex,
  long InputPinIndex
  );

Parameters

OutputPinIndex
[in] Output pin.
InputPinIndex
[in] Input pin.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMCrossbar::get_CrossbarPinInfo

IAMCrossbar Interface

Retrieves a pin that has audio or video data relating to a given pin.

Syntax

HRESULT get_CrossbarPinInfo (
  BOOL IsInputPin,

  long PinIndex,

  long *PinIndexRelated,

  long *PhysicalType
  );

Parameters

IsInputPin
[in] Specify TRUE for an input pin; FALSE for an output pin.
PinIndex
[in] Pin to find a related pin for.
PinIndexRelated
[out] Pointer to the index value of the related pin.
PhysicalType
[out] Pointer to the physical type of pin (audio or video). Returns a member of the PhysicalConnectorType enumerated data type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method retrieves, for example, the audio pin related to a given video pin.

IAMCrossbar::get_IsRoutedTo

IAMCrossbar Interface

Retrieves the input pin connected to a given output pin.

Syntax

HRESULT get_IsRoutedTo (

  long OutputPinIndex,

  long *InputPinIndex

  );

Parameters

OutputPinIndex
[in] Output pin.
InputPinIndex
[out] Pointer to the connected input pin.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMCrossbar::get_PinCounts

IAMCrossbar Interface

Retrieves the number of input and output pins.

Syntax

HRESULT get_PinCounts(

  long *OutputPinCount,

  long *InputPinCount

  );

Parameters

OutputPinCount
[out] Pointer to the number of output pins.
InputPinCount
[out] Pointer to the number of input pins.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMCrossbar::Route

IAMCrossbar Interface

Routes an input pin to an output pin.

Syntax

HRESULT Route (
  long OutputPinIndex,
  long InputPinIndex
  );

Parameters

OutputPinIndex
[in] Output pin.
InputPinIndex
[in] Input pin.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Pin indexes are zero based.


IAMDirectSound Interface

This interface is implemented by the DSound Audio Renderer filter. Applications use the IAMDirectSound interface to control whether the application's sounds will still be audible when other sound applications have the focus and to control which of the application's windows is associated with sound.

Note Only the GetWindowFocus and SetWindowFocus methods are currently implemented for this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMDirectSound methods | Description
GetDirectSoundInterface | Not currently implemented.
GetPrimaryBufferInterface | Not currently implemented.
GetSecondaryBufferInterface | Not currently implemented.
ReleaseDirectSoundInterface | Not currently implemented.
ReleasePrimaryBufferInterface | Not currently implemented.
ReleaseSecondaryBufferInterface | Not currently implemented.
SetWindowFocus | Sets the window that will handle sound playback for the current media file.
GetWindowFocus | Retrieves the window that is handling sound playback for the current media file.

IAMDirectSound::GetDirectSoundInterface

IAMDirectSound Interface

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT GetDirectSoundInterface(
  LPDIRECTSOUND *lplpds
);

Parameters

lplpds
Address of a pointer to an IDirectSound interface that will point to the current sound device's interface.

Return Value

Returns E_NOTIMPL.

When implemented, this method should return one of the following values.

E_FAIL | No sound device is available.
E_INVALIDARG | The lplpds parameter is null.
E_NOTIMPL | DirectSound isn't installed.
NOERROR | The method succeeded.

IAMDirectSound::GetPrimaryBufferInterface

IAMDirectSound Interface

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT GetDirectSoundInterface(
  LPDIRECTSOUNDBUFFER *lplpdsb
);

Parameters

lplpdsb
Address of a pointer to an IDirectSoundBuffer interface that will point to the current sound device's primary sound buffer.

Return Value

Returns E_NOTIMPL.

When implemented, this method should return one of the following values.

E_FAIL | No sound device is available.
E_INVALIDARG | The lplpdsb parameter is null.
E_NOTIMPL | DirectSound isn't installed.
NOERROR | The method succeeded.

IAMDirectSound::GetSecondaryBufferInterface

IAMDirectSound Interface

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT GetSecondaryBufferInterface(
  LPDIRECTSOUNDBUFFER *lplpdsb
);

Parameters

lplpdsb
Address of a pointer to an IDirectSoundBuffer interface. On exit, it will point to the current sound device's secondary sound buffer.

Return Value

Returns E_NOTIMPL.

When implemented, this method should return one of the following values.

E_FAIL | No sound device is available.
E_INVALIDARG | The lplpdsb parameter is null.
E_NOTIMPL | DirectSound isn't installed.
NOERROR | The method succeeded.

IAMDirectSound::GetWindowFocus

IAMDirectSound Interface

Retrieves the window that is handling sound playback for the current media file.

Syntax

HRESULT GetWindowFocus(
  HWND hWnd,
  BOOL bMixingOnOrOff
);

Parameters

hWnd
Handle to the sound playback window. If this value is null, the sound isn't associated with a window; note that Windows NT® 4.0 does not currently support windowless sound playback.
bMixingOnOrOff
Value indicating whether to mix the sound (TRUE) or not (FALSE).

Return Value

Returns one of the following values.
E_FAIL | No sound device is available.
E_INVALIDARG | The hWnd argument is invalid.
E_NOTIMPL | DirectSound isn't installed.
NOERROR | The method succeeded.

IAMDirectSound::ReleaseDirectSoundInterface

IAMDirectSound Interface

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT ReleaseDirectSoundInterface(
  LPDIRECTSOUND lpds
);

Parameters

lpds
Pointer to the IDirectSound interface to release.

Return Value

Returns E_NOTIMPL.

When implemented, this method should return one of the following values.

E_FAIL | There are no references to the specified IDirectSound interface, so it can't be released.
E_INVALIDARG | The lpds parameter is null.
NOERROR | The method succeeded.

IAMDirectSound::ReleasePrimaryBufferInterface

IAMDirectSound Interface

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT ReleasePrimaryBufferInterface(
  LPDIRECTSOUNDBUFFER lpdsb

);

Parameters

lpdsb
Pointer to the IDirectSoundBuffer interface to release.

Return Value

Returns E_NOTIMPL.

When implemented, this method should return one of the following values.

E_FAIL | There are no references to the specified IDirectSoundBuffer interface, so it can't be released.
E_INVALIDARG | The lpdsb parameter is null.
NOERROR | The method succeeded.

IAMDirectSound::ReleaseSecondaryBufferInterface

IAMDirectSound Interface

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT ReleaseSecondaryBufferInterface(
  LPDIRECTSOUNDBUFFER lpdsb
);

Parameters

lpdsb
Pointer to the IDirectSoundBuffer interface to release.

Return Value

Returns E_NOTIMPL.

When implemented, this method should return one of the following values.

E_FAIL | There are no references to the specified IDirectSoundBuffer interface, so it can't be released.
E_INVALIDARG | The lpdsb parameter is null.
NOERROR | The method succeeded.

IAMDirectSound::SetWindowFocus

IAMDirectSound Interface

Sets the window that will handle sound playback for the current media file.

Syntax

HRESULT SetWindowFocus(
  HWND hWnd,
  BOOL bMixingOnOrOff
);

Parameters

hWnd
Handle to the sound playback window. If this value is null, the sound will not be associated with any window; note that Windows NT 4.0 does not currently support windowless sound playback.
bMixingOnOrOff
Value indicating whether to mix the sound (TRUE) or not (FALSE).

Return Value

Returns one of the following values.
E_FAIL | No sound device is available.
E_INVALIDARG | The hWnd argument is invalid.
E_NOTIMPL | DirectSound isn't installed.
NOERROR | The method succeeded.


IAMDroppedFrames Interface

The IAMDroppedFrames interface provides information to an application from a capture filter about frames that the filter dropped (that is, did not send), the frame rate achieved (the length of time the graph ran divided by the number of frames not dropped), and the data rate achieved (the length of time the graph ran divided by the average frame size). A high number of dropped frames can detract from the smoothness of the video clip.

If your application uses the IAMStreamControl interface or ICaptureGraphBuilder::ControlStream to turn a pin off, a video capture driver may still be counting dropped and non-dropped frames, whose counts probably don't interest you. If your application is interested in the number of dropped and non-dropped frames only while the pin is ON, you can ask for the dropped and non-dropped counts by calling IAMDroppedFrames::GetNumDropped and IAMDroppedFrames::GetNumNotDropped immediately after turning on a pin with IAMStreamControl::StartAt or ICaptureGraphBuilder::ControlStream, and then subtract those numbers from the numbers returned from subsequent calls to GetNumDropped or GetNumNotDropped to find out just the number dropped while the pin was on (which is probably the figure you are interested in). If your call to IAMStreamControl::StartAt or ICaptureGraphBuilder::ControlStream is not a call to turn the pin on immediately, but instead turns the pin on at some specified time in the future, then you should wait until you get the notification (EC_STREAM_CONTROL_STARTED) before calling GetNumDropped and GetNumNotDropped initially. See the documentation on IAMStreamControl for more information on this. See the CAPTURE sample for an example of a capture application that uses both interfaces correctly.

A capture filter's video output pin should always implement this interface.

Every time a capture filter goes from State_Stopped to State_Paused, it should reset all counts to zero.

For more implementation details regarding this interface, see Write a Video Capture Filter.

Applications should use this interface all the time when capturing to update the current capture status. After capturing is done, applications should use this interface to determine the final capture results.

Note Not all methods of this interface might be implemented. Many filters only implement GetNumDropped and GetNumNotDropped.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMDroppedFrames methods | Description
GetNumDropped | Retrieves the total number of frames that the pin dropped since it last started streaming.
GetNumNotDropped | Retrieves the total number of frames that the pin delivered downstream (did not drop).
GetDroppedInfo | Retrieves an array of frame numbers that were dropped.
GetAverageFrameSize | Retrieves the average size of frames that were not dropped.

IAMDroppedFrames::GetAverageFrameSize

IAMDroppedFrames Interface

Retrieves the average size of frames that the pin dropped.

Syntax

HRESULT GetAverageFrameSize(
    long *plAverageSize );

Parameters

plAverageSize
[out, retval] Pointer to the average size of frames sent out by the pin since the pin started streaming, in bytes.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

If no data is captured in the call to GetAverageFrameSize, plAverageSize will return with the value of zero.

IAMDroppedFrames::GetDroppedInfo

IAMDroppedFrames Interface

Retrieves an array of frame numbers that the pin dropped.

Syntax

HRESULT GetDroppedInfo(
    long lSize,
    long *plArray,
    long *plNumCopied );

Parameters

lSize
[in] Requested number of elements in the array.
plArray
[out] Pointer to the array.
plNumCopied
[out, retval] Pointer to the number of array elements filled in. This number can differ from lSize because the filter determines an arbitrary number of elements to save and it might not save this information for as many frames as you requested.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The filter will fill the array with the frame numbers of up to the first lSize number of frames dropped, and it will set plNumCopied accordingly.

IAMDroppedFrames::GetNumDropped

IAMDroppedFrames Interface

Retrieves the total number of frames that the pin dropped since it last started streaming.

Syntax

HRESULT GetNumDropped(
    long *plDropped );

Parameters

plDropped
[out] Pointer to the total number of dropped frames.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMDroppedFrames::GetNumNotDropped

IAMDroppedFrames Interface

Retrieves the total number of frames that the pin delivered downstream (did not drop).

Syntax

HRESULT GetNumNotDropped(
  long *plNotDropped );

Parameters

plNotDropped
[out] Pointer to the total number of frames that weren't dropped.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.


IAMExtDevice Interface

The IAMExtDevice interface is the base interface for controlling external devices. You can implement this interface to control numerous types of devices; however, the current Microsoft® DirectShow® implementation is specific to VCRs. The IAMExtDevice interface controls general settings of external hardware and is intended to be used in combination with the IAMExtTransport interface, which controls a VCR's more specific settings. You can also implement the IAMTimecodeReader, IAMTimecodeGenerator, and IAMTimecodeDisplay interfaces if your filter manages SMPTE (Society of Motion Picture and Television Engineers) timecode, and the external device has the appropriate features.

Implement this interface when you want to build a filter or application that controls an external device, such as a VCR. Because this interface controls general information about a device, implement the IAMExtTransport interface in addition to control the external device's more specific properties.

An application can directly instantiate and control external devices, such as VCRs, but it is strongly recommended that you always instantiate these devices within the context of a filter graph, even if they are the only filters within the graph.

Use this interface when you want to add external device control to your application.

Applications should use the filter graph to enumerate the filters and then get the IAMExtDevice interface directly from the appropriate filter.

Hardware Requirements

To control an external VCR, certain hardware requirements are recommended. VCRs with an RS-422 serial interface require a special serial port card or an external RS-232-to-RS-422 adapter. In addition, for best performance, your computer should have a serial port card built with a 16550 high-performance UART (Universal Asynchronous Receiver/Transmitter) to sustain higher baud rates, such as 38.4 baud.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMExtDevice methods | Description
GetCapability | Retrieves the capabilities of the external device.
get_ExternalDeviceID | Retrieves the model number of the external device.
get_ExternalDeviceVersion | Retrieves the version number of the external device's operating software.
put_DevicePort | Specifies the communication port to which the external device is connected.
get_DevicePower | Retrieves whether the external device's power mode is on, off, or standby.
put_DevicePower | Sets the external device's power mode to on, off, or standby.
Calibrate | Calibrates the external device's transport mechanism.
get_DevicePort | Retrieves the communication port to which the external device is connected.

IAMExtDevice::Calibrate

IAMExtDevice Interface

Calibrates an external device's transport mechanism.

Syntax

HRESULT Calibrate(
    HEVENT hEvent,
    long Mode,
    long *pStatus
);

Parameters

hEvent
[in] Event used to signal completion of this process.
Mode
[in] Value that activates or deactivates the calibration process. Specify one of the following:
ED_ACTIVE | Activates calibration process.
ED_INACTIVE | Deactivates calibration process.
NULL | Used to determine if current status is active or inactive.
pStatus
[out] Pointer to a variable that will be set to OATRUE to indicate that an event is active or OAFALSE to indicate that it is inactive.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Use this method on certain external devices that require calibration; for example, when rewinding a tape and resetting the counter, or computing the frame offset for a timecode reader or generator.

Filters for various external devices can implement this method differently, depending on the calibration that the device needs. This method assumes the IMediaEventSink interface has already established an event sink, or that another event signaling method has been established.

IAMExtDevice::GetCapability

IAMExtDevice Interface

Retrieves the capabilities of the external device.

Syntax

HRESULT GetCapability(
    long Capability,
    long *pValue,
    double *pdblValue
);

Parameters

Capability
[in] Value that specifies which capability you want to check. This parameter must be one of the following values.
ED_DEVCAP_CAN_RECORD | Checks whether device can record.
ED_DEVCAP_CAN_RECORD_STROBE | Checks whether device can single-frame record.
ED_DEVCAP_CAN_SAVE | Checks whether device can save data.
ED_DEVCAP_DEVICE_TYPE | Checks the external device type.
ED_DEVCAP_HAS_AUDIO | Checks whether device has audio.
ED_DEVCAP_HAS_VIDEO | Checks whether the device has video.
ED_DEVCAP_USES_FILES | Checks whether device has a built-in file system.
pValue
[out] Pointer to a variable that will receive a value indicating the capabilities of the property specified in the Capability parameter. For all properties except ED_DEVCAP_DEVICE_TYPE, this variable will be set to OATRUE if the property is supported or OAFALSE if the property is not supported. For ED_DEVCAP_DEVICE_TYPE, the variable will be set to one of the following:
ED_DEVTYPE_ATR | Audio Tape Recorder
ED_DEVTYPE_CG | Character Generator
ED_DEVTYPE_DDR | Digital Disc Recorder
ED_DEVTYPE_DVE | Digital video effects unit
ED_DEVTYPE_GPI | General purpose interface trigger
ED_DEVTYPE_KEYER | Video keyer
ED_DEVTYPE_LASERDISK | Laser disc
ED_DEVTYPE_MIXER_AUDIO | Audio mixer
ED_DEVTYPE_MIXER_VIDEO | Video mixer
ED_DEVTYPE_ROUTER | Video router
ED_DEVTYPE_TBC | Timebase corrector
ED_DEVTYPE_TCG | Timecode generator/reader
ED_DEVTYPE_VCR | VCR
ED_DEVTYPE_WIPEGEN | Video wipe generator
ED_DEVTYPE_JOYSTICK | Joystick
ED_DEVTYPE_KEYBOARD | Keyboard
pdblValue
[out] Pointer to a variable indicating the capabilities of the specified property (if it is a double value). Pass NULL if not in use.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

All return values are in pValue unless you have large or floating point values to return, in which case they are returned in the pdblValue parameter.

IAMExtDevice::get_DevicePort

IAMExtDevice Interface

Retrieves the communication port to which the external device is connected.

Syntax

HRESULT get_DevicePort(
    long *pDevicePort
);

Parameters

pDevicePort
[out] Pointer to a variable that will be set to one of the following values, indicating which port the device is connected to.
DEV_PORT_1394 | IEEE 1394 Bus
DEV_PORT_ARTI | ARTI driver
DEV_PORT_COM1 | COM1
DEV_PORT_COM2 | COM2
DEV_PORT_COM3 | COM3
DEV_PORT_COM4 | COM4
DEV_PORT_DIAQ | Diaquest driver
DEV_PORT_SIM | Simulation port
DEV_PORT_USB | Universal Serial Bus

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtDevice::put_DevicePort

IAMExtDevice::get_DevicePower

IAMExtDevice Interface

Retrieves the external device's power mode: on, off, or standby.

Syntax

HRESULT get_DevicePower(
    long *pPowerMode
);

Parameters

pPowerMode
[out] Pointer to a variable that will be set to one of the following values indicating the external device's power mode.
ED_POWER_OFF | Off
ED_POWER_ON | On
ED_POWER_STANDBY | Standby

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtDevice::put_DevicePower

IAMExtDevice::get_ExternalDeviceID

IAMExtDevice Interface

Retrieves the model number of the external device.

Syntax

HRESULT get_ExternalDeviceID(
    LPOLESTR *ppszData
);

Parameters

ppszData
[out] Address of a pointer to a variable that will receive the manufacturer-specific identification number or text as a string.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMExtDevice::get_ExternalDeviceVersion

IAMExtDevice Interface

Retrieves the version number of the external device's operating software.

Syntax

HRESULT get_ExternalDeviceVersion(
    LPOLESTR *ppszData
);

Parameters

ppszData
[out] Address of a pointer to a variable that will receive the manufacturer-specific operating software version number from the external device.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMExtDevice::put_DevicePort

IAMExtDevice Interface

Specifies the communication port to which the external device is connected.

Syntax

HRESULT put_DevicePort(
    long DevicePort
);

Parameters

DevicePort
[in] Port to which the device will connect. Specify one of the following:
DEV_PORT_1394 | IEEE 1394 Bus
DEV_PORT_ARTI | ARTI driver
DEV_PORT_COM1 | COM1
DEV_PORT_COM2 | COM2
DEV_PORT_COM3 | COM3
DEV_PORT_COM4 | COM4
DEV_PORT_DIAQ | Diaquest driver
DEV_PORT_MIN | DEV_PORT_SIM
DEV_PORT_SIM | Simulation port (used for "no hardware" simulation)
DEV_PORT_USB | Universal serial bus

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtDevice::get_DevicePort

IAMExtDevice::put_DevicePower

IAMExtDevice Interface

Sets the external device's power mode to either on, off, or standby.

Syntax

HRESULT put_DevicePower(
    long PowerMode
);

Parameters

PowerMode
[in] Value indicating which power mode the device will have. Set to one of the following:
ED_POWER_OFF | Off
ED_POWER_ON | On
ED_POWER_STANDBY | Standby

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtDevice::get_DevicePower


IAMExtTransport Interface

The IAMExtTransport interface provides methods that control specific behaviors of an external VCR. These methods generally set and get the transport properties, which determine how the VCR and the computer exchange data. Because this interface controls specific behaviors of transport, it must be implemented in combination with the IAMExtDevice interface, which controls an external device's general behaviors. If you want to control an external device other than a VCR, you have two options. Either use the methods you need and return E_NOTIMPL for the rest, or design a new interface and aggregate it with IAMExtDevice.

This interface also provides methods that enable developers to define edit events that assist in the content authoring process. Edit events are made up of individual edit properties that are grouped together into edit property sets. These edit property sets can define an actual recording sequence on the transport or a simple positional command. They can, for example, specify certain modes of editing, record the inpoints and outpoints of a recording sequence, or memorize positions called bookmarks. The SetEditPropertySet method creates or registers a group of edit properties, called an edit property set, while the SetEditProperty enables the application to define parameters and values of individual edit properties. Because these are relatively sophisticated situations, their implementation is left to the advanced developer.

Implement this interface if you want to build a filter or application that controls an external device, such as a VCR. Because this interface controls specific information about a device, you should implement it with the IAMExtDevice interface.

An application can directly instantiate and control external device control filters, such as those for VCRs, but it is strongly recommended that you always instantiate them within the context of a filter graph, even if they are the only filter within the graph.

Implementations can vary depending on the type of external device being controlled. With certain devices, methods can return E_NOTIMPL if they are not applicable.

Use this interface if you want a filter to control video and audio tape machines that are external to the computer. Typical uses for this interface include the applications that implement "batch capture" and "print to tape" of audio and video.

Applications should use the filter graph to enumerate the filters and then get the IAMExtTransport interface directly from the appropriate filter.

Hardware Requirements

To control an external VCR, certain hardware requirements are recommended. VCRs with an RS-422 serial interface require a special serial port card or an external RS-232-to-RS-422 adapter. In addition, for best performance, your computer should have a serial port card built with a 16550 high-performance UART to sustain higher baud rates, such as 38.4 baud.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMExtTransport methods | Description
GetCapability | Retrieves the general capabilities of an external transport.
put_MediaState | Sets the current state of the media.
get_MediaState | Retrieves the current state of the media.
put_LocalControl | Sets the state of the external device to local or remote control.
get_LocalControl | Retrieves the state of the external device.
GetStatus | Determines the status of the external transport.
GetTransportBasicParameters | Retrieves the external transport's basic parameter settings.
SetTransportBasicParameters | Sets the external transport's basic parameters.
GetTransportVideoParameters | Retrieves the external transport's video parameter settings.
SetTransportVideoParameters | Sets the video parameters for the external transport.
GetTransportAudioParameters | Retrieves the external transport's audio parameter settings.
SetTransportAudioParameters | Sets audio parameter setting for the external transport.
put_Mode | Sets the movement of the transport to a new mode (play, stop, record, edit, and so on).
get_Mode | Retrieves the mode of the transport (play, stop, record, edit, and so on).
put_Rate | Sets the playback rate for variable-speed external devices.
get_Rate | Retrieves the playback rate set in put_Rate for variable-speed external devices.
GetChase | Retrieves the status of chase mode.
SetChase | Enables or disables chase mode.
GetBump | Retrieves status of bump mode.
SetBump | Temporarily changes the speed of playback for synchronization of multiple external devices.
get_AntiClogControl | Determines if the anti-headclog control is enabled or disabled.
put_AntiClogControl | Enables or disables the transport's anti-headclog control.
GetEditPropertySet | Retrieves the current state of an edit property set.
SetEditPropertySet | Registers an edit property set that describes a group of edit properties.
GetEditProperty | Retrieves individual parameters and values associated with a particular edit property set.
SetEditProperty | Defines individual parameters and values associated with a particular edit property set.
get_EditStart | Determines if the external transport's edit control is active.
put_EditStart | Activates edit control on a capable transport.

IAMExtTransport::get_AntiClogControl

IAMExtTransport Interface

Determines if the anti-headclog control is enabled or disabled.

Syntax

HRESULT get_AntiClogControl(
    long *pEnabled
);

Parameters

pEnabled
[out] Pointer to a value indicating whether anti-headclog is enabled. OATRUE indicates anti-headclog is enabled; OAFALSE indicates disabled.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtTransport::put_AntiClogControl

IAMExtTransport::GetBump

IAMExtTransport Interface

Retrieves the status of bump mode.

Syntax

HRESULT GetBump(
    long *pSpeed,
    long *pDuration
);

Parameters

pSpeed
[out] Pointer to the temporary speed (a multiple of normal speed).
pDuration
[out] Pointer to the duration of a bump in current time format.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method returns the temporary speed and remaining duration for an active "bump".

For supported time formats, see "IAMExtTransport Basic Parms" in DXMedia\Include\Edevdefs.h.

See Also

IAMExtTransport::SetBump

IAMExtTransport::GetCapability

IAMExtTransport Interface

Retrieves the general capabilities of an external transport.

Syntax

HRESULT GetCapability(
    long Capability,
    long *pValue,
    double *pdblValue
);

Parameters

Capability
[in] Capability to query for. Specify one of the following:
ED_TRANSCAP_CAN_BUMP_PLAY | Checks whether transport can vary speed for synchronizing.
ED_TRANSCAP_CAN_DELAY_AUDIO_IN | Checks whether transport does delayed-in audio edits.
ED_TRANSCAP_CAN_DELAY_AUDIO_OUT | Checks whether transport does delayed-out audio edits.
ED_TRANSCAP_CAN_DELAY_VIDEO_IN | Checks whether transport does delayed-in video edits.
ED_TRANSCAP_CAN_DELAY_VIDEO_OUT | Checks whether transport does delayed-out video edits.
ED_TRANSCAP_CAN_EJECT | Checks whether transport can eject its media.
ED_TRANSCAP_CAN_PLAY_BACKWARDS | Checks whether transport can play media in reverse (negative rate).
ED_TRANSCAP_CAN_SET_EE | Checks whether transport can show its input on its output.
ED_TRANSCAP_CAN_SET_PB | Checks whether transport can show media playback on its output.
ED_TRANSCAP_FWD_VARIABLE_MAX | Maximum forward speed (multiple of play speed) in pdblValue.
ED_TRANSCAP_FWD_VARIABLE_MIN | Minimum forward speed (multiple of play speed) in pdblValue.
ED_TRANSCAP_REV_VARIABLE_MAX | Maximum reverse speed (multiple of play speed) in pdblValue.
ED_TRANSCAP_REV_VARIABLE_MIN | Minimum reverse speed (multiple of play speed) in pdblValue.
ED_TRANSCAP_FWD_SHUTTLE_MAX | Maximum forward Shuttle mode speed (multiple of play speed) in pdblValue.
ED_TRANSCAP_LTC_TRACK | Track number of linear timecode (LTC) in pValue.
ED_TRANSCAP_NUM_AUDIO_TRACKS | Number of audio tracks in pValue.
ED_TRANSCAP_FWD_SHUTTLE_MIN | Minimum forward Shuttle speed (multiple of play speed) in pdblValue.
ED_TRANSCAP_REV_SHUTTLE_MAX | Maximum reverse Shuttle mode speed (multiple of play speed) in pdblValue.
ED_TRANSCAP_REV_SHUTTLE_MIN | Minimum reverse Shuttle mode speed (multiple of play speed) in pdblValue.
ED_TRANSCAP_HAS_DT_OATRUE | Specifies device has Dynamic Tracking.
pValue
[out] Pointer to a value indicating whether the capability specified in Capability is supported. Returns OATRUE if it is supported or OAFALSE if not.
pdblValue
[out] Pointer to a value indicating the capabilities of the property specified in Capability.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

All OATRUE and OAFALSE values are returned in pValue; numerical values are returned in pValue or pdblValue. Use the pdblValue parameter to return double values if the pValue parameter is insufficient. Return NULL if one of the parameters is not needed.

IAMExtTransport::GetChase

IAMExtTransport Interface

Retrieves the status of chase mode.

Syntax

HRESULT GetChase(
    long *pEnabled,
    long *pOffset,
    HEVENT *phEvent
);

Parameters

pEnabled
[out] Pointer to a value indicating whether chase is enabled. OATRUE specifies chase enabled; OAFALSE specifies chase disabled.
pOffset
[out] Pointer to an offset from the present time, indicating the offset the transport will maintain while playing.
phEvent
[out] Pointer to the completion notification that will signal that the chase offset is established.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The time for pOffset is given in the current time format (see "IAMExtTransport Basic Parms" in DXMedia\Include\Edevdefs.h for supported time formats).

See Also

IAMExtTransport::SetChase

IAMExtTransport::GetEditProperty

IAMExtTransport Interface

Retrieves the parameters and values associated with a particular edit event.

Syntax

HRESULT GetEditProperty(
    long EditID,
    long Param,
    long *pValue
);

Parameters

EditID
[in] Identification number of the edit property set.
Param
[in] Edit event parameter to determine the value of.
pValue
[out] Pointer to the returned value of the parameter specified in Param: OATRUE, OAFALSE, or a specific value.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtTransport::SetEditProperty

IAMExtTransport::GetEditPropertySet

IAMExtTransport Interface

Retrieves individual parameters and values associated with a particular edit property set.

Syntax

HRESULT GetEditPropertySet(
    long EditID,
    long *pState
);

Parameters

EditID
[in] Identification number of the edit property set.
pState
[out] Pointer to the state of the edit property set. Retrieves one of the following:
DC_SET_ACTIVE | Activates edit property set.
DC_SET_DELETE | Deletes edit property set.
DC_SET_INACTIVE | Deactivates edit property set.
DC_SET_REGISTER | Registers edit property set.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtTransport::SetEditPropertySet

IAMExtTransport::get_EditStart

IAMExtTransport Interface

Determines if the external transport's edit control is active.

Syntax

HRESULT get_EditStart(
    long *pValue
);

Parameters

pValue
[out] Pointer to a value indicating whether edit control is active. Returns OATRUE if edit control is active; OAFALSE if inactive.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtTransport::put_EditStart

IAMExtTransport::get_LocalControl

IAMExtTransport Interface

Retrieves the state of the external device.

Syntax

HRESULT get_LocalControl(
    long *pState
);

Parameters

pState
[out] Pointer to a value indicating local or remote control. Returns OATRUE for local control or OAFALSE for remote.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

To control an external device, it must be in remote mode.

See Also

IAMExtTransport::put_LocalControl

IAMExtTransport::get_MediaState

IAMExtTransport Interface

Retrieves the current state of the media set in put_MediaState.

Syntax

HRESULT get_MediaState(
    long *pState
);

Parameters

pState
[out] Pointer to a returned value indicating the current state of the media. Values will be device specific but can include the following:
ED_MEDIA_SPIN_DOWN | Stopped spinning (for disk media); unthreaded (for tape media).
ED_MEDIA_SPIN_UP | Started spinning but not at full speed (for disk media); threading the tape (for tape media).
ED_MEDIA_UNLOAD | Media is ejected from the drive (if device supports it).

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMExtTransport::get_Mode

IAMExtTransport Interface

Retrieves the mode of the transport (play, stop, record, edit, and so on).

Syntax

HRESULT get_Mode(
    long *pMode
);

Parameters

pMode
[out] Pointer to the current transport mode (see IAMExtTransport::put_Mode for possible modes).

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMExtTransport::get_Rate

IAMExtTransport Interface

Retrieves the playback rate for variable-speed external devices.

Syntax

HRESULT get_Rate(
    double *pdblRate
);

Parameters

pdblRate
[out] Pointer to the playback rate set in IAMExtTransport::put_Rate.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMExtTransport::GetStatus

IAMExtTransport Interface

Returns the extended information about the external transport's status.

Syntax

HRESULT GetStatus(
    long StatusItem,
    long *pValue
);

Parameters

StatusItem
[in] Item you want to determine the status of; can include one of the following:
ED_MODE_EDIT_CUE | Checks if device is cueing for an active edit event.
ED_MODE_FF | Checks if device is fast forwarding.
ED_MODE_FREEZE | Checks if device is paused in the Play mode.
ED_MODE_LINK_OFF | Checks if transport control isn't linked to filter graph's run, stop, and pause controls.
ED_MODE_LINK_ON | Checks if transport control is linked to filter graph's run, stop, pause controls.
ED_MODE_PLAY | Checks if device is playing.
ED_MODE_RECORD | Checks if device is recording.
ED_MODE_RECORD_STROBE | Checks if device is recording single-frame.
ED_MODE_RECORD_FREEZE | Checks if device is paused in the Record Mode.
ED_MODE_REW | Checks if device is rewinding.
ED_MODE_SHUTTLE | Checks if device is shuttling (high-speed movement with visible picture). Use IAMExtTransport::get_Rate to determine actual transport speed.
ED_MODE_STEP_FWD or ED_MODE_STEP | Checks if device is single-stepping (searching one frame at a time) in a forward direction.
ED_MODE_STOP | Checks if device is stopped.
pValue
[out] Pointer to a value indicating whether the item in StatusItem is active. Returns OATRUE if StatusItem is active or OAFALSE if not.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

When implementing this interface, be aware that transport StatusItem parameters are more extensive than most DirectShow interfaces and code should reflect this variety and check the transport status of appropriate parameters.

IAMExtTransport::GetTransportAudioParameters

IAMExtTransport Interface

Retrieves audio parameter setting for external transport.

Syntax

HRESULT GetTransportAudioParameters(
    long Param,
    long *pValue
);

Parameters

Param
[in] Audio parameter whose value you want to get. Specify one of the following:
ED_TRANSAUDIO_ENABLE_OUTPUT | Audio output channel(s)
ED_TRANSAUDIO_ENABLE_RECORD | Audio recording channel(s)
ED_TRANSAUDIO_ENABLE_SELSYNC | Audio selsync recording channel(s)
ED_TRANSAUDIO_SET_MONITOR | Monitor output audio channel(s)
ED_TRANSAUDIO_SET_SOURCE | Audio source channel(s)
pValue
[out] Pointer to the channel or channels set in the IAMExtTransport::SetTransportAudioParameters method.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMExtTransport::GetTransportBasicParameters

IAMExtTransport Interface

Retrieves the transport's basic parameter settings.

Syntax

HRESULT GetTransportBasicParameters(

  long Param,

  long *pValue,

  LPOLESTR *ppszData
);

Parameters

Param
[in] Parameter you want to receive the setting for (for possible parameters, see Edevdefs.h under "IAMExtTransport Basic Parms").
pValue
[out] Pointer to the setting of the parameter if it is numeric.
ppszData
[out] Address of a pointer to the setting of the parameter if it is a string.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtTransport::SetTransportBasicParameters

IAMExtTransport::GetTransportVideoParameters

IAMExtTransport Interface

Retrieves video parameter settings for external transport.

Syntax

HRESULT GetTransportVideoParameters(
    long Param,
    long *pValue
);

Parameters

Param
[in] Video parameter you want to receive the settings for. Can be either ED_TRANSVIDEO_SET_OUTPUT (video transport output parameters) or ED_TRANSVIDEO_SET_SOURCE (video transport input source).
pValue
[out] Pointer to a variable that will receive the video parameters. If Param ED_TRANSVIDEO_SET_SOURCE, pValue will receive the active video input. If Param is set to ED_TRANSVIDEO_SET_OUTPUT, pValue will receive one of the following values:
ED_E2E | Input video is visible on device's output regardless of transport mode.
ED_OFF | Video output is disabled.
ED_PLAYBACK | Video playing from media is displayed on the screen.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtTransport::SetTransportVideoParameters

IAMExtTransport::put_AntiClogControl

IAMExtTransport Interface

Enables or disables transport anti-headclog control.

Syntax

HRESULT put_AntiClogControl(
    long Enable
);

Parameters

Enable
[in] Value indicating whether to enable anti-headclog control; set OATRUE to enable, OAFALSE to disable.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Use this method to unclog video heads on VCRs that have an automatic head-cleaning feature.

See Also

IAMExtTransport::get_AntiClogControl

IAMExtTransport::put_EditStart

IAMExtTransport Interface

Activates the edit control on a capable transport.

Syntax

HRESULT put_EditStart(
    long Value
);

Parameters

Value
[in] Value indicating whether to active the edit control. OATRUE activates the edit control; OAFALSE deactivates it.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Use this method to manually enable edit control. Edit control is defined as the precise enabling of individual, or a set of, record tracks on a VCR; for example, a video-only insert edit, where only the video record head is enabled and a new video signal is recorded—the audio signal is left as is. Use this method to control "on the fly" editing on machines that have this feature.

See Also

IAMExtTransport::get_EditStart

IAMExtTransport::put_LocalControl

IAMExtTransport Interface

Sets the state of the external device to local or remote control.

Syntax

HRESULT put_LocalControl(
    long State
);

Parameters

State
[in] Current state; pass OATRUE for local, OAFALSE for remote.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtTransport::get_LocalControl

IAMExtTransport::put_MediaState

IAMExtTransport Interface

Sets the current state of the media.

Syntax

HRESULT put_MediaState(
    long State
);

Parameters

State
[in] Value specifying the state. Use one of the following:
ED_MEDIA_SPIN_DOWN | Stop spinning (for disc media); unthread the tape (for tape media).
ED_MEDIA_SPIN_UP | Start spinning (for disc media); thread the tape (for tape media).
ED_MEDIA_UNLOAD | Eject the media from the drive (if device supports it).

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Use the preceding parameters for disk and tape media. For other devices, you might need to specify new parameters.

See Also

IAMExtTransport::get_MediaState

IAMExtTransport::put_Mode

IAMExtTransport Interface

Sets the movement of the transport to a new mode (play, stop, record, edit, and so on).

Syntax

HRESULT put_Mode(
    long Mode
);

Parameters

Mode
[in] Transport mode. Specify one of the following:
ED_MODE_PLAY | Play
ED_MODE_STOP | Stop
ED_MODE_FREEZE | Freeze (pause)
ED_MODE_THAW | Resume
ED_MODE_FF | Fast forward
ED_MODE_REW | Rewind
ED_MODE_RECORD | Record
ED_MODE_RECORD_STROBE | Record single frame
ED_MODE_STEP_FWD | Single step forward
ED_MODE_STEP_REV | Single step backward
ED_MODE_SHUTTLE | Shuttle (high-speed movement with visible picture). Use with IAMExtTransport::put_Rate to set the transport speed.
ED_MODE_EDIT_CUE | Position transport to cue point for an active edit event
ED_MODE_LINK_ON | Link this method to the graph's IMediaControl::Run, Stop, and Pause methods
ED_MODE_LINK_OFF | Disengage this method from the graph's IMediaControl::Run, Stop, Pause methods.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMExtTransport::get_Mode

IAMExtTransport::put_Rate

IAMExtTransport Interface

Sets the playback rate for variable-speed external devices.

Syntax

HRESULT put_Rate(
    double dblRate
);

Parameters

dblRate
[in] Multiple of play speed where .5=half, 1=normal, 2=double, 3=triple, and so forth.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method enables an application to speed up or slow down playback relative to the normal default playback speed. A rate of 1.0 indicates normal playback speed. Specifying 2.0 causes playback at twice the normal rate.

You can also link this method to the IMediaPosition::put_Rate method as an alternate means of setting rates of playback relative to normal speed.

See Also

IAMExtTransport::get_Rate

IAMExtTransport::SetBump

IAMExtTransport Interface

Temporarily changes the speed of playback for synchronization of multiple external devices.

Syntax

HRESULT SetBump(
    long Speed,
    long Duration
);

Parameters

Speed
[in] Temporary speed (a multiple of normal speed).
Duration
[in] Duration of a bump in current time format.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method will cause a temporary speed variation of transport used during the physical synchronization process. This method will stay in effect until Duration time has expired.

For supported time formats, see "IAMExtTransport Basic Parms" in DXMedia\Include\Edevdefs.h.

See Also

IAMExtTransport::GetBump

IAMExtTransport::SetChase

IAMExtTransport Interface

Enables or disables chase mode.

Syntax

HRESULT SetChase(
    long Enable,
    long Offset,
    HEVENT hEvent
);

Parameters

Enable
[in] Value specifying whether chase is enabled. Specify OATRUE to enable chase; OAFALSE to disable.
Offset
[in] Offset from the time reference that the transport will maintain. Specify in current time format.
hEvent
[in] Event to signal offset established.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Use the SetChase method when you want an external transport to continuously follow a timecode signal with a fixed offset. For example, if your computer is generating timecode, it can tell a VCR capable of chasing to put itself in play mode and keep its media a fixed offset from the reference timecode. You determine the offset by comparing the timecode on the playback media to the reference (generated) timecode.

This method will stay in effect until canceled or complete and requires the filter to verify (by periodically reading the transport's timecode) that the transport is indeed maintaining the fixed offset.

Time for Offset is specified in current time format (for supported time formats, see "IAMExtTransport Basic Parms" in DXMedia\Include\Edevdefs.h).

See Also

IAMExtTransport::GetChase

IAMExtTransport::SetEditProperty

IAMExtTransport Interface

Defines individual parameters and values associated with a particular edit property set.

Syntax

HRESULT SetEditProperty(
    long EditID,
    long Param,
    long Value
);

Parameters

EditID
[in] Identification number of the edit property set.
Param
[in] Edit event parameter to define.
Value
[in] Value of the parameter specified in Param. Use OATRUE, OAFALSE, or a specific value.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Edit events can either refer to a group of predefined properties that define an actual recording sequence, or they can refer to simple positional commands. They can, for example, specify certain modes of editing, record inpoints and outpoints, or memorize positions called bookmarks. The SetEditPropertySet method defines and registers a group of edit events, called an edit property set, while the SetEditProperty method enables the user to define parameters and values of individual edit events.

To define a set of edit properties, first register an edit property set and get an EditID with the SetEditPropertySet method. Then use the SetEditProperty method to define specific parameters and values of individual edit properties. Finally, use the SetEditPropertySet method to activate the edit property set.

The file header file Edevdefs.h includes a complete listing of possible parameters and values for edit property sets.

See Also

IAMExtTransport::GetEditProperty

IAMExtTransport::SetEditPropertySet

IAMExtTransport Interface

Registers an edit property set that describes a group of edit properties.

Syntax

HRESULT SetEditPropertySet(
    long *pEditID,
    long State
);

Parameters

pEditID
[in, out] Pointer to the identification number of the edit property set.
State
[in] State of the edit property set. Specify one of the following:
DC_SET_ACTIVE | Activates edit property set.
DC_SET_DELETE | Deletes edit property set.
DC_SET_INACTIVE | Inactivates edit property set.
DC_SET_REGISTER | Registers edit property set.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Edit events refer to a group of predefined properties that define an actual recording sequence on the transport or a simple positional command. They can, for example, specify certain modes of editing, record inpoints and outpoints, or memorize positions called bookmarks. The SetEditPropertySet method defines and registers a group of edit properties, called an edit property set, while the SetEditProperty enables the user to define parameters and values of individual edit event properties.

To define a set of edit properties, first register an edit property set and get an EditID with the SetEditPropertySet method. The implementation of this method handles memory allocation for the property set. Then use the SetEditProperty method to define specific parameters and values of individual edit properties. Finally, use the SetEditPropertySet method to activate the edit property set.

For example, you would configure an insert edit on all tracks as shown in the following code.

// Register an edit property set ID (causes memory to be allocated)
SetEditPropertySet(&EditID, ED_REGISTER);

// Set the edit mode.
SetEditProperty(EditID, ED_EDIT_MODE, ED_EDIT_MODE_INSERT);

// Set the particulars about the event.
SetEditProperty(EditID, ED_EDIT_TRACK, ED_VIDEO | ED_AUDIO_ALL);
SetEditProperty(EditID, ED_REHEARSE_MODE, ED_EDIT_PERFORM);

// (Set the record and source times and so on.)

SetEditPropertySet(pEditID, ED_ACTIVE); // Activate it.
SetEditProperty(EditID, ED_EDIT_SEEK, OATRUE); // Cue up the machine.

// (Now start the graph.)

To do an immediate edit (editing "on the fly"), use the ED_EDIT_IMMEDIATE edit property.

You can also use the edit property set mechanism to do timecode searches. To do this, set the following properties.

  1. ED_EDIT_SRC_INPOINT to the target timecode value
  2. ED_EDIT_SEEK_MODE to ED_EDIT_SEEK_EDIT_IN
  3. ED_EDIT_SEEK to OATRUE—this initiates the search operation

VCR control filters can support one of several modes of editing and synchronization control:

  • Single machine master: This is the most common configuration for nonlinear editors. A single VCR is used for capture of source material as well as for recording the final product. The VCR's timecode is used as a master clock reference for the filter graph. This mode has the least demanding mechanical synchronization requirements for the VCR, because the digital playback engine is easier to synchronize to the reference clock than an external, mechanical device.
  • Single machine, synchronized to the reference clock: A single VCR is used for capture and playback. The VCR is synchronized the filter graph's reference clock.
  • Multiple machines with one as the master: This is a common configuration for linear and hybrid editors. It requires synchronizing the filter graph's clock to the master (record) VCR, and then synchronizing the playback VCR to the filter graph's clock.
  • Multiple machines, all synchronized to the reference clock: This is also common for linear and hybrid editors, and all VCRs synchronize to the filter graph's clock.

Determine master/subordinate mode for a particular device by testing the ED_TRANSCAP_IS_MASTER item with the IAMExtTransport::GetCapability method.

It is relatively straightforward to synchronize filter graph playback to a master VCR by using SMPTE timecode. The TIMECODE_SAMPLE returned from the IAMTimecodeReader::GetTimecode method contains a reference clock time stamp that reflects the time relationship between the VCR's frame position and the filter graph's clock. You can use this offset to trigger digital capture of playback with the stream control interfaces.

Synchronizing a VCR to the filter graph's clock requires sending a target time offset to the VCR control filter. In the simplest case, you can do this by implementing the IAMExtTransport::SetChase method. For single or multiple event edit support, use the ED_EDIT_OFFSET property of the edit property set.

For a complete listing of possible parameters and values for edit property sets, see Edevdefs.h in the DXMedia\Include folder.

See Also

IAMExtTransport::GetEditPropertySet

IAMExtTransport::SetTransportAudioParameters

IAMExtTransport Interface

Sets audio parameter setting for external transport.

Syntax

HRESULT SetTransportAudioParameters(
    long Param,
    long Value
);

Parameters

Param
[in] Audio parameter you want to set. Specify one of the following.
ED_TRANSAUDIO_ENABLE_OUTPUT | Enable audio channel(s) for output.
ED_TRANSAUDIO_ENABLE_RECORD | Enable audio channel(s) for recording.
ED_TRANSAUDIO_ENABLE_SELSYNC | Enable audio channel(s) for selsync recording.
ED_TRANSAUDIO_SET_MONITOR | Set the monitor output source.
ED_TRANSAUDIO_SET_SOURCE | Set the active audio input.
Value
[in] Audio channel or channels to set the parameter on.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Specify an exact channel or channels in Value by selecting ED_AUDIO_1 through ED_AUDIO_24 (use an or switch to combine), or all channels by selecting ED_AUDIO_ALL.

See Also

IAMExtTransport::GetTransportAudioParameters

IAMExtTransport::SetTransportBasicParameters

IAMExtTransport Interface

Sets basic parameters of external transport.

Syntax

HRESULT SetTransportBasicParameters(
    long Param,
    long Value,
    LPCOLESTR pszData
);

Parameters

Param
[in] Parameter you want to set (see Edevdefs.h for possible parameters under "IAMExtTransport Basic Parms").
Value
[in] Setting of the parameter if it is numeric.
pszData
[in] Pointer to the setting of the parameter if it is a string.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Basic settings include time formats, record formats, preroll setting, servo setting, and others (see Edevdefs.h).

See Also

IAMExtTransport::GetTransportBasicParameters

IAMExtTransport::SetTransportVideoParameters

IAMExtTransport Interface

Sets video parameters for external transport.

Syntax

HRESULT SetTransportVideoParameters(
    long Param,
    long Value
);

Parameters

Param
[in] Video parameter you want to set. Specify either ED_TRANSVIDEO_SET_OUTPUT (video transport output parameters) or ED_TRANSVIDEO_SET_SOURCE (video transport physical input).
Value
[in] Set the ED_TRANSVIDEO_SET_SOURCE flag to set the active video input, or set the ED_TRANSVIDEO_SET_OUTPUT flag to one of the following values.
ED_E2E | Input video is visible on device's output regardless of transport mode.
ED_OFF | Video output is disabled.
ED_PLAYBACK | Video playing from media is displayed on the screen.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

For the ED_TRANSVIDEO_SET_SOURCE flag, an external device filter uses physical pins to describe its inputs. Calls to the filter's pin enumerator will return an index value. The value is passed to this method as its as its Value parameter.

See Also

IAMExtTransport::GetTransportVideoParameters


IAMFilterMiscFlags Interface

The IAMFilterMiscFlags interface provides a way for the Filter Graph Manager to determine whether a filter's data stream is source data or data being rendered and thus how many EC_COMPLETE notifications to expect before a movie is done. This interface is implemented on the VFW Capture Filter, the File Writer, and the Audio Capture filter.

Applications don't use this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMFilterMiscFlags method | Description
GetMiscFlags | Retrieves the filter status flag.

IAMFilterMiscFlags::GetMiscFlags

IAMFilterMiscFlags Interface

Retrieves the filter status flag.

Syntax

ULONG GetMiscFlags(void);

Return Value

Returns AM_FILTER_MISC_FLAGS_IS_RENDERED if the stream is being rendered. Returns AM_FILTER_MISC_FLAGS_IS_SOURCE if the stream is the source data. Both flags are defined in the AM_FILTER_MISC_FLAGS enumeration. If the filter supports IMediaSeeking and renders some streams, then AM_FILTER_MISC_FLAGS_IS_RENDERER should be returned.


IAMGraphStreams Interface

This interface provides methods for controlling the behavior of a filter graph that renders a live source. (A live source is one that streams data in real time, such as a capture device or a network broadcast). The Filter Graph Manager implements this interface.

Applications can call methods on this interface to specify how the graph handles latency and synchronization when rendering a live source. For more information, see Live Sources.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMGraphStreams methods | Description
FindUpstreamInterface | Searches upstream from the specified pin for a pin or filter that supports the specified interface.
SyncUsingStreamOffset | Enables or disables synchronization using time-stamp offsets.
SetMaxGraphLatency | Sets the maximum latency for the graph.

IAMGraphStreams::FindUpstreamInterface

IAMGraphStreams Interface

Searches upstream from the specified pin for a pin or filter that supports the specified interface.

Syntax

HRESULT FindUpstreamInterface(
    IPin *pPin,
    REFIID riid,
    void **ppvInterface,
    DWORD dwFlags
);

Parameters

pPin
[in] Pointer to the IPin interface of the pin from which to begin searching.
riid
[in] Reference identifier of the interface to find.
ppvInterface
[out, iid_is(riid)] Address of a void pointer. If the method succeeds, this variable receives a pointer to the interface specified by riid.
dwFlags
[in] Combination of flags from the AM_INTF_SEARCH_FLAGS enumeration, specifying what to search (pins or filters).

Return Value

Returns one of the following HRESULT values.

E_NOINTERFACE | Interface not found.
E_POINTER | Invalid pointer.
S_OK | Success.

IAMGraphStreams::SetMaxGraphLatency

IAMGraphStreams Interface

Sets the maximum latency for the graph. You must call the SyncUsingStreamOffset method before calling this method.

Syntax

HRESULT SetMaxGraphLatency(
    REFERENCE_TIME rtMaxGraphLatency
);

Parameters

rtMaxGraphLatency
[in] Reference time that specifies the maximum latency.

Return Value

Returns S_OK if successful. If SyncUsingStreamOffset was not called, the method returns E_FAIL. Otherwise, it returns another HRESULT value.

Remarks

At connection time, some live source filters use the maximum latency to determine the size of buffer to allocate. Calling this method before constructing the graph can help to ensure that sufficient buffers are allocated for the expected latency.

IAMGraphStreams::SyncUsingStreamOffset

IAMGraphStreams Interface

Enables or disables synchronization using time-stamp offsets.

Syntax

HRESULT SyncUsingStreamOffset(
    BOOL bUseStreamOffset
);

Parameters

bUseStreamOffset
[in] Boolean value indicating whether to use a time-stamp offset. If TRUE, live sources will use a time-stamp offset to synchronize streams.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

By default, the filter graph does not attempt to synchronize live streams by means of time-stamp offsets. Call this method with a value of TRUE if you want the filter graph to determine the maximum latency in the graph and adjust time stamps accordingly. For more information, see IAMPushSource::SetStreamOffset.


IAMLatency Interface

This interface provides a method for a filter to report the amount of latency that it introduces into the graph. Latency is defined as the time that it takes the filter to process a sample. For a source filter, latency is the filter's maximum buffer size, measured in time. For example, a video capture filter that buffers one frame at 30 frames per second introduces a latency of about 33 milliseconds.

Currently, there is no support for using this interface by itself. A source filter that streams live or real-time data should implement the IAMPushSource interface, which inherits from this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMLatency methods | Description
GetLatency | Retrieves the expected latency associated with this filter.

IAMLatency::GetLatency

IAMLatency Interface

Retrieves the expected latency associated with this filter.

Syntax

HRESULT GetLatency(
    REFERENCE_TIME *prtLatency
);

Parameters

prtLatency
[in] Pointer to a variable that receives a reference time indicating the latency.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.


IAMLine21Decoder Interface

The IAMLine21Decoder interface is implemented by the Line 21 Decoder filter. This interface provides access to closed-captioned information and settings and is primarily used by applications to turn closed-captioning on and off.

Closed-captioned information is transmitted on line 21 of field 1 in the vertical blanking interval (VBI) of television signals. Video cassette recorders record this information on video tape, and you can use the Line21 Decoder and other Microsoft® DirectShow® filters to capture the line 21 data and save it on disk in a media file format such as Audio-Video Interleaved (AVI). The closed-captioned information appears as a separate stream within the media file.

Closed-captioned text is currently used in live television programming as well as in DVD movies. DVD movies contain line 21 data as part of the user data section of each Group of Pictures (GOP) in the video stream. Television receiver cards with Windows Driver Model (WDM) drivers provide line 21 data.

Applications can call the GetDrawBackgroundMode and SetDrawBackgroundMode methods so the user can select transparent or opaque captioning.

Requirements

Requires Il21dec.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMLine21Decoder methods | Description
GetDecoderLevel | Retrieves the closed-captioned decoder level.
GetCurrentService | Retrieves the current closed captioning service selected by the user.
SetCurrentService | Sets the current closed captioning service.
GetServiceState | Retrieves the closed captioning service state (on or off).
SetServiceState | Sets the closed captioning service state.
GetOutputFormat | Retrieves information about output video characteristics such as size and bit depth.
SetOutputFormat | Not implemented on the DirectShow Line21 Decoder Filter. Sets information that describes output video characteristics such as size and bit depth.
GetBackgroundColor | Retrieves the physical color to use as background for overlays.
SetBackgroundColor | Sets the physical color to use as background for overlays.
GetRedrawAlways | Retrieves whether the renderer should redraw the whole output bitmap for each sample.
SetRedrawAlways | Sets whether the renderer should redraw the whole output bitmap for each sample.
GetDrawBackgroundMode | Retrieves whether the caption text background should be opaque or transparent.
SetDrawBackgroundMode | Sets whether to make the caption text background opaque or transparent.

IAMLine21Decoder::GetBackgroundColor

IAMLine21Decoder Interface

Retrieves the physical color to use as background for overlays.

Syntax

HRESULT GetBackgroundColor(
    DWORD *pdwPhysColor
);

Parameters

pdwPhysColor
Pointer to the retrieved value indicating the background color. The color value is a DWORD consisting of an RGB triple combined using a bitwise OR. The number of bits in each color component depends on the current bit depth.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if a parameter is invalid or NOERROR to indicate success.

Remarks

Magenta is the default background color.

See Also

IAMLine21Decoder::SetBackgroundColor

IAMLine21Decoder::GetCurrentService

IAMLine21Decoder Interface

Retrieves the current closed captioning service selected by the user.

Syntax

HRESULT GetCurrentService(
    AM_LINE21_CCSERVICE *lpService
);

Parameters

lpService
Pointer to the current service. This value is a member of the AM_LINE21_CCSERVICE enumerated data type. The default service is AM_L21_CCSERVICE_Caption1.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if a parameter is invalid or NOERROR to indicate success.

See Also

IAMLine21Decoder::SetCurrentService

IAMLine21Decoder::GetDecoderLevel

IAMLine21Decoder Interface

Retrieves the closed-captioned decoder level.

Syntax

HRESULT GetDecoderLevel(
    AM_LINE21_CCLEVEL *lpLevel
);

Parameters

lpLevel
Pointer to the retrieved decoder level. AM_L21_CCLEVEL_TC2 (TC2) is the only supported operating channel level and is an enhanced and backward-compatible version of the original TC1 level.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if a parameter is invalid or NOERROR to indicate success.

Remarks

This method is for informational purposes only.

TC1 and TC2 are television set decoder levels that represent whether the television can handle some closed-captioned byte pairs and produce the desired captioning results. The Line 21 Decoder is capable of TC2 level decoding, which includes all TC1 decoding. Only the first 100,000 television sets manufactured that included closed-captioned capability were TC1 compliant; the later TV sets are TC2 compliant.

IAMLine21Decoder::GetDrawBackgroundMode

IAMLine21Decoder Interface

Retrieves whether the caption text background should be opaque or transparent.

Syntax

HRESULT GetDrawBackgroundMode(
    AM_LINE21_DRAWBGMODE *lpMode
);

Parameters

lpMode
Pointer to the retrieved mode, either AM_L21_DRAWBGMODE_Opaque or AM_L21_DRAWBGMODE_Transparent.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if a parameter is invalid or NOERROR to indicate success.

Remarks

By default, the caption background is opaque.

See Also

IAMLine21Decoder::SetDrawBackgroundMode

IAMLine21Decoder::GetOutputFormat

IAMLine21Decoder Interface

Retrieves information about output video characteristics such as size and bit depth.

Syntax

HRESULT GetOutputFormat(
    LPBITMAPINFOHEADER lpbmih
);

Parameters

lpbmih
Pointer to the retrieved BITMAPINFOHEADER structure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

If successful, the default implementation returns S_FALSE if downstream filters haven't defined an output format, or S_OK if an output format has been defined.

Remarks

The default video output size is 320 × 240 pixels.

IAMLine21Decoder::GetRedrawAlways

IAMLine21Decoder Interface

Retrieves whether the renderer should redraw the whole output bitmap for each sample.

Syntax

HRESULT GetRedrawAlways(
    LPBOOL lpbOption
);

Parameters

lpbOption
Pointer to a value indicating whether the whole bitmap should be redrawn; FALSE by default, indicating don't always redraw. TRUE means always redraw.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if a parameter is invalid or NOERROR to indicate success.

See Also

IAMLine21Decoder::SetRedrawAlways

IAMLine21Decoder::GetServiceState

IAMLine21Decoder Interface

Retrieves the closed captioning service state (on or off).

Syntax

HRESULT GetServiceState(
    AM_LINE21_CCSTATE *lpState
);

Parameters

lpState
Pointer to the retrieved state. Supported state values are AM_L21_CCSTATE_On and AM_L21_CCSTATE_Off. Closed-captioned text is off by default.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if a parameter is invalid or NOERROR to indicate success.

See Also

IAMLine21Decoder::SetServiceState

IAMLine21Decoder::SetBackgroundColor

IAMLine21Decoder Interface

Sets the physical color to use as background for overlays.

Syntax

HRESULT SetBackgroundColor(
    DWORD dwPhysColor
);

Parameters

dwPhysColor
DWORD value that specifies the physical background color. The color is specified as an RGB triple combined using a bitwise OR. The number of bits in each color component depends on the current bit depth.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if a parameter is invalid or NOERROR to indicate success.

Remarks

Magenta is the default background color.

See Also

IAMLine21Decoder::GetBackgroundColor

IAMLine21Decoder::SetCurrentService

IAMLine21Decoder Interface

Sets the current closed captioning service.

Syntax

HRESULT SetCurrentService(
    AM_LINE21_CCSERVICE Service
);

Parameters

Service
Specified service. This value is a member of the AM_LINE21_CCSERVICE enumerated data type. The default service is AM_L21_CCSERVICE_Caption1.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if a parameter is invalid or NOERROR to indicate success.

See Also

IAMLine21Decoder::GetCurrentService

IAMLine21Decoder::SetDrawBackgroundMode

IAMLine21Decoder Interface

Sets whether to make the caption text background opaque or transparent.

Syntax

HRESULT SetDrawBackgroundMode(
    AM_LINE21_DRAWBGMODE Mode
);

Parameters

Mode
Mode to set. Supported mode values are AM_L21_DRAWBGMODE_Opaque and AM_L21_DRAWBGMODE_Transparent.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if a parameter is invalid or NOERROR to indicate success.

Remarks

By default, the caption background is opaque.

See Also

IAMLine21Decoder::GetDrawBackgroundMode

IAMLine21Decoder::SetOutputFormat

IAMLine21Decoder Interface This method is not implemented on the DirectShow® Line21 Decoder Filter. Sets information that describes output video characteristics such as size and bit depth.

Syntax

HRESULT SetOutputFormat(
    LPBITMAPINFO lpbmi
);

Parameters

lpbmi
Pointer to the specified BITMAPINFO structure containing the desired output format.

Return Value

Returns E_NOTIMPL on the DirectShow Line21 Decoder Filter's implementation of the interface.

Remarks

The default video output size is 320 × 240 pixels.

See Also

IAMLine21Decoder::GetOutputFormat

IAMLine21Decoder::SetRedrawAlways

IAMLine21Decoder Interface

Sets whether the renderer should redraw the whole output bitmap for each sample.

Syntax

HRESULT SetRedrawAlways(
    BOOL bOption
);

Parameters

bOption
Value indicating whether the whole bitmap should be redrawn. TRUE indicates redraw always, FALSE means do not redraw always.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if a parameter is invalid or NOERROR to indicate success.

Remarks

Call this method from your filter if it dirties the buffer that it provides to the Line 21 Decoder filter. Typically, a mixer filter resides in the filter graph directly downstream from the Line 21 Decoder filter. The mixer filter should call this method and set bOption to TRUE to ensure the entire bitmap is redrawn properly.

A downstream mixer (or any filter that needs to do so) should only call this method with bOption set to TRUE if it provides the same buffer to the Line 21 Decoder as it uses to mix secondary video streams(s).

Redrawing (setting bOption to TRUE) degrades performance and increases CPU load, because it negates any potential optimizations.

See Also

IAMLine21Decoder::GetRedrawAlways

IAMLine21Decoder::SetServiceState

IAMLine21Decoder Interface

Sets the closed captioning service state.

Syntax

HRESULT SetServiceState(
    AM_LINE21_CCSTATE State
);

Parameters

State
Specified state. Supported state values are AM_L21_CCSTATE_On and AM_L21_CCSTATE_Off. Closed-captioned text is off by default.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if a parameter is invalid or NOERROR to indicate success.

See Also

IAMLine21Decoder::GetServiceState


IAMMediaContent Interface

Retrieves metadata from a stream. Applications can use this interface to retrieve information encoded into a stream, such as the author, title, and copyright. This interface is typically exposed by parser filters, such as the AVI Splitter and the MPEG-1 Stream Splitter.

Depending on the stream type, a filter might support a subset of the methods on this interface. For example, the AVI Splitter retrieves the copyright, author name, and title from INFO chunks in the AVI file. The remaining methods return E_NOTIMPL.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether type information is available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returns successfully.
GetIDsOfNames | Converts text names of properties and methods, including arguments, to their corresponding dispatch identifiers (DISPIDs).
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IAMMediaContent methods | Description
get_AuthorName | Retrieves the author name.
get_Title | Retrieves the title.
get_Rating | Retrieves the rating.
get_Description | Retrieves a description of the content.
get_Copyright | Retrieves copyright information.
get_BaseURL | Retrieves a base URL for the related Web content.
get_LogoURL | Retrieves a URL for the logo.
get_LogoIconURL | Retrieves a URL for the logo icon.
get_WatermarkURL | Retrieves a URL for the watermark.
get_MoreInfoURL | Retrieves a URL for additional information about the content.
get_MoreInfoBannerImage | Retrieves an image for a related-information banner.
get_MoreInfoBannerURL | Retrieves a URL for a related-information banner.
get_MoreInfoText | Retrieves additional information as text.

IAMMediaContent::get_AuthorName

IAMMediaContent Interface

Retrieves the author name.

Syntax

HRESULT get_AuthorName(
    BSTR *pbstrAuthorName
);

Parameters

pbstrAuthorName
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_Title

IAMMediaContent Interface

Retrieves the title.

Syntax

HRESULT get_Title(
    BSTR *pbstrTitle
);

Parameters

pbstrTitle
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_Rating

IAMMediaContent Interface

Retrieves the rating.

Syntax

HRESULT get_Rating(
    BSTR *pbstrRating
);

Parameters

pbstrRating
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_Description

IAMMediaContent Interface

Retrieves a description of the content.

Syntax

HRESULT get_Description(
    BSTR *pbstrDescription
);

Parameters

pbstrDescription
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_Copyright

IAMMediaContent Interface

Retrieves copyright information.

Syntax

HRESULT get_Copyright(
    BSTR *pbstrCopyright
);

Parameters

pbstrCopyright
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_BaseURL

IAMMediaContent Interface

Retrieves a base URL for the related Web content.

Syntax

HRESULT get_BaseURL(
    BSTR *pbstrBaseURL
);

Parameters

pbstrBaseURL
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_LogoURL

IAMMediaContent Interface

Retrieves a URL for the logo.

Syntax

HRESULT get_LogoURL(
    BSTR *pbstrLogoURL
);

Parameters

pbstrLogoURL
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_LogoIconURL

IAMMediaContent Interface

Retrieves a URL for the logo icon.

Syntax

HRESULT get_LogoIconURL(
    BSTR *pbstrLogoURL
);

Parameters

pbstrLogoURL
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_WatermarkURL

IAMMediaContent Interface

Retrieves a URL for the watermark.

Syntax

HRESULT get_WatermarkURL(
    BSTR *pbstrWatermarkURL
);

Parameters

pbstrWatermarkURL
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_MoreInfoURL

IAMMediaContent Interface

Retrieves a URL for additional information about the content.

Syntax

HRESULT get_MoreInfoURL(
    BSTR *pbstrMoreInfoURL
);

Parameters

pbstrMoreInfoURL
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_MoreInfoBannerImage

IAMMediaContent Interface

Retrieves an image for a related-information banner.

Syntax

HRESULT get_MoreInfoBannerImage(
    BSTR *pbstrMoreInfoBannerImage
);

Parameters

pbstrMoreInfoBannerImage
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_MoreInfoBannerURL

IAMMediaContent Interface

Retrieves a URL for a related-information banner.

Syntax

HRESULT get_MoreInfoBannerURL(
    BSTR *pbstrMoreInfoBannerURL
);

Parameters

pbstrMoreInfoBannerURL
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.

IAMMediaContent::get_MoreInfoText

IAMMediaContent Interface

Retrieves additional information as text.

Syntax

HRESULT get_MoreInfoText(
    BSTR *pbstrMoreInfoText
);

Parameters

pbstrMoreInfoText
Pointer to a variable that receives a BSTR with the information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_NOT_FOUND | Item not found.

Remarks

If the method succeeds, the caller must free the returned BSTR by calling the SysFreeString function.


IAMOpenProgress Interface

Reports the progress of a file-open operation.

Filters that open files over a network can expose this interface. An application can use it to query the progress of the download, or to abort the download. If the network is not responsive, a method such as IGraphBuilder::RenderFile might block for an indefinite period. To prevent your application from blocking, create a worker thread that uses IAMOpenProgress to monitor the progress. The worker thread can abort the operation if a predefined timeout occurs, or in response to a command from the user.

The URL File Source filter supports this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMOpenProgress methods | Description
QueryProgress | Retrieves the progress of the file-open operation.
AbortOperation | Aborts the file-open operation.

IAMOpenProgress::AbortOperation

IAMOpenProgress Interface

Aborts the file-open operation.

Syntax

HRESULT AbortOperation(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

IAMOpenProgress::QueryProgress

IAMOpenProgress Interface

Retrieves the progress of the file-open operation.

Syntax

HRESULT QueryProgress(
    LONGLONG *pllTotal,
    LONGLONG *pllCurrent
);

Parameters

pllTotal
[out] Pointer to a variable that receives the length of the entire file, in bytes.
pllCurrent
[out] Pointer to a variable that receives the length of the downloaded portion of the file, in bytes.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_S_ESTIMATED | The returned values are estimates.
E_UNEXPECTED | Unexpected error.


IAMOverlayFX Interface

The IAMOverlayFX interface is implemented on the Overlay Mixer filter. This interface enables applications to control how the video overlay appears on the user's screen.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMOverlayFX methods | Description
QueryOverlayFXCaps | Retrieves information about which overlay effects are available to the Overlay Mixer filter.
SetOverlayFX | Applies the specified effects to the overlay surface.
GetOverlayFX | Retrieves the effects currently applied to the overlay surface, if any.

IAMOverlayFX::GetOverlayFX

IAMOverlayFX Interface

Retrieves the effects currently applied to the overlay surface, if any. The application can call this method while the filter graph is running.

Syntax

HRESULT GetOverlayFX(
    DWORD *lpdwOverlayFX
);

Parameters

lpdwOverlayFX
[out] Pointer a variable that receives a value indicating which effects, if any, are currently applied to the overlay surface. The value is a logical combination of flags from the AMOVERLAYFX enumeration.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The Microsoft® DirectShow® implementation returns S_OK if successful, or E_POINTER to indicate a NULL pointer argument.

IAMOverlayFX::SetOverlayFX

IAMOverlayFX Interface

Applies the specified effects to the overlay surface.

Syntax

HRESULT SetOverlayFX(
    DWORD dwOverlayFX
);

Parameters

dwOverlayFX
[in] Value specifying which effects to apply. The value must be a logical combination of flags from the AMOVERLAYFX enumeration, or the method returns E_INVALIDARG.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The DirectShow implementation may return one of the following values, or others not listed.

E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
S_OK | Success.

Remarks

The application must call this method while the filter graph is running. The effects are applied immediately.

IAMOverlayFX::QueryOverlayFXCaps

IAMOverlayFX Interface

Retrieves information about which overlay effects are available to the Overlay Mixer filter.

Syntax

HRESULT QueryOverlayFXCaps(
    DWORD *lpdwOverlayFXCaps
);

Parameters

lpdwOverlayFXCaps
[out] Pointer to a variable that receives a value indicating the overlay effects capabilities of the overlay surface. The value is a logical combination of flags from the AMOVERLAYFX enumeration.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The DirectShow implementation returns one of the following values.

E_FAIL | Failure.
E_POINTER | Null pointer argument.
S_OK | Success.


IAMParse Interface

This interface is implemented on the MPEG-2 Splitter. The interface enables an application to query and set the parse time—a notional time associated with the current position in the stream of bytes supplied to the parser filter. This time is also tied to the origin of the time stamps in that time stamp zero corresponds to parse time zero.

Use this interface to retrieve or set the current stream parse time or to clear the data buffer of its current data.

Requirements

Requires Amparse.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMParse methods | Description
Flush | Empties the current file buffer.
GetParseTime | Retrieves the current stream parse time.
SetParseTime | Sets the current stream parse time.

IAMParse::Flush

IAMParse Interface

Clears the current file data to allow for a more rapid switch to a new file.

Syntax

HRESULT Flush(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

Although this method can make transitions much more immediate, it can also make them appear less seamless.

IAMParse::GetParseTime

IAMParse Interface

Retrieves the current stream parse time. For MPEG-2, this corresponds to the system clock time computed for the current stream position.

Syntax

HRESULT GetParseTime(
  REFERENCE_TIME *ptrParseTime
  );

Parameters

ptrParseTime
[out] Pointer to the current parse time.

Return Value

Returns S_OK if successful or VFW_E_NOT_CONNECTED otherwise. This means the parse time is not available because the input pin is not connected.

Remarks

The parse time for the MPEG-2 Splitter filter is the current stream position in system clock units. The initial value of the parse time is zero.

IAMParse::SetParseTime

IAMParse Interface

Sets the current stream parse time. For MPEG-2, this corresponds to the system clock time computed for the current stream position.

Syntax

HRESULT SetParseTime(
  REFERENCE_TIME rtPosition
  );

Parameters

rtPosition
[in] Current stream parse time.

Return Value

Returns S_OK if successful or VFW_E_NOT_CONNECTED otherwise. This means the parse time could not be set because the input pin is not connected.

Remarks

The parse time for the MPEG-2 Splitter filter is the current stream position in system clock units. The initial value of the parse time is zero.


IAMPushSource Interface

This interface provides methods for synchronizing a filter graph that renders a live source (that is, a source that streams data in real time, such as a capture device or a network broadcast). It inherits from the IAMLatency interface.

Source filters that stream live data should expose this interface on their output pins.

Generally, applications should not call the methods on this interface; instead, use the IAMGraphStreams interface. The filter graph manager uses the methods on this interface to address two problems that commonly occur when rendering live sources:

  • Latency: When a filter graph includes more than one live source, the sources often have different latencies, which can cause them to be out of sync. For example, if audio capture has a longer latency time than video capture, the audio will lag behind the video unless the graph compensates for the difference.
  • Rate Matching: When a renderer filter is connected to a live source, it must adjust its data consumption rate to match the source filter's production rate. Otherwise, there might be gaps in the data (if the renderer runs faster than the source) or data might get dropped (if the source runs faster).

To correct for latency, the filter graph calls IAMLatency::GetLatency on each output pin that exposes the IAMPushSource interface, and determines the maximum latency in the graph. It then calls IAMPushSource::SetStreamOffset on any filters with less than the maximum latency, so that they will adjust the time stamps they generate by the correct offset.

To perform rate matching, the filter graph needs to determine whether the renderer filter can match clock rates with the source filter. The IAMPushSource::GetPushSourceFlags method returns a set of flags indicating whether it is safe for the renderer to match rates with the source.

These issues do not affect capturing to a file. The File Writer filter relies on time stamps on the incoming samples to write the file correctly; the streams are then synchronized during playback. As for rate matching, the data is always written to the file as fast as possible.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMLatency methods | Description
GetLatency | Retrieves the expected latency associated with this filter.
IAMPushSource methods | Description
GetPushSourceFlags | Retrieves a combination of flags describing the behavior of the filter.
SetPushSourceFlags | Sets flags that specify the behavior of the filter.
SetStreamOffset | Sets the offset for time stamps generated by this filter.
GetStreamOffset | Retrieves the offset that the filter uses when generating time stamps.
GetMaxStreamOffset | Retrieves the maximum stream offset the filter can support.
SetMaxStreamOffset | Reference time specifying the maximum stream offset.

IAMPushSource::GetMaxStreamOffset

IAMPushSource Interface

Retrieves the maximum stream offset the filter can support.

Syntax

HRESULT GetMaxStreamOffset(
    REFERENCE_TIME *prtMaxOffset
);

Parameters

prtMaxOffset
[out] Pointer to a variable that receives a reference time indicating the maximum offset the filter can support.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The Microsoft® DirectShow® implementation returns E_POINTER or S_OK.

Remarks

If the stream offset is set to a value larger than the maximum supported offset, the filter is not guaranteed to have a buffer large enough to hold data for the entire amount of the offset. Unless there is another buffer downstream, data might be lost.

IAMPushSource::GetPushSourceFlags

IAMPushSource Interface

Retrieves a combination of flags describing the behavior of the filter.

Syntax

HRESULT GetPushSourceFlags(
    ULONG *pFlags
);

Parameters

pFlags
[out] Pointer to a variable that receives a combination of flags from the AM_PUSHSOURCE_FLAGS enumerated type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Call this method to determine whether a renderer filter can safely match clock rates with this source filter.

IAMPushSource::GetStreamOffset

IAMPushSource Interface

Retrieves the offset that the filter uses when generating time stamps.

Syntax

HRESULT GetStreamOffset(
    REFERENCE_TIME  *prtOffset
);

Parameters

prtOffset
[out] Pointer to a variable that receives a reference time indicating the current stream offset.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMPushSource::SetMaxStreamOffset

IAMPushSource Interface

Specifies the stream offset that will be allowed in the filter graph.

Syntax

HRESULT SetMaxStreamOffset(
    REFERENCE_TIME rtMaxOffset
);

Parameters

rtMaxOffset
[in] Reference time specifying the maximum stream offset.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

If this method is called prior to connecting the filter, the filter can allocate an appropriately sized buffer.

IAMPushSource::SetPushSourceFlags

IAMPushSource Interface

Sets flags that specify the behavior of the filter. Currently, applications should not call this method, because request flags are not supported and an application should not override the flags set by the filter.

Syntax

HRESULT SetPushSourceFlags(
    ULONG Flags
);

Parameters

Flags
[in] Combination of flags from the AM_PUSHSOURCE_FLAGS enumerated type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMPushSource::SetStreamOffset

IAMPushSource Interface

Sets the offset for time stamps generated by this filter.

Syntax

HRESULT SetStreamOffset(
    REFERENCE_TIME rtOffset
);

Parameters

rtOffset
[in] New stream offset for the filter.

Return Value

Returns S_FALSE if the specified offset is larger than the filter's maximum preferred offset. Otherwise, returns S_OK if successful or an HRESULT value indicating the cause of the error.

Remarks

The filter graph calls this method to adjust a filter's stream offset, in order to synchronize streams with different latency values.

If the return value is S_FALSE, the filter might not support a buffer large enough for the requested offset. Unless there is another buffer downstream, data might be lost. To retrieve the filter's maximum preferred offset, call the GetMaxStreamOffset method.


IAMResourceControl Interface

The IAMResourceControl interface enables an application to open and hold an audio device resource before it's actually needed, so that playback can be guaranteed, or so that the application can learn in advance that a device is not available.

A filter can implement IAMResourceControl for use with a resource that might sometimes be unavailable. This interface is implemented on the Microsoft® DirectShow® Audio Capture and Audio Renderer filters.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMResourceControl methods | Description
Reserve | Reserves or unreserves a device resource.

IAMResourceControl::Reserve

IAMResourceControl Interface

Reserves or unreserves a device resource.

Syntax

HRESULT Reserve(
    DWORD dwFlags
     PVOID pvReserved
);

Parameters

dwFlags
[in] Flag indicating whether to reserve or unreserve this device. For possible values, see Remarks.
pvReserved
[in] Must be NULL.

Return Value

Returns S_OK if the device was successfully reserved or unreserved, S_FALSE if the device is currently reserved and will continue to be held, or an an HRESULT error code if the device can't be reserved.

Remarks

The allowable values for dwFlags are defined in the AMRESCTL_RESERVEFLAGS enumeration.

Important A resource can be reserved multiple times. The reserve count is incremented or decremented only if S_OK is returned. Each successful call (one that returns S_OK) to reserve a device must be matched by a call to unreserve it.


IAMStreamConfig Interface

The IAMStreamConfig interface is implemented on the output pins of audio/video capture filters and compression filters, including the VFW Capture Filter, the MJPEG Compressor, the ACM Wrapper, the Audio Capture Filter, and the AVI Compressor. Filter developers can implement this interface on any output pin that handles audio or video data.

This interface enables applications to query what types of formats a filter supports on its output pin, and to set the format that the pin will offer to its downstream connecting pin. This in turn enables an application to simply call IGraphBuilder::Render on the pin, and the graph builder will create a graph appropriate to the desired format.

Note If an application attempts to use IPin::EnumMediaTypes to enumerate a pin's supported media types after calling SetFormat, only the one media type will be returned.

The IAMStreamConfig::GetStreamCaps method retrieves the AM_MEDIA_TYPE structure associated with the stream, as well as a VIDEO_STREAM_CONFIG_CAPS or an AUDIO_STREAM_CONFIG_CAPS structure that further describes the stream's characteristics. For video, this includes information on cropping, stretching, alignment, granularity and data rates.

For more information on GetStreamCaps see Exposing Capture and Compression Formats.

Filter developers: Implement this interface on the video output pin when you are writing a video capture or video compression filter. See the comments in axextend.idl for more information.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMStreamConfig methods | Description
SetFormat | Sets the audio or video stream's format.
GetFormat | Retrieves the audio or video stream's format.
GetNumberOfCapabilities | Retrieves the number of stream capabilities structures for the compressor.
GetStreamCaps | Obtains audio or video capabilities of a stream depending on which type of structure is pointed to in the pSCC parameter.

IAMStreamConfig::GetFormat

IAMStreamConfig Interface

Retrieves the audio or video stream's format.

Syntax

HRESULT GetFormat(
  AM_MEDIA_TYPE **pmt
  );

Parameters

pmt
[out] Address of a pointer to an AM_MEDIA_TYPE structure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

When you are done using the media type structure, call the DeleteMediaType function to free the structure.

IAMStreamConfig::GetNumberOfCapabilities

IAMStreamConfig Interface

Retrieves the number of stream capabilities structures for the compressor.

Syntax

HRESULT GetNumberOfCapabilities(
  int *piCount,
  int *piSize
  );

Parameters

piCount
[out] Pointer to the number of VIDEO_STREAM_CONFIG_CAPS and/or AUDIO_STREAM_CONFIG_CAPS structures supported.
piSize
[out] Pointer to the size of the configuration structure (either AUDIO_STREAM_CONFIG_CAPS or VIDEO_STREAM_CONFIG_CAPS).

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMStreamConfig::GetStreamCaps

IAMStreamConfig Interface

Obtains audio, video, or other capabilities of a stream depending on which type of structure is pointed to in the pSCC parameter.

Syntax

HRESULT GetStreamCaps(
  int iIndex,
  AM_MEDIA_TYPE **pmt,
  BYTE *pSCC
  );

Parameters

iIndex
[in] Index to the desired media type and capability pair. Use the GetNumberOfCapabilities method to retrieve the total number of these pairs. Possible index values range from zero to one less than the total number of pairs.
pmt
[out] Address of a pointer to an AM_MEDIA_TYPE structure.
pSCC
[out] Pointer to a stream configuration structure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method enables you to get more information about accepted media types rather than the traditional way of enumerating a pin's media types, so you typically should use it instead of pin enumeration. Information such as possible video capture rates, media types, and sizes is returned by the VIDEO_STREAM_CONFIG_CAPS structure. Audio capabilities of the filter's output pin, including the number of inputs, sampling rate, and bit rate granularity will be returned by an AUDIO_STREAM_CONFIG_CAPS structure.

Call DeleteMediaType to free the pmt media type.

For more information on GetStreamCaps, see Exposing Capture and Compression Formats.

IAMStreamConfig::SetFormat

IAMStreamConfig Interface

Sets the audio or video stream's format.

Syntax

HRESULT SetFormat(
  AM_MEDIA_TYPE *pmt
  );

Parameters

pmt
[in] Pointer to an AM_MEDIA_TYPE structure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

A call to this method will fail if the pin is streaming.

If your output pin isn't connected and you can connect it with this media type, return S_OK from this method and start enumerating the specified media type as follows: Specify this format as format number zero in the CTransformOutputPin::GetMediaType function's iPosition parameter. You can offer and accept only this type to ensure that the pins will use this format for the connection when it occurs.

If your output pin is already connected and you can provide this type, then reconnect your pin. If the other pin can't accept the media type, fail this call and leave your connection alone.

Passing in NULL as a parameter value can cause some filters to set their default format and forget a previous format you have given it with this method.

The frame rate at which your filter should produce data is determined by the AvgTimePerFrame field of the VIDEOINFOHEADER of the media type your output pin is connected with. You may not be able to capture at any arbitrary frame rate, but only certain rates. If your pin is connected with a media type that asks for a frame rate you can't provide, you should provide frames at the next lowest frame rate possible. For instance, if your media type has AvgTimePerFrame=333333 (approximately 1/30 of a second, meaning 30 frames per second), and you can only capture 29.97 or 35 frames per second, you should provide frames at 29.97 frames per second, since that is the closest value lower than 30 that you can provide. You can provide a higher frame rate than asked if the frame rate you provide does not create frame durations more than 1 microsecond shorter than requested, since the AvgTimePerFrame may simply have rounding errors. If the AvgTimePerFrame field is 0, you can supply frames at any default frame rate that you want.


IAMStreamControl Interface

Controls individual streams on a filter. Pins on some filters expose this interface. For example, the AVI Mux filter supports this interface on its input pins, and the Audio Capture and WDM Video Capture filters support it on their output pins.

This interface enables an application to turn streams on and off at specified times. For example, an application might turn off an audio stream, to mute the audio, while video playback continued. Capture applications can use this interface to specify exact start and stop times for capture, and to control capture and preview streams independently of each other.

Call the StartAt method to specify the reference time when the pin will start streaming. Call the StopAt method to specify when the pin will stop streaming. Then call IMediaControl::Run on the filter graph manager.

When using this interface, you should be aware of the following limitations:

  • There must be a reference clock in the filter graph.
  • Preview pins on capture cards with hardware overlay do not support this interface.
  • If you are capturing audio and video to an interleaved AVI file, the AVI Mux filter requires both streams. If you stop one of the streams, the filter cannot interleave the data. For more information, see IConfigInterleaving.

Depending on the application, you might find the ICaptureGraphBuilder2::ControlStream method more convenient, because it supports stream control at the graph level, without the application having to enumerate individual filters and pins.

Filter developers: The CBaseStreamControl base class implements this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMStreamControl methods | Description
StartAt | Informs the pin when to start sending streaming data.
StopAt | Informs the pin when to suspend processing and supplying data.
GetInfo | Retrieves information about the current streaming settings.

IAMStreamControl::GetInfo

IAMStreamControl Interface

Retrieves information about the current streaming settings, including start and stop times.

Syntax

HRESULT GetInfo(
    AM_STREAM_INFO *pInfo
);

Parameters

pInfo
[out] Pointer to an AM_STREAM_INFO structure that contains current stream settings.

Return Value

If the method succeeds, the return value is S_OK. Otherwise, returns an HRESULT value indicating the cause of the failure.

Remarks

The dwFlags member of the AM_STREAM_INFO structure contains flags that indicate whether valid start and stop times have been set, and whether the filter is currently discarding data.

IAMStreamControl::StartAt

IAMStreamControl Interface

Informs the pin when to start sending streaming data. When streaming actually starts, the filter sends an EC_STREAM_CONTROL_STARTED notification code.

Syntax

HRESULT StartAt(
    const REFERENCE_TIME *ptStart,
    DWORD dwCookie
);

Parameters

ptStart
[in] Pointer to the time at which to start streaming. If NULL, start immediately (without sending an event notification); if MAX_TIME, cancel the existing start request.
dwCookie
[in] Value to send with the event notification once the start occurs. (Ignored if ptStart is MAX_TIME or NULL.)

Return Value

If the method succeeds, the return value is S_OK. Otherwise, returns an HRESULT value indicating the cause of the failure.

Remarks

Streams are enabled by default, so it is only necessary to call this method if you have previously called the StopAt method.

When the pin actually begins streaming, it signals the EC_STREAM_CONTROL_STARTED event. The first event parameter is a pointer to the pin's IPin interface, and the second is the value given in the dwCookie parameter. This enables applications to tie the events back to their requests.

If start and stop are scheduled for a single point in time, the effect is as if the start occurred an infinitesimal time before the stop. You can use this to capture a single frame.

IAMStreamControl::StopAt

IAMStreamControl Interface

Informs the pin when to suspend processing and supplying data.

Syntax

HRESULT StopAt(
    const REFERENCE_TIME *ptStop,
    BOOL bSendExtra,
    DWORD dwCookie
);

Parameters

ptStop
[in] Pointer to the time at which to stop streaming. If NULL, stop immediately (without sending an event notification); if MAX_TIME, cancel the existing stop request.
bSendExtra
[in] Boolean value indicating whether to send an extra sample after the scheduled stop time. If TRUE, send an extra sample.
dwCookie
[in] Value to send with the event notification once the stop occurs. (Ignored if ptStart is MAX_TIME or NULL).

Return Value

If the method succeeds, the return value is S_OK. Otherwise, returns an HRESULT value indicating the cause of the failure.

Remarks

When the pin actually stops streaming, it signals the EC_STREAM_CONTROL_STOPPED event. The first event parameter is a pointer to the pin's IPin interface, and the second is the value given in the dwCookie parameter. This enables applications to tie the events back to their requests.

In video capture, you would typically call this method on both the output pin of a capture filter and the input pin of a multiplexer, and pay attention only to the notification from the multiplexer. This ensures that the capture filter doesn't needlessly capture extra frames, while guaranteeing that the multiplexer has, in fact, saved the last frame to a file.

In addition, you should specify TRUE for the bSendExtra parameter on the capture pin, and specify FALSE to the multiplexer pin. If an extra frame is not sent, the multiplexer will wait for the stop time indefinitely and not realize it already has received all the capture information. The multiplexer will discard the extra sample sent by the capture pin, so it will not get written to the file. Do not set bSendExtra to TRUE unless you also use IAMStreamControl on another downstream pin too, as in the preceding case.

If you call StopAt with a time that is in the middle of a packet, the filter will deliver the whole packet before going into a discarding state. Also, if start and stop are scheduled for a single point in time, the effect is as if the start occurred an infinitesimal time before the stop. You can use this to capture a single frame.


IAMStreamSelect Interface

Controls which logical streams are played and retrieves information about them. An example of logical stream selection is selection from a set of audio streams that encode different national languages. Perhaps you could choose English from among a set of audio streams that include English, German, and French.

The MPEG-1 Stream Splitter filter implements this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMStreamSelect methods | Description
Count | Retrieves the total count of available streams.
Info | Retrieves information about a given stream.
Enable | Enables or disables a given stream.

IAMStreamSelect::Count

IAMStreamSelect Interface

Retrieves the total count of available streams.

Syntax

HRESULT Count(
  DWORD *pcStreams
  );

Parameters

pcStreams
[out] Pointer to a value indicating the number of available streams.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current Microsoft® DirectShow® implementation returns S_OK.

IAMStreamSelect::Enable

IAMStreamSelect Interface

Enables or disables a given stream.

Syntax

HRESULT Enable(
  long lIndex,
  DWORD dwFlags
  );

Parameters

lIndex
[in] Index number of desired stream. Zero-based.
dwFlags
[in] Flag indicating whether to enable or disable the stream. Valid values include the following:
Zero | Disable all streams in the group containing this stream.
AMSTREAMSELECTENABLE_ENABLE | Enable only this stream within the given group and disable all others.
AMSTREAMSELECTENABLE_ENABLEALL | Enable all streams in the group containing this stream.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_NOTIMPL if support for the specified flag has not been implemented, E_INVALIDARG if the stream ID is invalid, or S_OK otherwise.

IAMStreamSelect::Info

IAMStreamSelect Interface

Retrieves information about a given stream.

Syntax

HRESULT Info(
  long lIndex,
  AM_MEDIA_TYPE **ppmt,
  DWORD *pdwFlags,
  LCID *plcid,
  DWORD *pdwGroup,
  WCHAR **ppszName,
  IUnknown **ppObject,
  IUnknown **ppUnk
  );

Parameters

lIndex
[in] Index number of desired stream. Zero-based.
ppmt
[out] Address of a pointer to the stream's media type. Optional. Use the DeleteMediaType function to free the AM_MEDIA_TYPE structure when done.
pdwFlags
[out] Optional pointer to flags indicating the stream state. Valid values include the following:
Zero | This stream is disabled.
AMSTREAMSELECTINFO_ENABLED | The stream is enabled, and others in this group might be enabled too.
AMSTREAMSELECTINFO_EXCLUSIVE | This stream is the only enabled stream in the group.
plcid
[out] Pointer to the locale context (LCID) value. This parameter points to a zero value if there is no LCID. Optional.
pdwGroup
[out] Pointer to the logical group. Optional.
ppszName
[out] Address of a pointer to the stream name. Optional. Free with the CoTaskMemFree function when done.
ppObject
[out] Address of a pointer to the pin or filter object associated with this stream. Optional. The object can change if the IAMStreamSelect::Enable method is called. This parameter contains a null value upon return from this method if there is no associated object.
ppUnk
[out] Address of a pointer to a stream-specific interface.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns S_FALSE if lIndex is out of range, or S_OK otherwise.

Remarks

The first stream in each group is the default.


IAMTimecodeDisplay Interface

The IAMTimecodeDisplay interface contains properties and methods that define behavior of an external SMPTE/MIDI timecode display device. You should implement this interface in combination with IAMExtDevice, IAMExtTransport, and the other timecode interfaces to control an external device, such as a VCR, which can read, generate and/or display timecode data. This interface controls the physical timecode character generator display that is either built into a VCR or is on some other similar external device.

For more information on SMPTE timecode, see SMPTE Timecode.

Implement this interface on an external device filter that will control the timecode display on an external timecode reader or generator. Timecode readers or generators can be built into a VCR or can be a separate external device. Do not try to implement this interface if your external device can't display timecode or if your timecode is being generated through an internal card with no integral or overlay hardware.

This interface is not intended for rendering in a Microsoft® DirectShow® filter graph; it is purely for use on external device displays.

Use this interface when applications need to control an external device and how its timecode information is displayed.

Hardware Requirements

See the IAMExtTransport interface for hardware requirements.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimecodeDisplay methods | Description
GetTCDisplayEnable | Determines whether an external device's timecode character generator output is enabled or disabled.
SetTCDisplayEnable | Enables or disables an external device's timecode character output generator.
GetTCDisplay | Retrieves current settings of the timecode character generator output.
SetTCDisplay | Sets the timecode character generator output characteristics.

IAMTimecodeDisplay::GetTCDisplay

IAMTimecodeDisplay Interface

Retrieves current settings of the timecode character generator output.

Syntax

HRESULT GetTCDisplay(
  long Param,
  long *pValue
  );

Parameters

Param
[in] Timecode display characteristic. Specify one of the following items you want to get settings for.
ED_TCD_BORDER | White border for black characters, black border for white characters
ED_TCD_INTENSITY | Intensity (brightness) of characters
ED_TCD_INVERT | Black characters on white background or white characters on black background
ED_TCD_POSITION | Position of characters
ED_TCD_SIZE | Size of characters
ED_TCD_SOURCE | Source of display's data
ED_TCD_TRANSPARENCY | Transparency of characters
pValue
[out] Pointer to the current setting of the parameter specified in Param. This parameter retrieves one of the following values.

If ED_TCD_SOURCE specified in Param, will return one of the following:
ED_TCG | Timecode generator
ED_TCR | Timecode reader

If ED_TCD_SIZE specified in Param, will return one of the following:
ED_LARGE | Large
ED_MED | Medium
ED_SMALL | Small

If ED_TCD_POSITION specified in Param, will return one of the following:
ED_BOTTOM | Bottom
ED_MIDDLE | Middle
ED_TOP | Top

in combination with one of the following:
ED_CENTER | Center
ED_LEFT | Left
ED_RIGHT | Right

If ED_TCD_INTENSITY specified in Param, will return one of the following:
ED_HIGH | High
ED_LOW | Low

If ED_TCD_TRANSPARENCY is specified in Param, will return a value from 0 to 4, 0 being completely opaque.

If ED_TCD_INVERT is specified in Param, will return one of the following:
OAFALSE | Black characters on white background
OATRUE | White characters on black background

If ED_TCD_BORDER specified in Param, will return one of the following:
OAFALSE | Black characters for white border
OATRUE | White border for black characters

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMTimecodeDisplay::SetTCDisplay

IAMTimecodeDisplay::GetTCDisplayEnable

IAMTimecodeDisplay Interface

Determines whether an external device's timecode character generator output is enabled or disabled.

Syntax

HRESULT GetTCDisplayEnable(
  long *pState
  );

Parameters

pState
[out] Pointer to a value indicating whether timecode character generator output is enabled. OATRUE indicates enabled; OAFALSE indicates disabled.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method is not intended for character rendering inside a filter graph, it is purely intended for hardware displays. Ensure that your external timecode reader or generator has display capability before trying to use this method.

See Also

IAMTimecodeDisplay::SetTCDisplayEnable

IAMTimecodeDisplay::SetTCDisplay

IAMTimecodeDisplay Interface

Sets the timecode character generator output characteristics.

Syntax

HRESULT SetTCDisplay(
  long Param,
  long Value
  );

Parameters

Param
[in] Timecode display characteristic. Specify one of the following properties you want to set properties for.
ED_TCD_BORDER | White border for black characters, black border for white characters
ED_TCD_INTENSITY | Intensity (brightness) of characters
ED_TCD_INVERT | Black characters on white background or white characters on black background
ED_TCD_POSITION | Position of characters
ED_TCD_SIZE | Size of characters
ED_TCD_SOURCE | Source of the display's data
ED_TCD_TRANSPARENCY | Transparency of characters
Value
[in] Setting of the parameter specified in Param. Must be one of the following:

If ED_TCD_SOURCE specified in Param, set one of the following:
ED_TCG | Timecode generator
ED_TCR | Timecode reader

If ED_TCD_SIZE is specified in Param, set one of the following:
ED_LARGE | Large
ED_MED | Medium
ED_SMALL | Small

If ED_TCD_POSITION specified in Param, set one of the following:
ED_BOTTOM | Bottom
ED_MIDDLE | Middle
ED_TOP | Top

in combination with one of the following:
ED_CENTER | Center
ED_LEFT | Left
ED_RIGHT | Right

If ED_TCD_INTENSITY is specified in Param, set one of the following:
ED_HIGH | High
ED_LOW | Low

If ED_TCD_TRANSPARENCY is specified in Param, set a value from 0 to 4, 0 being completely opaque, 4 being as dark as possible.

If ED_TCD_INVERT is specified in Param, set one of the following:
OAFALSE | Black on white
OATRUE | White on black

If ED_TCD_BORDER is specified in Param, set one of the following:
OAFALSE | Black characters for white border
OATRUE | White border for black characters

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMTimecodeDisplay::GetTCDisplay

IAMTimecodeDisplay::SetTCDisplayEnable

IAMTimecodeDisplay Interface

Enables or disables an external device's timecode character output generator.

Syntax

HRESULT SetTCDisplayEnable(
  long State
  );

Parameters

State
[in] Value specifying whether to enable or disable the timecode character output generator. Specify OATRUE to enable or OAFALSE to disable.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method is not intended for rendering characters inside a filter graph, it is purely intended for hardware displays. Ensure that your external timecode reader or generator has display capability before trying to use this method.

See Also

IAMTimecodeDisplay::GetTCDisplayEnable


IAMTimecodeGenerator Interface

The IAMTimecodeGenerator interface contains properties and methods that specify how an external SMPTE/MIDI timecode generator should supply data to the filter graph and the formats in which timecode should be supplied. You should implement this interface in combination with the IAMExtDevice and IAMExtTransport interfaces to control an external device, such as a VCR. This interface provides methods that enable applications to specify various SMPTE/MIDI timecode modes or formats that an external device should use in the generation of timecode, and methods that verify that the generator is working properly.

SMPTE timecode is a frame addressing system that identifies video and audio sources, makes automatic track synchronization possible, and provides a container for additional data related to the production. SMPTE timecode's main purpose is to provide a machine-readable address for video and audio. It is displayed in hh:mm:ss:ff format and is thoroughly defined in ANSI/SMPTE 12-1986.

For more information on SMPTE timecode see SMPTE Timecode.

For more information on methods that access an external timecode reader, see the IAMTimecodeReader interface.

Implement this interface on an external device filter when you want to control how an external timecode generator produces SMPTE/MIDI timecode information.

Expose the IMediaSeeking interface on your filter to enable applications to convert timecode to Microsoft® DirectShow® reference time (by using IMediaSeeking::ConvertTimeFormat).

Your external device must be able to read timecode and send it to the computer over its control interface (see hardware requirements). If this is not the case, you must either have a timecode reader card in your computer, or you can write a software decoder that converts VITC embedded in captured video frames or LTC captured as an audio signal into DirectShow timecode samples.

Use this interface when you want to generate SMPTE timecode in an external device.

Hardware Requirements

For hardware requirements, see the IAMExtTransport interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimecodeGenerator methods | Description
GetTCGMode | Retrieves the SMPTE timecode generator properties.
SetTCGMode | Sets the SMPTE timecode generator properties.
put_VITCLine | Specifies which line(s) to insert the vertical interval timecode information into.
get_VITCLine | Retrieves which line(s) the vertical interval timecode information has been inserted into.
SetTimecode | Sets the timecode, userbit value, or both.
GetTimecode | Retrieves the most recent timecode and/or userbit value available in the stream.

IAMTimecodeGenerator::GetTCGMode

IAMTimecodeGenerator Interface

Retrieves the SMPTE timecode generator properties.

Syntax

HRESULT GetTCGMode(
  long Param,
  long *pValue
  );

Parameters

Param
[in] Timecode generator mode. Specify one of the following modes you want to get settings for.
ED_TCG_FRAMERATE | Frame rate
ED_TCG_REFERENCE_SOURCE | Source of the count value
ED_TCG_SYNC_SOURCE | Source of the hardware clock reference
ED_TCG_TIMECODE_TYPE | SMPTE timecode format of the generator
pValue
[out] Pointer to the current setting of the mode specified in Param.

If you specify ED_TCG_FRAMERATE in Param, this parameter retrieves one of the following:
ED_FORMAT_SMPTE_24 | 24 frames per second
ED_FORMAT_SMPTE_25 | 25 frames per second
ED_FORMAT_SMPTE_30 | 30 frames per second. Nondrop frame
ED_FORMAT_SMPTE_30DROP | 30 frames per second. Drop frame (actually 29.97 fps)

If you specify ED_TCG_REFERENCE_SOURCE in Param, this parameter retrieves one of the following:
ED_TCG_FREE | No count reference source
ED_TCG_READER | Synchronize to reader value (jamsync)

If you specify ED_TCG_SYNC_SOURCE in Param, this parameter retrieves one of the following:
ED_TCG_FREE | Lock to nothing (freerun)
ED_TCG_READER | Lock to timecode reader
ED_TCG_VIDEO | Lock to incoming video

If you specify ED_TCG_TIMECODE_TYPE in Param, this parameter retrieves one of the following:
ED_TCG_MIDI_FULL | MIDI full frame timecode
ED_TCG_MIDI_QF | MIDI quarter frame timecode
ED_TCG_SMPTE_LTC | Linear timecode
ED_TCG_SMPTE_VITC | Vertical interval timecode

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method returns various settings of the timecode generator. For more information on ED_TCG_TIMECODE_TYPE, see IAMTimecodeReader::SetTCRMode.

IAMTimecodeGenerator::GetTimecode

IAMTimecodeGenerator Interface

Retrieves the most recent timecode and/or userbit value available in the stream.

Syntax

HRESULT GetTimecode(
  PTIMECODE_SAMPLE pTimecodeSample
  );

Parameters

pTimecodeSample
[out] Pointer to a TIMECODE_SAMPLE timecode structure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Use this method to obtain the most recent timecode value available in the stream. The application can use this to monitor the timecode and verify the generator is working properly.

See Also

IAMTimecodeGenerator::SetTimecode

IAMTimecodeGenerator::get_VITCLine

IAMTimecodeGenerator Interface

Retrieves which line(s) the vertical interval timecode information has been inserted into.

Syntax

HRESULT get_VITCLine(
  long *pLine );

Parameters

pLine
[out] Pointer to the vertical line(s) containing the timecode information (valid lines are 11-20).

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

To get VITC information from multiple lines, make successive calls to this method, once for each line desired, with the hi bit set for each line.

See Also

IAMTimecodeGenerator::put_VITCLine

IAMTimecodeGenerator::put_VITCLine

IAMTimecodeGenerator Interface

Specifies which line to insert the vertical interval timecode information into.

Syntax

HRESULT put_VITCLine(
    long Line );

Parameters

Line
[in] Vertical line to contain the timecode information (valid lines are 11-20; 0 means autoselect).

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

To generate VITC on specific multiple lines, make successive calls to this method, once for each line desired.

Set the hi bit to add to this line to any previously set lines.

See Also

IAMTimecodeGenerator::get_VITCLine

IAMTimecodeGenerator::SetTCGMode

IAMTimecodeGenerator Interface

Sets the SMPTE timecode generator properties.

Syntax

HRESULT SetTCGMode(
  long Param,
  long Value
  );

Parameters

Param
[in] Timecode generator mode. Specify one of the following modes.
ED_TCG_FRAMERATE | Frame rate
ED_TCG_REFERENCE_SOURCE | Source of the count value
ED_TCG_SYNC_SOURCE | Source of the hardware clock reference
ED_TCG_TIMECODE_TYPE | SMPTE timecode format of the generator
Value
[in] Setting of the mode specified in Param.

If ED_TCG_FRAMERATE is specified in Param, this parameter is set to one of the following:
ED_FORMAT_SMPTE_24 | 24 frames per second
ED_FORMAT_SMPTE_25 | 25 frames per second
ED_FORMAT_SMPTE_30 | 30 frames per second. Nondrop frame
ED_FORMAT_SMPTE_30DROP | 30 frames per second. Drop frame (actually 29.97 frames per second)

If ED_TCG_REFERENCE_SOURCE is specified in Param, set one of the following:
ED_TCG_FREE | No count reference source
ED_TCG_READER | Sync to reader value (jamsync)

If ED_TCG_SYNC_SOURCE is specified in Param, set one of the following:
ED_TCG_FREE | Lock to nothing (freerun)
ED_TCG_READER | Lock to timecode reader
ED_TCG_VIDEO | Lock to incoming video

If ED_TCG_TIMECODE_TYPE is specified in Param, set one of the following:
ED_TCG_MIDI_FULL | MIDI Full Frame timecode
ED_TCG_MIDI_QF | MIDI quarter frame timecode
ED_TCG_SMPTE_LTC | Linear timecode
ED_TCG_SMPTE_VITC | Vertical interval timecode

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

For more information on ED_TCG_TIMECODE_TYPE, see the IAMTimecodeReader::SetTCRMode method.

See Also

IAMTimecodeGenerator::GetTCGMode

IAMTimecodeGenerator::SetTimecode

IAMTimecodeGenerator Interface

Sets the timecode, userbits value, or both.

Syntax

HRESULT SetTimecode(
  PTIMECODE_SAMPLE pTimecodeSample
  );

Parameters

pTimecodeSample
[in] Pointer to a TIMECODE_SAMPLE timecode structure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

To set only timecode, set userbit value to NULL, and vice versa. If generator is running, these values will take effect immediately.

See Also

IAMTimecodeGenerator::GetTimecode


IAMTimecodeReader Interface

You can implement the IAMTimecodeReader interface to read SMPTE (Society of Motion Picture and Television Engineers) or MIDI timecode from an external device. It contains properties and methods that specify the timecode format that an external device should read, and how it is embedded in the media. It is expected that you will use this interface with the IAMExtDevice and IAMExtTransport interfaces to control an external device, such as a VCR, which can read timecode data.

SMPTE timecode is a frame addressing system that identifies video and audio sources, makes automatic track synchronization possible, and provides a container for additional data related to the source material. SMPTE timecode's main purpose is to provide a machine-readable address for video and audio. It is displayed in hh:mm:ss:ff (hours, minutes, seconds, frames) format and is thoroughly defined in ANSI/SMPTE 12-1986.

For more information on SMPTE timecode, see SMPTE Timecode.

Implement this interface on an external device filter when you want to specify how an external device should read SMPTE/MIDI timecode information.

Expose the IMediaSeeking interface on your filter so that applications can convert timecode to Microsoft® DirectShow® reference time (by using the IMediaSeeking::ConvertTimeFormat method).

Your external device must be able to read timecode and send it to the computer over its control interface. If this is not the case, you must either have a timecode reader card in your computer, or you can write a software decoder that converts VITC (Vertical Interval Timecode) in captured video frames or LTC (Linear Timecode) captured as an audio signal into DirectShow timecode samples.

Use this interface when you need to read timecode information for controlling an external device, or when you want to use timecode information from an external device in applications that must refer to original program information.

Applications generally save timecode in one of two ways. It is either written to the capture file as an additional stream or as a discontinuity table stored in the extended AVI file index. It is commonly used to trigger capture or playback and to create edit decision lists that describes how source material is organized into a finished product.

If you intend to capture timecode, treat it as a separate stream that has its own media type. It can be consumed by an appropriate file-writing multiplexer filter. However, sometimes there are errors in reading the timecode off the tape because of dropouts and other mechanical tape problems. In such cases, the timecode source filter should simply drop samples and mark the next valid one with the discontinuity property.

If you intend to use timecodes to trigger capture or playback from a timecoded (or "striped") videotape, the sequence of events goes as follows:

  1. Build a capture graph, open a target AVI file, and preallocate disk space if necessary. If the captured material will be appended to an existing AVI file, seek to the end of the file before writing. The capture graph is paused at this point.
  2. Search the VCR to the capture start point and note the timecode. You can either enter this value manually into your program, or the application can automatically read it. Automatic reading requires that the graph is running but the stream control interfaces on the file multiplexer's input pins are discarding incoming samples, effectively gating the capture.
  3. Cue the VCR to preroll position, usually five seconds before the target point.
  4. Start the VCR and the graph. When the trigger point is reached (or the trigger point minus the file writer's preroll), the stream control interfaces release the file multiplexer and it begins streaming media samples to the file writer.
  5. You can stop the capture process manually or by setting a duration property on the stream control interface.

You must consider discontinuous timecode, both during preroll and during the capture process; it is reasonable to demand that the timecode be continuous and monotonically increasing throughout the preroll and capture start point. This prevents a potentially ambiguous calculation of relative stream times by the IMediaSeeking::ConvertTimeFormat method. Also, the timecode need not be the only gating signal for triggered capture. Any time-stamped data stored in the vertical blanking interval, such as Intercast or closed-captioned data (XDS), can be used to start the streaming of video and audio data to disk.

Hardware Requirements

See the IAMExtTransport interface for hardware requirements.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTimecodeReader methods | Description
GetTCRMode | Retrieves properties of the timecode reader.
SetTCRMode | Sets the timecode reader properties.
put_VITCLine | Specifies the vertical interval line that the timecode reader will use to read timecode.
get_VITCLine | Retrieves the vertical interval line that the timecode reader is using to read timecode.
GetTimecode | Retrieves the most recent timecode, userbits, and flag values available in the stream.

IAMTimecodeReader::GetTCRMode

IAMTimecodeReader Interface

Retrieves the timecode reader's properties.

Syntax

HRESULT GetTCRMode(

  long Param,

  long *pValue

  );

Parameters

Param
[in] Timecode reader property to get (either ED_TCR_SOURCE or ED_TCR_NOTIFY_ENABLE).
pValue
[out] Pointer to the value of the requested timecode reader property. If Param is set to ED_TCR_NOTIFY_ENABLE, then this parameter will return OATRUE—meaning that notifications are enabled—or OAFALSE. If Param is set to ED_TCR_SOURCE, then this value must be one of the following:
ED_TCR_CT | Control track
ED_TCR_LTC | Linear timecode
ED_TCR_VITC | Vertical interval timecode
ED_TCR_LAST_VALUE | Last read value

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Linear timecode is recorded on an analog audio track as a bi-phase mark-encoded signal. Each timecode frame is one video frame time in duration.

Vertical timecode is usually stored in two lines of a video signal's vertical interval, somewhere between lines 11 and 20.

Control track is a once-per-frame signal recorded on a special track on a tape. The head and drive servo mechanisms use it to keep everything locked. It is also used to drive the counter on machines without timecode capability, and can optionally be used on machines equipped with a timecode reader.

Note that ED_TCR_LAST_VALUE is used when implementing timecode notification because the application does not want to initiate another timecode request to the external device. This method is not recommended for frame-accurate applications because of multithreading issues.

See Also

IAMTimecodeReader::SetTCRMode

IAMTimecodeReader::GetTimecode

IAMTimecodeReader Interface

Retrieves the most recent timecode, userbit, and flag values available in the stream.

Syntax

HRESULT GetTimecode(
  PTIMECODE_SAMPLE pTimecodeSample
  );

Parameters

pTimecodeSample
[out] Pointer to a TIMECODE_SAMPLE timecode structure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Use this method to monitor the timecode and to parse duplicates and discontinuities. The source filter supplying the timecode, or possibly a downstream filter, might want to parse for discontinuities or errors because you have to look at every sample to be able to retrieve the most recent timecode.

Applications can fill undefined bits in the timecode word to store synchronization information, or to encode original film and audio tape information. These undefined bits, or userbits, are retrieved by calling this method.

IAMTimecodeReader::get_VITCLine

IAMTimecodeReader Interface

Retrieves the vertical interval line that the timecode reader is using to read timecode.

Syntax

HRESULT get_VITCLine(
  long *pLine );

Parameters

pLine
[out] Pointer to the vertical line containing timecode information (valid lines are from 11 through 20).

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The high bit indicates that multiple lines are used and successive calls will cycle through the line numbers.

See Also

IAMTimecodeReader::put_VITCLine

IAMTimecodeReader::put_VITCLine

IAMTimecodeReader Interface

Specifies the vertical interval line that the timecode reader will use to read timecode.

Syntax

HRESULT put_VITCLine(
  long Line );

Parameters

Line
[in] Vertical line containing timecode information (valid lines are 11-20; 0 means autoselect).

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

If VITC mode is specified in the IAMTimecodeReader::SetTCRMode method, you must specify which line or lines will contain timecode information. To read VITC on specific multiple lines, the caller would make successive calls to put_VITCLine, once for each line desired.

Set the hi bit to add to the list of lines for readers that test across multiple lines.

See Also

IAMTimecodeReader::get_VITCLine

IAMTimecodeReader::SetTCRMode

IAMTimecodeReader Interface

Sets the timecode reader properties.

Syntax

HRESULT SetTCRMode(
  long Param,
  long Value
  );

Parameters

Param
[in] Property you want to set (use ED_TCR_SOURCE or ED_TCR_NOTIFY_ENABLE).
Value
[in] Value of the specified property; If Param returns ED_TCR_NOTIFY_ENABLE, then this value will return OATRUE or OAFALSE. IfParam returns ED_TCR_SOURCE, then this value must be one of the following:
ED_TCR_CT | Control Track
ED_TCR_LTC | Linear Timecode
ED_TCR_VITC | Vertical Interval Timecode
ED_TCR_LAST_VALUE | Return last read value.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Linear timecode is recorded on an analog audio track as an NRZ bi-phase mark-encoded signal. Each timecode frame is one video frame time in duration.

Vertical timecode is usually stored in two lines of a video signal's vertical interval, somewhere between 10 and 20.

Control track is a once-per-frame signal recorded on a special track on a tape. The head and drive servo mechanisms use it to keep everything locked. It is also used to drive the counter on machines without timecode capability, and can optionally be used on machines equipped with a timecode reader.

Note that ED_TCR_LAST_VALUE is used when implementing timecode notification because the application does not want to initiate another timecode request to the external device. This method is not recommended for frame-accurate applications because of multithreading issues.

See Also

IAMTimecodeReader::GetTCRMode


IAMTuner Interface

The IAMTuner interface is the base class for IAMTVTuner, which inherits all the IAMTuner methods. For more information on controlling a TV tuner using Microsoft® DirectShow®, see the IAMTVTuner documentation.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTuner methods | Description
put_Channel | Sets the TV channel.
get_Channel | Retrieves the TV channel that the tuner is set to.
ChannelMinMax | Retrieves the minimum and maximum channel available.
put_CountryCode | Sets the country code to establish the frequency to use.
get_CountryCode | Retrieves the country code.
put_TuningSpace | Sets a storage index for regional channel-to-frequency mappings.
get_TuningSpace | Retrieves the storage index for regional fine tuning.
Logon | Logs a user onto the system.
Logout | Logs a user off the system.
SignalPresent | Retrieves the strength of the signal on a given channel.
put_Mode | Sets a multifunction tuner to the specified mode.
get_Mode | Retrieves the current mode on a multifunction tuner.
GetAvailableModes | Retrieves the tuner's supported modes.
RegisterNotificationCallBack | Allows an object that implements the IAMTunerNotification interface to receive event notifications when the tuner changes state.
UnRegisterNotificationCallBack | Unregisters an object for event notifications.

IAMTuner::ChannelMinMax

IAMTuner Interface

Retrieves the highest and lowest channels available.

Syntax

HRESULT ChannelMinMax(
    long *lChannelMin,
    long *lChannelMax
);

Parameters

lChannelMin
[out] Pointer to a variable that receives the lowest channel.
lChannelMax
[out] Pointer to a variable that receives the highest channel.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

International Analog TV Tuning

IAMTuner::get_Channel

IAMTuner Interface

Retrieves the TV channel that the tuner is set to.

Syntax

HRESULT get_Channel (
    long *plChannel,
    long *plVideoSubChannel,
    long *plAudioSubChannel
);

Parameters

plChannel
[out] Pointer to a variable that receives the channel. For frequencies, see International Analog TV Tuning.
plVideoSubChannel
[out] Pointer to a variable that receives a predefined video subchannel value. Specify AMTUNER_SUBCHAN_NO_TUNE for no tuning or AMTUNER_SUBCHAN_DEFAULT for default subchannel.
plAudioSubChannel
[out] Pointer to a variable that receives a predefined audio subchannel value. Specify AMTUNER_SUBCHAN_NO_TUNE for no tuning or AMTUNER_SUBCHAN_DEFAULT for default subchannel.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMTuner::get_CountryCode

IAMTuner Interface

Retrieves the country code that establishes the current channel-to-frequency mapping.

Syntax

HRESULT get_CountryCode(
    long *plCountryCode
);

Parameters

plCountryCode
[out] Pointer to a variable that receives the country code currently in use by the TV Tuner filter.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The put_CountryCode method determines which channel-to-frequency mapping table to use. This establishes the base frequencies for the given country. Use the IAMTVTuner::AutoTune method to determine the exact frequencies for specific regions.

Override the country code when a country wants to receive broadcast video from a different national source. For a list of country codes, see International Analog TV Tuning.

IAMTuner::get_Mode

IAMTuner Interface

Retrieves the current mode on a multifunction tuner.

Syntax

HRESULT get_Mode(
    AMTunerModeType *plMode
);

Parameters

plMode
[out] Pointer to a variable that receives a flag indicating the current mode setting. The possible values are defined in the AMTunerModeType enumeration.

Return Value

Returns an HRESULT value.

IAMTuner::get_TuningSpace

IAMTuner Interface

Retrieves the tuning space.

Syntax

HRESULT get_TuningSpace(
    long *plTuningSpace
);

Parameters

*plTuningSpace
[out] Pointer to a variable that receives the current tuning space.

Return Value

Returns an HRESULT value.

Remarks

The application defines the value retrieved by this method; it is set through a call to put_TuningSpace.

IAMTuner::GetAvailableModes

IAMTuner Interface

Retrieves the tuner's supported modes.

Syntax

HRESULT GetAvailableModes(
    long *plModes
);

Parameters

plModes
[out] Pointer to a variable that receives any combination of the values as specified in the AMTunerModeType enumeration.

Return Value

Returns an HRESULT value.

IAMTuner::Logon

IAMTuner Interface

Logs a user onto the system.

Syntax

HRESULT Logon(
    HANDLE hCurrentUser
);

Parameters

hCurrentUser
[in] Handle to an application-defined data structure that identifies the current user.

Return Value

Returns an HRESULT value.

Remarks

The Logon and Logout methods enable you to implement selective user access.

IAMTuner::Logout

IAMTuner Interface

Logs out the current user.

Syntax

HRESULT Logout(void);

Return Value

Returns an HRESULT value.

IAMTuner::put_Channel

IAMTuner Interface

Sets the TV channel.

Syntax

HRESULT put_Channel(
    long lChannel,
    long lVideoSubChannel,
    long lAudioSubChannel
);

Parameters

lChannel
[in] TV channel number.
lVideoSubChannel
Predefined video subchannel value. Specify AMTUNER_SUBCHAN_NO_TUNE for no tuning or AMTUNER_SUBCHAN_DEFAULT for default subchannel. Meaningful only for satellite broadcasts.
lAudioSubChannel
Predefined audio subchannel value. Specify AMTUNER_SUBCHAN_NO_TUNE for no tuning or AMTUNER_SUBCHAN_DEFAULT for default subchannel. Meaningful only for satellite broadcasts.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method handles the channel-to-frequency function call that converts the TV channel to a TV frequency. For a list of frequencies for channels, see International Analog TV Tuning.

IAMTuner::put_CountryCode

IAMTuner Interface

Sets the country code to establish the frequency to use.

Syntax

HRESULT put_CountryCode(
    long lCountryCode
);

Parameters

lCountryCode
[in] Value indicating the country code.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method establishes the base frequencies for the given country. Use the IAMTVTuner::AutoTune method to determine the exact frequencies for specific regions, unless there are previously cached settings for the new country.

Because channels in different countries map to different frequencies, worldwide mapping tables are provided in the appendix International Analog TV Tuning. Override the existing country code by selecting the new value from the appendix and passing it in as the parameter for the put_CountryCode method. This is useful when a country wants to receive broadcast video from a different national source.

IAMTuner::put_Mode

IAMTuner Interface

Sets a multifunction tuner to the specified mode.

Syntax

HRESULT put_Mode(
    AMTunerModeType lMode
);

Parameters

lMode
[in] Flag indicating which mode to switch to. Possible values are defined in the AMTunerModeType enumeration.

You can also set the mode to digital TV if the card supports it. To do this, define AMTUNER_MODE_DTV with a value of 0x0010.

Return Value

Returns an HRESULT value.

IAMTuner::put_TuningSpace

IAMTuner Interface

Sets a storage index for regional channel-to-frequency mappings.

Syntax

HRESULT put_TuningSpace(
    long lTuningSpace
);

Parameters

lTuningSpace
[in] Value indicating the current locale.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

As TV tuners move into portable systems, you must retain locale-specific mappings of available channels and their actual frequencies. Formulating different lTuningSpace values for each locale provides a way of switching the channel-to-frequency mappings when moving from region to region.

IAMTuner::RegisterNotificationCallBack

IAMTuner Interface

Allows an object that implements the IAMTunerNotification interface to receive event notifications when the tuner changes state.

Syntax

HRESULT RegisterNotificationCallBack(
    IAMTunerNotification *pNotify
    long lEvents
);

Parameters

pNotify
[in] Pointer to the IAMTunerNotification interface of an object that will receive the tuner event notifications.
lEvents
[in] Flag indicating that an event has occurred. The only value currently defined is AMTUNER_EVENT_CHANGED.

Return Value

Returns an HRESULT value.

IAMTuner::SignalPresent

IAMTuner Interface

Retrieves the strength of the signal on a given channel.

Syntax

HRESULT SignalPresent(
    long *plSignalStrength
);

Parameters

plSignalStrength
[out] Pointer to a variable that receives a value indicating whether a signal is present on the current channel. Can be one of the following values.
AMTUNER_HASNOSIGNALSTRENGTH | -1
AMTUNER_NOSIGNAL | 0
AMTUNER_SIGNALPRESENT | 1

A value of AMTUNER_HASNOSIGNALSTRENGTH means the signal strength cannot be determined at this time.

Return Value

Returns an HRESULT value.

IAMTuner::UnRegisterNotificationCallBack

IAMTuner Interface

Unregisters an object for event notifications.

Syntax

HRESULT UnRegisterNotificationCallBack(
    IAMTunerNotification *pNotify
);

Parameters

pNotify
[in] Pointer to the IAMTunerNotification interface that was specified in a previous call to RegisterNotificationCallBack.

Return Value

Returns an HRESULT value.


IAMTunerNotification Interface

An application that captures or displays television signals can implement the IAMTunerNotification interface in order to receive event notifications from the TV tuner filter called through IAMTuner::RegisterNotificationCallBack.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTunerNotification methods | Description
OnEvent | Handles events from the TV tuner card.

IAMTunerNotification::OnEvent

IAMTunerNotification Interface

Handles events from the TV tuner card.

Syntax

HRESULT OnEvent(
    AMTunerEventType Event
);

Parameters

Event
[in] Flag identifying the type of event. Currently, the only value defined is AMTUNER_EVENT_CHANGED.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.


IAMTVAudio Interface

The IAMTVAudio interface is implemented on the TV Audio filter. This interface enables applications to control settings unique to audio from television sources, including secondary audio program (SAP), and stereo or mono selection. These controls are generally found on devices external to the system audio mixer.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTVAudio methods | Description
GetHardwareSupportedTVAudioModes | Retrieves a bitmask of the formats available in the hardware.
GetAvailableTVAudioModes | Retrieves a bitmask of the possible modes.
get_TVAudioMode | Retrieves the current TV audio mode.
put_TVAudioMode | Sets the current TV audio mode.

IAMTVAudio::GetHardwareSupportedTVAudioModes

IAMTVAudio Interface

Retrieves a bitmask of the formats available in the hardware.

Syntax

HRESULT GetHardwareSupportedTVAudioModes(
  long *plModes
  );

Parameters

plModes
[out] Pointer to a TVAudioMode type, identifying the audio mode.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

IAMTVAudio::GetAvailableTVAudioModes

IAMTVAudio Interface

Retrieves a bitmask of the possible modes.

Syntax

HRESULT GetAvailableTVAudioModes(
  long *plModes
);

Parameters

plModes
[out] Pointer to a TVAudioMode type, identifying the audio mode.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

IAMTVAudio::get_TVAudioMode

IAMTVAudio Interface

Retrieves the current TV audio mode.

Syntax

HRESULT get_TVAudioMode(
  long *plModes
);

Parameters

plModes
[out] Pointer to a TVAudioMode type, identifying the audio mode.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

IAMTVAudio::put_TVAudioMode

IAMTVAudio Interface

Sets the current TV audio mode.

Syntax

HRESULT put_TVAudioMode(
  long plModes
);

Parameters

plModes
[in] A TVAudioMode type, identifying the audio mode.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.


IAMTVAudioNotification Interface

An application using the TV Audio filter can implement the IAMTVAudioNotification interface to receive event notifications from a TV tuner card through IAMTuner::RegisterNotificationCallBack.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTVAudioNotification methods | Description
OnEvent | Handles events from a TV tuner card controlled by the IAMTVAudio interface.

IAMTVAudioNotification::OnEvent

IAMTVAudioNotification Interface

Handles events from a TV tuner card controlled by the IAMTVAudio interface.

Syntax

HRESULT OnEvent(
    AMTVAudioEventType Event
);

Parameters

Event
[in] Flag identifying the type of event. The only value currently defined is AMTVAUDIO_EVENT_CHANGED.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.


IAMTVTuner Interface

The IAMTVTuner interface is implemented on the TV Tuner filter. This interface inherits from IAMTuner and provides methods that enable an application to control a TV tuner device. The interface supports tuners for analog broadcast television and AM/FM radio.

IAMTVTuner supports tuners with multiple input pins, to allow for multiple devices and multiple transmission types.

IAMTVTuner maps TV channels to specific frequencies through the IAMTuner::put_Channel and IAMTVTuner::AutoTune methods. These methods handle the details of the conversion so that the hardware driver receives an exact frequency. The TV Tuner filter supports worldwide tuning coverage.

Use this interface from an application to set TV channels and to get or set information about their frequencies, and to determine what analog video standards your TV tuner card supports.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMTuner methods | Description
put_Channel | Sets the TV channel.
get_Channel | Retrieves the TV channel that the encoder is currently set to.
ChannelMinMax | Retrieves the highest and lowest channels available.
put_CountryCode | Sets the country code to establish the frequency to use.
get_CountryCode | Retrieves the country code that establishes the current channel-to-frequency mapping.
put_TuningSpace | Sets a storage index for regional channel-to-frequency mappings.
get_TuningSpace | Retrieves the storage index for regional fine tuning.
Logon | Logs a user onto the system.
Logout | Logs a user off the system.
SignalPresent | Retrieves the strength of the signal on a given channel.
put_Mode | Sets the mode of operation for a multifunction tuner.
get_Mode | Retrieves the mode of operation for a multifunction tuner.
GetAvailableModes | Determines which video modes are available on the tuner.
RegisterNotificationCallBack | Allows an object that implements the IAMTunerNotification interface to receive event notifications when the tuner changes state.
UnRegisterNotificationCallBack | Unregister an object for notification of events.
IAMTVTuner methods | Description
get_AvailableTVFormats | Retrieves all the analog video TV standards that the tuner supports.
get_TVFormat | Retrieves the current analog video TV standard in use.
AutoTune | Scans for a precise signal on the channel's frequency.
StoreAutoTune | Saves the fine-tuning information for all channels.
get_NumInputConnections | Retrieves the number of TV sources plugged into the tuner filter.
put_InputType | Sets the tuner input type (cable or antenna).
get_InputType | Retrieves the input type.
put_ConnectInput | Sets the hardware tuner input connection.
get_ConnectInput | Retrieves the hardware tuner input connection.
get_VideoFrequency | Retrieves the current video frequency.
get_AudioFrequency | Retrieves the current audio frequency.

IAMTVTuner::AutoTune

IAMTVTuner Interface

Scans for a precise signal on the channel's frequency.

Syntax

HRESULT AutoTune(
    long lChannel,
    long *plFoundSignal
);

Parameters

lChannel
[in] TV channel number.
plFoundSignal
[out] Pointer to a variable indicating whether the channel's frequency was found; nonzero indicates found, zero indicates not found.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

TV channels generally map to a unique frequency depending on regional variances. To avoid interference between multiple transmitters that are assigned the same channel when they are in close geographic proximity, small frequency offsets are introduced at each transmitter. In the United States, this offset ranges up to +/– 26.25 kilohertz (kHz).

This method handles the channel-to-frequency conversion and scans for the most precise frequency. Store these values by calling the IAMTVTuner::StoreAutoTune method. You can find base frequencies for channels in the appendix International Analog TV Tuning.

IAMTVTuner::get_AudioFrequency

IAMTVTuner Interface

Retrieves the currently tuned audio frequency.

Syntax

HRESULT get_AudioFrequency(
    long *lFreq
);

Parameters

lFreq
[out] Pointer to the audio frequency.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This is a diagnostic method that enables you to examine the exact frequency being used for a given channel.

IAMTVTuner::get_AvailableTVFormats

IAMTVTuner Interface

Retrieves all the analog video TV standards that the tuner supports.

Syntax

HRESULT get_AvailableTVFormats(
    long *lAnalogVideoStandard
);

Parameters

lAnalogVideoStandard
[out] Pointer to the combination of supported analog video standards.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

For supported formats, see the AnalogVideoStandard enumerated data type.

IAMTVTuner::get_ConnectInput

IAMTVTuner Interface

Retrieves the hardware tuner input connection.

Syntax

HRESULT get_ConnectInput (
    long *plIndex
);

Parameters

plIndex
[out] Pointer to the input pin to get the connection for.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMTVTuner::get_InputType

IAMTVTuner Interface

Retrieves the input type set in put_InputType.

Syntax

HRESULT get_InputType (
    long lIndex,
    TunerInputType *pInputType
);

Parameters

lIndex
[in] Index value that specifies the input pin that will be set.
pInputType
[out] Pointer to the TunerInputType connection type; either cable (TunerInputCable) or antenna (TunerInputAntenna).

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMTVTuner::get_NumInputConnections

IAMTVTuner Interface

Retrieves the number of TV sources plugged into the tuner filter.

Syntax

HRESULT get_NumInputConnections(
    long *plNumInputConnections
);

Parameters

plNumInputConnections
[out] Pointer to the number of TV sources plugged into the tuner filter.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMTVTuner::get_TVFormat

IAMTVTuner Interface

Retrieves the current analog video TV standard in use.

Syntax

HRESULT get_TVFormat(
    long *plAnalogVideoStandard
);

Parameters

plAnalogVideoStandard
[out] Pointer to the analog video standard currently in use by the TV Tuner filter.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

For supported formats, see the AnalogVideoStandard enumerated data type.

IAMTVTuner::get_VideoFrequency

IAMTVTuner Interface

Retrieves the current video frequency.

Syntax

HRESULT get_VideoFrequency(
    long *lFreq
);

Parameters

lFreq
[out] Pointer to the video frequency.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

This is a diagnostic method that enables you to examine the exact frequency being used for a given channel.

IAMTVTuner::put_ConnectInput

IAMTVTuner Interface

Sets the hardware tuner input connection.

Syntax

HRESULT put_ConnectInput(
    long lIndex
);

Parameters

lIndex
[in] Index value of the input pin to set connection for.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMTVTuner::put_InputType

IAMTVTuner Interface

Sets the tuner input type (cable or antenna).

Syntax

HRESULT put_InputType(
    long lIndex,
    TunerInputType InputType
);

Parameters

lIndex
[in] Index value that specifies the input pin to be set.
InputType
[in] Value indicating the connection type, as specified in the TunerInputType data type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMTVTuner::StoreAutoTune

IAMTVTuner Interface

Saves the fine-tuning information for all channels.

Syntax

HRESULT StoreAutoTune(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Override the channel-to-frequency information stored by this method by setting a new country code in the IAMTuner::put_CountryCode method. For a listing of country codes, see International Analog TV Tuning.


IAMVfwCaptureDialogs Interface

The IAMVfwCaptureDialogs interface is implemented on the VFW Video Capture filter. This interface enables an application to display one of the three dialog boxes (Source, Format, or Display) provided by Microsoft® Video for Windows® capture drivers. Any application that enables the user to change settings in a Video for Windows capture driver-supplied dialog box should use this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMVfwCaptureDialogs methods | Description
HasDialog | Determines if the specified dialog box exists in the driver.
ShowDialog | Displays the specified dialog box.
SendDriverMessage | Sends a driver-specific message.

IAMVfwCaptureDialogs::HasDialog

IAMVfwCaptureDialogs Interface

Determines if the specified dialog box exists in the driver.

Syntax

HRESULT HasDialog(
  int iDialog );

Parameters

iDialog
[in] Desired dialog box. This is a member of the VfwCaptureDialogs enumerated data type.

Return Value

Returns S_OK if the driver contains the dialog box or S_FALSE otherwise.

Remarks

This method calls the Video for Windows videoDialog function to query for the existence of the appropriate dialog box.

IAMVfwCaptureDialogs::SendDriverMessage

IAMVfwCaptureDialogs Interface

Sends a driver-specific message.

Syntax

HRESULT SendDriverMessage(
  int iDialog,
  int uMsg,
  long dw1,
  long dw2 );

Parameters

iDialog
[in] Handle of the driver dialog box. This is a member of the VfwCaptureDialogs enumerated data type.
uMsg
[in] Message to send to the driver.
dw1
[in] Message data.
dw2
[in] Message data.

Return Value

Return value varies depending on the implementation within each driver.

Remarks

You should never need to use this method. This method can send any private message to the capture driver. Behavior might be undetermined in response to arbitrary messages; use this method at your own risk.

This method calls the Video for Windows videoMessage function to send the driver message.

IAMVfwCaptureDialogs::ShowDialog

IAMVfwCaptureDialogs Interface

Displays the specified dialog box.

Syntax

HRESULT ShowDialog(
  int iDialog,
  long hwnd );

Parameters

iDialog
[in] Dialog box to display. This is a member of the VfwCaptureDialogs enumerated data type.
hwnd
[in] Handle of the dialog box's parent window.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

You can't use this method when the driver is streaming or displaying another dialog box. While the driver displays the dialog box you can't stream (pause or run) the filter.

IAMVfwCaptureDialogs::ShowDialog calls the Video for Windows® VideoDialog function to display the appropriate dialog box.

If you use this method to bring up a VfwCaptureDialog_Format dialog box, it will return the VFW_E_CANNOT_CONNECT error code if a capture filter is already connected in a graph and the existing graph cannot accept the new format. Capture applications must rebuild the part of the filter graph that is downstream of the capture filter if this error occurs.


IAMVfwCompressDialogs Interface

The IAMVfwCompressDialogs interface is implemented on the AVI Compressor filter. The interface enables an application to display a Video for Windows codec "Configure" or "About" dialog box and to set and retrieve compressor status.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMVfwCompressDialogs methods | Description
ShowDialog | Displays the specified dialog box.
GetState | Retrieves the current configuration settings for the VCM codec currently being used.
SetState | Sets configuration for the VCM codec.
SendDriverMessage | Sends a driver-specific message.

IAMVfwCompressDialogs::GetState

IAMVfwCompressDialogs Interface

Retrieves the current configuration settings for the VCM codec currently being used.

Syntax

HRESULT GetState(

  LPVOID pState,

  int *pcbState

Parameters

pState
[out] State of the VCM codec.
pcbState
[in, out] Pointer to the size of the state.

Return Value

Return value varies depending on the implementation within each driver.

Remarks

This method calls the COM ICGetState macro.

IAMVfwCompressDialogs::SendDriverMessage

IAMVfwCompressDialogs Interface

Sends a driver-specific message.

Syntax

HRESULT SendDriverMessage(
  int uMsg,
  long dw1,
  long dw2 );

Parameters

uMsg
[in] Message to send to the driver.
dw1
[in] Message data.
dw2
[in] Message data.

Return Value

Return value varies depending on the implementation within each driver.

Remarks

You should never need to use this method. This method can send any private message to the video compressor (codec). Behavior might be undetermined in response to arbitrary messages; use this method at your own risk.

This method calls the Video for Windows video compression manager (VCM) ICSendMessage function to send the message.

IAMVfwCompressDialogs::SetState

IAMVfwCompressDialogs Interface

Sets configuration for the VCM codec.

Syntax

HRESULT SetState(
  LPVOID pState,
  int cbState );

Parameters

pState
[in] State of the VCM codec.
cbState
[in] Size of the state.

Return Value

Return value varies depending on the implementation within each driver.

Remarks

This method calls the COM ICSetState macro, which notifies a video compression driver to set the state of the compressor.

IAMVfwCompressDialogs::ShowDialog

IAMVfwCompressDialogs Interface

Displays the specified dialog box.

Syntax

HRESULT ShowDialog(
  int iDialog,
  long hwnd );

Parameters

iDialog
[in] Dialog box to display. This is a member of the VfwCompressDialogs enumerated data type.
hwnd
[in] Handle of the dialog box's parent window.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method returns an error when asked to display a dialog box while the driver is streaming or displaying another dialog box. While the driver displays the dialog box you can't stream (pause or run) the filter.

IAMVfwCompressDialogs::ShowDialog calls the Video for Windows video compression manager (VCM) functions ICConfigure, ICAbout, ICQueryConfigure, and ICQueryAbout to display the appropriate dialog box or determine if one exists.

The VfwCompressDialog_QueryConfig and VfwCompressDialog_QueryAbout members of the VfwCompressDialogs enumerated data type tell you whether or not the configure dialog or about dialog is available. If passed one of these flags, the filter will return S_OK if the dialog exists, and S_FALSE if it does not. If a dialog is available, you call ShowDialog with the value VfwCompressDialog_Config or VfwCompressDialog_About to bring up the dialog.


IAMVideoAccelerator Interface

The IAMVideoAccelerator interface enables a video decoder filter to access video accelerator functionality. The Overlay Mixer filter's input pin supports this interface. If a video decoder filter calls methods on this interface, the decoder should support the IAMVideoAcceleratorNotify interface on its output pin. Applications should not call methods on this interface.

Note This interface is available in Microsoft® Windows® 2000.

The sequence of events for connecting the video decoder filter is as follows:

  1. The filter graph manager calls the IPin::Connect method on the video decoder filter's output pin.
  2. The video decoder can call IAMVideoAccelerator::GetVideoAcceleratorGUIDs on the Overlay Mixer's input pin to retrieve a list of video accelerator GUIDs, which specify the video accelerator formats accepted by the Overlay Mixer.
  3. For a given video accelerator GUID, the video decoder can call IAMVideoAccelerator::GetUncompFormatsSupported to determine a suitable pixel format to propose.
  4. The video decoder calls the IPin::ReceiveConnection method on the Overlay Mixer's input pin, specifying a video accelerator GUID as the subtype of the media type. Within this call, the Overlay Mixer calls several methods on the decoder filter's output pin:
    • IAMVideoAcceleratorNotify::GetUncompSurfacesInfo, to determine how many output surfaces to create. The decoder returns information about the minimum and maximum number of surfaces to allocate, and the required pixel format.
    • IAMVideoAcceleratorNotify::SetUncompSurfacesInfo, to notify the video decoder of the actual number of surfaces allocated.
    • IAMVideoAcceleratorNotify::GetCreateVideoAcceleratorData, to get the video accelerator creation data to pass to the driver and to create its internal video accelerator object.
  5. The video decoder calls IAMVideoAccelerator::GetCompBufferInfo to retrieve information about the compressed data buffers associated with the video acceleration GUID previously specified.

To support dynamic format changes, this sequence can also occur while the filters are connected and running.

During operation, the video decoder performs the following steps.

  1. For each uncompressed data buffer, it calls IAMVideoAccelerator::BeginFrame to begin processing the output frame.
  2. To send uncompressed data to the video accelerator, the decoder calls the following methods.
    • IAMVideoAccelerator::GetBuffer, to lock and obtain access to a buffer.
    • Execute, to process data in a set of compressed buffers.
    • IAMVideoAccelerator::ReleaseBuffer, to release the lock on a buffer.
    • IAMVideoAccelerator::QueryRenderStatus to query whether a buffer can be written to or read from.
  3. To end frame processing, it calls IAMVideoAccelerator::EndFrame.
  4. To display a frame, it calls IAMVideoAccelerator::DisplayFrame.

Before locking a buffer with the GetBuffer method, the video decoder should verify that any decompression operations that update that buffer are complete. Similarly for DisplayFrame, the video decoder must check that all decompression operations that update that frame are complete.

Requirements

Requires Videoacc.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMVideoAccelerator methods | Description
GetVideoAcceleratorGUIDs | Retrieves a list of the GUIDs for the video accelerator formats accepted.
GetUncompFormatsSupported | Retrieves a list of pixel formats that can be used to render a specified video accelerator format.
GetInternalMemInfo | Retrieves information about the uncompressed data memory requirements, based on the video accelerator GUID, the uncompressed size, and the pixel format.
GetCompBufferInfo | Retrieves compressed buffer information.
GetInternalCompBufferInfo | Called after the pins are connected, retrieving compressed buffer information given the connected type.
BeginFrame | Begins frame processing.
EndFrame | Ends frame processing and passes miscellaneous data to the video accelerator driver.
GetBuffer | Retrieves the compressed buffer of a specified index and type.
ReleaseBuffer | Releases a compressed buffer after processing.
Execute | Performs a decompression operation.
QueryRenderStatus | Queries the decode status of a set of macro blocks.
DisplayFrame | Displays a decoded frame.

IAMVideoAccelerator::GetVideoAcceleratorGUIDs

IAMVideoAccelerator

Retrieves a list of the GUIDs for the video accelerator formats accepted.

Syntax

HRESULT GetVideoAcceleratorGUID(
  LPDWORD pdwNumGuidsSupported,
  LPGUID pGuidsSupported
);

Parameters

pdwNumGuidsSupported
[in] [out] If pGuidsSupported is NULL, pdwNumGuidsSupported returns with the number of video accelerator format GUIDs supported. Otherwise, this parameter is a pointer to the maximum number of GUIDs to return in pGuidsSupported. If fewer than this number are supported, pdwNumGuidsSupported is updated to be the number of GUIDs actually returned.
pGuidsSupported
[in] [out] If this parameter is not NULL, the GUIDs supported are returned in this array, whose size in bytes is at least sizeof(GUID) * (*pdwNumGuidsSupported).

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMVideoAccelerator::GetUncompFormatsSupported

IAMVideoAccelerator

Retrieves a list of pixel formats that can be used to render a specified video accelerator format.

Syntax

HRESULT GetUncompFormatsSupported(
    const GUID *pGuid,
    LPDWORD pdwNumFormatsSupported,
    LPDDPIXELFORMAT pFormatsSupported
);

Parameters

pGuid
[in] Pointer to a video accelerator GUID.
pdwNumFormatsSupported
[in] [out] If pFormatsSupported is NULL, pdwNumFormatsSupported returns with the number of pixel formats to which the video accelerator format, defined by pGuid, can be converted. Otherwise, this parameter is the number of pixel formats to return in pFormatsSupported. When the method returns, this parameter is the actual number of pixel formats returned.
pFormatsSupported
[in] [out] Pointer to a DDPIXELFORMAT structure. If this parameter is not NULL, up to *pdwNumFormatsSupported pixel formats are copied into this array. The size of the buffer should be at least *pdwNumFormatsSupported * sizeof(DDPIXELFORMAT).

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMVideoAccelerator::GetInternalMemInfo

IAMVideoAccelerator

Retrieves information about the uncompressed data memory requirements, based on the video accelerator GUID, the uncompressed size, and the pixel format.

Syntax

HRESULT GetInternalMemInfo(
    const GUID *pGuid,
    const AMVAUncompDataInfo *pamvaUncompDataInfo,
    LPAMVAInternalMemInfo pamvaInternalMemInfo
);

Parameters

pGuid
[in] Pointer to a video accelerator GUID.
pamvaUncompDataInfo
[in] Pointer to an AMVAUncompDataInfo structure containing the size and pixel format of the uncompressed data.
pamvaInternalMemInfo
[in] [out] Pointer to an AMVAInternalMemInfo structure containing information on the scratch memory requirement.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMVideoAccelerator::GetCompBufferInfo

IAMVideoAccelerator

Retrieves compressed buffer information.

Syntax

HRESULT GetCompBufferInfo(
    const GUID *pGuid,
    const AMVAUncompDataInfo *pamvaUncompDataInfo,
    LPDWORD pdwNumTypesCompBuffers,
    LPAMVACompBufferInfo pamvaCompBufferInfo
);

Parameters

pGuid
[in] Pointer to a video accelerator format GUID.
pamvaUncompDataInfo
[in] Pointer to an AMVAUncompDataInfo structure containing the size and pixel format of the uncompressed data.
pdwNumTypesCompBuffers
[in] [out] Pointer to a variable of type DWORD. If pamvaCompBufferInfo is not NULL, this parameter receives the number of uncompressed buffer types. Otherwise, on input this parameter specifies the maximum number of compressed buffer types to return, and on output receives the actual number of compressed buffer types.
pamvaCompBufferInfo
[out] If non-NULL, then up to pdwNumTypesCompBuffers AMVACompBufferInfo structures are returned. This data includes the width, height, pixel format, and DirectDraw capabilities to be used to create the surface and the size in bytes the surface will occupy.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method returns the information necessary to create a video accelerator surface of the required type using DirectDraw. A video accelerator driver may support multiple compressed buffer types (for instance, video accelerator data and Inverse Discrete Cosine Transfer [IDCT] data).

IAMVideoAccelerator::GetInternalCompBufferInfo

IAMVideoAccelerator

Called after the pins are connected, retrieving compressed buffer information given the connected type.

Syntax

HRESULT GetInternalCompBufferInfo(
    LPDWORD pdwNumTypesCompBuffers,
    LPAMVACompBufferInfo pamvaCompBufferInfo
);

Parameters

pdwNumTypesCompBuffers
[in] [out] Pointer to a variable of type DWORD. If pamvaCompBufferInfo is not NULL, this parameter receives the number of uncompressed buffer types. Otherwise, on input this parameter specifies the maximum number of compressed buffer types to return, and on output receives the actual number of compressed buffer types.
pamvaCompBufferInfo
[out] If non-NULL, then up to pdwNumTypesCompBuffers AMVACompBufferInfo structures are returned. This data includes the width, height, pixel format, and DirectDraw capabilities to be used to create the surface and the size in bytes the surface will occupy.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

A video accelerator driver may support multiple compressed buffer types (for instance, video accelerator data and Inverse Discrete Cosine Transfer [IDCT] data.)

IAMVideoAccelerator::BeginFrame

IAMVideoAccelerator

Begins frame processing.

Syntax

HRESULT BeginFrame(
    const AMVABeginFrameInfo *pamvaBeginFrameInfo
    );

Parameters

pamvaBeginFrameInfo
[in] Pointer to an AMVABeginFrameInfo structure containing the information needed to begin processing the frame.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method can only be called after the pins are connected.

The AMVABeginFrameInfo structure contains an index to the destination buffer. Valid index values are from zero to dwActualUncompSurfacesAllocated–1), obtained by calling IAMVideoAcceleratorNotify::SetUncompSurfacesInfo.

The decoder should not make any assumption about the initial contents of the frame, as the frame memory used might not be the same as the memory last used with this frame index.

A call to this method might block operation processing if no non-busy frame buffer is available.

IAMVideoAccelerator::EndFrame

IAMVideoAccelerator

Ends frame processing and passes miscellaneous data to the video accelerator driver.

Syntax

HRESULT EndFrame(
    const AMVAEndFrameInfo *pEndFrameInfo
);

Parameters

pEndFrameInfo
[in] Pointer to an AMVAEndFrameInfo structure containing miscellaneous data for the video accelerator driver.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

IAMVideoAccelerator::GetBuffer

IAMVideoAccelerator

Retrieves the compressed buffer of a specified index and type.

Syntax

HRESULT GetBuffer(
    DWORD dwTypeIndex,
    DWORD dwBufferIndex,
    BOOL bReadOnly,
    LPVOID *ppBuffer,
    LONG *lpStride
);

Parameters

dwTypeIndex
[in] Zero-based index into the surface types supported by the video accelerator driver, or 0xFFFFFFFF. See Remarks.
dwBufferIndex
[in] Buffer index within the type. The valid range is from zero to the value of the dwNumCompBuffers member of the AMVACompBufferInfo structure.
bReadOnly
[in] Boolean value indicating whether the buffer will be updated. If TRUE, the buffer will not be updated, allowing access to busy reference frames.
ppBuffer
[out] Pointer to the buffer that will contain the compressed data. The size of this buffer is determined by the dwBytesToAllocate member of the AMVACompBufferInfo structure returned for the dwSurfaceTypeIndex entry from the GetInternalCompBufferInfo method.
lpStride
[out] Stride compatible with the compression type. Generally, this will be equal to the dwWidthToCreate member of the AMVACompBufferInfo structure. Note that this might not be equal to dwWidthToCreate for output display buffers or other uncompressed types.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method locks and obtains access to a single buffer. Buffers are identified by type and by index within that type. The IAMVideoAccelerator::GetInternalCompBufferInfo method returns the number of types in its pdwNumTypesCompBuffers parameter, which defines the valid range for dwTypeIndex. For each type, the dwNumCompBuffers member of the AMVACompBufferInfo structure gives the number of buffers, which defines the valid range for dwBufferIndex. Note that dwTypeIndex and dwBufferIndex both specify zero-based offsets.

Alternatively, use a type index of 0xFFFFFFFF to retrieve a pointer to an output buffer. Currently, this is only valid between calls to BeginFrame and EndFrame. In this case the buffer index must equal the dwDestSurfaceIndex member of the AMVABeginFrameInfo structure that was passed to the last BeginFrame call.

This method will fail if the filter's pins are not connected.

Until all compressed buffers are released, it is possible that this thread will hold the Win16 lock or the DirectDraw lock.

IAMVideoAccelerator::ReleaseBuffer

IAMVideoAccelerator

Releases a compressed buffer after processing.

Syntax

HRESULT ReleaseBuffer(
    DWORD dwTypeIndex,
    DWORD dwBufferIndex
);

Parameters

dwTypeIndex
[in] Zero-based index into the surface types supported by the video accelerator driver, or 0xFFFFFFFF.
dwBufferIndex
[in] Buffer index within the type. The valid range is from zero to the value of the dwNumCompBuffers member of the AMVACompBufferInfo structure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

It is only valid to call this method after the pins are connected. Calling this method unlocks a single buffer. The video decoder calls this method when the buffer is no longer required and after any calls to Execute have been made. Note that the buffer pointer is no longer valid after this call.

IAMVideoAccelerator::Execute

IAMVideoAccelerator

Performs a decompression operation.

Syntax

HRESULT Execute(
    DWORD dwFunction,
    LPVOID lpPrivateInputData,
    DWORD cbPrivateInputData,
    LPVOID lpPrivateOutputData,
    DWORD cbPrivateOutputData,
    DWORD dwNumBuffers,
    const AMVABUFFERINFO *pamvaBufferInfo
);

Parameters

dwFunction
[in] Function number. This can be zero if this argument is the default or is ignored.
lpPrivateInputData
[in] Pointer to private input data passed to the driver.
cbPrivateInputData
[in] Length of private input data.
lpPrivateOutputData
[in] Pointer to private output data passed to the driver.
cbPrivateOutputData
[in] Length of private data buffer.
dwNumBuffers
[in] Number of AMVABUFFERINFO structures.
pamvaBufferInfo
[in] Pointer to a list of AMVABUFFERINFO structures to be passed.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

It is only valid to call this method after the pins are connected.

The associated buffer list is passed along with a function number (defaulting to zero) and any necessary private data describing the decompression operation. For example, decompressed reference frame information is passed in the buffer list. The buffer list order is important and is defined by the particular decompression operation being performed.

Private data can be passed to and from a driver.

IAMVideoAccelerator::QueryRenderStatus

IAMVideoAccelerator

Queries the decode status of a set of macro blocks.

Syntax

HRESULT QueryRenderStatus(
    DWORD dwTypeIndex,
    DWORD dwBufferIndex,
    DWORD dwFlags
);

Parameters

dwTypeIndex
[in] Type index for buffer to be tested.
dwBufferIndex
[in] Buffer index for buffer to be tested.
dwFlags
[in] Flag indicating the type of query to perform. If zero, this method tests whether the surface is safe to use for updates. If AMVA_QUERYRENDERSTATUSF_READ, this method tests whether the surface is safe to use for reading.

Return Value

Returns an HRESULT value. Returns S_OK if the operation is complete; returns E_PENDING if the operation is still in progress. If the operation failed, this method returns another failure code, which can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

Calling this method will report progress and failures.

IAMVideoAccelerator::DisplayFrame

IAMVideoAccelerator

Displays a decoded frame.

Syntax

HRESULT DisplayFrame(
    DWORD dwFlipToIndex,
    IMediaSample *pMediaSample
);

Parameters

dwFlipToIndex
[in] The surface index of the decompressed frame to display.
pMediaSample
[in] Pointer to an IMediaSample interface containing start and stop time stamps.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

It is only valid to call this method after all pins are connected. This call is non-blocking.

The video decoder invokes this method after calling EndFrame for the surface whose index is dwFlipToIndex. This index must have previously been the value of the dwDestSurfaceIndex member in the AMVABeginFrameInfo structure passed in a call to BeginFrame.


IAMVideoAcceleratorNotify Interface

The IAMVideoAcceleratorNotify interface is supported by the video decoder's output pin. The methods are called during pin connection with the downstream Overlay Mixer to set up the IAMVideoAccelerator interface.

Note This interface is available in Microsoft® Windows® 2000.

Requirements

Requires Videoacc.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMVideoAcceleratorNotify methods | Description
GetUncompSurfacesInfo | Retrieves the decompressed buffer information for a given video accelerator GUID.
SetUncompSurfacesInfo | Sets the uncompressed buffer information.
GetCreateVideoAcceleratorData | Retrieves the information needed to create a video accelerator object.

IAMVideoAcceleratorNotify::GetUncompSurfacesInfo

IAMVideoAcceleratorNotify

Retrieves the decompressed buffer information for a given video accelerator GUID.

Syntax

HRESULT GetUncompSurfacesInfo(
    const GUID *pGuid,
    LPAMVAUncompBufferInfo pUncomBufferInfo
);

Parameters

pGuid
[in] Pointer to a GUID identifying the video accelerator for which information is returned.
pUncompBufferInfo
[in, out] Pointer to a AMVAUncompBufferInfo structure, containing uncompressed surface information.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

Calling this method returns the video decoder's requirements for the minimum and maximum number of surfaces, as well as the pixel format. This method provides information necessary to allocate uncompressed data buffers.

IAMVideoAcceleratorNotify::SetUncompSurfacesInfo

IAMVideoAcceleratorNotify

Sets the uncompressed buffer information.

Syntax

HRESULT SetUncompSurfacesInfo(
    DWORD  dwActualUncompSurfacesAllocated
);

Parameters

dwActualUncompSurfacesAllocated
[in] The number of surfaces allocated.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

Calling this method tells the video decoder how many decompressed surfaces are actually allocated.

IAMVideoAcceleratorNotify::GetCreateVideoAcceleratorData

IAMVideoAcceleratorNotify

Retrieves the information needed to create a video accelerator object.

Syntax

HRESULT GetCreateVideoAcceleratorData(
    const GUID *pGuid,
    LPWDORD pdwSizeMiscData,
    LPVOID *ppMiscData
);

Parameters

pGuid
[in] Pointer to a GUID identifying the video accelerator.
pdwSizeMiscData
[out] Pointer to a variable that receives the size of the data returned in ppMiscData, in bytes.
ppMiscData
[out] Address to a pointer of type void that receives the miscellaneous data (or NULL if pdwSizeMiscData is 0). This pointer should be allocated with CoTaskMemAlloc, a helper function from the COM library. It is freed by the caller. See Remarks.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method retrieves a pointer to any miscellaneous data that the video decoder needs to send to the video accelerator driver when the video accelerator is initialized. It is the caller's responsibility to call CoTaskMemFree on ppMiscData.


IAMVideoCompression Interface

The IAMVideoCompression pin interface enables you to control compression parameters that aren't part of the media type.

The put_PFramesPerKeyFrame and get_PFramesPerKeyFrame methods refer to predicted (P) frames and bidirectional (B) frames, which are MPEG concepts and not generally applicable to simpler types of compressors.

Implement this interface on the output pin of a video capture or video compressor filter that provides compressed video data.

An application can use this interface to control how video is compressed, including characteristics such as the number of key frames and frame quality. Use it to retrieve a textual description of the compressor and other available information, including the compressor's capabilities.

Note This interface is not always available unless the output pin of a capture filter is connected to another filter in the graph.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMVideoCompression methods | Description
put_KeyFrameRate | Sets the key-frame rate.
get_KeyFrameRate | Retrieves the key-frame rate.
put_PFramesPerKeyFrame | Sets the predicted (P) frame frequency.
get_PFramesPerKeyFrame | Retrieves the P frame frequency.
put_Quality | Sets the quality of the video image compression.
get_Quality | Retrieves the current image quality setting.
put_WindowSize | Sets the number of frames over which the compressor must maintain an average data rate.
get_WindowSize | Retrieves the number of frames over which the compressor must maintain an average data rate.
GetInfo | Retrieves compressor information.
OverrideKeyFrame | Forces a particular frame to be a key frame.
OverrideFrameSize | Overrides a particular frame's data rate.

IAMVideoCompression::GetInfo

IAMVideoCompression Interface

Retrieves compressor information.

Syntax

HRESULT GetInfo(
    WCHAR *pszVersion,
    int *pcbVersion,
    LPWSTR pszDescription,
    int *pcbDescription,
    long *pDefaultKeyFrameRate,
    long *pDefaultPFramesPerKey,
    double *pDefaultQuality,
    long *pCapabilities
    ) PURE;

Parameters

pszVersion
[out] Pointer to a version string, such as "Version 2.1.0".
pcbVersion
[in, out] Size needed for a version string. Pointer to the number of bytes in the Unicode™ string, not the number of characters, so it must be twice the number of characters the string can hold. Call with this set to NULL to retrieve the current size.
pszDescription
[out] Pointer to a description string, such as "Awesome Video Compressor".
pcbDescription
[in, out] Size needed for a description string. Pointer to the number of bytes in the Unicode™ string, not the number of characters, so it must be twice the number of characters the string can hold. Call with this set to NULL to retrieve the current size.
pDefaultKeyFrameRate
[out] Pointer to receive the default key-frame rate.
pDefaultPFramesPerKey
[out] Pointer to receive the default predicted (P) frames per key frame.
pDefaultQuality
[out] Pointer to receive the default quality.
pCapabilities
[out] Pointer to receive the compression capabilities, which are a combination of the CompressionCaps data type flags.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMVideoCompression::get_KeyFrameRate

IAMVideoCompression Interface

Retrieves the current key-frame rate.

Syntax

get_KeyFrameRate(
    long *pKeyFrameRate
    ) PURE;

Parameters

pKeyFrameRate
[out] Pointer to the compressor's current key-frame rate. A negative value means it is using the default frame rate for the video compressor. A zero value means only the first frame is a key frame.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

To determine if the compressor supports this method, check for the CompressionCaps_CanKeyFrame flag returned in the pCapabilities parameter of the IAMVideoCompression::GetInfo method.

See Also

IAMVideoCompression::put_KeyFrameRate

IAMVideoCompression::get_PFramesPerKeyFrame

IAMVideoCompression Interface

Retrieves the predicted (P) frame interval.

Syntax

HRESULT get_PFramesPerKeyFrame(
    long *pPFramesPerKeyFrame
    ) PURE;

Parameters

pPFramesPerKeyFrame
[out] Pointer to receive the number of P frames per key frame. A negative value means the compressor will use its default value.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The Video for Windows capture filter (VFW Video Capture) and the AVI compression filter (AVI Compressor) do not currently support this interface and return E_NOTIMPL.

Remarks

To determine if the compressor supports this method, check for the CompressionCaps_CanBFrame flag returned in the pCapabilities parameter of the IAMVideoCompression::GetInfo method.

As an example of the relationship between the types of frames, suppose a key frame occurs once in every 10 frames, and there are 3 P frames per key frame. The P frames will be spaced evenly between the key frames. The other 6 frames, which occur between the key frames and the P frames, will be bidirectional (B) frames.

See Also

IAMVideoCompression::put_KeyFrameRate

IAMVideoCompression::get_Quality

IAMVideoCompression Interface

Retrieves the current image quality setting.

Syntax

HRESULT get_Quality(
    double *pQuality
    ) PURE;

Parameters

pQuality
[out] Pointer to the current quality setting.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The quality is a value between 0 and 1. One indicates the highest (best) quality and 0 indicates the lowest (worst) quality. A negative number means it is using the compressor default. The compressor interprets this number; this interpretation varies from compressor to compressor. When the compressor is not compressing to a specific data rate, the value will roughly determine the image size or quality.

To determine if the compressor supports this method, check for the CompressionCaps_CanQuality flag returned in the pCapabilities parameter of the IAMVideoCompression::GetInfo method.

If you are compressing to a fixed data rate, a high quality value means use all of the data rate, and a low quality value means you can use much lower than the data rate.

IAMVideoCompression::get_WindowSize

IAMVideoCompression Interface

Retrieves the number of frames over which the compressor must maintain an average data rate.

Syntax

HRESULT get_WindowSize(
    DWORDLONG *pWindowSize
    );

Parameters

pWindowSize
[out] Pointer to a DWORDLONG value that will receive the window size.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IAMVideoCompression::put_WindowSize

IAMVideoCompression::OverrideFrameSize

IAMVideoCompression Interface

Overrides a frame's data rate.

Syntax

HRESULT OverrideFrameSize(
    long FrameNumber,
    long Size
    ) PURE;

Parameters

FrameNumber
[in] Frame number for which to change the size.
Size
[in] Desired size, in bytes, for the specified frame.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The Video for Windows capture filter (VFW Video Capture) and the AVI compression filter (AVI Compressor) do not currently support this interface and return E_NOTIMPL.

Remarks

To determine if the compressor might support this method, check for the CompressionCaps_CanCrunch flag returned in the pCapabilities parameter of the IAMVideoCompression::GetInfo method. The flag might also be set to indicate that the dwBitRate value can be set in the AM_MEDIA_TYPE's VIDEOINFOHEADER structure.

The frame number refers to which frame goes out of the filter after it is streaming. For example, frame 0 means the first frame this pin delivers. Frame 11 means the twelfth frame it delivers. Be sure to call this method before the filter delivers the frame for which you want to provide a different size.

Overriding the frame size (or "crunching" the frame) instructs the filter to make the frame size this many bytes or less instead of the originally planned size.

IAMVideoCompression::OverrideKeyFrame

IAMVideoCompression Interface

Forces a frame to be a key frame.

Syntax

HRESULT OverrideKeyFrame(
    long FrameNumber
    ) PURE;

Parameters

FrameNumber
[in] Number of the frame to be made a key frame when the graph runs, even if it wouldn't usually be a key frame.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The Video for Windows capture filter (VFW Video Capture) and the AVI compression filter (AVI Compressor) do not currently support this interface and return E_NOTIMPL.

Remarks

After a compressor creates a key frame, it might reset its count to determine when the next key frame should occur. For example, assume a key frame typically occurs once every 10 frames. If you mark frame 5 as a key frame using OverrideKeyFrame, the compressor might wait 10 more frames until creating the next key frame.

IAMVideoCompression::put_KeyFrameRate

IAMVideoCompression Interface

Sets the key-frame rate.

Syntax

HRESULT put_KeyFrameRate(
    long KeyFrameRate
    ) PURE;

Parameters

KeyFrameRate
[in] Desired key-frame rate. A negative value means use the default frame rate for the video compressor. A zero value means that only the first frame is a key frame.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

To determine if the compressor supports this method, check for the CompressionCaps_CanKeyFrame flag returned in the pCapabilities parameter of the IAMVideoCompression::GetInfo method.

IAMVideoCompression::put_PFramesPerKeyFrame

IAMVideoCompression Interface

Sets predicted (P) frame interval.

Syntax

HRESULT put_PFramesPerKeyFrame(
    long PFramesPerKeyFrame
    ) PURE;

Parameters

PFramesPerKeyFrame
[in] Desired P frame interval. A negative value means use the default frame rate for the video compressor.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The Video for Windows capture filter (VFW Video Capture) and the AVI compression filter (AVI Compressor) do not currently support this interface and return E_NOTIMPL.

Remarks

To determine if the compressor supports this method, check for the CompressionCaps_CanBFrame flag returned in the pCapabilities parameter of the IAMVideoCompression::GetInfo method.

As an example of the relationship between the types of frames, suppose a key frame occurs once in every 10 frames, and there are 3 P frames per key frame. The P frames will be spaced evenly between the key frames. The other 6 frames, which occur between the key frames and the P frames, will be bidirectional (B) frames.

IAMVideoCompression::put_Quality

IAMVideoCompression Interface

Sets the quality of the video image.

Syntax

HRESULT put_Quality(
    double Quality
    ) PURE;

Parameters

Quality
[in] Desired quality.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The quality is a value between 0 and 1, inclusive. One indicates the highest (best) quality and 0 indicates the lowest (worst) quality. A negative number means use the compressor default. The compressor (codec) interprets this number; interpretation varies from codec to codec. When the compressor is not compressing to a specific data rate, the value will roughly determine the image size or quality.

To determine if the compressor supports this method, check the CompressionCaps_CanQuality flag returned in the pCapabilities parameter of the IAMVideoCompression::GetInfo method.

If you are compressing to a fixed data rate, a high quality value means use all of the data rate, and a low quality value means you can use much lower than the data rate.

IAMVideoCompression::put_WindowSize

IAMVideoCompression Interface

Sets the number of frames over which the compressor must maintain an average data rate.

Syntax

HRESULT put_WindowSize(
    DWORDLONG WindowSize
    );

Parameters

WindowSize
[in] Window size, or number of frames, whose average size cannot exceed the data rate that the compressor has been asked to provide.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

For a window of size n, the average frame size of any consecutive n frames will not exceed the stream's specified data rate, although individual frames can be larger or smaller. For example, if you have set a data rate of 100 kilobytes (KB) per second on a 10 frames per second (fps) movie, that will usually mean each frame must be less than or equal to 10 KB. However, by setting a window size of n, you are specifying that as long as the average length of those n frames is less than or equal to 10 KB, it doesn't matter how large the individual frames are. For example, some could be smaller and some could actually be larger than 10 KB, as long as the average is less than or equal to 10 KB.

See Also

IAMVideoCompression::get_WindowSize


IAMVideoControl Interface

The IAMVideoControl interface enables you to flip a picture horizontally and/or vertically, set up a stream so it can capture from an external trigger (such as a camera button that the user pushes), simulate an external trigger in software, and list the available frame rates.

This interface uses the video control flags in the VideoControlFlags enumeration.

Implement this interface when your filter needs to control the video image or to list the frame rates.

Use this interface when your application runs on hardware that is capable of flipping and external triggering.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMVideoControl methods | Description
GetCaps | Retrieves the capabilities of the underlying hardware.
SetMode | Sets the video control mode of operation.
GetMode | Retrieves the video control mode of operation.
GetCurrentActualFrameRate | Retrieves the actual frame rate at which the device is streaming. This method is used with devices, such as the Universal Serial Bus (USB) or cameras that use the IEEE 1394 serial standard, where the maximum frame rate can be limited by bandwidth availability. This is only available during video streaming.
GetMaxAvailableFrameRate | Retrieves the maximum frame rate currently available based on bus bandwidth usage for connections such as USB and IEEE 1394 camera devices where the maximum frame rate can be limited by bandwidth availability.
GetFrameRateList | Retrieves a list of available frame rates.

IAMVideoControl::GetCaps

IAMVideoControl Interface

Retrieves the capabilities of the underlying hardware.

Syntax

HRESULT GetCaps (

  IPin *pPin,

  long *pCapsFlags

  );

Parameters

pPin
[in] Pointer to the pin to query capabilities from.
pCapsFlags
[out] Pointer to a value representing a combination of the flags from the VideoControlFlags enumeration.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Possible capabilities include one or more of the following: flipping the picture horizontally, flipping the picture vertically, enabling external triggers, and simulating external triggers.

IAMVideoControl::GetCurrentActualFrameRate

IAMVideoControl Interface

Retrieves the actual frame rate, expressed as a frame duration in 100-nanosecond units. USB (Universal Serial Bus) and IEEE 1394 cameras may provide lower frame rates than requested because of bandwidth availability. This is only available during video streaming.

Syntax

HRESULT GetCurrentActualFrameRate (

  IPin *pPin,

  LONGLONG *ActualFrameRate

  );

Parameters

pPin
[in] Pointer to the pin to retrieve the frame rate from.
ActualFrameRate
[out] Pointer to the frame rate in frame duration in 100-nanosecond units.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMVideoControl::GetFrameRateList

IAMVideoControl Interface

Retrieves a list of available frame rates.

Syntax

HRESULT GetFrameRateList (

  IPin *pPin,

  long iIndex,

  SIZE Dimensions,

  long *ListSize,

  LONGLONG **FrameRates

  );

Parameters

pPin
[in] Pointer to the pin to query for the list of frame rates.
iIndex
[in] Index of the format to query for frame rates. This index corresponds to the order in which formats are enumerated by IAMStreamConfig::GetStreamCaps. The value must range between zero and the number of supported VIDEO_STREAM_CONFIG_CAPS structures returned by IAMStreamConfig::GetNumberOfCapabilities) minus one.
Dimensions
[in] Frame image size (width and height) in pixels.
ListSize
[out] Pointer to the number of elements in the list of frame rates.
FrameRates
[out] Address of a pointer to an array of frame rates in 100-nanosecond units. Can be NULL if you only need ListSize.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The caller is responsible for freeing the memory through a call to CoTaskMemFree.

IAMVideoControl::GetMaxAvailableFrameRate

IAMVideoControl Interface

Retrieves the maximum frame rate currently available, based on bus bandwidth usage for connections, such as USB and IEEE 1394, where the maximum frame rate may be limited by bandwidth availability.

Syntax

HRESULT GetMaxAvailableFrameRate(

  IPin *pPin,

  long iIndex,

  SIZE Dimensions,

  LONGLONG *MaxAvailableFrameRate

  );

Parameters

pPin
[in] Pointer to the pin to retrieve the maximum frame rate from.
iIndex
[in] Index of the format to query for maximum frame rate. This index corresponds to the order in which formats are enumerated by IAMStreamConfig::GetStreamCaps. The value must range between zero and the number of supported VIDEO_STREAM_CONFIG_CAPS structures returned by IAMStreamConfig::GetNumberOfCapabilities) minus one.
Dimensions
[in] Frame image size (width and height) in pixels.
MaxAvailableFrameRate
[out] Pointer to the maximum available frame rate. The frame rate is expressed as frame duration in 100-nanosecond units.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IAMVideoControl::GetMode

IAMVideoControl Interface

Retrieves the video control mode of operation.

Syntax

HRESULT GetMode (

  IPin *pPin,

  long *Mode

  );

Parameters

pPin
[in] Pointer to the pin to retrieve the video control mode from.
Mode
[out] Pointer to a value representing a combination of the flags from the VideoControlFlags enumeration, which specify the video control mode.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Possible modes of operation include one or more of the following: flipping the picture horizontally, flipping the picture vertically, enabling external triggers, and simulating external triggers.

IAMVideoControl::SetMode

IAMVideoControl Interface

Sets the video control mode of operation.

Syntax

HRESULT SetMode (

  IPin *pPin,

  long Mode

  );

Parameters

pPin
[in] Pointer to the pin to set the video control mode on.
Mode
[in] Value specifying a combination of the flags from the VideoControlFlags enumeration to set the video control mode.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Possible modes of operation include one or more of the following: flipping the picture horizontally, flipping the picture vertically, enabling external triggers, and simulating external triggers.


IAMVideoDecimationProperties Interface

The IAMVideoDecimationProperties interface enables an application to control where video decimation occurs. The Overlay Mixer filter implements this interface.

If a video window is smaller than the native size of the video being displayed, the video renderer must decimate the incoming video—that is, scale the video down to the smaller size. Decimation can be performed in one of the following places.

  • The overlay hardware on the VGA chip.
  • The scaler built in to the video port (if the connection is through a video port).
  • The decoder supplying video to the renderer.

An application can call methods on this interface to select a particular decimation strategy, in order to optimize performance. However, most applications will have no occasion to use this interface. Unless your application is designed to support particular hardware, there is no reason to modify the Overlay Mixer filter's default behavior for decimation.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMVideoDecimationProperties methods | Description
QueryDecimationUsage | Retrieves the current decimation strategy.
SetDecimationUsage | Sets the decimation strategy.

IAMVideoDecimationProperties::QueryDecimationUsage

IAMVideoDecimationProperties Interface

Retrieves the current decimation strategy.

Syntax

HRESULT QueryDecimationUsage(
    DECIMATION_USAGE *lpUsage
);

Parameters

lpUsage
[out] Pointer to a variable of type DECIMATION_USAGE that receives the decimation setting.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The Microsoft® DirectShow® implementation returns S_OK if successful, or E_FAIL or another error code otherwise.

IAMVideoDecimationProperties::SetDecimationUsage

IAMVideoDecimationProperties Interface

Sets the decimation strategy.

Syntax

HRESULT SetDecimationUsage(
    DECIMATION_USAGE Usage
);

Parameters

Usage
[in] Member of the DECIMATION_USAGE enumeration that specifies the decimation strategy.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The DirectShow implementation returns S_OK if successful, or E_INVALIDARG otherwise.


IAMVideoProcAmp Interface

The IAMVideoProcAmp interface is implemented on the WDM Video Capture filter. The interface enables applications to adjust the qualities of the incoming video signal such as brightness, contrast, hue, saturation, gamma, and sharpness. It defines a uniform range for these settings regardless of whether the adjustment is made in the analog or digital domain.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMVideoProcAmp methods | Description
GetRange | Retrieves minimum, maximum, and default values for setting properties.
Set | Sets video quality for a specified property.
Get | Retrieves video quality for a specified property.

IAMVideoProcAmp::Get

IAMVideoProcAmp Interface

Retrieves video quality for a specified property.

Syntax

HRESULT Get(

  long Property,

  long *lValue,

  long *Flags );

Parameters

Property
[in] Specific property to retrieve the setting of. Specify a member of the VideoProcAmpProperty enumerated type.
lValue
[out] Pointer to the current value of the property.
Flags
[out] Pointer to a member of the VideoProcAmpFlags enumerated type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
NOERROR | No error.

IAMVideoProcAmp::GetRange

IAMVideoProcAmp Interface

Retrieves minimum, maximum, and default values for setting properties.

Syntax

HRESULT GetRange(

  long Property,

  long *pMin,

  long *pMax,

  long *pSteppingDelta,

  long *pDefault,

  long *pCapsFlags );

Parameters

Property
[in] Specific property to determine the range of. Specify a member of the VideoProcAmpProperty enumerated type.
pMin
[out] Pointer to the minimum setting range.
pMax
[out] Pointer to the maximum setting range.
pSteppingDelta
[out] Pointer to the step size.
pDefault
[out] Pointer to the default value.
pCapsFlags
[out] Pointer to a member of the VideoProcAmpFlags enumerated type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
NOERROR | No error.

IAMVideoProcAmp::Set

IAMVideoProcAmp Interface

Sets video quality for a specified property.

Syntax

HRESULT Set(
  long Property,
  long lValue,
  long Flags );

Parameters

Property
[in] Specific property to set. Specify a member of the VideoProcAmpProperty enumerated type.
lValue
[in] Value indicating the setting of the property.
Flags
[in] Member of the VideoProcAmpFlags enumerated type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
NOERROR | No error.


IAsyncReader Interface

The IAsyncReader interface is implemented by the output pin on the Async File Source filter. The interface allows multiple overlapped reads from different positions in the media stream. These methods are called by the input pin on the downstream filter. Applications do not use this interface at all.

Filter developers: Implement this interface on a pin if your filter reads data of media type MEDIATYPE_Stream from some source. During connection an output pin supporting IAsyncReader should check whether its QueryInterface method is called asking for the IAsyncReader interface. If it is not, then the output pin should fail the connect unless it establishes some other transport to use during the connection.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAsyncReader methods | Description
RequestAllocator | Retrieves the actual allocator to be used.
Request | Queues a request for data.
WaitForNext | Blocks until the next sample is completed or the time-out occurs.
SyncReadAligned | Performs an aligned synchronized read.
SyncRead | Performs a synchronized read.
Length | Retrieves the total length of the stream, and the currently available length.
BeginFlush | Causes all outstanding reads to return.
EndFlush | Ends the flushing operation.

IAsyncReader::BeginFlush

IAsyncReader Interface

Starts the flushing operation.

Syntax

HRESULT BeginFlush(void);

Return Value

Returns S_OK if successful, S_FALSE otherwise.

Remarks

Causes all outstanding reads to return, possibly with a failure code (VFW_E_TIMEOUT), indicating that the outstanding reads were canceled. Between IAsyncReader::BeginFlush and IAsyncReader::EndFlush calls, IAsyncReader::Request calls will fail and IAsyncReader::WaitForNext calls will always complete immediately.

IAsyncReader::EndFlush

IAsyncReader Interface

Completes the flushing operation.

Syntax

HRESULT EndFlush(void);

Return Value

Returns S_OK if successful, S_FALSE otherwise.

Remarks

Between IAsyncReader::BeginFlush and IAsyncReader::EndFlush calls, IAsyncReader::Request calls will fail and IAsyncReader::WaitForNext calls will always complete immediately. This method is called so the source thread can wait in the IAsyncReader::WaitForNext method again.

IAsyncReader::Length

IAsyncReader Interface

Retrieves the stream's total length, and the currently available length.

Syntax

HRESULT Length(

  LONGLONG *pTotal,

  LONGLONG *pAvailable

  );

Parameters

pTotal
Pointer to the total allocated length.
pAvailable
Pointer to the available length.

Return Value

Returns S_OK if successful, E_UNEXPECTED if the file has not been opened.

Remarks

Read operations beyond the available length but within the total length will normally succeed, but they might block for a long period of time.

IAsyncReader::Request

IAsyncReader Interface

Queues a request for data.

Syntax

HRESULT Request(

  IMediaSample *pSample,

  DWORD dwUser

  );

Parameters

pSample
Pointer to the media sample being requested.
dwUser
[in] User context.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current Microsoft® DirectShow® implementation return values include:
VFW_E_BADALIGN | An invalid alignment was specified.
VFW_E_MEDIA_TIME_NOT_SET | Time has not been set.
HRESULT_FROM_WIN32 | Request for data past end of file.
NOERROR | No error.
S_OK | Success.

Remarks

Media sample start and stop times contain the requested absolute byte position (start-inclusive and stop-exclusive). This method might fail if the sample is not obtained from an agreed allocator or if the start or stop position does not match the agreed alignment. The samples allocated from the source pin's allocator might fail IMediaSample::GetPointer until after returning from IAsyncReader::WaitForNext.

The stop position must be aligned, which means it might exceed duration. On completion, the stop position will be corrected to the unaligned actual data.

The dwUser parameter is used by the caller to identify the sample that returned from the IAsyncReader::WaitForNext method. It has no meaning within IAsyncReader but could be used to track individual sample information.

IAsyncReader::RequestAllocator

IAsyncReader Interface

Retrieves the actual allocator to be used.

Syntax

HRESULT RequestAllocator(

  IMemAllocator *pPreferred,

  ALLOCATOR_PROPERTIES *pProps,

  IMemAllocator **ppActual

  );

Parameters

pPreferred
[in] Pointer to the preferred allocator.
pProps
[in] Pointer to the preferred allocator properties (size, count, and alignment).
ppActual
[out] Address of a pointer to the actual allocator used.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current DirectShow implementation return values include:
E_FAIL | Failure to initialize an allocator.
VFW_E_BADALIGN | An invalid alignment was specified.
S_OK | Allocator was returned.

Remarks

The preferred allocator and preferred allocator properties must be passed in. This method returns the actual allocator to be used.

IMemAllocator::GetProperties should be called on the returned allocator to learn the alignment and prefix chosen. This allocator will not be committed and decommitted by the asynchronous reader, only by the consumer. This method must be called before calling IAsyncReader::Request.

IAsyncReader::SyncRead

IAsyncReader Interface

Performs a synchronous read.

Syntax

HRESULT SyncRead(

  LONGLONG llPosition,

  LONG lLength,

  BYTE *pBuffer

  );

Parameters

llPosition
[in] Absolute file position.
lLength
[in] Number of bytes required.
pBuffer
[out] Pointer to where the data is written.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current DirectShow implementation return values include:
VFW_E_BADALIGN | An invalid alignment was specified.
HRESULT_FROM_WIN32 | Microsoft® Win32® error.
S_FALSE | Size changed (probably due to end of file).
S_OK | Success.

Remarks

The SyncRead method works in a stopped state as well as in a running state. The read is not necessarily aligned. This method fails if the read is beyond the actual total length.

IAsyncReader::SyncReadAligned

IAsyncReader Interface

Performs a synchronous read of the data.

Syntax

HRESULT SyncReadAligned(

  IMediaSample *pSample

  );

Parameters

pSample
Pointer to the sample to read.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current DirectShow implementation return values include:
VFW_E_BADALIGN | An invalid alignment was specified.
HRESULT_FROM_WIN32 | Win32 error.
S_FALSE | Size changed (probably due to end of file).
S_OK | Success.

Remarks

The sample passed in must have been acquired from the agreed allocator. The start and stop positions must be aligned equivalent to an IAsyncReader::Request/IAsyncReader::WaitForNext pair, but may avoid the need for a thread on the source filter.

IAsyncReader::WaitForNext

IAsyncReader Interface

Blocks until the next read requested through IAsyncReader::Request completes or the time-out occurs.

Syntax

HRESULT WaitForNext(

  DWORD dwTimeout,

  IMediaSample **ppSample,

  DWORD *pdwUser

  );

Parameters

dwTimeout
[in] Time-out in milliseconds; can be zero or INFINITE.
ppSample
[out] Address of a pointer to the completed sample.
pdwUser
[out] Pointer to the user context.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current DirectShow implementation return values include:
VFW_E_TIMEOUT | A time-out has expired.
VFW_E_WRONG_STATE | The operation could not be performed because the filter is in the wrong state.
E_FAIL | Failure.
S_OK | Success.

Remarks

Samples may not be returned in order. If there is a read error of any sort, a notification will already have been sent by the source filter, and HRESULT will be an error. If ppSample is not null, a request has been completed with the result code returned.

The pdwUser parameter returns the caller's context DWORD corresponding to the sample returned.


IBaseFilter Interface

Provides methods for controlling a filter. All Microsoft® DirectShow® filters expose this interface. This interface derives from the IMediaFilter interface, and inherits the IPersist interface through IMediaFilter.

The filter graph manager uses this interface to control filters. Applications and other filters can use this interface to enumerate pins and query for filter information. They should not use it to change the state of a filter. Instead, call IMediaControl interfaces on the filter graph manager.

Filter developers: Implement this interface on every DirectShow filter. The CBaseFilter base class implements this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaFilter methods | Description
Stop | Stops the filter.
Pause | Pauses the filter.
Run | Runs the filter.
GetState | Retrieves the filter's state (running, stopped, or paused).
SetSyncSource | Sets a reference clock for the filter.
GetSyncSource | Retrieves the reference clock that the filter is using.
IBaseFilter methods | Description
EnumPins | Enumerates the pins on this filter.
FindPin | Retrieves the pin with the specified identifier.
QueryFilterInfo | Retrieves information about the filter.
JoinFilterGraph | Notifies the filter that it has joined or left the filter graph.
QueryVendorInfo | Retrieves a string containing vendor information.

IBaseFilter::EnumPins

IBaseFilter Interface

Enumerates the pins on this filter.

Syntax

HRESULT EnumPins(
    IEnumPins **ppEnum
);

Parameters

ppEnum
[out] Address of a variable that receives a pointer to the IEnumPins interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | Null pointer argument

Remarks

This method returns an enumerator that supports the IEnumPins interface, which works like a standard COM enumerator. For more information, see Enumerating Pins.

If the method succeeds, the IEnumPins interface has an outstanding reference count. Be sure to release the interface when you are done.

IBaseFilter::FindPin

IBaseFilter Interface

Retrieves the pin with the specified identifier.

Syntax

HRESULT FindPin(
    LPCWSTR Id,
    IPin **ppPin
);

Parameters

Id
[in] Pointer to a constant, null-terminated Unicode™ string that identifies the pin. Call the IPin::QueryId method to retrieve a pin's identifier.
ppPin
[out] Address of a variable that receives a pointer to the pin's IPin interface. If the method fails, *ppPin is set to NULL.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_NOT_FOUND | Could not find a pin with this identifier.

Remarks

This method supports graph persistence. Use the IPin::QueryId method to save a pin's state, and use this method to restore the state. The pin's identifier string is defined by the filter implementation. The identifier must be unique within the filter.

If the method succeeds, the IPin interface that it returns has an outstanding reference count. Be sure to release the interface when you are done.

IBaseFilter::JoinFilterGraph

IBaseFilter Interface

Notifies the filter that it has joined or left the filter graph.

Syntax

HRESULT JoinFilterGraph(
    IFilterGraph *pGraph,
    LPCWSTR pName
);

Parameters

pGraph
[in] Pointer to the filter graph manager's IFilterGraph interface, or NULL if the filter is leaving the graph.
pName
[in, string] Pointer to a null-terminated Unicode™ string that specifies a name for the filter.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

When the filter graph manager adds a filter to the filter graph, it calls this method with a pointer to itself. When it removes the filter from the graph, it calls this method with a NULL pointer.

Applications should never call this method. To add a filter to the graph, call the IFilterGraph::AddFilter method on the filter graph manager.

The filter should store the IFilterGraph interface pointer, so that it can post event notifications. However, it must not add a reference count to this interface. Doing so would create a circular reference count, because the filter graph manager keeps a reference count on the filter. A circular reference will prevent the interface from being released properly. The IFilterGraph interface is guaranteed to be valid until the filter graph manager notifies the filter that it has been removed from the graph.

The name passed in the pName parameter can be retrieved by calling the QueryFilterInfo method.

IBaseFilter::QueryFilterInfo

IBaseFilter Interface

Retrieves information about the filter.

Syntax

HRESULT QueryFilterInfo(
    FILTER_INFO *pInfo
);

Parameters

pInfo
[out] Pointer to a FILTER_INFO structure.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success
E_POINTER | Null pointer argument

Remarks

This method fills the FILTER_INFO structure with the filter information. On return, if the pGraph member of the FILTER_INFO structure is non-NULL, the IFilterGraph interface has an outstanding reference count. Be sure to release the interface when you are done.

IBaseFilter::QueryVendorInfo

IBaseFilter Interface

Retrieves a string containing vendor information.

Syntax

HRESULT QueryVendorInfo(
    LPWSTR *pVendorInfo
);

Parameters

pVendorInfo
[out] Address of a variable that receives a pointer to a wide-character string containing the vendor information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.

Remarks

This method is optional; filters are not required to support it.

If the method is supported, it uses the CoTaskMemAlloc function to allocate memory for the string. Call the CoTaskMemFree function to free the memory.


IBasicAudio Interface

The IBasicAudio Automation interface is implemented on the Audio Renderer and Default DirectSound Device filters but is exposed through the Filter Graph Manager by means of a plug-in distributor. Applications should always retrieve this interface from the Filter Graph Manager. The interface enables C++ and Microsoft® Visual Basic® applications to control the basic volume and balance properties of the audio stream.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether there is type information available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returned successfully.
GetIDsOfNames | Converts text names of properties and methods (including arguments) to their corresponding DISPIDs.
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IBasicAudio methods | Description
put_Volume | Sets the volume (amplitude) of the audio signal.
get_Volume | Retrieves the volume (amplitude) of the audio signal.
put_Balance | Sets the balance for the audio signal.
get_Balance | Retrieves the balance for the audio signal.

IBasicAudio::get_Balance

IBasicAudio Interface

Retrieves the balance for the audio signal.

Syntax

HRESULT get_Balance(

  long *plBalance

  );

Parameters

plBalance
[out] Pointer to the returned value of the Balance property.

Return Value

Returns an HRESULT value.

Remarks

The Balance property is a value between –10,000 and 10,000. A value of –10,000 indicates that the right speaker has been disabled and only the left speaker is receiving an audio signal. A value of 0 indicates that both speakers are receiving equivalent audio signals. A value of 10,000 indicates that the left speaker has been disabled and only the right speaker is receiving an audio signal.

As with the Volume property, units correspond to .01 decibels (multiplied by –1 when plBalance is a positive value). For example, a value of 1000 indicates –10 dB on the right channel and –90 dB on the left channel.

IBasicAudio::get_Volume

IBasicAudio Interface

Retrieves the volume (amplitude) of the audio signal.

Syntax

HRESULT get_Volume(

  long *plVolume

  );

Parameters

plVolume
[out] Pointer to the returned value of the Volume property. Divide by 100 to get equivalent decibel value (for example –10,000 = –100 dB).

Return Value

Returns an HRESULT value.

Remarks

IBasicAudio::put_Balance

IBasicAudio Interface

Sets the balance of the audio signal.

Syntax

HRESULT put_Balance(
  long lBalance
  );

Parameters

lBalance
[in] Value to which to set the Balance property. The allowable input range is –10,000 to 10,000. A value of 0 sets a neutral balance—both left and right speakers will be given the same amplitude audio signal.

Return Value

Returns an HRESULT value. E_INVALIDARG is returned for values outside the allowable input range and E_FAIL is returned if the underlying device returns an error.

Remarks

As with the Volume property, units correspond to .01 decibels (multiplied by –1 when lBalance is a positive value). For example, a value of 1000 indicates –10 dB on the right channel and –90 dB on the left channel.

IBasicAudio::put_Volume

IBasicAudio Interface

Sets the volume (amplitude) of the audio signal.

Syntax

HRESULT put_Volume(
  long lVolume
  );

Parameters

lVolume
[in] Value to which to set the Volume property. The allowable input range is –10,000 to 0.

Return Value

Returns an HRESULT value. E_INVALIDARG is returned for values outside the allowable input range and E_FAIL is returned if the underlying device returns an error.

Remarks

Full volume is 0, and –10,000 is silence; the scale is logarithmic. Multiply the desired decibel level by 100 (for example –10,000 = –100 dB).


IBasicVideo Interface

The IBasicVideo interface is implemented on the Video Renderer and exposed on the Filter Graph Manager through a plug-in distributor. Applications should always retrieve this interface through the Filter Graph Manager. The interface enables applications to set video properties such as the bit rate, and destination and source rectangles. It is a dual interface, so it is accessible to applications written in Microsoft® Visual Basic® as well as C++.

The IBasicVideo interface methods require only that the Video Renderer be connected. If it is not connected, all the interface methods return VFW_E_NOT_CONNECTED. Properties set on the Video Renderer persist between successive connections and disconnections.

When working with video, the application can select a portion of the video to use. This portion is the source rectangle that the IBasicVideo interface controls. IBasicVideo enables you to set and retrieve the source rectangle. All the rectangles that IBasicVideo uses employ top, left, width, and height rather than top, left, right, and bottom, which is favored in Microsoft® Win32® programming. When no source rectangle has been set, the properties of the source rectangle return the full, native video size. All rectangle dimensions are given in pixels.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether there is type information available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returned successfully.
GetIDsOfNames | Converts text names of properties and methods (including arguments) to their corresponding DISPIDs.
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IBasicVideo methods | Description
get_AvgTimePerFrame | Retrieves the average time between successive frames in 100-nanosecond units.
get_BitRate | Retrieves an approximate bit rate for the video stream.
get_BitErrorRate | Retrieves an approximate bit error rate for the video stream.
get_VideoWidth | Retrieves the current video width.
get_VideoHeight | Retrieves the current video height.
put_SourceLeft | Sets the x-axis coordinate for the source video rectangle.
get_SourceLeft | Retrieves the x-axis coordinate for the source video rectangle.
put_SourceWidth | Sets the width of the source video rectangle.
get_SourceWidth | Retrieves the width of the source video rectangle.
put_SourceTop | Sets the y-axis coordinate for the source video rectangle.
get_SourceTop | Retrieves the y-axis coordinate for the source video rectangle.
put_SourceHeight | Sets the height of the source video rectangle.
get_SourceHeight | Retrieves the height of the source video rectangle.
put_DestinationLeft | Sets the x-axis coordinate for the destination video rectangle.
get_DestinationLeft | Retrieves the x-axis coordinate for the destination video rectangle.
put_DestinationWidth | Sets the width of the destination video rectangle.
get_DestinationWidth | Retrieves the width of the destination video rectangle.
put_DestinationTop | Sets the y-axis coordinate for the destination video rectangle.
get_DestinationTop | Retrieves the y-axis coordinate for the destination video rectangle.
put_DestinationHeight | Sets the height of the destination video rectangle.
get_DestinationHeight | Retrieves the height of the destination video rectangle.
SetSourcePosition | Sets the source video rectangle.
GetSourcePosition | Retrieves the source video rectangle.
SetDefaultSourcePosition | Informs the renderer to use the default source rectangle.
SetDestinationPosition | Sets the destination rectangle for the window.
GetDestinationPosition | Retrieves the destination video rectangle for the window.
SetDefaultDestinationPosition | Sets the default destination position for the window.
GetVideoSize | Retrieves the native video dimensions.
GetVideoPaletteEntries | Retrieves the color palette entries required by the video.
GetCurrentImage | Returns a copy of the current image that is waiting at the renderer.
IsUsingDefaultSource | Determines if the renderer is using the default source rectangle.
IsUsingDefaultDestination | Determines if the renderer is using the default destination rectangle.

IBasicVideo::get_AvgTimePerFrame

IBasicVideo Interface

Retrieves the average time between successive frames in 100-nanosecond units.

Syntax

HRESULT get_AvgTimePerFrame(
    REFTIME *pAvgTimePerFrame
);

Parameters

pAvgTimePerFrame
[out] Pointer to the time between frames.

Return Value

Returns an HRESULT value.

IBasicVideo::get_BitErrorRate

IBasicVideo Interface

Retrieves a bit error rate for the video stream (one error for approximately this many bits).

Syntax

HRESULT get_BitErrorRate(
    long *pBitErrorRate
);

Parameters

pBitErrorRate
[out] Pointer to the approximate bit error rate.

Return Value

Returns an HRESULT value.

IBasicVideo::get_BitRate

IBasicVideo Interface

Retrieves an approximate bit rate for the video stream (in bits per second).

Syntax

HRESULT get_BitRate(
    long *pBitRate
);

Parameters

pBitRate
[out] Pointer to the approximate bit rate.

Return Value

Returns an HRESULT value.

IBasicVideo::GetCurrentImage

IBasicVideo Interface

Retrieves the current image waiting at the renderer.

Syntax

HRESULT GetCurrentImage(
    long *pBufferSize,
    long *pDIBImage
);

Parameters

pBufferSize
[in, out] Pointer to the size of the buffer the caller is passing in.
pDIBImage
[out] Pointer to a buffer where the complete image will be stored in device-independent bitmap (DIB) format. The buffer must be cast to a long pointer for the function.

Return Value

Returns an HRESULT value.

Remarks

This method fails if the renderer is using DirectDraw acceleration. Unfortunately, this depends on the end-user's hardware configuration, so in practice this method is not reliable. A better way to obtain a sample from a stream in the graph is to use the ISampleGrabber interface.

Pause the video renderer before calling this method, or the else method returns VFW_E_NOT_PAUSED. Make sure that the pause operation has completed by calling IMediaControl::GetState; if the pause operation has not completed, a call to GetCurrentImage will return E_UNEXPECTED. Depending on what data the source filter has available, the video renderer is not guaranteed to service this request. If no image is available, it returns E_FAIL.

Obtain the size of the buffer required to hold the image by calling this method with a null image pointer. In this case, the buffer size is filled out with the byte count required. The buffer size pointer must always be valid. If the application calls this method and the buffer size is too small to hold the complete image, the renderer returns E_OUTOFMEMORY.

If the method is successful, the output image pointer is filled with the entire DIB image, including the Microsoft Win32 BITMAPINFOHEADER structure, any required palette, and bit masks as defined in the Win32 BITMAPINFO structure. The format of the image that is returned depends on the type provided by the source filter, and cannot be explicitly defined in advance. Typically, the image will be a 24-bit, 16-bit, or 8-bit palettized image.

IBasicVideo::get_DestinationHeight

IBasicVideo Interface

Retrieves the height of the destination rectangle.

Syntax

HRESULT get_DestinationHeight(
    long *pDestinationHeight
);

Parameters

pDestinationHeight
[out] Pointer to the current height, in pixels.

Return Value

Returns an HRESULT value.

IBasicVideo::get_DestinationLeft

IBasicVideo Interface

Retrieves the destination x-axis origin coordinate.

Syntax

HRESULT get_DestinationLeft(
    long *pDestinationLeft
);

Parameters

pDestinationLeft
[out] Pointer to the current x-axis origin.

Return Value

Returns an HRESULT value.

Remarks

Setting this coordinate does not affect the destination rectangle width.

IBasicVideo::GetDestinationPosition

IBasicVideo Interface

Retrieves the position of the destination rectangle in window coordinates.

Syntax

HRESULT GetDestinationPosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft
[out] Pointer to the x-axis origin of the destination window.
pTop
[out] Pointer to the y-axis origin of the destination window.
pWidth
[out] Pointer to the width of the destination window, in pixels.
pHeight
[out] Pointer to the height of the destination window, in pixels.

Return Value

Returns an HRESULT value.

Remarks

This method has the same effect as individually calling the IBasicVideo::get_DestinationLeft, IBasicVideo::get_DestinationTop, IBasicVideo::get_DestinationWidth, and IBasicVideo::get_DestinationHeight methods.

IBasicVideo::get_DestinationTop

IBasicVideo Interface

Retrieves the destination y-axis origin coordinate.

Syntax

HRESULT get_DestinationTop(
    long *pDestinationTop
);

Parameters

pDestinationTop
[out] Pointer to the current y-axis origin.

Return Value

Returns an HRESULT value.

Remarks

Setting this coordinate does not affect the destination rectangle height.

IBasicVideo::get_DestinationWidth

IBasicVideo Interface

Retrieves the width of the destination rectangle.

Syntax

HRESULT get_DestinationWidth(
    long *pDestinationWidth
);

Parameters

pDestinationWidth
[out] Pointer to the current width, in pixels.

Return Value

Returns an HRESULT value.

IBasicVideo::get_SourceHeight

IBasicVideo Interface

Retrieves the height of the source rectangle.

Syntax

HRESULT get_SourceHeight(
    long *pSourceHeight
);

Parameters

pSourceHeight
[out] Pointer to the current rectangle height, in pixels.

Return Value

Returns an HRESULT value.

IBasicVideo::get_SourceLeft

IBasicVideo Interface

Retrieves the source rectangle x-axis coordinate.

Syntax

HRESULT get_SourceLeft(
    long *pSourceLeft
);

Parameters

pSourceLeft
[out] Pointer to the x-axis origin of the source rectangle.

Return Value

Returns an HRESULT value.

Remarks

This method has no effect on the source rectangle width.

IBasicVideo::GetSourcePosition

IBasicVideo Interface

Retrieves the source position rectangle, clipped to the available video.

Syntax

HRESULT GetSourcePosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft
[out] Pointer to the x-axis origin of the source window.
pTop
[out] Pointer to the y-axis origin of the source window.
pWidth
[out] Pointer to the width of the source window, in pixels.
pHeight
[out] Pointer to the height of the source window, in pixels.

Return Value

Returns an HRESULT value.

Remarks

This method has the same effect as individually calling the
IBasicVideo::get_SourceLeft, IBasicVideo::get_SourceTop,
IBasicVideo::get_SourceWidth, and
IBasicVideo::get_SourceHeight methods.

IBasicVideo::get_SourceTop

IBasicVideo Interface

Retrieves the source rectangle y-axis origin coordinate.

Syntax

HRESULT get_SourceTop(
    long *pSourceTop
);

Parameters

pSourceTop
[out] Pointer to the new top coordinate.

Return Value

Returns an HRESULT value.

Remarks

Setting this method has no effect on the source rectangle height.

IBasicVideo::get_SourceWidth

IBasicVideo Interface

Retrieves the source rectangle width.

Syntax

HRESULT get_SourceWidth(
    long *pSourceWidth
);

Parameters

pSourceWidth
[out] Pointer to the current width, in pixels.

Return Value

Returns an HRESULT value.

Remarks

This method has no effect on the source rectangle x-axis coordinate.

IBasicVideo::get_VideoHeight

IBasicVideo Interface

Retrieves the current video height.

Syntax

HRESULT get_VideoHeight(
    long *pVideoHeight
);

Parameters

pVideoHeight
[out] Pointer to the native height of the video, in pixels.

Return Value

Returns an HRESULT value.

Remarks

This method returns the actual height of the video supplied to the renderer. It does not address any set source rectangle, but simply returns the native vertical dimension. Applications can use this method to negotiate size requirements with in-place container documents.

IBasicVideo::GetVideoPaletteEntries

IBasicVideo Interface

Retrieves the palette colors for the video.

Syntax

HRESULT GetVideoPaletteEntries(
    long StartIndex,
    long Entries,
    long *pRetrieved,
    long *pPalette
);

Parameters

StartIndex
[in] Start index for the palette.
Entries
[in] Number of palette entries required.
pRetrieved
[out] Pointer to the number of entries actually returned.
pPalette
[out] Pointer to an array of Microsoft Win32 PALETTEENTRY structures.

Return Value

Returns an HRESULT value.

Remarks

An application can query the colors required by the video with this method. An application can pass in a null pPalette parameter, and the pRetrieved parameter is filled in with the number of colors in use. The pPalette parameter is a pointer to an array of PALETTEENTRY structures. With the StartIndex and Entries parameters, an application can request any contiguous section of the palette in a single method. The interface was modeled on the Win32 GetSystemPaletteEntries function.

IBasicVideo::GetVideoSize

IBasicVideo Interface

Retrieves the native video dimensions.

Syntax

HRESULT GetVideoSize(
    long *pWidth,
    long *pHeight
);

Parameters

pWidth
[out] Pointer to the width of the video window, in pixels.
pHeight
[out] Pointer to the height of the video window, in pixels.

Return Value

Returns an HRESULT value.

Remarks

This method retrieves the native video width and height, disregarding any source rectangle that might have been set. Microsoft® ActiveX® controls or other applications can use this information to negotiate space in compound documents.

IBasicVideo::get_VideoWidth

IBasicVideo Interface

Retrieves the current video width.

Syntax

HRESULT get_VideoWidth(
    long *pVideoWidth
);

Parameters

pVideoWidth
[out] Pointer to the native width of the video, in pixels.

Return Value

Returns an HRESULT value.

Remarks

This method returns the actual width of the video supplied to the renderer. It does not address any set source rectangle, but simply returns the native horizontal dimension. Applications can use it to negotiate size requirements with in-place ActiveX documents.

IBasicVideo::IsUsingDefaultDestination

IBasicVideo Interface

Determines if the renderer is using the default destination rectangle.

Syntax

HRESULT IsUsingDefaultDestination(void);

Return Value

Returns an HRESULT value. Returns S_OK if using the default destination; otherwise, returns S_FALSE.

Remarks

The IBasicVideo::SetDefaultDestinationPosition method can be used to tell the filter to use the default settings for the destination rectangle. This method returns whether they are in use.

IBasicVideo::IsUsingDefaultSource

IBasicVideo Interface

Determines if the renderer is using the default source rectangle.

Syntax

HRESULT IsUsingDefaultSource(void);

Return Value

Returns an HRESULT value. Returns S_OK if using the default source; otherwise, returns S_FALSE.

Remarks

You can use the IBasicVideo::SetDefaultSourcePosition method to inform the filter to use the default settings for the source rectangle. This method returns whether the settings are in use.

IBasicVideo::put_DestinationHeight

IBasicVideo Interface

Sets the height of the destination rectangle.

Syntax

HRESULT put_DestinationHeight(
    long DestinationHeight
);

Parameters

DestinationHeight
[in] New height, in pixels.

Return Value

Returns an HRESULT value.

Remarks

Setting this coordinate does not affect the destination rectangle y-axis origin.

IBasicVideo::put_DestinationLeft

IBasicVideo Interface

Sets the destination x-axis origin coordinate.

Syntax

HRESULT put_DestinationLeft(
    long DestinationLeft
);

Parameters

DestinationLeft
[in] New x-axis origin.

Return Value

Returns an HRESULT value.

Remarks

Setting this coordinate does not affect the destination rectangle width.

IBasicVideo::put_DestinationTop

IBasicVideo Interface

Sets the destination y-axis origin coordinate.

Syntax

HRESULT put_DestinationTop(
    long DestinationTop
);

Parameters

DestinationTop
[in] New y-axis origin.

Return Value

Returns an HRESULT value.

IBasicVideo::put_DestinationWidth

IBasicVideo Interface

Sets the width of the destination rectangle.

Syntax

HRESULT put_DestinationWidth(
    long DestinationWidth
);

Parameters

DestinationWidth
[in] New width, in pixels.

Return Value

Returns an HRESULT value.

Remarks

Setting this coordinate does not affect the destination rectangle x-axis origin.

IBasicVideo::put_SourceHeight

IBasicVideo Interface

Sets the height of the source rectangle.

Syntax

HRESULT put_SourceHeight(
    long SourceHeight
);

Parameters

SourceHeight
[in] New rectangle height, in pixels.

Return Value

Returns an HRESULT value.

Remarks

Setting the height of the source rectangle has no effect on the source y-axis coordinate.

IBasicVideo::put_SourceLeft

IBasicVideo Interface

Sets the source rectangle x-axis coordinate.

Syntax

HRESULT put_SourceLeft(
    long SourceLeft
);

Parameters

SourceLeft
[in] The x-axis origin of the source rectangle.

Return Value

Returns an HRESULT value.

Remarks

Setting this method has no effect on the source rectangle width.

IBasicVideo::put_SourceTop

IBasicVideo Interface

Sets the source rectangle y-axis origin coordinate.

Syntax

HRESULT put_SourceTop(
    long SourceTop
);

Parameters

SourceTop
[in] New top coordinate.

Return Value

Returns an HRESULT value.

Remarks

Setting this method has no effect on the source rectangle height.

IBasicVideo::put_SourceWidth

IBasicVideo Interface

Sets the source rectangle width.

Syntax

HRESULT put_SourceWidth(
    long SourceWidth
);

Parameters

SourceWidth
[in] New width of the source rectangle, in pixels.

Return Value

Returns an HRESULT value.

Remarks

Setting this method has no effect on the source rectangle x-axis coordinate.

IBasicVideo::SetDefaultDestinationPosition

IBasicVideo Interface

Sets the default destination position of the video window so that the renderer uses the entire window for playback.

Syntax

HRESULT SetDefaultDestinationPosition(void);

Return Value

Returns an HRESULT value.

IBasicVideo::SetDefaultSourcePosition

IBasicVideo Interface

Informs the renderer to use the default source rectangle.

Syntax

HRESULT SetDefaultSourcePosition(void);

Return Value

Returns an HRESULT value.

IBasicVideo::SetDestinationPosition

IBasicVideo Interface

Sets the destination rectangle in window coordinates.

Syntax

HRESULT SetDestinationPosition(
    long Left,
    long Top,
    long Width,
    long Height
);

Parameters

Left
[in] The x-axis origin of the destination window.
Top
[in] The y-axis origin of the destination window.
Width
[in] Width of the destination window, in pixels.
Height
[in] Height of the destination window, in pixels.

Return Value

Returns an HRESULT value.

Remarks

This method has the same effect as individually calling the IBasicVideo::put_DestinationLeft, IBasicVideo::put_DestinationTop, IBasicVideo::put_DestinationWidth, and IBasicVideo::put_DestinationHeight methods.

IBasicVideo::SetSourcePosition

IBasicVideo Interface

Sets the source rectangle and is clipped against the available video.

Syntax

HRESULT SetSourcePosition(
    long Left,
    long Top,
    long Width,
    long Height
);

Parameters

Left
[in] The x-axis origin of the source window.
Top
[in] The y-axis origin of the source window.
Width
[in] Width of the source window, in pixels.
Height
[in] Height of the source window, in pixels.

Return Value

Returns an HRESULT value.

Remarks

This method has the same effect as individually calling the IBasicVideo::put_SourceLeft, IBasicVideo::put_SourceTop, IBasicVideo::put_SourceWidth, and IBasicVideo::put_SourceHeight methods.

Setting this coordinate does not affect the destination rectangle height.


IBasicVideo2 Interface

The IBasicVideo2 interface derives from IBasicVideo and provides an additional method for applications to retrieve the preferred aspect ratio of the video stream. The interface is implemented on the Video Renderer filter but exposed to applications on the Filter Graph Manager. See IBasicVideo for more detailed information.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether there is type information available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returned successfully.
GetIDsOfNames | Converts text names of properties and methods (including arguments) to their corresponding DISPIDs.
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IBasicVideo methods | Description
get_AvgTimePerFrame | Retrieves the average time between successive frames in 100-nanosecond units.
get_BitRate | Retrieves an approximate bit rate for the video stream.
get_BitErrorRate | Retrieves an approximate bit error rate for the video stream.
get_VideoWidth | Retrieves the current video width.
get_VideoHeight | Retrieves the current video height.
put_SourceLeft | Sets the x-axis coordinate for the source video rectangle.
get_SourceLeft | Retrieves the x-axis coordinate for the source video rectangle.
put_SourceWidth | Sets the width of the source video rectangle.
get_SourceWidth | Retrieves the width of the source video rectangle.
put_SourceTop | Sets the y-axis coordinate for the source video rectangle.
get_SourceTop | Retrieves the y-axis coordinate for the source video rectangle.
put_SourceHeight | Sets the height of the source video rectangle.
get_SourceHeight | Retrieves the height of the source video rectangle.
put_DestinationLeft | Sets the x-axis coordinate for the destination video rectangle.
get_DestinationLeft | Retrieves the x-axis coordinate for the destination video rectangle.
put_DestinationWidth | Sets the width of the destination video rectangle.
get_DestinationWidth | Retrieves the width of the destination video rectangle.
put_DestinationTop | Sets the y-axis coordinate for the destination video rectangle.
get_DestinationTop | Retrieves the y-axis coordinate for the destination video rectangle.
put_DestinationHeight | Sets the height of the destination video rectangle.
get_DestinationHeight | Retrieves the height of the destination video rectangle.
SetSourcePosition | Sets the source video rectangle.
GetSourcePosition | Retrieves the source video rectangle.
SetDefaultSourcePosition | Informs the renderer to use the default source rectangle.
SetDestinationPosition | Sets the destination rectangle for the window.
GetDestinationPosition | Retrieves the destination video rectangle for the window.
SetDefaultDestinationPosition | Sets the default destination position for the window.
GetVideoSize | Retrieves the native video dimensions.
GetVideoPaletteEntries | Retrieves the color palette entries required by the video.
GetCurrentImage | Returns a copy of the current image that is waiting at the renderer.
IsUsingDefaultSource | Determines if the renderer is using the default source rectangle.
IsUsingDefaultDestination | Determines if the renderer is using the default destination rectangle.
IBasicVideo2 methods | Description
GetPreferredAspectRatio | Retrieves the movie's preferred aspect ratio.

IBasicVideo2::GetPreferredAspectRatio

IBasicVideo2 Interface

Retrieves a pair of dimensionless values whose ratio defines the movie's preferred aspect ratio.

Syntax

HRESULT GetPreferredAspectRatio (
    long *plAspectX,
    long *plAspectY
    );

Parameters

plAspectX
[out] Pointer to a value that indicates the movie's x-axis aspect ratio.
plAspectY
[out] Pointer to a value that indicates the movie's y-axis aspect ratio.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The current DirectShow implementation return values include the following:
S_OK | Success.
E_INVALIDARG | One or both of the parameters are invalid.
E_NOINTERFACE | The renderer does not implement IBasicVideo2.

Remarks

See the VIDEOINFOHEADER2 structure documentation for more information on movie aspect ratios.


ICaptureGraphBuilder2 Interface

This interface provides methods for building capture graphs, preview graphs, and file recompression graphs. The capture graph builder implements this interface.

This interface replaces the ICaptureGraphBuilder interface. It works with Microsoft® Windows® Driver Model (WDM) capture drivers that can capture more than one media type, such as both audio and video. The original ICaptureGraphBuilder interface does not work with devices that use the same driver for both video and audio capture.

For more information on using this interface, see How to Write a Capture Application and Recompressing an AVI File.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
ICaptureGraphBuilder2 methods | Description
SetFiltergraph | Specifies a filter graph for the capture graph builder to use.
GetFiltergraph | Retrieves the filter graph that the builder is using.
SetOutputFileName | Creates the file writing section of the filter graph.
FindInterface | Searches the graph for a specified interface, starting from a specified filter.
RenderStream | Connects an output pin on a source filter to a rendering filter, optionally through a compression filter.
ControlStream | Sets the start and stop times for one or more streams of captured data.
AllocCapFile | Preallocates a capture file to a specified size.
CopyCaptureFile | Copies the valid media data from a capture file.
FindPin | Retrieves a particular pin on a filter, or determines whether a given pin matches the specified criteria.

ICaptureGraphBuilder2::AllocCapFile

ICaptureGraphBuilder2 Interface

Preallocates a capture file to a specified size. For best results, always capture to a defragmented, preallocated capture file that is larger than the size of the capture data.

Syntax

HRESULT AllocCapFile(
    LPCOLESTR lpwstr,
    DWORDLONG dwlSize
);

Parameters

lpwstr
[in] Pointer to a Unicode™ string that contains the name of the file to create or resize.
dwlSize
[in] Size of the file to allocate, in bytes.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

This method fails if the file is read-only.

It is best to allocate as much space as possible—ideally, more than needed. However, this can result in a very large file that contains relatively little data. For example, a 1-gigabyte (GB) capture file might contain a few megabytes of captured video. Use the CopyCaptureFile method to copy the data into a new file. That method copies only the data and ignores the empty portion of the original file.

Note The AllocCapFile method takes longer on Microsoft® Windows NT® 4.x or Microsoft® Windows® 2000 than it does on other Windows platforms, because the method must write over the entire preallocated file. However, it is still recommended that you use this method, because it results in better capture performance.

ICaptureGraphBuilder2::ControlStream

ICaptureGraphBuilder2 Interface

Sets the start and stop times for one or more streams of captured data.

This method locates output pins on capture filters, using search criteria that you supply in the method call. Then it calls IAMStreamControl methods on those pins. This method enables an application to control streams without the application needing to enumerate the filters and pins in the graph.

Use this method for frame-accurate capture, or for individual control of capture and preview. For example, you can stop capturing to disk but leave video preview running.

Syntax

HRESULT ControlStream(
    const GUID *pCategory,
    const GUID *pType,
    IBaseFilter *pFilter,
    REFERENCE_TIME *pstart,
    REFERENCE_TIME *pstop,
    WORD wStartCookie,
    WORD wStopCookie
);

Parameters

pCategory
[in] Pointer to a member of the AMPROPERTY_PIN_CATEGORY property set, specifying the pin category. The value of this parameter cannot be NULL.
pType
[in] Pointer to a major type GUID that specifies the media type, or NULL. If this parameter is NULL, set the pFilter parameter to NULL as well. Otherwise, you might control the wrong pin and get unpredictable results.
pFilter
[in] Pointer to an IBaseFilter interface that specifies which filter to control. To control all the capture filters in the graph, set this parameter to NULL.
pstart
[in] Pointer to a variable that contains the start time. To start immediately, set the value to NULL. To cancel the previous start request, set the value to MAX_TIME. If there is no previous request, the value MAX_TIME has no effect.
pstop
[in] Pointer to a variable that contains the stop time. To stop immediately, set the value to NULL. To cancel the previous stop request, set the value to MAX_TIME. If there is no previous request, the value MAX_TIME has no effect.
wStartCookie
[in] Value that is sent as the second parameter of the EC_STREAM_CONTROL_STARTED event notification. See Remarks for more information.
wStopCookie
[in] Value that is sent as the second parameter of the EC_STREAM_CONTROL_STOPPED event notification. See Remarks for more information.

Return Value

Returns an HRESULT value. Possible values include the following:

S_FALSE | At least one downstream renderer will not send a stop notification.
S_OK | Success.
E_FAIL | Could not find a matching pin, or the pin did not support stream control.
E_POINTER | NULL pointer argument.

Remarks

The first three parameters specify which pins to control. A capture graph can have more than one capture filter. For example, it might have filters for video, audio, and closed captioning data. Also, a capture filter can have more than one output pin. Some capture filters have separate pins for preview and capture, or separate pins for video-only data and audio-video interleaved data. To control video preview, for example, specify PIN_CATEGORY_PREVIEW for pCategory and MEDIATYPE_Video for pType.

To control a pin, this method calls the IAMStreamControl::StartAt and IAMStreamControl::StopAt methods. Each pin sends an EC_STREAM_CONTROL_STARTED event notification when it starts. The second parameter of the event notification is the value given in wStartCookie. When the pin stops, it sends an EC_STREAM_CONTROL_STOPPED event notification. The second parameter of that event notification is the value given in wStopCookie.

When this method locates a matching pin, it searches downstream for another filter that supports IAMStreamControl (typically a multiplexer). If it finds one, it also sets the start and stop times on that filter. This generates two pairs of stop notifications: one for the capture filter, and one for the downstream filter. Only the stop notification from the downstream filter uses the wStopCookie parameter. Waiting for this event guarantees that the downstream filter receives the last sample.

If no downstream filter supports IAMStreamControl, the method returns S_FALSE. In that case, you might receive the stop notification before the last sample is rendered.

ICaptureGraphBuilder2::CopyCaptureFile

ICaptureGraphBuilder2 Interface

Copies the valid media data from a capture file.

Typically, you will first capture to a large preallocated file. This method copies just the valid data to a new file. As a result, the new file can be much smaller than the original file.

Syntax

HRESULT CopyCaptureFile(
    LPOLESTR lpwstrOld,
    LPOLESTR lpwstrNew,
    int fAllowEscAbort,
    IAMCopyCaptureFileProgress *pCallback
);

Parameters

lpwstrOld
[in] Pointer to a Unicode™ string that contains the source file name.
lpwstrNew
[in] Pointer to a Unicode string that contains the destination file name. Valid data is copied to this file.
fAllowEscAbort
[in] Boolean value that specifies whether pressing the ESC key cancels the copy operation. If the value is TRUE and the user presses the ESC key, the operation halts. If the value is FALSE, the method ignores the ESC key.
pCallback
[in] Pointer to an IAMCopyCaptureFileProgress interface to display progress information, or NULL. See Remarks for more information.

Return Value

Returns an HRESULT value. Possible values include the following:

S_FALSE | User canceled the operation before it completed.
S_OK | Success.
E_FAIL | Failure.
E_INVALIDARG | Could not open the source file or destination file.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

The source and destination files must be AVI files. Other file types are not supported.

To display the progress of the copy operation, implement the IAMCopyCaptureFileProgress interface and pass a pointer to the interface in the pCallback parameter. If pCallback is non-NULL, this method periodically calls the IAMCopyCaptureFileProgress::Progress method with an integer between 0 and 100 that specifies the percentage complete.

ICaptureGraphBuilder2::FindInterface

ICaptureGraphBuilder2 Interface

Searches the graph for a specified interface, starting from a specified filter. You can restrict the search to a section of the graph upstream or downstream of the filter, or restrict it to a particular pin category or media type.

Syntax

HRESULT FindInterface(
    const GUID *pCategory,
    const GUID *pType,
    IBaseFilter *pf,
    REFIID riid,
    void **ppint
);

Parameters

pCategory
[in] Pointer to a GUID that specifies the search criteria. See Remarks for more information. The following values are possible:
  • LOOK_UPSTREAM_ONLY
  • LOOK_DOWNSTREAM_ONLY
  • Member of the AMPROPERTY_PIN_CATEGORY property set, specifying a pin category.
  • NULL
pType
[in] Pointer to a major type GUID that specifies the media type of an output pin, or NULL.
pf
[in] Pointer to the IBaseFilter interface of the filter.
riid
[in] Reference identifier (ID) of the interface.
ppint
[out] Address of a variable that receives the interface pointer. Be sure to release the retrieved interface pointer when you are done with the interface.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_FAIL | Failure.
E_NOINTERFACE | No such interface supported.
E_POINTER | NULL pointer argument.

Remarks

In a capture graph, various filters and pins might expose interfaces for setting properties such as compression parameters (IAMVideoCompression) or stream formats (IAMStreamConfig). Depending on the capture device, other useful interfaces might include IAMCrossbar, which routes analog signals, or IAMTVTuner, which controls a TV tuner device. You can use this method to find an interface, without writing special code that traverses the graph.

Important Do not call this method to obtain an IVideoWindow interface pointer. Always query the filter graph manager for this interface. Otherwise, the filter graph manager will not respond correctly to changes in screen resolution and other events.

If the pCategory parameter is NULL, this method searches the entire graph for the requested interface. Starting from the filter specified by the pf parameter, it queries the following objects in the graph.

  • The filter
  • The filter's pins
  • All the downstream filters, including their pins
  • All the upstream filters, including their pins

You can restrict the search by setting the pCategory and pType parameters.

  • If pCategory equals &LOOK_UPSTREAM_ONLY, the search starts from the filter's input pins and continues upstream. It does not include the filter or anything downstream from the filter. The pType parameter is ignored.
  • If pCategory equals &LOOK_DOWNSTREAM_ONLY, the search starts from the filter's output pins and continues downstream. It does not include the filter or anything upstream from the filter. The pType parameter is ignored.
  • If pCategory specifies a pin category, the downstream portion of the search is restricted to output pins on the filter that match both the pin category and the media type given in the pType parameter. In this case, the method also searches the filter and everything upstream from the filter.

Pin categories are useful for finding pin interfaces on capture filters. For example, a capture filter might have separate pins for capture and preview. If you specify a pin category, you should also specify the media type, to make certain the method selects the correct filter and pin.

Some video capture filters have a video port pin (PIN_CATEGORY_VIDEOPORT) instead of a preview pin. If you specify PIN_CATEGORY_PREVIEW and MEDIATYPE_Video, the method treats any video port pins as preview pins. Your application does not have to test for this possibility.

Supporting Filters. If a capture device uses a Windows Driver Model (WDM) driver, the graph may require certain filters upstream from the WDM Video Capture filter, such as a TV Tuner filter or an Analog Video Crossbar filter. If your graph requires any of these WDM filters, this method automatically inserts them into the graph. The method queries the input pins on the capture filter to determine what mediums they support, and connects them to matching filters.

ICaptureGraphBuilder2::FindPin

ICaptureGraphBuilder2 Interface

Retrieves a particular pin on a filter, or determines whether a given pin matches the specified criteria.

Syntax

HRESULT FindPin(
    IUnknown *pSource,
    PIN_DIRECTION pindir,
    const GUID *pCategory,
    const GUID *pType,
    BOOL fUnconnected,
    int num,
    IPin **ppPin
);

Parameters

pSource
[in] Pointer to an interface on a filter, or to an interface on a pin.
pindir
[in] Member of the PIN_DIRECTION enumeration that specifies the pin direction (input or output).
pCategory
[in] Pointer to a member of the AMPROPERTY_PIN_CATEGORY property set, specifying a pin category. Use NULL to match any category.
pType
[in] Pointer to a major type GUID that specifies the media type. Use NULL to match any media type.
fUnconnected
[in] Boolean value that specifies whether the pin must be unconnected. If TRUE, the pin must be unconnected. If FALSE, the pin can be connected or unconnected.
num
[in] Zero-based index of the pin to retrieve, from the set of matching pins. If pSource is a pointer to a filter, and more than one pin matches the search criteria, this parameter specifies which pin to retrieve. If pSource is a pointer to a pin, this parameter is ignored.
ppPin
[out] Address of a pointer to receive the IPin interface of the matching pin.

Return Value

Returns S_OK if a matching pin is found, or E_FAIL otherwise.

Remarks

If pSource is a pointer to a filter, the method searches for the nth pin on that filter that matches the search criteria, where n is given by the num parameter. If the method finds a matching pin, it returns a pointer to the pin in the ppPin parameter.

If pSource is a pointer to a pin, the method tests that pin against the search criteria. If the pin matches the criteria, the method returns S_OK, and returns a pointer to the pin's IPin interface in the ppPin parameter. Otherwise, it returns E_FAIL.

In either case, if the method succeeds, the IPin interface returned in the ppPin parameter has an outstanding reference count. Be sure to release the interface when you are done using it.

Typically, an application will not need to use this method. It is provided for unusually complex tasks, when the RenderStream method cannot build the filter graph. Use this method to retrieve a desired pin from a capture filter, and then build the rest of the graph manually.

ICaptureGraphBuilder2::GetFiltergraph

ICaptureGraphBuilder2 Interface

Retrieves the filter graph that the capture graph builder is using.

Syntax

HRESULT GetFiltergraph(
    IGraphBuilder **ppfg
);

Parameters

ppfg
[out] Address of a variable that receives an IGraphBuilder interface pointer.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | No filter graph.

Remarks

This method increments the reference count on the IGraphBuilder interface. Be sure to release the interface when you are done with it.

ICaptureGraphBuilder2::RenderStream

ICaptureGraphBuilder2 Interface

Connects an output pin on a source filter to a rendering filter, optionally through a compression filter.

Syntax

HRESULT RenderStream(
    const GUID *pCategory,
    const GUID *pType,
    IUnknown *pSource,
    IBaseFilter *pfCompressor,
    IBaseFilter *pfRenderer
);

Parameters

pCategory
[in] Pointer to a member of the AMPROPERTY_PIN_CATEGORY property set, specifying a pin category; or NULL to use any pin, regardless of category. Typical values include the following.
  • PIN_CATEGORY_CAPTURE
  • PIN_CATEGORY_PREVIEW
  • PIN_CATEGORY_VBI
  • PIN_CATEGORY_CC
pType
[in] Pointer to a major type GUID that specifies the media type of the output pin; or NULL to use any pin, regardless of media type.
pSource
[in] Pointer to an interface on a source filter, or to an interface on an output pin.
pfCompressor
[in] Optional pointer to the IBaseFilter interface of a compression filter.
pfRenderer
[in] Optional pointer to the IBaseFilter interface of a renderer filter or multiplexer filter.

Return Value

Returns an HRESULT value. Possible return values include the following:

S_OK | Success.
VFW_S_NOPREVIEWPIN | Preview was rendered through a Smart Tee filter.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

This method renders a stream, either for preview or for writing to a file. The method automatically handles many of the complexities of capture graphs.

The pSource parameter specifies an output pin or a filter. If you specify an output pin, the method renders the stream from that pin. Set the pCategory and pType parameters to NULL in this case. If you specify a filter, the method searches the filter for an output pin whose pin category matches the pCategory parameter, and whose media type matches the pType parameter.

The pfRenderer parameter specifies a sink filter, typically either the File Writer filter or a multiplexer filter such as the AVI Mux. You can obtain a pointer to the multiplexer by calling the SetOutputFileName method. The pointer is returned in the ppf parameter of that method.

If pfRenderer is NULL, the method uses a default renderer: the Video Renderer for video, or the Default DirectSound Device for audio.

The pfCompressor parameter specifies a compression filter, or in general any transform filter. If you don't want to compress the stream, set this parameter to NULL.

Smart Tee. Some capture filters have a capture pin but no preview pin. To preview, the capture pin must be connected to the Smart Tee filter. This filter splits the data into two streams, a capture stream and a preview stream. When you specify PIN_CATEGORY_PREVIEW or PIN_CATEGORY_CAPTURE, the method inserts a Smart Tee filter if one is needed. Then it renders the specified stream on the Smart Tee filter. If you render a preview stream and the method uses a Smart Tee filter, it returns VFW_S_NOPREVIEWPIN.

Closed Captioning. You can use this method to capture or preview closed captioning. Some capture filters deliver Vertical Blanking Interval (VBI) data, others deliver closed captioning data. To handle either case, call the method twice, once using PIN_CATEGORY_VBI and once using PIN_CATEGORY_CC. The method inserts any filters needed to convert VBI data to closed captioning. To preview the data, set the pfRenderer parameter to NULL. To capture the data to a file, use the multiplexer filter's IBaseFilter interface pointer. You can capture and preview the data in the same graph. Call the method once using NULL and again using the multiplexer. Set the pfCompressor parameter to NULL.

Video Port Pins. Filters that work with video port extension (VPE) video capture hardware might have video port pins (PIN_CATEGORY_VIDEOPORT) instead of preview pins. For preview or capture to work, a video port pin must connect to the Overlay Mixer filter. The method handles this detail. You do not have to specify PIN_CATEGORY_VIDEOPORT. Specify PIN_CATEGORY_PREVIEW or PIN_CATEGORY_CAPTURE, and the method will connect the pin correctly. In a similar way, some filters deliver VBI data using video port pins (PIN_CATEGORY_VIDEOPORT_VBI). As with PIN_CATEGORY_VIDEOPORT, the method handles this detail. You do not have to specify PIN_CATEGORY_VIDEOPORT_VBI.

Supporting Filters. If a capture device uses a Windows Driver Model (WDM) driver, the graph may require certain filters upstream from the WDM Video Capture filter, such as a TV Tuner filter or a Analog Video Crossbar filter. If this method successfully renders the stream, it also inserts any WDM filters that are required in your graph. The method queries the input pins on the capture filter to determine what mediums they support, and connects them to matching filters.

File Sources. Although this method is designed for building capture graphs, another use for it is to transcode or recompress a file. The following discussion assumes that the file has at most one video stream and one audio stream, or else a single interleaved stream. Otherwise, the method will not work correctly. A file source has one output pin, so set pCategory and pType to NULL. Call the method twice—once to render the video stream and once to render the audio stream. The first call connects the source filter to a parser filter and renders one of the parser filter's output pins. The second call renders the parser's remaining output pin. If you are compressing one stream but not the other, make sure to specify the compressor filter (the pfCompressor parameter) in the first call. If pfCompressor is NULL in the first call, the method might render either stream (video or audio). For a complete example, see Recompressing an AVI File.

ICaptureGraphBuilder2::SetFiltergraph

ICaptureGraphBuilder2 Interface

Specifies a filter graph for the capture graph builder to use.

Syntax

HRESULT SetFiltergraph(
    IGraphBuilder *pfg
);

Parameters

pfg
[in] Pointer to the filter graph's IGraphBuilder interface.

Return Value

Returns an HRESULT value. Possible values include the following:

E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected error.

Remarks

If you do not call this method, the capture graph builder automatically creates a filter graph when it needs one. If the capture graph builder already has a filter graph, this method returns E_UNEXPECTED.

ICaptureGraphBuilder2::SetOutputFileName

ICaptureGraphBuilder2 Interface

Creates the file writing section of the filter graph.

Syntax

HRESULT SetOutputFileName(
    const GUID *pType,
    LPCOLESTR lpwstrFile,
    IBaseFilter **ppf,
    IFileSinkFilter **pSink
);

Parameters

pType
[in] Pointer to a GUID that represents either the media subtype of the output or the class identifier (CLSID) of a multiplexer filter or file writer filter. If you specify a media subtype, it must be one of the following:
MEDIASUBTYPE_Avi | Audio-Video Interleaved (AVI)
MEDIASUBTYPE_Asf | Advanced Streaming Format (ASF)
lpwstrFile
[in] Pointer to a Unicode™ string that contains the output file name.
ppf
[out] Address of a pointer that receives the multiplexer's IBaseFilter interface.
pSink
[out] Address of a pointer that receives the file writer's IFileSinkFilter interface. Can be NULL.

Return Value

Returns an HRESULT value. Possible values include the following:
S_OK | Success.
E_FAIL | Failure.
E_POINTER | Null pointer argument.

Remarks

This method inserts the multiplexer and the File Writer filter into the filter graph. It also calls IFileSinkFilter::SetFileName to set the output file name.

You can use the pointer to the multiplexer filter, returned in the ppf parameter, as the pfRenderer parameter in the RenderStream method.

If the method succeeds, the IBaseFilter interface returned in the ppf parameter has an outstanding reference count. If the method succeeds and pSink is not NULL, the IFileSinkFilter interface also has an outstanding reference count. Be sure to release both interfaces when you are done using them.


IConfigAviMux Interface

The IConfigAviMux interface controls how the AVI multiplexer filter writes files out to disk. Microsoft® DirectShow® currently exposes this interface through the property page of the AVI multiplexer filter and you can use it to set the master stream and compatibility indexes.

IConfigAviMux provides backward compatibility with older Video for Windows® Audio-Video Interleaved (AVI) index formats (idx1) as well as extended AVI 2.0 index formats (indx) to allow for file sizes greater than 1 gigabyte (GB). Set and retrieve the compatibility indexes by using the IConfigAviMux::SetOutputCompatibilityIndex and IConfigAviMux::GetOutputCompatibilityIndex methods. See AVI 2.0 File Format Extensions for more information on AVI 2.0.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IConfigAviMux methods | Description
SetMasterStream | Sets the master stream that other streams must synchronize to after the file is saved to disk.
GetMasterStream | Retrieves the master stream that other streams must synchronize to after the file is written out.
SetOutputCompatibilityIndex | Sets the AVI index format for the file that the multiplexer saves to.
GetOutputCompatibilityIndex | Retrieves the AVI index format for the file that the multiplexer will write to.

IConfigAviMux::GetMasterStream

IConfigAviMux Interface

Retrieves the master stream that other streams must synchronize to after the file is written out.

Syntax

HRESULT GetMasterStream(
  LONG *pStream
  );

Parameters

pStream
[out] Pointer to the master stream.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

To eliminate capture drifts that can occur between audio sampling rates and video frame rates, it is recommended that you use combined audio/video cards for capture of large files.

See Also

IConfigAviMux::SetMasterStream

IConfigAviMux::GetOutputCompatibilityIndex

IConfigAviMux Interface

Retrieves the AVI index format for the file that the multiplexer will write to.

Syntax

HRESULT GetOutputCompatibilityIndex(
  BOOL *pfOldIndex
  );

Parameters

pfOldIndex
[out] Pointer to a value indicating the index format. Returns TRUE if AVI 1.0 (idx1) index format or AVI 2.0 (indx) index format is set; returns FALSE if only AVI 2.0 (indx) index format is set.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

SetOutputCompatibilityIndex

IConfigAviMux::SetMasterStream

IConfigAviMux Interface

Sets the master stream that other streams must synchronize to after the file is saved to disk.

Syntax

HRESULT SetMasterStream(
  LONG iStream
  );

Parameters

iStream
[in] Master input stream. Set to –1 to disable.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Different streams in the capture scenario can capture at different rates if you are using separate audio and video capture cards. By specifying a master stream that all others must synchronize to, this method adjusts the frame rate or audio sampling rate to account for drifts in the rates.

To eliminate capture drifts that can occur between audio sampling rates and video frame rates, it is recommended that you use combined audio/video cards for capture of large files.

See Also

IConfigAviMux::GetMasterStream

IConfigAviMux::SetOutputCompatibilityIndex

IConfigAviMux Interface

Sets the AVI index format for the file that the multiplexer saves to.

Syntax

HRESULT SetOutputCompatibilityIndex(
  BOOL fOldIndex
  );

Parameters

fOldIndex
[in] Value specifying the AVI index format. TRUE indicates either AVI 1.0 (idx1) index format or AVI 2.0 (indx) index format; FALSE indicates only AVI 2.0 (indx) index format.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

In addition to backward compatibility with Video for Windows® AVI index formats (idx1), DirectShow also supports extended AVI 2.0 index format (indx), which this method can specify. AVI 2.0 index format allows for increased AVI file size (greater than 1 GB), hierarchical indexing, incremental growth of files, and minimal disk seeks. See AVI 2.0 File Format Extensions for more information on AVI 2.0.

See Also

IConfigAviMux::GetOutputCompatibilityIndex


IConfigInterleaving Interface

The IConfigInterleaving interface is implemented on the AVI multiplexer filter. The interface controls how files are written out to disk and sets interleaving configuration information such as frequency and preroll parameters.

This interface uses the InterleavingMode enumerated data type, which specifies how audio samples and video frames will be saved on a disk. Capture interleaving settings can range from INTERLEAVE_NONE to INTERLEAVE_FULL, depending on whether you will author immediately or later.

Video-authoring applications that handle capturing should use this interface when they need to control how audio samples and video frames will be saved on a disk.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IConfigInterleaving methods | Description
put_Mode | Sets how audio samples and video frames will be saved on disk by specifying quality of interleaving.
get_Mode | Retrieves the interleaving quality setting.
put_Interleaving | Sets the audio preroll time and the frequency of the interleaving.
get_Interleaving | Retrieves the audio preroll time and the frequency of the interleaving.

IConfigInterleaving::get_Interleaving

IConfigInterleaving Interface

Retrieves the audio preroll time and the frequency of the interleaving.

Syntax

HRESULT get_Interleaving(
    REFERENCE_TIME *prtInterleave,
    REFERENCE_TIME *prtPreroll );

Parameters

prtInterleave
[out] Pointer to the frequency of the streams in the file, in 100-nanosecond units.
prtPreroll
[out] Pointer to the audio preroll, in 100-nanosecond units.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IConfigInterleaving::put_Interleaving

IConfigInterleaving::get_Mode

IConfigInterleaving Interface

Retrieves the interleaving quality setting.

Syntax

HRESULT get_Mode(
    InterleavingMode *pMode );

Parameters

pMode
[out] Pointer to the interleaving quality setting specified in the InterleavingMode enumerated data type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The interleaving mode is specified in the InterleavingMode enumerated data type and is set in the IConfigInterleaving::put_Mode method.

See Also

IConfigInterleaving::put_Mode

IConfigInterleaving::put_Interleaving

IConfigInterleaving Interface

Sets the audio preroll time and the frequency of the interleaving.

Syntax

HRESULT put_Interleaving(
    const REFERENCE_TIME *prtInterleave,
    const REFERENCE_TIME *prtPreroll );

Parameters

prtInterleave
[in] Pointer to the frequency of the streams in the file, in 100-nanosecond units.
prtPreroll
[in] Pointer to the audio preroll, in 100-nanosecond units.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

An audio preroll of 750 milliseconds is recommended when authoring a file for distribution.

The default value for prtInterleave is 1000 milliseconds; however, you can adjust this. The smaller the number, the larger the file.

See Also

IConfigInterleaving::get_Interleaving

IConfigInterleaving::put_Mode

IConfigInterleaving Interface

Sets how audio samples and video frames are to be written to disk, by specifying quality of interleaving.

Syntax

HRESULT put_Mode(
    InterleavingMode mode );

Parameters

mode
[in] Interleaving quality setting specified in the InterleavingMode enumerated data type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Applications that require full interleaving authoring quality should specify INTERLEAVE_FULL, INTERLEAVE_CAPTURE, and INTERLEAVE_NONE settings when you will author at a later time.

See Also

IConfigInterleaving::get_Mode


ICreateDevEnum Interface

Creates an enumerator for a list of filters and hardware devices in a specified filter category. The returned enumerator supports the IEnumMoniker interface.

The system device enumerator exposes this interface. It differentiates between individual hardware devices, even if the same filter supports them.

Applications can use this interface to find instances of filters that represent hardware devices. First create an instance of the system device enumerator, and then use it to create an enumerator for a particular category of device. For more information, see Enumerating Devices and Filters.

For more information on using enumerators, see the IEnumXXXX topic in the Platform SDK documentation.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
ICreateDevEnum methods | Description
CreateClassEnumerator | Creates a class enumerator for the specified category.

ICreateDevEnum::CreateClassEnumerator

ICreateDevEnum Interface

Creates an enumerator for the specified type of object.

Syntax

HRESULT CreateClassEnumerator(

  REFCLSID clsidDeviceClass,

  IEnumMoniker **ppEnumMoniker,

  DWORD dwFlags

  );

Parameters

clsidDeviceClass
[in] REFCLSID value that specifies the type of device to enumerate. (See Filter Categories.)
ppEnumMoniker
[out] Address of a pointer to the Win32 IEnumMoniker (or derived) interface implemented by the new class enumerator.
dwFlags
[in] Reserved. Must be 0.

Return Value

Returns one of the following values.
NOERROR | Success.
S_OK | Success.
E_OUTOFMEMORY | There is not enough memory available to create a class enumerator.
S_FALSE | The category specified by clsidDeviceClass does not exist.

Remarks

If no devices are found, the method does not return with a moniker of zero elements, instead, no moniker is returned.

The new class enumerator is a nonaggregate object that will run in the same process as the class that called this method.


IDDrawExclModeVideo Interface

The IDDrawExclModeVideo interface is implemented by the Overlay Mixer filter. The interface enables video playback while in Microsoft® DirectDraw® exclusive full-screen mode. Game applications can use DirectDraw in exclusive full-screen mode and continue playing video. For example, the video can be in the background and graphics can be used on top of it. The application passes in a DirectDraw object and primary surface, and these are passed to the Overlay Mixer filter in the filter graph.

The DVD graph builder object uses IDDrawExclModeVideo to play DVD content while in DirectDraw exclusive full-screen mode. This interface can also be used alone to play MPEG-1 or AVI videos in games.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDDrawExclModeVideo methods | Description
SetDDrawObject | Sets the DirectDraw object to be used in subsequent drawing.
GetDDrawObject | Retrieves the DirectDraw object being used by the Overlay Mixer.
SetDrawParameters | Specifies which part of the original video will appear at which position of the screen.
SetDDrawSurface | Sets the DirectDraw surface to be used in subsequent drawing.
GetDDrawSurface | Retrieves the DirectDraw surface being used by the Overlay Mixer.
GetNativeVideoProps | Retrieves the width, height, and aspect ratio of the Overlay Mixer's primary stream.
SetCallbackInterface | Specifies the callback interface to the Overlay Mixer so that the calling application can be notified about adjustments to the display during video playback.

IDDrawExclModeVideo::GetDDrawObject

IDDrawExclModeVideo Interface

Retrieves the DirectDraw object being used by the Overlay Mixer filter.

Syntax

HRESULT GetDDrawObject(
    LPDIRECTDRAW *pDDrawObject,
    LPBOOL *pbUsingExternal
);

Parameters

pDDrawObject
[out] Address of a pointer to the IDirectDraw interface that the Overlay Mixer is using.
pbUsingExternal
[out] Address of a pointer to a value indicating whether the Overlay Mixer is using a DirectDraw object specified by SetDDrawObject; TRUE if the Overlay Mixer is using a DirectDraw object specified SetDDrawObject or FALSE otherwise.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The current Microsoft® DirectShow® implementation return values include the following:

S_OK | Success.
E_INVALIDARG | Argument is invalid.
A DirectDraw error code | A DirectDraw error is encountered when trying to set the specified surface on the Overlay Mixer.

Remarks

If the filter graph has not set a DirectDraw object and the Overlay Mixer has not yet allocated one, then pDDrawObject will be set to NULL and pbUsingExternal will be set to FALSE.

IDDrawExclModeVideo::GetDDrawSurface

IDDrawExclModeVideo Interface

Retrieves the DirectDraw surface being used by the Overlay Mixer.

Syntax

HRESULT GetDDrawSurface(
    LPDIRECTDRAWSURFACE *pDDrawSurface,
    LPBOOL *pdUsingExternal
);

Parameters

pDDrawSurface
[out] Address of a pointer to the IDirectDrawSurface interface that is being used by the Overlay Mixer.
pdUsingExternal
[out] Address of a pointer to a Boolean value indicating whether the Overlay Mixer is using a DirectDraw surface specified by SetDDrawSurface; TRUE if the Overlay Mixer is using a DirectDraw surface specified by SetDDrawSurface or FALSE otherwise.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The current DirectShow implementation return values include the following:

S_OK | Success.
E_INVALIDARG | Argument is invalid.
A DirectDraw error code | A DirectDraw error is encountered when trying to set the specified surface on the Overlay Mixer.

Remarks

If the filter graph has not set a DirectDraw surface and the Overlay Mixer has not yet allocated one, then pDDrawSurface will be set to NULL and pdUsingExternal will be set to FALSE.

IDDrawExclModeVideo::GetNativeVideoProps

IDDrawExclModeVideo Interface

Retrieves the current video size and picture aspect ratio of the Overlay Mixer's primary stream.

Syntax

HRESULT GetNativeVideoProps(
    LPDWORD *pdwVideoWidth,
    LPDWORD *pdwVideoHeight,
    LPDWORD *pdwPictAspectRatioX,
    LPDWORD *pdwPictAspectRatioY
);

Parameters

pdwVideoWidth
[out] Address of a pointer to the width of the video.
pdwVideoHeight
[out] Address of a pointer to the height of the video.
pdwPictAspectRatioX
[out] Address of a pointer to the x-axis aspect ratio.
pdwPictAspectRatioY
[out] Address of a pointer to the y-axis aspect ratio.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The current DirectShow implementation return values include the following:

S_OK | Success.
E_INVALIDARG | Argument is invalid.

Remarks

The filter graph should look for the EC_VIDEO_SIZE_CHANGED event, and on its receipt call this method to adjust the aspect ratio and position.

IDDrawExclModeVideo::SetCallbackInterface

IDDrawExclModeVideo Interface

Retrieves a pointer to the callback interface of the Overlay Mixer so that the calling application can be notified about adjustments to the display during video playback.

Syntax

HRESULT SetCallbackInterface(
    IDDrawExclModeVideoCallback *pCallback
    DWORD dwFlag
);

Parameters

pCallback
[out] Pointer to the object that implements the IDDrawExclModeVideoCallback interface. If pCallback is NULL, the callback interface is set to NULL and no more callbacks are made. If there was a previous callback interface, it is released and no more callbacks are made to it. If pCallback is not NULL and this method returns S_OK, then the reference count of the object pCallback points to is incremented.
dwFlag
[in] Must be zero.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The current DirectShow implementation return values include the following:

S_OK | Success.
E_INVALIDARG | Argument is invalid.

Remarks

An application should use this method to get notification about the overlay size, position, or color key change happening, so that it can hide or show the video, or adjust the video at the start, end, or during playback. By calling this method, an application can access the IDDrawExclModeVideoCallback interface and pass the pointer to that interface to the Overlay Mixer.

IDDrawExclModeVideo::SetDDrawObject

IDDrawExclModeVideo Interface

Sets the DirectDraw object to be used in subsequent drawing.

Syntax

HRESULT SetDDrawObject(
    LPDIRECTDRAW *pDDrawObject
);

Parameters

pDDrawObject
[in] Address of a pointer to the IDirectDraw interface on the object to use.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The current DirectShow implementation return values include the following:

S_OK | Success.
E_INVALIDARG | Argument is invalid.
A DirectDraw error code | A DirectDraw error is encountered when trying to set the specified surface on the Overlay Mixer.

Remarks

A game application can use this method to share the DirectDraw object it has created for itself to the Overlay Mixer filter, so that the video can be drawn in a specified surface, as set in SetDDrawSurface.

IDDrawExclModeVideo::SetDrawParameters

IDDrawExclModeVideo Interface

Specifies which part of the original video will appear at which position of the screen.

Syntax

HRESULT SetDrawParameters(
    RECT *pSrcRect,
    RECT *pDestRect
);

Parameters

pSrcRect
[in] Pointer to the RECT structure of the original video.
pDestRect
[in] Pointer to the RECT that indicates where the video will appear on the screen.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

See Also

IDDrawExclModeVideoCallback

IDDrawExclModeVideo::SetDDrawSurface

IDDrawExclModeVideo Interface

Specifies the DirectDraw surface to be used in subsequent drawing.

Syntax

HRESULT SetDDrawSurface(
    LPDIRECTDRAWSURFACE *pDDrawSurface
);

Parameters

pDDrawSurface
[in] Address of a pointer to the IDirectDrawSurface interface on the surface to use.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The current DirectShow implementation return values include the following:

S_OK | Success.
E_INVALIDARG | Argument is invalid.
A DirectDraw error code | A DirectDraw error is encountered when trying to set the specified surface on the Overlay Mixer.

Remarks

A game application can use this to share the DirectDraw surface it has created for itself to the Overlay Mixer filter so that the video can be drawn in a specified surface. This surface must be associated with the object specified in SetDDrawObject.


IDDrawExclModeVideoCallback Interface

The IDDrawExclModeVideoCallback interface enables applications to get synchronous notification about changes to the overlay position, size, visibility, and so on, so that the application can adjust its video visibility, size, and position. This avoids any color key flash at the beginning, end, or during playback. The application must implement a COM object supporting this interface.

Implement this interface if you are using an IDDrawExclModeVideo interface and want the callback information (presumably always).

Use this interface if you're using the Microsoft® DirectShow® Overlay Mixer filter, and more generally if you are writing a filter that supports IDDrawExclModeVideo or needs to generate callbacks to enable an application to draw color keys at the right time.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDDrawExclModeVideoCallback methods | Description
OnUpdateOverlay | Informs the application when the overlay surface for the video is about to change.
OnColorKeyChange | Informs the application that the color key has changed so that the application can use the new color key to overlay graphics on the video.

IDDrawExclModeVideoCallback::OnColorKeyChange

IDDrawExclModeVideoCallback Interface

Informs the application that the color key has changed so that the application can use the new color key to overlay graphics on the video.

Syntax

HRESULT OnColorKeyChange (
    COLORKEY const *pKey,
    DWORD dwColor
);

Parameters

pKey
[out] Pointer to a COLORKEY structure that contains the key type and a palette index.
dwColor
[out] Value indicating the 8-bit palette index of the COLORKEY returned in pKey, if the current display mode is 8-bit palettized. Otherwise, it is a value representing the color key in the pixel format of the current display mode.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The current DirectShow implementation return values include the following:
S_OK | Success.
E_INVALIDARG | One of the parameters is invalid.

IDDrawExclModeVideoCallback::OnUpdateOverlay

IDDrawExclModeVideoCallback Interface

Informs the application when the overlay surface for the video is about to become visible, invisible, change size, or change position, so that the application can repaint its window appropriately.

Syntax

HRESULT OnUpdateOverlay(
    BOOL bBeforeChange,
    DWORD dwFlags,
    BOOL bOldVisible,
    LPRECT *prcSrcOld,
    LPRECT *prcDestOld,
    BOOL bNewVisible,
    LPRECT *prcSrcNew,
    LPRECT *prcDestNew,
);

Parameters

bBeforeChange
[in] Boolean value specifying whether the call is being made before or after the overlay-related change. TRUE specifies before, FALSE specifies after.
dwFlags
[in] Value from the AM_OVERLAY_NOTIFY_FLAGS data type that specifies what is about to change or what changed.
bOldVisible
[in] Boolean value specifying whether the old window is visible. TRUE means the old window is visible.
prcSrcOld
[in] Pointer to the rectangle representing the old source position of the DirectDraw surface.
prcDestOld
[in] Pointer to the rectangle representing the old destination position of the rectangle in the overlay surface.
bNewVisible
[in] Boolean specifying whether the new window is visible. TRUE means the new window is visible.
prcSrcNew
[in] Pointer to the rectangle representing the new source position of the DirectDraw surface.
prcDestNew
[in] Pointer to the rectangle representing the new destination position of the rectangle in the overlay surface.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The current DirectShow implementation return values include the following:
S_OK | Success.
E_INVALIDARG | Invalid parameter.

Remarks

The application should call this method once before the overlay-related change occurs and once after the changes are done. In the call before the change, the overlay change doesn't happen until the application completes executing this method.


IDecimateVideoImage Interface

The IDecimateVideoImage interface specifies decimation on a decoder filter. The term decimation refers to scaling the video output down to a size smaller than the native size of the video.

Applications must not call methods on this interface. The Overlay Mixer filter uses this interface to decimate video at the video decoder.

Decoder filters that can decimate their video output should support this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDecimateVideoImage methods | Description
SetDecimationImageSize | Specifies the dimensions to which the decoder should decimate its output image.
ResetDecimationImageSize | Specifies that the decoder should no longer decimate its output image.

IDecimateVideoImage::ResetDecimationImageSize

IDecimateVideoImage Interface

Specifies that the decoder should no longer decimate its output image.

Syntax

HRESULT ResetDecimationImageSize(void);

Return Value

Returns an HRESULT value indicating the success or failure of the call.

IDecimateVideoImage::SetDecimationImageSize

IDecimateVideoImage Interface

Specifies the dimensions to which the decoder should decimate its output image.

Syntax

HRESULT SetDecimationImageSize(
    long lWidth,
    long lHeight
);

Parameters

lWidth
[in] Width of the video image, in pixels.
lHeight
[in] Height of the video image, in pixels.

Return Value

Returns one of the following HRESULT values.

E_FAIL | The decoder cannot perform any decimation, or needs to halt decimation it is currently performing.
S_OK | The decoder can decimate the video to the requested size.


IDeferredCommand Interface

Enables an application to cancel or modify graph-control commands that the application previously queued using the IQueueCommand interface.

When an application calls an IQueueCommand method on the filter graph manager, it receives a pointer to the IDeferredCommand interface. The application can use the interface to cancel or postpone the command, or retrieve the return value from the command.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDeferredCommand methods | Description
Cancel | Cancels a command that the application previously queued.
Confidence | Retrieves a confidence value that indicates how likely it is for the command to be invoked at the requested time.
Postpone | Specifies a new invocation time for the command.
GetHResult | Retrieves the return value from the invoked command.

IDeferredCommand::Cancel

IDeferredCommand Interface

Cancels a command that the application previously queued.

Syntax

HRESULT Cancel(void);

Return Value

Returns S_OK if successful. If the request was already canceled, returns VFW_E_ALREADY_CANCELLED.

IDeferredCommand::Confidence

IDeferredCommand Interface

Retrieves a confidence value that indicates how likely it is for the command to be invoked at the requested time.

This method is not implemented and returns E_NOTIMPL.

Syntax

HRESULT Confidence(
    LONG *pConfidence
);

Parameters

pConfidence
Pointer to a variable that receives the confidence level, on a scale of 0 to 100.

Return Value

Returns E_NOTIMPL.

IDeferredCommand::GetHResult

IDeferredCommand Interface

Retrieves the return value from the invoked command.

Syntax

HRESULT GetHResult(
    HRESULT *phrResult
);

Parameters

phrResult
Pointer to a variable that receives the HRESULT value.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_ABORT | Command has not yet been invoked.
E_POINTER | NULL pointer argument.

IDeferredCommand::Postpone

IDeferredCommand Interface

Specifies a new invocation time for the command.

Syntax

HRESULT Postpone(
    REFTIME newtime
);

Parameters

newtime
New time at which to invoke the command.

Return Value

Returns S_OK if successful. If the requested time has already passed, returns VFW_E_TIME_ALREADY_PASSED.


IDirectDrawVideo Interface

The IDirectDrawVideo interface is implemented on the Video Renderer and provides applications with information about DirectDraw surfaces and hardware capabilities. Applications use this interface to control what DirectDraw features the Video Renderer will take advantage of. For example, if you are positive that you don't want the Video Renderer to use a hardware overlay you can disable its use via the SetSwitches method.

Note You can't use this interface to force the Video Renderer to use a particular DirectDraw feature; you can only stop it from using that feature.

There is some duplication in this interface with the IDirectDraw interface; however, this interface enables simple access to that information without calling the DirectDraw provider directly.

The Video Renderer doesn't load DirectDraw until it is connected, and likewise DirectDraw is unloaded only when the renderer is disconnected. When the renderer has allocated the DirectDraw surfaces it will use for video playback, an application can obtain a DDSURFACEDESC structure describing it. By passing in a pointer to a DDSURFACEDESC structure, the renderer will fill in the structure with the details of the current surface. If DirectDraw has not been loaded, the renderer will return E_FAIL. If the renderer is using DCI (the predecessor to DirectDraw), the DDSURFACEDESC structure is not filled in but the call will return S_FALSE. The only type of DCI surfaces the renderer uses are primary surfaces.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDirectDrawVideo methods | Description
GetCaps | Retrieves a DirectDraw-defined DDCAPS structure containing the hardware capabilities.
GetEmulatedCaps | Retrieves a DirectDraw-defined DDCAPS structure containing the emulated capabilities.
CanUseOverlayStretch | Determines whether the renderer will check overlay restrictions.
CanUseScanLine | Determines whether the renderer will check the current scan line when drawing.
GetDirectDraw | Retrieves the IDirectDraw interface.
GetFourCCCodes | Retrieves the multimedia format type FOURCC DWORD.
GetSurfaceDesc | Retrieves a description of the DirectDraw surface in use.
GetSurfaceType | Retrieves the actual surface type.
GetSwitches | Retrieves the surface types that the renderer is allowed to use.
SetDefault | Makes the current property settings the global default.
SetDirectDraw | Passes the IDirectDraw interface to a loaded driver.
SetSwitches | Sets the surface types that the renderer is allowed to use.
UseOverlayStretch | Determines whether the renderer should check overlay stretch limitations.
UseScanLine | Determines whether the renderer should check the current scan line when drawing a video.
UseWhenFullScreen | Determines whether DirectShow should change display mode when going to full-screen mode.
WillUseFullScreen | Determines whether DirectShow will change display mode when going to full-screen mode.

IDirectDrawVideo::CanUseOverlayStretch

IDirectDrawVideo Interface

Determines whether the renderer will check overlay restrictions.

Syntax

HRESULT CanUseOverlayStretch(
    long *UseOverlayStretch
);

Parameters

UseOverlayStretch
Pointer to a value indicating whether the renderer can use overlay restrictions. OATRUE indicates the renderer will check overlay restrictions; OAFALSE indicates it will not.

Return Value

Returns an HRESULT value.

Remarks

For a description of overlay stretching, see IDirectDrawVideo::UseOverlayStretch.

IDirectDrawVideo::CanUseScanLine

IDirectDrawVideo Interface

Determines whether the renderer will check the current scan line when drawing.

Syntax

HRESULT CanUseScanLine(
    long *UseScanLine
);

Parameters

UseScanLine
Pointer to a value indicating whether the renderer will use scan line information. OATRUE indicates the renderer will check the current scan line when drawing; OAFALSE indicates it will not.

Return Value

Returns an HRESULT value.

Remarks

For a description of the use of scan line detection in the DirectShow video renderer, see IDirectDrawVideo::UseScanLine.

IDirectDrawVideo::GetCaps

IDirectDrawVideo Interface

Retrieves a DirectDraw-defined DDCAPS structure containing the hardware capabilities.

Syntax

HRESULT GetCaps(
    DDCAPS *pCaps
);

Parameters

pCaps
Pointer to a DDCAPS structure containing the hardware capabilities.

Return Value

Returns an HRESULT value.

Remarks

If the renderer has not loaded DirectDraw, this method returns E_FAIL.

IDirectDrawVideo::GetDirectDraw

IDirectDrawVideo Interface

Retrieves the IDirectDraw interface.

Syntax

HRESULT GetDirectDraw(
    LPDIRECTDRAW *ppDirectDraw
);

Parameters

ppDirectDraw
Address of a pointer to the IDirectDraw interface.

Return Value

Returns an HRESULT value.

Remarks

If an application wants to load DirectDraw but allow the renderer to also allocate surfaces, it can let the renderer load DirectDraw and then obtain a reference-incremented interface to it through this method. The interface returned should be released by the application when it is finished with it.

IDirectDrawVideo::GetEmulatedCaps

IDirectDrawVideo Interface

Retrieves a DirectDraw-defined DDCAPS structure containing the emulated capabilities.

Syntax

HRESULT GetEmulatedCaps(
    DDCAPS *pCaps
);

Parameters

pCaps
Pointer to a DDCAPS structure containing the emulated capabilities.

Return Value

Returns an HRESULT value. If the renderer has not loaded DirectDraw, this method returns E_FAIL.

IDirectDrawVideo::GetFourCCCodes

IDirectDrawVideo Interface

Retrieves the multimedia format type.

Syntax

HRESULT GetFourCCCodes(
    DWORD *pCount,
    DWORD *pCodes
);

Parameters

pCount
Pointer to the number of FOURCC codes in the pCodes array.
pCodes
Pointer to an array of DWORD media tags formerly used for Microsoft multimedia types.

Return Value

Returns an HRESULT value.

Remarks

In the original Microsoft® Windows® multimedia APIs, media types were tagged with 32-bit values created from four 8-bit characters and were known as FOURCC codes. Because FOURCC codes are unique, a one-to-one mapping has been made possible by allocating a range of 4 billion GUIDs representing FOURCCs.

This method retrieves the FOURCC codes that the current display driver can support. The number available is obtained by calling the method with a valid pCount pointer, but with pCodes set to NULL. In this case, the pCount variable will be filled in with the number of FOURCC codes available. An application can then allocate enough DWORD values for this many FOURCC codes and call the method again with the array pointer in pCodes.

IDirectDrawVideo::GetSurfaceDesc

IDirectDrawVideo Interface

Retrieves a DDSURFACEDESC structure describing the current DirectDraw surface.

Syntax

HRESULT GetSurfaceDesc(
    DDSURFACEDESC *pSurfaceDesc
);

Parameters

pSurfaceDesc
Pointer to a DDSURFACEDESC structure describing the current DirectDraw surface.

Return Value

Returns an HRESULT value. If no surface has been allocated, this method will return E_FAIL. If a DCI primary surface is in use, the DDSURFACEDESC structure will not be filled in and the call will return S_FALSE.

Remarks

Surfaces are allocated only when the renderer is paused. After the renderer has been paused, it cannot release the surfaces when stopped.

IDirectDrawVideo::GetSurfaceType

IDirectDrawVideo Interface

Retrieves the actual surface type as a DirectShow DirectDraw Surface (AMDDS) definition.

Syntax

HRESULT GetSurfaceType(
    DWORD *pSurfaceType
);

Parameters

pSurfaceType
Pointer to a field filled in with one bit setting selected from the following list of AMDDS definitions.
AMDDS_NONE | No use for DCI/DirectDraw.
AMDDS_DCIPS | Use DCI primary surface.
AMDDS_PS | Use DirectDraw primary surface.
AMDDS_RGBOVR | RGB overlay surfaces.
AMDDS_YUVOVR | YUV overlay surfaces.
AMDDS_RGBOFF | RGB off-screen surfaces.
AMDDS_YUVOFF | YUV off-screen surfaces.
AMDDS_RGBFLP | RGB flipping surfaces.
AMDDS_YUVFLP | YUV flipping surfaces.
AMDDS_ALL | All the previous flags.
AMDDS_DEFAULT | Use all available surfaces.
AMDDS_YUV | (AMDDS_YUVOFF | AMDDS_YUVOVR | AMDDS_YUVFLP).
AMDDS_RGB | (AMDDS_RGBOFF | AMDDS_RGBOVR | AMDDS_RGBFLP).
AMDDS_PRIMARY | (AMDDS_DCIPS | AMDDS_PS).

Return Value

Returns an HRESULT value.

Remarks

It is not always easy to discover which kind of surface is being used by looking at a DDSURFACEDESC structure. Therefore, an application can call GetSurfaceType to retrieve the surface type. The field will be filled in with one bit setting selected from the preceding list of AMDDS definitions.

IDirectDrawVideo::GetSwitches

IDirectDrawVideo Interface

Retrieves the surface types that the renderer is allowed to use.

Syntax

HRESULT GetSwitches(
    DWORD *pSwitches
);

Parameters

pSwitches
Pointer to a bit mask containing one or more of the following DirectShow DirectDraw Surface (AMDDS) surface types.
AMDDS_NONE | No use for DCI/DirectDraw.
AMDDS_DCIPS | Use DCI primary surface.
AMDDS_PS | Use DirectDraw primary surface.
AMDDS_RGBOVR | RGB overlay surfaces.
AMDDS_YUVOVR | YUV overlay surfaces.
AMDDS_RGBOFF | RGB off-screen surfaces.
AMDDS_YUVOFF | YUV off-screen surfaces.
AMDDS_RGBFLP | RGB flipping surfaces.
AMDDS_YUVFLP | YUV flipping surfaces.
AMDDS_ALL | All the previous flags.
AMDDS_DEFAULT | Use all available surfaces.
AMDDS_YUV | (AMDDS_YUVOFF | AMDDS_YUVOVR | AMDDS_YUVFLP).
AMDDS_RGB | (AMDDS_RGBOFF | AMDDS_RGBOVR | AMDDS_RGBFLP).
AMDDS_PRIMARY | (AMDDS_DCIPS | AMDDS_PS).

Return Value

Returns an HRESULT value.

IDirectDrawVideo::SetDefault

IDirectDrawVideo Interface

Makes the current property settings the global default.

Syntax

HRESULT SetDefault(void);

Return Value

Returns an HRESULT value.

Remarks

All properties set through IDirectDrawVideo are specific to that particular instance. Call this method to make properties set on this instance of IDirectDrawVideo the global default of all DirectShow instances of this interface. After it is called, the current property settings will persist between the subsequent starting of other DirectShow filter graphs and between any computer restarts.

IDirectDrawVideo::SetDirectDraw

IDirectDrawVideo Interface

Passes the IDirectDraw interface to a loaded driver.

Syntax

HRESULT SetDirectDraw(
    LPDIRECTDRAW pDirectDraw
);

Parameters

pDirectDraw
Pointer to the IDirectDraw interface to be passed.

Return Value

Returns an HRESULT value.

Remarks

To have the renderer release a DirectDraw interface previously passed in through SetDirectDraw, an application can call SetDirectDraw and pass in NULL. However, the renderer will continue using that DirectDraw interface until it is disconnected. Therefore, calling SetDirectDraw with a null parameter does not make the renderer stop using it immediately.

This method was created because only one instance of IDirectDraw could be loaded per process in versions of DirectDraw prior to DirectX 7.0. If you are using DirectX 7.0 or later, you never need to call this method. If an application wanted to load IDirectDraw but allow the Video Renderer to also allocate surfaces, the application could open IDirectDraw itself and then pass the interface to the loaded driver through IDirectDrawVideo::SetDirectDraw. Alternatively, the application could let the renderer load DirectDraw and then obtain a reference-incremented interface to it through IDirectDrawVideo::GetDirectDraw. Because DirectShow ships with the most recently shipped version of DirectDraw, however, this method is not required unless the application wants to change display modes itself and pass in a DirectDraw object, which the renderer can then use to allocate surfaces.

IDirectDrawVideo::SetSwitches

IDirectDrawVideo Interface

Sets the surface types that the renderer is allowed to use.

Syntax

HRESULT SetSwitches(
    DWORD Switches
);

Parameters

Switches
Bit mask containing one or more of the following DirectShow DirectDraw Surface (AMDDS) surface types.
AMDDS_NONE | No use for DCI/DirectDraw.
AMDDS_DCIPS | Use DCI primary surface.
AMDDS_PS | Use DirectDraw primary surface.
AMDDS_RGBOVR | RGB overlay surfaces.
AMDDS_YUVOVR | YUV overlay surfaces.
AMDDS_RGBOFF | RGB off-screen surfaces.
AMDDS_YUVOFF | YUV off-screen surfaces.
AMDDS_RGBFLP | RGB flipping surfaces.
AMDDS_YUVFLP | YUV flipping surfaces.
AMDDS_ALL | All the previous flags.
AMDDS_DEFAULT | Use all available surfaces.
AMDDS_YUV | (AMDDS_YUVOFF | AMDDS_YUVOVR | AMDDS_YUVFLP).
AMDDS_RGB | (AMDDS_RGBOFF | AMDDS_RGBOVR | AMDDS_RGBFLP).
AMDDS_PRIMARY | (AMDDS_DCIPS | AMDDS_PS).

Return Value

Returns an HRESULT value.

Remarks

This method must be called before the Video Renderer is connected.

IDirectDrawVideo::UseOverlayStretch

IDirectDrawVideo Interface

Determines whether the renderer should check overlay stretch limitations.

Syntax

HRESULT UseOverlayStretch(
    long UseOverlayStretch
);

Parameters

UseOverlayStretch
Value specifying whether the renderer checks overlay stretching. Set to OATRUE for the renderer to check overlay stretching; otherwise, set to OAFALSE.

Return Value

Returns an HRESULT value.

Remarks

Some display cards provide the use of overlay surfaces through DirectDraw. An overlay surface is a block of video memory whose contents are overlaid onto the display during the monitor's vertical refresh. DirectShow uses all available overlay surfaces where possible because they typically offer higher-quality video and very fast performance. On some display cards set to relatively high bit depths, the overlay must be displayed on the screen larger than its real size (to accommodate certain display hardware bandwidth limitations). If the overlay is not displayed large enough, certain undesirable effects can be seen on the display (sometimes described as a "fleeting shimmering" effect).

If UseOverlayStretch is set to OATRUE (on, the default), DirectShow will ensure the overlay is adequately stretched before displaying it. If it is set to OAFALSE (off), DirectShow will not check that the overlay is adequately stretched, and the user is likely to experience artifacts on the screen (although it will also guarantee that the overlay will be used if possible).

IDirectDrawVideo::UseScanLine

IDirectDrawVideo Interface

Determines whether the renderer should check the current scan line when drawing a video.

Syntax

HRESULT UseScanLine(
    long UseScanLine
);

Parameters

UseScanLine
Long integer value that specifies whether or not to use the scan line information. Set to OATRUE to use scan line information or OAFALSE to ignore it.

Return Value

Returns E_INVALIDARG if the argument is invalid or NOERROR otherwise.

Remarks

If you blit an image to the video memory while the monitor's scan line is scanning over a visible portion of the screen, the complete image will be a composite of the old and new images. This composite is known as a torn video image. You can avoid torn images by waiting until the previous image is complete before blitting the new image. Some video cards can retrieve the scan line's current position; if this information is available, you can have DirectShow try to reduce tearing by waiting until the scan line is off-screen before blitting the new image. Note that checking the scan line location increases load on the processor and can reduce the amount of video frames delivered to the screen. If scan line information is available, DirectShow uses it by default. Set UseScanLine to OAFALSE if you want to save processing time at the expense of minor image degradation.

IDirectDrawVideo::UseWhenFullScreen

IDirectDrawVideo Interface

Determines whether DirectShow should change display mode when going to full-screen mode.

Syntax

HRESULT UseWhenFullScreen(
    long UseWhenFullScreen
);

Parameters

UseWhenFullScreen
Value specifying whether to change the display mode. Set to OATRUE to cause the renderer to use DirectShow in full-screen mode; otherwise, set to OAFALSE.

Return Value

Returns an HRESULT value.

Remarks

When asked to go to full-screen mode, DirectShow has a number of choices. The first choice is to determine if any filters in the graph can support full-screen playback directly; if one can, it will be asked to do so.

The second choice is to automatically add a special full-screen renderer to the filter graph that uses DirectDraw mode-changing services to play back the video. By changing display modes, the video effectively fills more (but not necessarily all) of the display. So, for example, if the current mode is 1024 × 768 pixels, a video might look relatively small, but when displayed in a 320 × 240 display mode it might look very presentable.

The third and final choice is to simply take any renderer supporting the IVideoWindow interface and have its window stretched full-screen. This will typically offer lower performance than the second option (swapping in a full-screen DirectDraw-enabled renderer). If the UseWhenFullScreen parameter is set to On (OATRUE), the window will always be stretched full-screen for full-screen playback; if set to Off (the default), the filter graph manager is free to swap in the DirectDraw-enabled full-screen renderer.

IDirectDrawVideo::WillUseFullScreen

IDirectDrawVideo Interface

Determines whether DirectShow will change display mode when going to full-screen mode.

Syntax

HRESULT WillUseFullScreen(
    long *UseWhenFullScreen
);

Parameters

UseWhenFullScreen
Pointer to a value indicating whether DirectShow will use DirectX in full-screen mode. OATRUE indicates it will use full-screen mode; OAFALSE indicates it will not.

Return Value

Returns an HRESULT value.

Remarks

For a description of this feature, see IDirectDrawVideo::UseWhenFullScreen.


IDirectDrawMediaSample Interface

The IDirectDrawMediaSample interface is supported by objects that also support IMediaSample. The "buffer" for this type of sample is a Microsoft® DirectDraw® surface. This type of sample is allocated by the IDirectDrawMediaSampleAllocator for connections between the Overlay Mixer and upstream decoder filters. It enables the decoder filter to unlock the surface but still hold on to it, so that other components can access it.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDirectDrawMediaSample methods | Description
GetSurfaceAndReleaseLock | Retrieves and unlocks the surface that the sample represents.
LockMediaSamplePointer | Locks the surface that the sample represents.

IDirectDrawMediaSample::GetSurfaceAndReleaseLock

IDirectDrawMediaSample Interface

Retrieves and unlocks the surface that the sample represents.

Syntax

HRESULT GetSurfaceAndReleaseLock(
    IDirectDrawSurface **ppDirectDrawSurface
    RECT *pRect
);

Parameters

ppDirectDrawSurface
[out] Address of a pointer to the sample's IDirectDrawSurface interface.
pRect
[out] Pointer to a variable that receives the address of the rectangle defining the part of the surface that the sample represents.

Return Value

Returns an HRESULT value.

Remarks

The caller should release the returned surface pointer, except when calling the Overlay Mixer filter's implementation of this interface.

IDirectDrawMediaSample::LockMediaSamplePointer

IDirectDrawMediaSample Interface

Locks the surface that the sample represents.

Syntax

HRESULT LockMediaSamplePointer(void);

Return Value

Returns an HRESULT value.

Remarks

Call this method only after calling GetSurfaceAndReleaseLock.


IDirectDrawMediaSampleAllocator Interface

The IDirectDrawMediaSampleAllocator interface is implemented on the allocator created by the Overlay Mixer for its upstream connection with a video decoder. This allocator allocates IDirectDrawMediaSample media samples that also support the IMediaSample interface.

Decoder filters should not have to use this interface to connect to the Overlay Mixer. Applications never use this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDirectDrawMediaSampleAllocator methods | Description
GetDirectDraw | Retrieves the DirectDraw instance used to allocate surfaces.

IDirectDrawMediaSampleAllocator::GetDirectDraw

IDirectDrawMediaSampleAllocator Interface

Retrieves a pointer to the DirectDraw instance used to allocate surfaces.

Syntax

HRESULT GetDirectDraw(
    IDirectDraw **ppDirectDraw
);

Parameters

ppDirectDraw
[out] Address of a pointer that receives the DirectDraw object's IDirectDraw interface.

Return Value

Returns an HRESULT value.

Remarks

The caller should release the returned IDirectDraw pointer, except when calling the Overlay Mixer filter's implementation of this interface.


IDistributorNotify Interface

The IDistributorNotify interface is an optional interface for use by plug-in distributors to notify them of changes in the filter graph state. Applications never use this interface.

Implement this interface when writing a plug-in distributor (PID) that is aggregated with the filter graph manager if you want the PID to receive notifications of control and changes in the composition of filter graphs.

PIDs might often use methods on the filter graph manager. During a call to an IDistributorNotify method, do not take any lock that might be held by another code path that calls the filter graph manager. To do so could result in a deadlock.

The filter graph manager queries for this interface on any plug-in distributors that it aggregates. If found, it calls the appropriate Run, Pause, or SetSyncSource method before calling them on the IBaseFilter interface of each filter. It calls the NotifyGraphChange method whenever a filter is added or removed, or connections are changed.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDistributorNotify methods | Description
Stop | Called when the filter graph is entering a stopped state.
Pause | Called when the filter graph is entering a paused state.
Run | Called when the filter graph is entering a running state.
SetSyncSource | Called when a new clock is registered.
NotifyGraphChange | Called when the set of filters in the filter graph change or their connections change.

IDistributorNotify::NotifyGraphChange

IDistributorNotify Interface

Called when the set of filters in the filter graph change or their connections change.

Syntax

HRESULT NotifyGraphChange(void);

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed:
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method is called whenever an IFilterGraph::AddFilter, IFilterGraph::RemoveFilter, or IFilterGraph::ConnectDirect method is called or a method is called that will lead to one of these being called (such as IGraphBuilder::RenderFile).

Make sure you use Release on any held filters that have been removed at this point. For performance reasons, PIDs might choose not to rescan the filters until the PIDs actually need the interfaces, because there might be several separate notifications sent. However, it is important to release any cached interfaces immediately.

IDistributorNotify::Pause

IDistributorNotify Interface

Called when the filter graph is entering a paused state.

Syntax

HRESULT Pause(void);

Return Value

Returns S_OK if the transition is complete; otherwise, returns one of the following values.
Error value | Transition failed.
S_FALSE | Transition is not complete, but no error has occurred.

Remarks

This method is called before the filters are notified.

IDistributorNotify::Run

IDistributorNotify Interface

Called when the filter graph is entering a running state.

Syntax

HRESULT Run(
  REFERENCE_TIME tStart
  );

Parameters

tStart
Stream-time offset that will be passed to every filter's IMediaFilter::Run method.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method is called before the filters are notified.

IDistributorNotify::SetSyncSource

IDistributorNotify Interface

Called when a new clock is registered.

Syntax

HRESULT SetSyncSource(

  IReferenceClock *pClock

  );

Parameters

pClock
[in] Pointer to the IReferenceClock interface.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method is called before the filters are notified. Make sure to use AddRef on the pClock parameter if the plug-in distributor intends to hold it beyond this method call.

IDistributorNotify::Stop

IDistributorNotify Interface

Called when the filter graph is entering a stopped state.

Syntax

HRESULT Stop(void);

Return Value

Returns S_OK if the transition is complete; otherwise, returns one of the following values.
Error value | Transition failed.
S_FALSE | Transition is not complete, but no error has occurred.

Remarks

This method is called before the filters are notified.


IDMOWrapperFilter Interface

Enables applications to use a Microsoft® DirectX® Media Object (DMO) in a filter graph. The DMO Wrapper filter exposes this interface.

To add a DMO to the filter graph, create an instance of the DMO Wrapper filter and query it for the IDMOWrapperFilter interface. Then call the Init method to initialize the filter with the DMO. For more information, see Using DMOs in a DirectShow Application.

Requirements

Requires Dmodshow.h

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDMOWrapperFilter methods | Description
Init | Initializes the DMO Wrapper filter with the specified DMO.

IDMOWrapperFilter::Init

IDMOWrapperFilter Interface

Initializes the DMO Wrapper filter with the specified DMO.

Syntax

HRESULT Init(
    REFCLSID clsidDMO,
    REFCLSID catDMO
);

Parameters

clsidDMO
Class identifier (CLSID) of the DMO.
catDMO
CLSID that specifies the category of the DMO.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

For a list of DMO categories, see Category GUIDs. In some cases, the DMO Wrapper filter performs optimizations based on the category.


IDvdCmd Interface

The IDvdCmd interface is implemented on command synchronization objects allocated by the DVD Navigator. If instructed by an application in an IDvdControl2 "play" method call such as PlayTitle, PlayAtTimeInTitle, and so on, the DVD Navigator will allocate a command synchronization object and pass a pointer to its IDvdCmd interface back to the application. The command synchronization object stores the results of the command at both the start (when the command has begun processing) and the end after it has completed. The application can use the object to block the DVD Navigator until the command starts or completes.

For complete information on using command synchronization objects and the IDvdCmd interface, see Synchronizing DVD Commands. (This article also discusses alternate ways to synchronize commands without using command synchronization objects.)

Note Although the DVD Navigator allocates the command synchronization object, the application must call Release on the object when it is done with it.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDvdCmd methods | Description
WaitForStart | Blocks the DVD Navigator until the command associated with this object begins.
WaitForEnd | Blocks the DVD Navigator until the command associated with this object completes or is canceled.

IDvdCmd::WaitForEnd

IDvdCmd Interface

Blocks the DVD Navigator until the command associated with this object completes or is canceled.

Syntax

HRESULT WaitForEnd(void);

Return Value

Returns S_OK if successful or an HRESULT error code otherwise.

IDvdCmd::WaitForStart

IDvdCmd Interface

Blocks the DVD Navigator until the command associated with this object begins.

Syntax

HRESULT WaitForStart(void);

Return Value

Returns S_OK if successful or an HRESULT error code otherwise.


IDvdControl2 Interface

The Microsoft® DirectShow® DVD Navigator source filter exposes the IDvdControl2 interface to enable applications to navigate and play DVD-Video titles, including karaoke titles. After creating a DVD filter graph through the IDvdGraphBuilder interface, a DVD player application uses the methods of IDvdControl2 and IDvdInfo2 to send DVD commands to and retrieve state information from the DVD Navigator.

IDvdControl2 is a significant improvement over the older DVD control interface, IDvdControl. The new interface does not inherit from the old one; it encapsulates a completely new implementation. IDvdControl2 provides the full functionality required by the DVD Annex J specification, as well as methods for playback, menu navigation, and parental control.

For more information on writing a DVD player application using the DVD Navigator, including topics on the DVD filter graph, command synchronization, parental controls, menus, and karaoke support, see DVD Application and Decoder Development in DirectShow.

Methods by Category

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDvdControl2 methods | Description
Playback
Pause | Pauses or resumes playback at the current location.
PlayAtTime | Starts playback from the specified time in the current title.
PlayAtTimeInTitle | Starts playback from the specified time in the specified title.
PlayBackwards | Plays backward at the specified speed from the current location.
PlayChapter | Starts playback from the specified chapter in the current title.
PlayChapterInTitle | Starts playback from the beginning of the specified chapter of the specified title.
PlayChaptersAutoStop | Plays the number of chapters specified, starting at the specified chapter within the specified title.
PlayForwards | Plays forward at the specified speed from the current location.
PlayNextChapter | Starts playback from the beginning of the next chapter in the current title.
PlayPeriodInTitleAutoStop | Starts playback in the specified title from the specified start time until the specified end time.
PlayPrevChapter | Starts playback from the beginning of the previous chapter in the current title.
PlayTitle | Starts playback from the beginning of the specified title.
ReplayChapter | Starts playback from the beginning of the current chapter.
Stop | Stops playback of a title or menu by moving the DVD Navigator into the DVD Stop domain.
Menus
ActivateAtPosition | Activates the menu button under the mouse pointer position.
ActivateButton | Activates the selected menu button.
Resume | Leaves a menu and resumes playback.
ReturnFromSubmenu | Returns the display from a submenu to its parent menu.
SelectAtPosition | Highlights the menu button under the mouse pointer position.
SelectAndActivateButton | Selects and activates the specified menu button.
SelectButton | Selects the specified menu button.
SelectDefaultMenuLanguage | Sets the default language for all menus and menu buttons.
SelectRelativeButton | Selects the specified relative button (upper, lower, right, left).
ShowMenu | Displays the specified menu, if available.
Video Stream
SelectAngle | Sets the new angle when the DVD Navigator is in an angle block.
StillOff | Resumes playback, canceling still mode.
SelectVideoModePreference | Sets the video mode display for subsequent playback—wide screen, letterbox, or pan-scan.
Audio Stream
SelectAudioStream | Selects the audio stream to play.
SelectDefaultAudioLanguage | Sets the default audio language.
SelectKaraokeAudioPresentationMode | Sends karaoke auxiliary channels to the left or right speaker.
Subpicture Stream
SelectDefaultSubpictureLanguage | Sets the default language for subpicture text.
SelectSubpictureStream | Sets the subpicture stream to display.
SetSubpictureState | Turns the subpicture display on or off.
Parental Levels
AcceptParentalLevelChange | Accepts or rejects a request from the DVD Navigator to play content at a higher parental management level.
SelectParentalCountry | Sets the country for interpreting parental access levels and setting default languages.
SelectParentalLevel | Sets the parental access level for the logged-on user.
DVD Navigator Control
SetDVDDirectory | Sets the DVD drive that the DVD Navigator will read from.
SetOption | Enables or disables a DVD Navigator internal behavioral flag.
SetState | Saves the current disc position and state of the DVD Navigator for retrieval at a later time.
SetGPRM | Sets a general parameter register value.

IDvdControl2::AcceptParentalLevelChange

IDvdControl2 Interface

Accepts or rejects a request from the DVD Navigator to play content at a higher parental management level.

Syntax

HRESULT AcceptParentalLevelChange(
    BOOL bAccept
);

Parameters

bAccept
[in] Flag that indicates whether the application accepts the parental management level change. Specify TRUE to accept the change and play the higher-level content, or FALSE to reject the change.

Return Value

Returns S_OK if successful, or an error code otherwise.

Remarks

A temporary parental management level (PML) command is a marker on the DVD disc indicating that the content that follows has a PML higher than the level specified for the title as a whole. This marker also contains instructions on where to branch depending on whether the change is accepted or rejected. If you specify FALSE, the DVD Navigator follows the rejected branch on the disc. If you specify TRUE, the DVD Navigator follows the branch to the higher-level content.

Use AcceptParentalLevelChange in conjunction with the SetOption method. The sequence of events is as follows: First, call SetOption(DVD_NotifyParentalLevelChange, TRUE) to tell the DVD Navigator to always wait after sending an EC_DVD_PARENTAL_LEVEL_CHANGE event notification to the application. In your event handler, implement code to determine whether to accept or reject the change, and then call AcceptParentalLevelChange to notify the DVD Navigator of the decision.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | All

See Also

Enforcing Parental Management Levels

IDvdControl2::ActivateAtPosition

IDvdControl2 Interface

Activates the menu button under the mouse pointer position.

Syntax

HRESULT ActivateAtPosition(
    POINT point
);

Parameters

point
[in] Point on the client window area, in screen pixel coordinates.

Return Value

Returns one of the following values.
S_OK | The click occurred in the highlighted button rectangle, and the button was successfully activated.
E_INVALIDARG | The point lies outside the valid video region.
E_UNEXPECTED | The button is present but is not working.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not in a menu domain.
VFW_E_DVD_NO_BUTTON | There is no menu button under the mouse pointer position.
VFW_E_DVD_OPERATION_INHIBITED | The operation is inhibited by user operation (UOP) control.

Remarks

The mouse pointer coordinates are relative to the upper left of the client area, which isn't necessarily the video display area if the video is in letterbox format.

Use this method when the user is navigating through a menu by moving the mouse pointer directly over the menu buttons. If the user is using the relative buttons to navigate the menu, use ActivateButton rather than ActivateAtPosition.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
None DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu

See Also

Working With DVD Menus

IDvdControl2::ActivateButton

IDvdControl2 Interface

Activates the selected menu button.

Syntax

HRESULT ActivateButton(void);

Return Value

Returns one of the following values.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in an invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the DVD Navigator from entering a paused state.
VFW_E_DVD_NO_BUTTON | No button is selected.

Remarks

An application might or might not have four relative buttons on the side of the video display to represent the buttons on a physical remote control. These enable a user to select menu buttons but not activate them. A fifth button is required to activate the selected button. Call ActivateButton in response to a mouse click on the fifth button.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Button_Activate DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

See Also

Working With DVD Menus

IDvdControl2::Pause

IDvdControl2 Interface

Pauses or resumes playback at the current location.

Syntax

HRESULT Pause(
    BOOL bState
);

Parameters

bState
[in] Value of type Boolean that specifies whether to pause playback; TRUE means to pause.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the DVD Navigator from entering a paused state.

Remarks

Putting the DVD Navigator into a paused state freezes playback and any internal timers, similar to IMediaControl2::Pause. If the filter graph is not running, this method does nothing.

This method is demonstrated in the DVDSample application in CDvdCore::Pause.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
PauseOn/PauseOff DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

IDvdControl2::PlayAtTime

IDvdControl2 Interface

Starts playback from the specified time in the current title.

Syntax

HRESULT PlayAtTime(
    DVD_HMSF_TIMECODE *pTime,
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

pTime
[in] Pointer to a DVD_HMSF_TIMECODE structure that specifies the time at which to start playback.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

This method is demonstrated in the DVDSample application in CDvdCore::PlayTime.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Time_Search | DVD_DOMAIN_Title

See Also

Synchronizing DVD Commands

IDvdControl2::PlayAtTimeInTitle

IDvdControl2 Interface

Starts playback from the specified time in the specified title.

Syntax

HRESULT PlayAtTimeInTitle(
    ULONG uiTitle,
    DVD_HMSF_TIMECODE *pTime,
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

uiTitle
[in] Value that specifies the number of the title to play; this value must be from 1 through 99.
pTime
[in] Pointer to a DVD_HMSF_TIMECODE structure that specifies where playback will begin.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
E_INVALIDARG | Invalid argument.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J command name Valid domains
Time_Play DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title
DVD_DOMAIN_Stop

See Also

Synchronizing DVD Commands

IDvdControl2::PlayBackwards

IDvdControl2 Interface

Plays backward at the specified speed from the current location.

Syntax

HRESULT PlayBackwards(
    double dwSpeed,
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

dwSpeed
[in] Value that specifies the speed of backward play. This value is a multiplier, where 1.0 is the authored speed. So, a value of 2.5 plays backward at two and one-half times the authored speed, while a value of 0.5 plays backward at half the authored speed. The actual speed of playback depends on the video decoder's capabilities and might differ from the specified rate. For reverse play, audio is muted and no subpicture is displayed. Any speed below 0.00001 is converted to 0.00001.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

This method is demonstrated in the DVDSample application in CDvdCore::Rewind. For playing backwards one frame at a time, use the IVideoFrameStep interface as demonstrated in the sample application in CDvdCore::FrameStep.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Backward_Scan DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

IDvdControl2::PlayChapter

IDvdControl2 Interface

Starts playback from the specified chapter in the current title.

Syntax

HRESULT PlayChapter(
    ULONG ulChapter,
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

ulChapter
[in] Value that specifies the chapter in the current title where the DVD Navigator will start playback; this value must be from 1 through 999.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
E_INVALIDARG | Invalid argument.

Remarks

The DVD Navigator begins playback at the specified chapter and continues to the subsequent chapters. Use PlayChaptersAutoStop to play the current chapter only.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

This method is demonstrated in the DVDSample application in CDvdCore::PlayChapter.
Annex J Command Name | Valid Domains
PTT_Search | DVD_DOMAIN_Title

See Also

Synchronizing DVD Commands

IDvdControl2::PlayChapterInTitle

IDvdControl2 Interface

Starts playback from the beginning of the specified chapter of the specified title.

Syntax

HRESULT PlayChapterInTitle(
    ULONG ulTitle,
    ULONG ulChapter,
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

ulTitle
[in] Value that specifies the title in which the chapter is located; this value must be from 1 through 99.
ulChapter
[in] Value that specifies the chapter in the specified title where the DVD Navigator will start playback; this value must be from 1 through 999.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
E_INVALIDARG | Invalid argument.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

This method is demonstrated in the DVDSample application in CDvdCore::PlayChapterInTitle.
Annex J Command Name Valid Domains
PTT_Play DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title
DVD_DOMAIN_Stop

See Also

Synchronizing DVD Commands

IDvdControl2::PlayChaptersAutoStop

IDvdControl2 Interface

Plays the number of chapters specified, starting at the specified chapter within the specified title.

Syntax

HRESULT PlayChaptersAutoStop(
    ULONG ulTitle,
    ULONG ulChapter,
    ULONG ulChaptersToPlay,
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

ulTitle
[in] Value that specifies the title in which the chapter is located; this value must be from 1 through 99.
ulChapter
[in] Value that specifies the chapter in the specified title where the DVD Navigator will start playback; this value must be from 1 through 999.
ulChaptersToPlay
[in] Number of chapters to play from the start chapter.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
E_UNEXPECTED | The DVD Navigator is not initialized or the title is not a One Sequential PGC Title.
E_INVALIDARG | The ulTitle value does not exist or is greater than the number of titles, or ulChapter does not exist or is greater than the number of chapters, or ulChapter plus ulChaptersToPlay is greater than the number of chapters.
VFW_E_DVD_GRAPHNOTREADY | The graph is not in a running state.

Remarks

This method works only on One_Sequential_PGC_Titles. When the specified number of chapters have been played, the DVD Navigator sends the application an EC_DVD_CHAPTER_AUTOSTOP event notification.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None. | All.

See Also

EC_DVD_CHAPTER_AUTOSTOP, Synchronizing DVD Commands

IDvdControl2::PlayForwards

IDvdControl2 Interface

Plays forward at the specified speed from the current location.

Syntax

HRESULT PlayForwards(
    double dwSpeed,
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

dwSpeed
[in] Value that specifies the playback speed. This value is a multiplier, where 1.0 is the authored speed, so a value of 2.5 plays at two and one-half times the authored speed, while a value of 0.5 plays at half the authored speed. The actual speed of playback depends on the capabilities of the video decoder.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

This method is demonstrated in the DVDSample application in CDvdCore::FastForward.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Forward_Scan DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

IDvdControl2::PlayNextChapter

IDvdControl2 Interface

Starts playback from the beginning of the next chapter in the current title.

Syntax

HRESULT PlayNextChapter(
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

After playing the next chapter, the DVD Navigator continues playing, following the branching instructions on the disc. To play only the next chapter, call PlayChaptersAutoStop.

This method is demonstrated in the DVDSample application in CDvdCore::NextChapter.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
NextPG_Search DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

See Also

Synchronizing DVD Commands

IDvdControl2::PlayPeriodInTitleAutoStop

IDvdControl2 Interface

Starts playback in the specified title from the specified start time until the specified end time.

Syntax

HRESULT PlayPeriodInTitleAutoStop(
    ULONG ulTitle
    DVD_HMSF_TIMECODE *pStartTime
    DVD_HMSF_TIMECODE *pEndTime
    DWORD dwFlags
    IDvdCmd **ppCmd
);

Parameters

ulTitle
[in] Value that specifies the title; this value must be from 1 through 99.
pStartTime
[in] Pointer to a DVD_HMSF_TIMECODE structure that specifies the time at which to start playing.
pEndTime
[in] Pointer to a DVD_HMSF_TIMECODE structure that specifies the time at which to stop playing.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
E_INVALIDARG | Invalid argument.

Remarks

The actual start and end times are the times before or equal to the frame number specified in the DVD_HMSF_TIMECODE. The frame rate code is ignored on pStartTime and pEndTime.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
None DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title
DVD_DOMAIN_Stop

See Also

Synchronizing DVD Commands

IDvdControl2::PlayPrevChapter

IDvdControl2 Interface

Starts playback from the beginning of the previous chapter in the current title.

Syntax

HRESULT PlayPrevChapter(
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

dwFlags
Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

This method is demonstrated in the DVDSample application in CDvdCore::PrevChapter.
Annex J Command Name Valid Domains
PrevPG_Search DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

See Also

Synchronizing DVD Commands

IDvdControl2::PlayTitle

IDvdControl2 Interface

Starts playback from the beginning of the specified title.

Syntax

HRESULT PlayTitle(
    ULONG uiTitle
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

uiTitle
Value that specifies the title number; this value must be from 1 through 99.
dwFlags
Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
E_INVALIDARG | Invalid argument.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Title_Play DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title
DVD_DOMAIN_Stop

See Also

Synchronizing DVD Commands

IDvdControl2::ReplayChapter

IDvdControl2 Interface

Starts playback from the beginning of the current chapter.

Syntax

HRESULT ReplayChapter(
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

dwFlags
Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
TopPG_Search DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

See Also

Synchronizing DVD Commands

IDvdControl2::Resume

IDvdControl2 Interface

Leaves a menu and resumes playback.

Syntax

HRESULT Resume(
    DWORD dwFlags,
    IDvdCmd **ppCmd
    );

Parameters

dwFlags
Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_NO_RESUME_INFORMATION | Resume was called from the Video Manager Menu.

Remarks

This method returns to playback from the location where play left off.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

This method is demonstrated in the DVDSample application in CDvdCore::RootMenu and CDvdCore::TitleMenu.
Annex J Command Name Valid Domains
Resume DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Stop

IDvdControl2::ReturnFromSubmenu

IDvdControl2 Interface

Returns the display from a submenu to its parent menu.

Syntax

HRESULT ReturnFromSubmenu(
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

dwFlags
Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
Pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

If the DVD Navigator is at the top-level menu, this method calls the Resume method so that play continues where it left off.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
GoUP DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

See Also

Synchronizing DVD Commands, Working With DVD Menus

IDvdControl2::SelectAndActivateButton

IDvdControl2 Interface

Selects and activates the specified menu button.

Syntax

HRESULT SelectAndActivateButton(
    ULONG ulButton
);

Parameters

ulButton
[in] Value from 1 through 36 that specifies the button to select and activate.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | ulButton is out of range.
E_UNEXPECTED | The ulButton value is valid, but the DVD Navigator filter couldn't activate it.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Button_Select_And_Activate DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

See Also

Working With DVD Menus

IDvdControl2::SelectAngle

IDvdControl2 Interface

Sets the new angle when the DVD Navigator is in an angle block.

Syntax

HRESULT SelectAngle(
    ULONG ulAngle,
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

ulAngle
[in] Value of the new angle, which must be from 1 through 9.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | ulAngle is out of range.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in the First Play domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

Note that angle and menu button indexes are one-based while audio stream and subpicture stream indexes are zero-based.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Angle_Change DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title
DVD_DOMAIN_Stop

See Also

DVD Domains

IDvdControl2::SelectAtPosition

IDvdControl2 Interface

Highlights the menu button under the mouse pointer position.

Syntax

HRESULT SelectAtPosition(
    POINT point
);

Parameters

point
[in] Point on the screen, in screen pixel coordinates.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_NO_BUTTON | No button is present at the mouse pointer position.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in the Stop domain.

Remarks

Note that angle and menu button indexes are one-based while audio stream and subpicture stream indexes are zero-based.

Call ActivateButton in response to a mouse click when the pointer is over a menu button.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

This method is demonstrated in the DVDSample application in CDvdCore::OnMouseEvent.

Annex J Command Name Valid Domains
None DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title
DVD_DOMAIN_FirstPlay

See Also

ActivateAtPosition, DVD Domains, Working With DVD Menus

IDvdControl2::SelectAudioStream

IDvdControl2 Interface

Selects the audio stream to play.

Syntax

HRESULT SelectAudioStream(
    ULONG ulAudio,
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

ulAudio
[in] Value that specifies the audio track to use, which must be an integral value from 0 through 7, or DVD_DEFAULT_AUDIO_STREAM to specify the default stream.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | ulAudio is out of range, or doesn't correspond to an audio stream.
E_UNEXPECTED | The ulAudio value is valid, but the DVD Navigator couldn't set it for some reason.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_STREAM_DISABLED | The specified stream is disabled.

Remarks

This method affects the audio of the current Video Title Set (VTS). When called from within a menu, this method sets the audio stream of the title from which the menu was called.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Audio_Stream_Change DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title
DVD_DOMAIN_Stop

IDvdControl2::SelectButton

IDvdControl2 Interface

Selects the specified menu button.

Syntax

HRESULT SelectButton(
    ULONG ulButton
);

Parameters

ulButton
[in] Value from 1 through 36 that specifies the button to select.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in an invalid domain.
VFW_E_DVD_NO_BUTTON | No button is selected.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the DVD Navigator from entering a paused state.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Button_Select DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

See Also

Working With DVD Menus

IDvdControl2::SelectDefaultAudioLanguage

IDvdControl2 Interface

Sets the default audio language.

Syntax

HRESULT SelectDefaultAudioLanguage(
    LCID Language
    DVD_AUDIO_LANG_EXT audioExtension
);

Parameters

Language
[in] Locale identifier that specifies the default language.
audioExtension
[in] DVD_AUDIO_LANG_EXT value that specifies the default audio language extension.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | The audioExtension value is invalid.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in the Stop domain.

Remarks

This method selects the default language and language extensions to use when the disc is played. For example, if Language is specified as 0x409 for English and audioExtension is specified as DVD_AUD_EXT_NotSpecified, the DVD Navigator will look for the basic audio stream in English. If audioExtension is specified as DVD_AUD_EXT_VisuallyImpaired, the DVD Navigator will first look for a special audio stream in English for people with low vision. If the default stream is not found on a disc, the DVD Navigator will select the closest match.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

IDvdControl2::SelectDefaultMenuLanguage

IDvdControl2 Interface

Sets the default language for all menus and menu buttons.

Syntax

HRESULT SelectDefaultMenuLanguage(
    LCID Language
);

Parameters

Language
Variable of type LCID that specifies the default language.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in a valid domain.

Remarks

This method selects the default text language to use for menus when the disc is played. For example, if Language is specified as 0x409 for U.S. English, the DVD Navigator tries to show U.S. English text in menus. If the default menu language is not found on a disc, the DVD Navigator selects the closest match.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

IDvdControl2::SelectDefaultSubpictureLanguage

IDvdControl2 Interface

Sets the default language for subpicture text.

Syntax

HRESULT SelectDefaultSubpictureLanguage(
    LCID Language
    DVD_SUBPICTURE_LANG_EXT subpictureExtension
);

Parameters

Language
[in] Locale identifier that specifies the default language.
subpictureExtension
[in] DVD_SUBPICTURE_LANG_EXT value that specifies the default subpicture extension.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | TLanguage is invalid.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in a valid domain.

Remarks

This method selects the default language and format to use for subpictures and menus when the disc is played. For example, if Language is specified as 0x409 for U.S. English and subpictureExtension is specified as DVD_SP_EXT_Caption_Big, the DVD Navigator tries to show U.S. English text in the "big caption" format in subpictures. If the default language or language extension is not found on a disc, the DVD Navigator selects the closest match.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

IDvdControl2::SelectKaraokeAudioPresentationMode

IDvdControl2 Interface

Sends karaoke auxiliary channels to the left or right speakers.

Syntax

HRESULT SelectKaraokeAudioPresentationMode(
    ULONG ulMode
);

Parameters

ulMode
[in] Bitwise OR of DVD_KARAOKE_DOWNMIX flags indicating how to downmix the five karaoke channels to channels 0 and 1, which are usually output to the left and right speakers.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is in an invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the current operation.

Remarks

When the DVD Navigator enters karaoke mode, it queries the audio decoder to discover whether it supports karaoke downmixing. If the decoder supports it, then channels 2 through 4 (the karaoke auxiliary channels with the guide vocals, guide melodies, and sound effects) are muted. Use this method to turn individual channels on or off and direct them to channels 0 and 1.

This method is demonstrated in the DVDSample application in CKaraokeDlg::DoModal.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Karaoke_Audio_Presentation_Mode_Change DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title
DVD_DOMAIN_Stop

IDvdControl2::SelectParentalCountry

IDvdControl2 Interface

Sets the country for interpreting parental access levels and setting default languages.

Syntax

HRESULT SelectParentalCountry(
    BYTE country[2]
);

Parameters

country
[in] Array of values of type BYTE that specifies the current country according to ISO 3166.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in a valid domain.

Remarks

The parental country determines the meaning of the eight generic parental levels as well as the default language for the soundtrack and menus. For details, see Enforcing Parental Management Levels.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Parental_Country_Select | DVD_DOMAIN_Stop

See Also

IDvdControl2::SelectParentalLevel

IDvdControl2::SelectParentalLevel

IDvdControl2 Interface

Sets the parental access level for the logged-on user.

Syntax

HRESULT SelectParentalLevel(
    ULONG ulParentalLevel
);

Parameters

ulParentalLevel
Value that specifies the parental access level for the current user. For details, see Remarks.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.

Remarks

There are eight generic parental levels defined in the DVD specification, numbered from 1 (most restrictive) through 8 (least restrictive). The meaning of these levels varies from region to region and depends on the current country (see SelectParentalCountry). For the United States and Canada (DVD Region 1), the suggested values are as follows:
Parental level | Meaning
1 | The rating is G, general.
3 | The rating is PG, parental guidance suggested.
4 | The rating is PG-13, parental guidance suggested, not recommended for those under 13.
6 | The rating is R, restricted.
7 | The rating is NC-17, not appropriate for those under 17.

This method sets the current user's access level; this access level determines what content the user can play. Higher levels can play lower-level content; lower levels can't play higher-level content. In other words, adults can watch child-safe content, but children can't watch adult content.

DVD player applications can enforce restrictions on the parental level setting, such as providing password protection for raising the current parental level. The application's user interface should have a way to set the level and to disable checking completely. Some discs might be authored to disallow even level 8, meaning that no level is valid and no one could watch the disc if parental management is enabled. On such discs, parental management must be disabled for the discs to be viewed. Parental management in the DVD Navigator filter is disabled by default.

To disable parental management after it has been enabled, pass 0xffffffff for ulParentalLevel.

This method is demonstrated in the DVDSample application in CDvdCore::SetParentalLevel.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Parental_Level_Select | DVD_DOMAIN_Stop

IDvdControl2::SelectRelativeButton

IDvdControl2 Interface

Sets the specified relative button (upper, lower, right, or left).

Syntax

HRESULT SelectRelativeButton(
    DVD_RELATIVE_BUTTON buttonDir,
);

Parameters

buttonDir
DVD_RELATIVE_BUTTON value indicating the button to select.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator filter is not in a valid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
(Left/Right/Upper/Lower)_Button_Select DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

See Also

DVD_RELATIVE_BUTTON, Working With DVD Menus

IDvdControl2::SelectSubpictureStream

IDvdControl2 Interface

Sets the subpicture stream to display.

Syntax

HRESULT SelectSubpictureStream(
    ULONG ulSubPicture,
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

ulSubPicture
Value that specifies the subpicture stream, which must be from 0 through 31, or 63.
0-31 | The stream is valid.
63 | The stream is the dummy stream, which means it is a muted, low-bitrate stream.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | ulSubPicture is out of range or doesn't correspond to an SP stream.
E_UNEXPECTED | The ulSubPicture parameter is valid, but DVD Navigator cannot set it for some other reason.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.
VFW_E_DVD_STREAM_DISABLED | The specified stream is disabled.

Remarks

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Sub-picture_Stream_Change DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title
DVD_DOMAIN_Stop

See Also

Audio and Subpicture Streams

IDvdControl2::SelectVideoModePreference

IDvdControl2 Interface

Sets the specified video mode display (wide screen, letterbox, or pan-scan) for playback.

Syntax

HRESULT SelectVideoModePreference(
    ULONG ulPreferredDisplayMode
);

Parameters

ulPreferredDisplayMode
[in] Value that specifies the new display mode for DVD content. Member of the DVD_PREFERRED_DISPLAY_MODE enumerated data type.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

This method changes the default video window's aspect ratio and can also specify a default aspect ratio conversion mechanism.

For anamorphic 16 x 9 source video, formed by stretching the 720 x 480 source video to a 16 x 9 aspect ratio.

Widescreen The 16 x 9 source video should be placed and stretched into the largest 16 x 9 area of the client output window. The highlights are relative to the inside of the 16 x 9 area. Black bars should be added to either the top/bottom or to the sides to maintain a 16 x 9 area.

Pan Scan The video shown is computed by taking a 4 x 3 subwindow from the stretched 16 x 9 video (the horizontal offset is provided in the MPEG-2 video's window's offset). The 4 x 3 subwindow is placed into the largest 4 x 3 area of the output client window. The highlight's coordinates are relative to the 4 x 3 output window (and have no relationship to the source 16 x 9 video). Black bars should be added to either the top/bottom or to the sides to maintain a 4 x 3 area.

Letterbox A 4 x 3 display area is formed by taking the largest 4 x 3 area of the output client window. Black bars should be added to either the top/bottom or to the sides to maintain a 4 x 3 area. The source 16 x 9 video is placed in the largest 16 x 9 subwindow inside of the 4 x 3 subwindow. Black bars should be added to the top and bottom of the subwindow to maintain a 16 x 9 area. The highlight's coordinates are relative to the 4 x 3 subwindow (and have no relationship to the source 16 x 9 video). It is technically possible for a disk to specify a highlight that lies outside of the 16 x 9 area (but still in the 4 x 3 window).

For 4 x 3 video, the video is placed in the largest 4 x 3 output area of the output client window. Black bars should be added to either the top/bottom or to the sides to maintain a 4 x 3 area.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Video_PresentationMode_Change DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title
DVD_DOMAIN_Stop

IDvdControl2::SetDVDDirectory

IDvdControl2 Interface

Sets the DVD drive that the DVD Navigator filter will read from.

Syntax

HRESULT SetDVDDirectory(
    LPCWSTR  pszwPath
);

Parameters

pszwPath
[in] Variable of type LPCWSTR that specifies the path of the root directory.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | The pszwPath parameter points to an invalid DVD path, or a DVD drive is not found while enumerating.
E_UNEXPECTED | The DVD Navigator is not initialized.
S_FALSE | The pszwPath parameter is NULL and the DVD Navigator can't find any DVD volume.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain. For details, see Remarks.

Remarks

If pszwPath is NULL, the DVD Navigator tries to select a DVD volume on any available drive. On startup, the DVD Navigator automatically looks for a drive, starting at drive C, with a VIDEO_TS folder in the root folder. It is therefore only necessary to call SetDVDDirectory when you have more than one DVD drive on a machine, or if your DVD drive letter is A or B. When specifying the path, include the video_ts folder.

SetDVDDirectory("e:\video_ts");

Some DVD volumes may have their video in a directory named something other than "video_ts." The general idea is that an additional "DVD volume" (the set of .IFO. VOB, and .BUP files that would normally be stored in the VIDEO_TS directory) can be placed in a subdirectory on the disc. By changing the root to point to this directory, MSWebDVD will operate on this separate DVD volume. A new set of menus, titles, etc. will be available, independent of the titles in the VIDEO_TS root, which will no longer be accessible. Such directories are called "hidden directories." The following example shows how to set a hidden directory as the root, where "hidden" is a placeholder for whatever name the disc authors have given to the directory.

SetDVDDirectory("d:\\webdvd\\hidden");

If the filter graph is running and the DVD Navigator finds a DVD in the directory specified by pszwPath, the DVD Navigator automatically begins playing the disc. This conforms with the DVD specification and ensures that the new disc is initialized properly. If you do not want the new disc to play automatically after SetDVDDirectory returns, you must set the DVD_ResetOnStop flag in SetOption to TRUE and stop the filter graph through a call to IMediaControl::Stop on the Filter Graph Manager. If DVD_ResetOnStop is set to FALSE, then SetDVDDirectory returns VFW_E_DVD_INVALIDDOMAIN.

This method is demonstrated in the DVDSample application in CDvdCore::SetDirectory.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | DVD_DOMAIN_Stop

IDvdControl2::SetGPRM

IDvdControl2 Interface

Sets a general parameter register value.

Syntax

HRESULT SetGPRM(
    ULONG ulIndex
    WORD wValue
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

ulIndex
[in] Register index; may be a value from zero through 15.
wValue
[in] A 16-bit value contained in the specified register.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | The ulIndex parameter is greater than 15 or any other of the input parameters are invalid.

Remarks

A DVD disc uses general parameter registers to store various types of information. By manually setting one or more of these registers, an application might be able to provide certain custom functionality. This is an advanced command and should not be used unless you have a thorough understanding of the DVD specification.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
none | All

See Also

IDvdInfo2::GetAllGPRMs

IDvdControl2::SetOption

IDvdControl2 Interface

Enables or disables a DVD Navigator filter's internal behavioral flag.

Syntax

HRESULT SetOption(
    DVD_OPTION_FLAG flag
    BOOL bEnable
);

Parameters

flag
[in] DVD_OPTION_FLAG value that specifies the flag to alter. For details, see Remarks.
bEnable
[in] Variable of type BOOL that specifies whether to enable to disable flag. Set to TRUE to enable flag, or FALSE to disable it.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | The flag value is not DVD_ResetOnStop or DVD_NotifyParentalLevelChange.

Remarks

Call SetOption with the desired flags immediately after creating an instance of the DVD Navigator and whenever you want to change any behaviors.
Flag | Meaning
DVD_ResetOnStop Set to TRUE to cause the Navigator to enter the DVD Stop domain when the filter graph stops. This is the default behavior. When the Navigator resumes playback from the Stop domain, it starts at the beginning of the disc. This is not always the desired behavior, because the filter graph can be stopped unexpectedly if the screen resolution changes, a screen saver starts, the computer goes into suspend mode, or for some other reason. To prevent the Navigator from entering the DVD Stop domain when the graph makes a transition into a Stop state, set this flag to FALSE. This causes the Navigator, when the filter graph restarts, to resume playback from the point where it stopped.

Typically, an application should set this flag to FALSE right after or before calling IMediaControl::Run to start playback of a DVD-Video. It should set the flag to TRUE before calling IMediaControl::Stop in response to an explicit user command to Stop playback.

DVD_NotifyParentalLevelChange Tells the DVD Navigator whether the application should be notified when the Navigator encounters parental level changes on the disc. If this flag is set to TRUE, when the Navigator encounters a temporary parental management level command, it sends the application an EC_DVD_PARENTAL_LEVEL_CHANGE event and blocks until it receives the application's response through AcceptParentalLevelChange.

If you set the flag to FALSE, when the Navigator encounters a temporary parental management level command and the current parental level is too low, the Navigator automatically rejects it and branches to whatever path the disc specifies when such a command is rejected. An EC_DVD_PARENTAL_LEVEL_CHANGE event is sent telling the application what the required level should be. It is up to the application to stop playback, put up a password dialog box and restart the movie playback so that it can succeed on the next attempt.

DVD_HMSF_TimeCodeEvents | Set this flag to TRUE to receive EC_DVD_CURRENT_HMSF_TIME time events in the DVD_HMSF_TIMECODE format instead of the earlier BCD format as passed with EC_DVD_CURRENT_TIME event. The DVD_HMSF_TIMECODE format is easier to work with. This flag defaults to FALSE to facilitate backward compatibility with applications that use the BCD format.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
None | All

See Also

DVD Command Flags

IDvdControl2::SetState

IDvdControl2 Interface

Saves the current disc position and state of the DVD Navigator filter.

Syntax

HRESULT SetState(
    IDvdState*pState,
    DWORD    dwFlags,
    IDvdCmd  **ppCmd
);

Parameters

pState
[in] Pointer to the IDvdState interface on the object that contains the state information.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns S_OK if successful, or an HRESULT value otherwise.

Remarks

The DVD Navigator uses the location information in the given state object to restore the playback position to a specific location on the disc.

This method is demonstrated in the DVDSample application in CDvdCore::RestoreBookmark.

IDvdControl2::SetSubpictureState

IDvdControl2 Interface

Turns the subpicture display on or off.

Syntax

HRESULT SetSubpictureState(
    BOOL bState,
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

bState
[in] Boolean value that specifies whether the subpicture display is on; TRUE sets subpicture display on for subsequent playback.
dwFlags
[in] Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
[out] Address of a pointer to an IDvdCmd object that can be used to synchronize DVD commands.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in the First Play domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

Subpicture streams are typically used in menus for button text and sometimes button graphics, and in video playback for subtitles, credits, or other overlaid graphics. Do not confuse subpictures with closed captions; the latter are encoded within the video stream. In general, this method is intended for controlling subpicture display over video while the DVD Navigator filter is playing video in the DVD Title domain.

This method corresponds to the second parameter of the Annex J "Sub-picture_Stream_Change" command.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Sub-picture_stream_Change DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title
DVD_DOMAIN_Stop

See Also

SelectSubpictureStream

IDvdControl2::ShowMenu

IDvdControl2 Interface

Displays the specified menu, if available.

Syntax

HRESULT ShowMenu(
    DVD_MENU_ID MenuID
    DWORD dwFlags,
    IDvdCmd **ppCmd
);

Parameters

MenuID
[in] A DVD_MENU_ID value that specifies the menu to display.
dwFlags
Bit flag that contains one or more DVD_CMD_FLAGS values specifying command synchronization options.
ppCmd
Address of a pointer to an IDvdCmd object that can be used to synchronize commands to the DVD Navigator filter.

Return Value

Returns one of the following values.

S_OK | Success.
E_INVALIDARG | The MenuID value is out of range.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

The Video Manager Menu (VMGM) should be accessible from the Title or the Video Title Set domains. The Video Title Set menus (VTSMs) might only be accessible through the VMGM. Any submenus under each VTSM (for chapters, angles, and audio and subpicture streams) are only accessible through that VTSM.

This method is demonstrated in the DVDSample application application in CDvdCore::RootMenu and CDvdCore::TitleMenu.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name | Valid Domains
Menu_Call | All.

See Also

Working With DVD Menus

IDvdControl2::StillOff

IDvdControl2 Interface

Resumes playback, canceling still mode.

Syntax

HRESULT StillOff(void);

Return Value

Returns one of the following values.

S_OK | Success.
E_UNEXPECTED | The DVD Navigator filter is in a menu domain and the menu has buttons.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.
VFW_E_DVD_OPERATION_INHIBITED | UOP control prohibits the operation.

Remarks

A still is a static image presented by the disc. It is not the same as the frozen display image that appears when the user clicks the Pause button. When the DVD Navigator encounters a still image, it sends the application an EC_DVD_STILL_ON message, goes into still-store mode displaying the image, and waits for StillOff to be called before resuming playback.

If the DVD Navigator is not in still-store mode, this method does nothing.

Although menus can be presented as stills, do not call this method while in a menu domain because the DVD Navigator will have no information on where to resume playback.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Still_Off DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title

IDvdControl2::Stop

IDvdControl2 Interface

Stops playback of a title or menu by moving the DVD Navigator into the DVD Stop domain.

Syntax

HRESULT Stop(void);

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Invalid domain.

Remarks

Calling this method puts the DVD Navigator into the Stop domain, but the DVD filter graph as a whole remains in a running state, ready to play at any time. From the Stop, domain the user can display a menu or initiate playback directly through any "Play" method.

The following table shows the Annex J command name to which this method name corresponds, and the domains in which this method is valid.

Annex J Command Name Valid Domains
Stop DVD_DOMAIN_FirstPlay
DVD_DOMAIN_VideoManagerMenu
DVD_DOMAIN_VideoTitleSetMenu
DVD_DOMAIN_Title


IDvdGraphBuilder Interface

The IDvdGraphBuilder interface is implemented on the DVD Graph Builder object. The RenderDvdVideoVolume method automatically builds a filter graph for DVD-Video playback from the available software and hardware on the system. For information on how to build the DVD filter graph and obtain the pointers to all the necessary interfaces, see Building The DVD Filter Graph. The DVDSample application also demonstrates this process in DvdCore.cpp.

Note A DVD filter graph requires either a hardware or software MPEG-2 decoder, which DirectShow does not provide. You must install a DirectShow-compatible third-party decoder on your computer before attempting to build the DVD filter graph.

Generally, you should not add, remove, connect, disconnect, or access individual filters in the graph created by RenderDvdVideoVolume, because doing so might confuse the cleanup code. The purpose of the DvdGraphBuilder object is to simplify the developement of DVD-Video applications. If you need a specific type of graph for a particular solution, you should manually create the entire filter graph.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDvdGraphBuilder methods | Description
GetFiltergraph | Retrieves the IGraphBuilder interface for the filter graph used by the DVD-Video graph builder object.
GetDvdInterface | Retrieves specific interface pointers in the DVD-Video playback graph to make DVD-Video playback development easier.
RenderDvdVideoVolume | Completes building a filter graph according to user specifications for playing a DVD-Video volume.

IDvdGraphBuilder::GetDvdInterface

IDvdGraphBuilder Interface

Retrieves specific interface pointers in the DVD-Video playback graph to make DVD-Video playback development easier.

Syntax

HRESULT GetDvdInterface(
    REFIID riid,
    void **ppvIF
    );

Parameters

riid
[in] IID of the required interface.
ppvIF
[out] Address of a pointer to the retrieved interface.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The DirectShow implementation return values include the following:
E_INVALIDARG | The ppvIF parameter is invalid.
E_NOINTERFACE | The riid parameter value is not supported.
VFW_E_DVD_GRAPHNOTREADY | The graph has not been built through the IDvdGraphBuilder::RenderDvdVideoVolume method before retrieving this interface.

Remarks

Use this method to get the IDvdControl2 and IDvdInfo2 interfaces to control playback of a DVD-Video volume, and to get the IAMLine21Decoder interface to turn closed captioning on and off. You also use this method to get the IBasicVideo, IVideoWindow, and IBasicAudio interfaces. You only need a pointer to IBasicAudio if an audio renderer is used to render audio.

Remember to release the interface when you're done by using the following code.

*ppvIF->Release();

The IMixerPinConfig2 interface can be retrieved from the first input pin (primary video stream) of the Overlay Mixer in the DVD-Video playback graph using this interface. The IDDrawExclModeVideo interface can also be retrieved from the Overlay Mixer in the DVD-Video playback graph. This interface is required to playback video in DirectDraw exclusive mode, as some games require. Unlike other interfaces, it is not necessary to build the graph using the RenderDvdVideoVolume method before calling GetDvdInterface. This interface should be retrieved before using the RenderDvdVideoVolume method to build the graph.

IDvdGraphBuilder::GetFiltergraph

IDvdGraphBuilder Interface

Retrieves the IGraphBuilder interface for the filter graph used by the DVD-Video graph builder object.

Syntax

HRESULT GetFiltergraph(
    IGraphBuilder **ppGB
    );

Parameters

ppGB
[out] Address of a pointer to the IGraphBuilder interface that the DVD-Video graph builder object is using.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns E_INVALIDARG if ppGB is invalid.

Remarks

Remember to release the IGraphBuilder interface when you're done by using the following code.

*ppGB->Release();

IDvdGraphBuilder::RenderDvdVideoVolume

IDvdGraphBuilder Interface

Completes building a filter graph according to user specifications for playing a DVD-Video volume.

Syntax

HRESULT RenderDvdVideoVolume(
    LPCWSTR lpcwszPathName,
    DWORD dwFlags,
    AM_DVD_RENDERSTATUS *pStatus
    );

Parameters

lpcwszPathName
[in] Pointer to the path for the DVD-Video volume to play. Can be NULL.
dwFlags
[in] Member of the AM_DVD_GRAPH_FLAGS enumerated data type indicating the type of decoder—hardware or software or a mix of hardware and software) to include in the filter graph. Maximum hardware decoding (AM_DVD_HWDEC_PREFER) is the default.
pStatus
[out] Pointer to the retrieved AM_DVD_RENDERSTATUS structure, which returns indication of any failure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The DirectShow implementation return values include the following:
E_INVALIDARG | The dwFlags parameter specifies conflicting options, or pStatus is a bad pointer.
S_FALSE | Graph has been built, but not perfectly. The pStatus parameter provides details of the problems.
S_OK | Success. Playback graph built successfully, all streams rendered, and the DVD-Video volume was specified or found.
VFW_E_DVD_DECNOTENOUGH | AM_DVD_HWDEC_ONLY or AM_DVD_SWDEC_ONLY was specified and there weren't enough hardware or software decoders to decode all streams.
VFW_E_DVD_RENDERFAIL | Some basic error occurred in building the graph. Possibilities include the DVD Navigator filter or the video or audio renderer not instantiating, a trivial connection or pin enumeration failing, or none of the streams rendering.

Remarks

The AM_DVD_RENDERSTATUS structure reflects failure codes for this method. Reasons for this method returning S_FALSE include the following:

  • The graph has been completely built, but one of the following is true.
    • Overlay mixing doesn't work—the application didn't use the AM_DVD_NOVPE flag and the video stream couldn't be put through the Overlay Mixer. In this case, if the video is decoded in software the application will have enough information to inform the user that the video won't be visible. Hardware-decoded video will be visible only on a TV connected to the NTSC out port of the hardware video decoder.
    • Video decoder doesn't produce line 21 data. The application can display a warning or informative message that closed captioning is not available because of the decoder.
    • No volume path is specified and DVD Navigator didn't locate any DVD-Video volume to be played. The application can ask the user to insert a DVD-Video disc if none is available in the drive when playback starts.
  • Some streams didn't render or didn't render completely. Volume can be partially played back. The application can indicate to the user that some streams can't be played.

This method builds the graph without any knowledge of the DVD-Video file or volume to play. The DVD-Video graph builder builds the graph even if lpcwszPathName is NULL or if the DVD Navigator filter does not find a default DVD-Video volume to play. An application can later specify the volume by using the IDvdControl::SetRoot method.


IDvdInfo2 Interface

The IDvdInfo2 interface is implemented by the DVD Navigator source filter and provides methods to query for various attributes of the disc or the DVD Navigator's state. IDvdInfo2 is the companion interface to IDvdControl2. IDvdInfo2 groups the DVD Navigator's "get" methods and IDvdControl2 groups the "set" methods. Together they provide DVD navigation and playback functionality beyond the DVD Annex J specification.

Note The information provided by some of these methods can also be obtained through event notifications sent from the DVD Navigator to the application's message loop. For example, to get the current DVD domain, you can call IDvdInfo2::GetCurrentDomain or you can handle the EC_DVD_DOMAIN_CHANGE event in your application's message loop and extract the new domain from the event's lParam1 parameter.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDvdInfo2 methods | Description
Menus
GetButtonAtPosition | Retrieves the button located at the specified point within the display window.
GetButtonRect | Retrieves the rectangle coordinates of the specified button.
GetCurrentButton | Retrieves the number of available buttons and the number of the currently selected button.
GetDefaultMenuLanguage | Retrieves the default menu language.
GetMenuLanguages | Retrieves all the languages available for all menus on the disc.
GetVMGAttributes | Retrieves attributes of all video, audio, and subpicture streams for the video manager menu.
Titles
GetNumberOfChapters | Retrieves the number of chapters in a given title.
GetTitleAttributes | Retrieves attributes of all video, audio, and subpicture streams for the specified title and its menus.
GetTotalTitleTime | Retrieves the total playback time for the current title.
Disc Information
GetAllSPRMs | Retrieves the current contents of all system parameter registers (SPRMs).
GetAllGPRMs | Retrieves the current contents of all general parameter registers (GPRMs).
GetCurrentUOPS | Retrieves a set of flags indicating which navigation commands, if any, the content authors have explicitly disabled for the current disc location.
GetDiscID | Retrieves a system-generated 64-bit "unique" identification number for the specified DVD.
GetDVDVolumeInfo | Retrieves the current DVD volume information.
Video Stream
GetCurrentAngle | Retrieves the number of available angles in the current angle block and the currently selected angle number.
GetCurrentVideoAttributes | Retrieves the video attributes of the current title or menu.
Audio Stream
GetAudioAttributes | Retrieves the attributes of the specified audio stream in the current title or menu.
GetAudioLanguage | Retrieves the language of the specified audio stream within the current title.
GetCurrentAudio | Retrieves the number of available audio streams and the number of the currently selected audio stream.
GetDecoderCaps | Retrieves the DVD decoder's maximum data rate for video, audio, and subpicture (in forward and reverse) as well as support for various types of audio (Dolby AC-3, MPEG-2, DTS, SDDS, LPCM).
GetDefaultAudioLanguage | Retrieves the default audio language.
GetKaraokeAttributes | Retrieves the karaoke attributes of the specified audio stream in the current title or menu.
IsAudioStreamEnabled | Determines if the specified audio stream is enabled in the current title.
Subpicture Stream
GetCurrentSubpicture | Retrieves the number of available subpicture streams in the current title, the currently selected subpicture stream number, and the state of the subpicture.
GetDefaultSubpictureLanguage | Retrieves the default subpicture language.
GetSubpictureAttributes | Retrieves the attributes of the specified subpicture stream in the current title or menu.
GetSubpictureLanguage | Retrieves the language of the specified subpicture stream within the current title.
IsSubpictureStreamEnabled | Determines if the specified subpicture stream is enabled in the current title.
Parental Levels
GetPlayerParentalLevel | Retrieves the current parental level and ISO 3166 country code settings for the DVD Navigator.
GetTitleParentalLevels | Retrieves the parental levels that are defined for a particular title.
DVD Navigator State Information
GetCmdFromEvent | Retrieves an IDvdCmd object from an EC_DVD_CMD_START, EC_DVD_CMD_END, or VFW_E_DVD_CMD_CANCELLED event.
GetCurrentDomain | Retrieves the DVD domain in which the DVD Navigator is currently located.
GetCurrentLocation | Retrieves the current playback location.
GetDVDDirectory | Retrieves the root directory that is set in the DVD Navigator.
GetState | Retrieves a bookmark containing the disc location and DVD Navigator state information.
DVD Text Strings
GetDVDTextNumberOfLanguages | Retrieves the number of text languages for the current DVD or disc side.
GetDVDTextLanguageInfo | Retrieves the information for the specified text string language block.
GetDVDTextStringAsNative | Retrieves the text string for the specified language as an array of bytes.
GetDVDTextStringAsUnicode | Retrieves the text string for the specified language in Unicode™.

IDvdInfo2::GetAllGPRMs

IDvdInfo2 Interface

Retrieves the current contents of all general parameter registers (GPRMs).

Syntax

HRESULT GetAllGPRMs(
  GPRMARRAY *pRegisterArray
);

Parameters

pRegisterArray
[out] Pointer to a GPRMARRAY that receives all 16 current GPRM values. See Remarks.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.

Remarks

GPRMs are 16-bit registers that each disc can use in unique ways for temporary data storage. The file Dvdif.idl contains the following typedefs.

typedef WORD DVD_REGISTER;
typedef DVD_REGISTER    GPRMARRAY[16];
typedef DVD_REGISTER    SPRMARRAY[24];

Note A player application using the DVD Navigator does not need to access these registers for any Annex J playback or navigation control. This method is provided for player applications implementing advanced functionality. Do not attempt to modify the GPRMs directly unless you have a thorough knowledge of the DVD specification, and the ways in which the GPRMs are used on the particular discs to be played.

See Also

IDvdControl2::SetGPRM

IDvdInfo2::GetAllSPRMs

IDvdInfo2 Interface

Retrieves the current contents of all system parameter registers (SPRMs).

Syntax

HRESULT GetAllSPRMs(
  SPRMARRAY *pRegisterArray
);

Parameters

pRegisterArray
[out] Pointer to a variable of type SPRMARRAY that receives the address of an array of SPRMs. See Remarks.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.

Remarks

The 24 SPRMs are used to hold information on current language, subpicture, and other navigation data. The file Dvdif.idl contains the following typedefs.

typedef WORD DVD_REGISTER;
typedef DVD_REGISTER    GPRMARRAY[16];
typedef DVD_REGISTER    SPRMARRAY[24];

Note A player application doesn't need to access these registers for any standard navigation functionality. To use these registers effectively, you will probably need a more detailed knowledge of the DVD navigation commands than is provided in this documentation. The following table lists the contents of each register. Bits within the word are referred to as b0 (low order bit) through b15 (high order bit).

Register | Contents
0 | ISO-639 language code (two lowercase ASCII letters). Default value is undefined.
1 | Low 4 bits (b0-b3) contain audio stream number (0 to 7) or 15 (none). Default value is 15.
2 | Low 6 bits (b0-b5) contain subpicture stream number (0 to 31) or 62 (none) or 63 (dummy stream for forced subpicture). 7th bit (b6) contains subpicture display flag (0 = don’t display subpicture). Default value is 62.
3 | Low 4 bits (b0-b3) contain angle number (1 to 9). Default value is 1.
4 | Low 7 bits (b0-b6) contain title number (1 to 99). Default value is 1.
5 | Low 7 bits (b0-b6) contain title number within current VTS (1 to 99). Default value is 1.
6 | Low 15 bits (b0-b14) contain PGC number in current title (1 to 32767). Default value is undefined.
7 | Low 10 bits (b0-b9) contain chapter number (1 to 99). Default value is 1. Value undefined unless title is one_sequential_PGC_title.
8 | High 6 bits (b10-b15) contain button number (1 to 36). Default value is 1024 (button 1).
9 | Timer count, in seconds (0 to 65535). Default value is 0.
10 | Low 15 bits (b0-b14) contain PGC number in current title (1 to 32767). Default value is undefined.
11 | Six flags (b2: mix ch2 to ch1, b3: mix ch3 to ch1, b4: mix ch4 to ch1, b10 mix ch2 to ch0, b11: mix ch3 to ch0, b12: mix ch4 to ch0). Flag value of 0 means don’t mix. Default value for all flags is 0. Value undefined if not playing Karaoke stream.
12 | ISO-3166 country code (two uppercase ASCII letters) or 65535 (not specified). Default value is undefined.
13 | Low 4 bits (b0-b3) contain parental level (1 to 8) or 15 (none). Default value is undefined.
14 | b8-b9 contain preferred display mode (0 = 4:3, 3 = 16:9). b10-b11 contain current video output mode (0 = normal [4:3 or 16:9], 1 = panscan, 2 = letterbox). Default value is undefined.
15 | Nine flags (b2: SDDS karaoke, b3: DTS karaoke, b4: MPEG karaoke, b6: Dolby Digital karaoke, b7: PCM karaoke, b10: SDDS playback, b11: DTS playback, b12: MPEG playback, b14: Dolby Digital playback). Flag value of 0 means incapable, 1 means capable. Default value is undefined.
16 | ISO-639 language code (two lowercase ASCII letters) or 65535 (not specified). Default value is 65535.
17 | Language extension code (0 = not specified, 1 = normal audio, 2 = audio for visually impaired, 3 = director comments #1, 4 = director comments #2). Default value is 0.
18 | ISO-639 language code (two lowercase ASCII letters) or 65535 (not specified). Default value is 65535.
19 | Language extension code (0 = not specified, 1 = normal subtitles, 2 = large subtitles, 3 = subtitles for children, 5 = normal Closed Captions, 6 = large Closed Captions, 7 = Closed Captions for children, 9 = forced subtitles, 13 = director comments, 14 = large director comments, 15 = director comments for children). Default value is 0.
20 | Low 8 bits (b0-b7) contain region code (1 to 8).

IDvdInfo2::GetAudioAttributes

IDvdInfo2 Interface

Retrieves the attributes of the specified audio stream in the current title or menu.

Syntax

HRESULT GetAudioAttributes(
  ULONG ulStream,
  DVD_AudioAttributes *pATR
);

Parameters

ulStream
[in] Variable of type ULONG specifying the audio stream whose attributes you wish to query. See Remarks.
pATR
[out] Pointer to a DVD_AudioAttributes structure that is filled with the attributes of the specified audio stream.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_NO_ATTRIBUTES | The stream's audio attributes are not available for some reason.
E_POINTER | Invalid argument.

Remarks

ulStream can be any index number from 0 through 7 or one of the following values:

DVD_DEFAULT_AUDIO_STREAM | to query for the attributes of the default audio stream.
DVD_STREAM_DATA_CURRENT | to query the current stream.
DVD_STREAM_DATA_VMGM | to query for the VMGM's audio attributes
DVD_STREAM_DATA_VTSM | to query for the VTSM's audio attributes

The use of this method is demonstrated in the DVDSample application in CDvdCore::GetAudioAttributes() and CAudioLangDlg::GetAudioLang.

IDvdInfo2::GetAudioLanguage

IDvdInfo2 Interface

Retrieves the language of the specified audio stream within the current title.

Syntax

HRESULT GetAudioLanguage(
  ULONG ulStream,
  LCID *pLanguage
);

Parameters

ulStream
[in] Audio stream number for the language being retrieved.
pLanguage
[out] Pointer to an LCID that receives the language information.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The pLanguage parameter is NULL.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_INVALIDDOMAIN | DVD Navigator is not in a valid domain.

Remarks

This method does not return languages for menus. It sets the value pointed to by pLanguage to zero if the stream contains an unknown language. Call the Microsoft® Win32® GetLocaleInfo function as follows to create a human-readable string name from pLanguage. LOCALE_SENGLANGUAGE is the locale information type, pszString is a pointer to a buffer to receive the requested data, and cbSize specifies the size of pszString.

GetLocaleInfo(*pLanguage, LOCALE_SENGLANGUAGE, pszString, cbSize);

See Also

IDvdControl2::SelectAudioStream

IDvdInfo2::GetButtonAtPosition

IDvdInfo2 Interface

Retrieves the button located at the specified point within the display window.

Syntax

HRESULT GetButtonAtPosition(
  POINT point,
  ULONG *puButtonIndex
);

Parameters

point
[in] Current mouse pointer position as retrieved through the Win32 WM_MOUSEMOVE message.
puButtonIndex
[out] Pointer to a variable of type ULONG that receives the index (from 1 through 36) of the button at the current mouse pointer position.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The puButtonIndex parameter is invalid.
VFW_E_DVD_NO_BUTTON | No button at point.

Remarks

This method is typically called in response to a mouse pointer move within a DVD menu display window. Be sure to check for success in the HRESULT before trying to retrieve the button number; this method only sets the value of puButtonIndex if a button is found at the specified point. DVD buttons do not necessarily have highlighted rectangles, button rectangles can overlap, and button rectangles do not always correspond to the visual representation of the buttons.

See Also

IDvdControl2::ActivateButton

IDvdInfo2::GetButtonRect

IDvdInfo2 Interface

Retrieves the rectangle coordinates for the specified menu button. (This method is currently not implemented.)

Syntax

HRESULT GetButtonRect(
  ULONG ulButton
  RECT *pRect
);

Parameters

ulButton
[in] Variable of type ULONG, from 1 through 36, that specifies the button.
pRect
[out] Pointer to a variable of type RECT that receives the coordinates of the button's rectangle.

Return Value

Returns one of the following HRESULT values.

E_NOTIMPL This method is currently not implemented

IDvdInfo2::GetCmdFromEvent

IDvdInfo2 Interface

Retrieves an IDvdCmd object from an EC_DVD_CMD_START or EC_DVD_CMD_END event.

Syntax

HRESULT GetCmdFromEvent(
  LONG_PTR lParam1,
  IDvdCmd **ppCmdObj
);

Parameters

lParam1
[in] Event notification's lParam1 parameter.
ppCmdObj
[out] Address of a pointer to an IDvdCmd command object that is associated with the command that fired the event.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_FAIL | The command no longer exists.
E_POINTER | Invalid argument.

Remarks

This method maps the lParam1 parameter of an EC_DVD_CMD_START or EC_DVD_CMD_END event into an IDvdCmd object that is associated with the command that fired the event. You can then call WaitForStart or WaitForEnd to control the blocking behavior of the DVD Navigator with respect to that command. The IDvdCmd object is created by the DVD Navigator and the returned pointer has already had its reference count incremented, so you must release it after WaitForStart or WaitForEnd returns.

See Also

Synchronizing DVD commands, EC_DVD_CMD_START, EC_DVD_CMD_END

IDvdInfo2::GetCurrentAngle

IDvdInfo2 Interface

Retrieves the number of available angles in the current angle block and the currently selected angle number.

Syntax

HRESULT GetCurrentAngle(
  ULONG *pulAnglesAvailable,
  ULONG *pulCurrentAngle
);

Parameters

pulAnglesAvailable
[out] Pointer to a variable of type ULONG that receives the number of available angles. There are up to nine angles in an angle block, numbered 1 through 9. If the value equals 1, then the DVD Navigator is not in an angle block.
pulCurrentAngle
[out] Pointer to a variable of type ULONG that receives the current angle number.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | DVD Navigator is not initialized or not in a valid domain.

Remarks

Note that angle and menu button indexes are 1-based, while audio and subpicture stream indexes are 0-based. When the DVD Navigator is about to enter an angle block, it sends the application an EC_DVD_ANGLES_AVAILABLE event notification with the lParam set to 1. Applications will typically call GetCurrentAngle and IDvdControl2::SelectAngle within their event handler for EC_DVD_ANGLES_AVAILABLE.

This method is demonstrated in the DVDSample application in CAngleDlg::MakeAngleList.

See Also

IDvdControl2::SelectAngle, EC_DVD_ANGLES_AVAILABLE, EC_DVD_ANGLE_CHANGE

IDvdInfo2::GetCurrentAudio

IDvdInfo2 Interface

Retrieves the number of available audio streams and the number of the currently selected audio stream.

Syntax

HRESULT GetCurrentAudio(
  ULONG *pulStreamsAvailable,
  ULONG *pulCurrentStream
);

Parameters

pulStreamsAvailable
[out] Pointer to a variable of type ULONG that receives the number of available audio streams.
pulCurrentStream
[out] Pointer to a variable of type ULONG that receives the currently selected audio stream number in the current title.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Input arguments are invalid.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not initialized or not in a valid domain.

Remarks

To get the available audio languages on the disc, call GetCurrentAudio and then call GetAudioLanguage for each stream, starting from zero through (pulStreamsAvailable - 1) to get the language content.

See Also

EC_DVD_AUDIO_STREAM_CHANGE, IDvdControl2::SelectAudioStream

IDvdInfo2::GetCurrentButton

IDvdInfo2 Interface

Retrieves the number of available buttons and the number of the currently selected button.

Syntax

HRESULT GetCurrentButton(
  ULONG *pulButtonsAvailable,
  ULONG *pulCurrentButton
);

Parameters

pulButtonsAvailable
[out] Pointer to a variable of type ULONG that receives the number of buttons available.
pulCurrentButton
[out] Pointer to a variable of type ULONG that receives the number (from 1 through 36) of the currently selected button.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | One of the pointer arguments is not valid.

Remarks

If buttons are not present, both pulButtonsAvailable and pulCurrentButton are set to zero.

See Also

EC_DVD_BUTTON_CHANGE, IDvdControl2::ActivateButton

IDvdInfo2::GetCurrentDomain

IDvdInfo2 Interface

Retrieves the domain in which the DVD Navigator is currently located.

Syntax

HRESULT GetCurrentDomain(
  DVD_DOMAIN *pDomain
);

Parameters

pDomain
[out] Pointer to a variable of type DVD_DOMAIN that receives the current domain.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_UNEXPECTED | Unexpected error.
E_POINTER | Invalid argument.

Remarks

You can use this method to test whether the DVD Navigator is finished playing in a particular title domain. An application doesn't have to test for the current domain before calling an IDvdControl2 method such as PlayTitle, PlayForwards, and so on. The DVD Navigator tests for the domain and simply does nothing, returning VFW_E_DVD_INVALIDDOMAIN, if the current command is invalid for the domain.

See Also

Domains EC_DVD_DOMAIN_CHANGE

IDvdInfo2::GetCurrentLocation

IDvdInfo2 Interface

Retrieves the current playback location.

Syntax

HRESULT GetCurrentLocation(
  DVD_PLAYBACK_LOCATION2 *pLocation
);

Parameters

pLocation
[out] Pointer to a variable of type DVD_PLAYBACK_LOCATION2 that receives the playback location information.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The pLocation parameter is invalid.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is in an invalid domain.

Remarks

This method retrieves information sufficient to restart playback of a video from the current playback location in titles that don't explicitly disable seeking to the current location. After the disc has been ejected, the information returned by this method will not necessarily be sufficient to restart playback. To save the current location and state information to disc so that the user can return to the same location at any later time, use GetState.

IDvdInfo2::GetCurrentSubpicture

IDvdInfo2 Interface

Retrieves the number of available subpicture streams in the current title, the currently selected subpicture stream number, and the state of the subpicture.

Syntax

HRESULT GetCurrentSubpicture(
  ULONG *pulStreamsAvailable,
  ULONG *pulCurrentStream,
  BOOL *pbIsDisabled
);

Parameters

pulStreamsAvailable
[out] Pointer to a variable of type ULONG that receives the number of available subpicture streams.
pulCurrentStream
[out] Pointer to a variable of type ULONG that receives the number of the currently selected subpicture stream.
pbIsDisabled
[out] Pointer to a variable of type BOOL that receives a value indicating whether the subpicture display is disabled; TRUE means it is disabled.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not initialized or not in the Title domain.

Remarks

DVD content authors can specify that any particular subpicture stream on a disc is forcedly activated, meaning that the DVD authors require this stream to display whether the viewer wants to watch it or not. The DVD Navigator complies with all such commands from the disc, meaning that forcedly activated streams are displayed even if the application has disabled subpicture display with the IDvdControl2::SetSubpictureState method.

See Also

EC_DVD_SUBPICTURE_STREAM_CHANGE, IDvdControl2::SelectSubpictureStream

IDvdInfo2::GetCurrentVideoAttributes

IDvdInfo2 Interface

Retrieves the video attributes of the current title or menu.

Syntax

HRESULT GetCurrentVideoAttributes(
    DVD_VideoAttributes *pATR
);

Parameters

pATR
[out] Pointer to a DVD_VideoAttributes structure that receives the attributes.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

The use of this method is demonstrated in the DVDSample application in CDvdCore::GetVideoAttributes().

IDvdInfo2::GetDecoderCaps

IDvdInfo2 Interface

Retrieves the DVD decoder's maximum data rate for video, audio, and subpicture (in forward and reverse) as well as support for various types of audio (AC-3, MPEG-2, DTS, SDDS, LPCM).

Syntax

HRESULT GetDecoderCaps(
  DVD_DECODER_CAPS *pCaps
);

Parameters

pCaps
[out] Pointer to a variable of type DVD_DECODER_CAPS that receives the information about the decoder.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
VFW_E_WRONG_STATE | The filter graph has not been initialized.

IDvdInfo2::GetDefaultAudioLanguage

IDvdInfo2 Interface

Retrieves the default audio language.

Syntax

HRESULT GetDefaultAudioLanguage(
  LCID *pLanguage,
  DVD_AUDIO_LANG_EXT *pAudioExtension
);

Parameters

pLanguage
[out] Pointer to an LCID that receives the default language information.
pAudioExtension
Pointer to a variable of type DVD_AUDIO_LANG_EXT that receives a value indicating the default DVD audio language extension.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The pLanguage parameter is NULL.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_INVALIDDOMAIN | DVD Navigator is not in a valid domain.

See Also

IDvdControl2::SelectAudioStream, IDvdControl2::SelectDefaultAudioLanguage

IDvdInfo2::GetDefaultMenuLanguage

IDvdInfo2 Interface

Retrieves the default menu language.

Syntax

HRESULT GetDefaultMenuLanguage(
  LCID *pLanguage
);

Parameters

pLanguage
[out] Pointer to an LCID that receives the language information.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The pLanguage parameter is NULL.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_INVALIDDOMAIN | DVD Navigator is not in a valid domain.

See Also

IDvdControl2::SelectDefaultMenuLanguage

IDvdInfo2::GetDefaultSubpictureLanguage

IDvdInfo2 Interface

Retrieves the default subpicture language.

Syntax

HRESULT GetDefaultSubpictureLanguage(
  LCID *pLanguage,
  DVD_SUBPICTURE_LANG_EXT *pSubpictureExtension
);

Parameters

pLanguage
[out] Pointer to an LCID that receives the language information.
pSubpictureExtension
[out] Pointer to a variable of type DVD_SUBPICTURE_LANG_EXT that receives one of the allowable values indicating the default language extension.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | The pLanguage parameter is NULL.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_INVALIDDOMAIN | DVD Navigator is not in a valid domain.

See Also

IDvdControl2::SelectDefaultSubpictureLanguage

IDvdInfo2::GetDiscID

IDvdInfo2 Interface

Retrieves a system-generated 64-bit identification number for the specified DVD.

Syntax

HRESULT GetDiscID(
    LPCWSTR pszwPath,
    ULONGLONG *pullDiscID
  );

Parameters

pszwPath
[in] Path of the volume to use for the disc ID. Specify NULL to use the current DVD volume.
pullDiscID
[out] Pointer to a variable of type ULONGLONG that receives the 64-bit disc ID.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

The DVD Navigator calculates a "unique" ID based on based on file sizes, dates, and other information, and not the BCA value. This number is guaranteed to be the same each time the disc is played. The ID applies to all replicated copies of a disc. In other words, all copies of a specific movie will have the same ID. The odds that two separate titles will have the same ID is sufficiently remote that this ID can be considered "unique" for all practical purposes.

IDvdInfo2::GetDVDDirectory

IDvdInfo2 Interface

Retrieves the root directory that is set in the DVD Navigator.

Syntax

HRESULT GetDVDDirectory(
  LPWSTR pszwPath,
  ULONG ulMaxSize,
  ULONG *pulActualSize
);

Parameters

pszwPath
[out, size_is(cbMaxSize)] Pointer to a buffer that receives the path string.
ulMaxSize
[in] Size of the buffer, in WCHARs.
pulActualSize
[out] Pointer to a variable that receives the size of actual data returned, in WCHARs.

Remarks

This method is demonstrated in the DVDSample application in CDvdCore::GetDriveLetter.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | The buffer is not large enough to hold the string.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not in a valid domain.

IDvdInfo2::GetKaraokeAttributes

IDvdInfo2 Interface

Retrieves the karaoke attributes of the specified audio stream in the current title or menu.

Syntax

HRESULT GetKaraokeAttributes(
  ULONG ulStream,
  DVD_KaraokeAttributes *pATR
);

Parameters

ulStream
[in] Variable of type ULONG specifying the index of the audio stream whose attributes you want to query. See Remarks.
pATR
[out] Pointer to a DVD_KaraokeAttributes structure that is filled with the karaoke attributes.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.
VFW_E_DVD_NOT_IN_KARAOKE_MODE | The specified stream is not in karaoke format.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not in the title domain.
VFW_E_DVD_NO_ATTRIBUTES | The karaoke attributes for the specified stream are not available for some reason.

Remarks

This method does not explicitly return the number of channels in the stream. You can obtain that information through a call to IDvdInfo2::GetAudioAttributes. This method is demonstrated in the DVDSample application in CKaraokeDlg::DoModal.

The ulStream parameter may be a value from 0 through 7, or one of the following:
DVD_STREAM_DATA_CURRENT (0x800) | to query the currently selected audio stream.
DVD_DEFAULT_AUDIO_STREAM | to query the default audio stream.

IDvdInfo2::GetSubpictureAttributes

IDvdInfo2 Interface

Retrieves the attributes of the specified subpicture stream in the specified title or menu.

Syntax

HRESULT GetSubpictureAttributes(
  ULONG ulStream,
  DVD_SubpictureAttributes *pAttributes
  );

Parameters

ulStream
[in] Index number, from 0 through 31, of the subpicture stream to query. See Remarks.
pAttributes
[out] Pointer to a DVD_SubpictureAttributes structure that receives the subpicture attributes.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_FAIL | No subpicture streams were found.
E_POINTER | Invalid argument.
VFW_E_ATTRIBUTES_DO_NOT_EXIST | The subpicture has no defined attributes.

Remarks

The index numbers 0-31 are valid only for titles. Menus have only one subpicture stream, which must be specified using one of the constants in the table below:

DVD_STREAM_DATA_CURRENT (0x800) | to query the currently selected subpicture stream.
DVD_STREAM_DATA_VMGM (0x400) | to query the subpicture attributes for the Video Manager or "Top" Menu.
DVD_STREAM_DATA_VTSM (0x401) | to query the subpicture attributes for the currently selected Video Title Set Menu.

This method is demonstrated in the DVDSample application in CDvdCore::GetSPAttributes() and CSPLangDlg::GetSPLang.

See Also

DVD Menus, IsSubpictureStreamEnabled

IDvdInfo2::GetCurrentUOPS

IDvdInfo2 Interface

Retrieves a set of flags indicating which navigation commands, if any, the content authors have explicitly disabled for the current disc location.

Syntax

HRESULT GetCurrentUOPS(
  ULONG *pulUOPs
);

Parameters

pulUOPs
[out] Pointer to a variable of type ULONG that is a bitwise OR of VALID_UOP_FLAG values. Each bit represents the state (valid or not valid) of a user operation (UOP). If the bit is set, then that user operation is prohibited. See Remarks.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | pulUOPs is not a valid pointer.

Remarks

DVD authors can insert UOP commands at almost any place on the disc to disallow a navigation command that would otherwise be permitted within the current DVD domain. In other words, UOP commands enable disc authors to override the usual navigation permissions.

A DVD player application should normally never have to use this method because the DVD Navigator automatically checks all UOP permissions before proceeding with any command, and will return VFW_E_DVD_OPERATION_INHIBITED from any method if the command is invalid under the current UOP. If your application needs to track the current UOP permissions itself, you can call GetCurrentUOPS whenever the current UOP permissions are required, or you can handle the EC_DVD_VALID_UOPS_CHANGE event notification in your message loop and retrieve the UOP information from the lParam1 parameter. The latter approach is generally more efficient.

See Also

EC_DVD_VALID_UOPS_CHANGE

IDvdInfo2::GetDVDVolumeInfo

IDvdInfo2 Interface

Retrieves the current DVD volume information.

Syntax

HRESULT GetDVDVolumeInfo(
    ULONG *pulNumOfVolumes,
    ULONG *pulVolume,
    DVD_DISC_SIDE *pSide,
    ULONG *pulNumOfTitles
    );

Parameters

pulNumOfVolumes
[out] Pointer to a variable of type ULONG that receives the number of volumes in the volume set.
pulVolume
[out] Pointer to a variable of type ULONG that receives the volume number for this root directory.
pSide
[out] Pointer to a variable of type DVD_DISC_SIDE that receives the current disc side.
pulNumOfTitles
[out] Pointer to a variable of type ULONG that receives the number of titles available in this volume.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.

Remarks

Some discs can be distributed as part of multidisc set. "Volume" in this context can mean either "disc" or "disc side", depending on how the disc was authored.

IDvdInfo2::GetDVDTextLanguageInfo

IDvdInfo2 Interface

Retrieves the information for the specified text string language block.

Syntax

HRESULT GetDVDTextLanguageInfo(
    ULONG ulLangIndex,
    ULONG *pulNumOfStrings,
    LCID pLangCode,
    DVD_TextCharSet *pbCharacterSet
  );

Parameters

ulLangIndex
[in] Index specifying the language block. See Remarks.
pulNumOfStrings
[out] Pointer to a variable of type ULONG that receives the number of strings for the specified language block.
pLangCode
[out] Pointer to a variable of type LCID that contains the ISO 639 language code.
pbCharacterSet
[out] Pointer to a DVD_TextCharSet enumeration that receives a value indicating which character set is used for the specified language.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | An unexpected internal error occurred.

Remarks

Call GetDVDTextNumberOfLanguages to set up the index of all the available text languages for menus and subpictures. Then, for each index entry, call GetDVDTextLanguageInfo to retrieve the information for that particular language (number of strings, language code, character set).

See Also

Working with DVD Text Strings

IDvdInfo2::GetDVDTextNumberOfLanguages

IDvdInfo2 Interface

Retrieves the number of text languages for the current DVD or disc side.

Syntax

HRESULT GetDVDTextNumberOfLanguages(
    ULONG *pulNumOfLangs
  );

Parameters

pulNumOfLangs
[out] Pointer to a variable of type ULONG that receives the number of text languages.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | An unexpected internal error occurred.

Remarks

Depending on how the disc is authored, the number of languages will be valid either for the entire disc, or for the current side only.

See Also

Working with DVD Text Strings

IDvdInfo2::GetDVDTextStringAsNative

IDvdInfo2 Interface

Retrieves the text string for the specified language as an array of bytes.

Syntax

HRESULT GetDVDTextStringAsNative(
  ULONG ulLangIndex,
  ULONG ulStringIndex,
  BYTE *pchBuffer,
  ULONG ulMaxBufferSize,
  ULONG *pulActualSize,
  DVD_TextStringType *pType
);

Parameters

ulLangIndex
[in] Language index.
ulStringIndex
[in] String index of the given language.
pchBuffer
[out] Pointer to a buffer that receives the text string. If pchBuffer is NULL, then this method returns only the size of the string in pulActualSize.
ulMaxBufferSize
[in] Maximum string size allowed (size of pchBuffer).
pulActualSize
[out] Actual length, in bytes, of the string returned in pchBuffer, including the terminating NULL.
pType
[out] Pointer to a variable of type DVD_TextStringType that receives the type of string data returned.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | An unexpected internal error occurred.

Remarks

In general, a robust application can handle Unicode™ strings. So, when getting a string, you generally first call GetDVDTextStringAsUnicode. But because some strings might contain characters that cannot be represented in Unicode, if GetDVDTextStringAsUnicode fails, the application can try calling GetDVDTextStringAsNative.

A terminating NULL is appended to the returned string.

See Also

Working with DVD Text Strings

IDvdInfo2::GetDVDTextStringAsUnicode

IDvdInfo2 Interface

Retrieves the text string for the specified language and string indexes in Unicode™.

Syntax

HRESULT GetDVDTextStringAsUnicode(
    ULONG ulLangIndex,
    ULONG ulStringIndex,
    TCHAR *pchBuffer,
    ULONG ulMaxBufferSize,
    ULONG *pulActualSize,
    enum DVD_TextStringType *pType
  );

Parameters

ulLangIndex
[in] Language index.
ulStringIndex
[in] String index of the given language.
pchBuffer
[out] Pointer to a buffer that receives the text string. If pchBuffer is NULL, then this method returns only the size of the string in pulActualSize.
ulMaxBufferSize
[in] Maximum string size allowed, calculated as sizeof(pchBuffer)/sizeof(*pchBuffer).
pulActualSize
[out] Pointer to a variable of type ULONG that receives the actual length of the string returned in pchBuffer, including the terminating NULL.
pType
[out] Pointer to a variable of type DVD_TextStringType that receives the type of string data returned.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | An unexpected internal error occurred.

Remarks

In general, a robust application can handle Unicode™ strings. So, when getting a string, you generally first call GetDVDTextStringAsUnicode. But because some strings might contain characters that cannot be represented in Unicode, if GetDVDTextStringAsUnicode fails, the application can try calling GetDVDTextStringAsNative.

A terminating NULL is appended to the returned string.

See Also

Working with DVD Text Strings

IDvdInfo2::GetMenuLanguages

IDvdInfo2 Interface

Retrieves all the languages available for all menus on the disc.

Syntax

HRESULT GetMenuLanguages(
    LCID *pLanguages,
    ULONG ulMaxLanguages,
    ULONG *puActualLanguages
  );

Parameters

pLanguages
[out] Pointer to an LCID array that receives the languages returned. To retrieve only the number of languages available for menus, and not the actual languages themselves, specify NULL for pLanguages.
ulMaxLanguages
[in] Maximum number of languages to retrieve.
puActualLanguages
[out] Pointer to a variable of type ULONG that receives the actual number of languages retrieved.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

IDvdInfo2::GetNumberOfChapters

IDvdInfo2 Interface

Retrieves the number of chapters in a given title.

Syntax

HRESULT GetNumberOfChapters(
  ULONG ulTitle,
  ULONG *pulNumOfChapters
);

Parameters

ulTitle
[in] Variable of type ULONG that specifies the title.
pulNumOfChapters
[out] Pointer to a variable of type ULONG that receives the number of chapters for the specified title.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | A parameter is invalid.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

Call this method to get the number of chapters before calling IDvdControl2::PlayChapter, to ensure that you specify a valid chapter number.

IDvdInfo2::GetPlayerParentalLevel

IDvdInfo2 Interface

Retrieves the current parental level and ISO 3166 country code settings for the DVD Navigator.

Syntax

HRESULT GetPlayerParentalLevel(
  ULONG *pulParentalLevel,
  ULONG *pulCountryCode
);

Parameters

pulParentalLevel
[out] Pointer to a variable of type ULONG that receives a value indicating the current parental level. Valid parental levels are 1 through 8 if parental management is enabled, 0xFFFFFFFF if parental management is disabled.
pulCountryCode
[out] Pointer to a variable of type ULONG that receives a value indicating the current country code (ISO 3166 Alpha-2 Code).

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | A parameter is invalid.

Remarks

Parental management is disabled by default in the DVD Navigator. This method is demonstrated in the DVDSample application in CDvdCore::GetParentalLevel.

See Also

Enforcing Parental Management Levels, EC_DVD_PARENTAL_LEVEL_CHANGE

IDvdInfo2::GetState

IDvdInfo2 Interface

Retrieves a bookmark containing the disc location and DVD Navigator state information.

Syntax

HRESULT GetState(
    IDvdState **pStateData
);

Parameters

pStateData
[out] Address of a pointer to the IDvdState interface of a DvdState object allocated by the DVD Navigator.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | DVD Navigator is not initialized.

Remarks

When this method is called, the DVD Navigator creates a new state object and saves the current location into it, as well as the current parental level and other state information. The DVDState object can be used to restore the DVD Navigator to the saved location at a later time through a call to IDvdControl2::SetState. This enables viewers to stop viewing in the middle of a disc, save the location, and come back at some later time to begin viewing where they left off, with all the internal settings restored as they were before.

The DVD Navigator calls AddRef on the DvdState object before returning it to the application. The application must call Release on the object when it is finished with it.

This method is demonstrated in the DVDSample application in CDvdCore::RestoreBookmark.

IDvdInfo2::GetSubpictureLanguage

IDvdInfo2 Interface

Retrieves the language of the specified subpicture stream within the current title.

Syntax

HRESULT GetSubpictureLanguage(
  ULONG ulStream,
  LCID *pLanguage
  );

Parameters

ulStream
[in] Number of the subpicture stream for which the language is being retrieved.
pLanguage
[out] Pointer to an LCID that receives the locale information. The language information can then be extracted from the LCID by using the Win32 MAKELANGID macro.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not initialized or not in a valid domain.

Remarks

To get the text languages available for a menu, call GetMenuLanguages. GetSubpictureLanguage sets the value pointed to by pLanguage to zero if the stream contains an unknown language. Call the Win32 GetLocaleInfo function as follows to create a human-readable string name from pLanguage. LOCALE_SENGLANGUAGE is the locale information type, pszString is a pointer to a buffer to receive the requested data, and cbSize specifies the size of pszString.

GetLocaleInfo(*pLanguage, LOCALE_SENGLANGUAGE, pszString, cbSize);

IDvdInfo2::GetTitleAttributes

IDvdInfo2 Interface

Retrieves attributes of all video, audio, and subpicture streams for the specified title and its menus.

Syntax

HRESULT GetTitleAttributes(
    ULONG ulTitle,
    DVD_MenuAttributes *pMenu,
    DVD_TitleAttributes *pTitle
    );

Parameters

ulTitle
[in] Variable of type ULONG, from 1 through 99, specifying the requested title number. Specify 0xFFFFFFFF for the current title.
pMenu
[out] Pointer to a DVD_MenuAttributes structure that receives the attributes of the menu associated with the specified title.
pTitle
[out] Pointer to a DVD_TitleAttributes structure that receives the attributes of the specified title.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | The nTitle parameter is invalid.
E_INVALIDDOMAIN | The DVD Navigator is not in the title domain.
E_POINTER | The pMenu or pTitle parameter is invalid.
E_UNEXPECTED | DVD Navigator is not initialized or some other internal error occurred.

IDvdInfo2::GetTitleParentalLevels

IDvdInfo2 Interface

Retrieves the parental levels that are defined for a particular title.

Syntax

HRESULT GetTitleParentalLevels(
    ULONG ulTitle,
    ULONG *pulParentalLevels
  );

Parameters

ulTitle
[in] Title for which parental levels are requested. Specify 0xfffffff to return the parental levels for the current title.
pulParentalLevels
[out] Pointer to a variable of type ULONG that receives a bitwise OR combination of DVD_PARENTAL_LEVEL values defined for the title.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

A title can contain different parental levels for different sections.

See Also

Setting and Enforcing Parental Management Levels

IDvdInfo2::GetTotalTitleTime

IDvdInfo2 Interface

Retrieves the total playback time for the current title.

Syntax

HRESULT GetTotalTitleTime(
    DVD_HMSF_TIMECODE *pTotalTime,
    ULONG *pulTimeCodeFlags
  );

Parameters

pTotalTime
[out] Pointer to a variable of type DVD_HMSF_TIMECODE that receives the total time in hours, minutes, seconds, and frames.
pulTimeCodeFlags
[out] Pointer to a variable of type ULONG that receives a DVD_TIMECODE_FLAGS value indicating the frame rate at which the disc was authored to play. Specify NULL if you don't want to receive the timecode information.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.
VFW_E_DVD_INVALIDDOMAIN | The DVD Navigator is not in the title domain.
VFW_S_DVD_NON_ONE_SEQUENTIAL | The title is not a one sequential video title.

Remarks

The total title time is the time required to play the title sequentially, not counting any stills, pauses, and so on.

This method is for use only with one sequential video titles, which are titles such as movies in which each chapter automatically branches to the next chapter so that the entire title plays continuously without stopping. Nonsequential video titles are titles whose chapters do not automatically play one after another. Because of variations in how DVD authors encode time information on nonsequential video titles, do not use this method to determine the total time for such titles.

IDvdInfo2::GetVMGAttributes

IDvdInfo2 Interface

Retrieves attributes of all video, audio, and subpicture streams for the Video Manager Menu.

Syntax

HRESULT GetVMGAttributes(
  DVD_MenuAttributes *pATR
);

Parameters

pATR
[out] Pointer to a DVD_MenuAttributes structure that receives the attributes.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

The Video Manager Menu is not associated with any particular title number.

IDvdInfo2::IsAudioStreamEnabled

IDvdInfo2 Interface

Determines if the specified audio stream is enabled in the current title.

Syntax

HRESULT IsAudioStreamEnabled(
    ULONG ulStreamNum,
    BOOL *pbEnabled
    );

Parameters

ulStreamNum
[in] Audio stream number to test.
pbEnabled
[out] Pointer to a variable of type BOOL that receives a value of TRUE if the audio stream is enabled, or FALSE otherwise.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

A DVD can have up to eight separate audio streams, although typically not all the streams will be enabled for each title. Use IsAudioStreamEnabled to determine whether a particular stream is enabled for the current title, and then call IDvdControl2::SelectAudioStream to select one of the enabled streams.

IDvdInfo2::IsSubpictureStreamEnabled

IDvdInfo2 Interface

Determines if the specified subpicture stream is enabled in the current title.

Syntax

HRESULT IsSubpictureStreamEnabled(
    ULONG ulStreamNum,
    BOOL *pbEnabled
);

Parameters

ulStreamNum
[in] Subpicture stream number to test.
pbEnabled
[out] Pointer to a variable of type BOOL that receives a value of TRUE if the audio stream is enabled, or FALSE otherwise.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_UNEXPECTED | The DVD Navigator is not initialized.

Remarks

A DVD can have up to 32 separate subpicture streams, although typically not all the streams will be enabled for each title. Use IsSubpictureStreamEnabled to determine whether a particular stream is enabled for the current title, and then call IDvdControl2::SelectSubpictureStream to select one of the enabled streams.


IDvdState Interface

The IDvdState interface is implemented by a DvdState object, which is created by the DVD Navigator filter when an application calls IDvdInfo2::GetState to save the state of the user's session to disk, including playback location, parental level, and region. An application can use the IDvdState methods to query for this information, which is saved in a DvdState object.

The DvdState objects implement IPersist to enable saving to disk. For sample code showing how to save bookmarks, see Saving and Restoring DvdState Objects.

The DVD Navigator initializes the DvdState object with the current playback location on the DVD, the user's parental level, and the DVD region. An alternative approach is for the application to create the state object by calling CoCreateInstance:

CoCreateInstance( CLSID_DVDState, NULL, CLSCTX_INPROC_SERVER,
    IID_IDvdState, (void **) ppState );

Call IDvdControl2::SetState to resume playback at a later time from the point where it left off when GetState was called, with the restored parental and region settings.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDvdState methods | Description
GetDiscID | Retrieves the unique identifier (ID) of the disc from which the bookmark was made.
GetParentalLevel | Retrieves the user's parental level as saved in the DvdState object.
GetRegion | Retrieves the DVD region as saved in the DvdState object.

IDvdState::GetDiscID

IDvdState Interface

Retrieves the unique ID of the disc from which the bookmark was made.

Syntax

HRESULT GetDiscID(
  ULONGLONG *pullUniqueID
  );

Parameters

pullUniqueID
[out] Pointer to a variable of type ULONGLONG that receives the ID.

Return Value

Returns one of the values shown in the following table.

S_OK | Success
E_POINTER | Invalid argument

IDvdState::GetParentalLevel

IDvdState Interface

Retrieves the user's parental level as saved in the DvdState object.

Syntax

HRESULT GetParentalLevel(
  ULONG *pulParentalLevel
  );

Parameters

pulParentalLevel
[out] Pointer to a variable of type ULONG that receives the parental level.

Return Value

Returns one of the following values.
S_OK | Success
E_POINTER | Invalid argument

IDvdState::GetRegion

IDvdState Interface

Retrieves the DVD region as saved in the DvdState object.

Syntax

HRESULT GetRegion(
  ULONG *pulRegion
  );

Parameters

pulRegion
[out] Pointer to a variable of type ULONG that receives the region value.

Return Value

Returns one of the following values.
S_OK | Success.
E_UNEXPECTED | DVD Navigator is not initialized.
E_POINTER | Invalid argument.


IDVEnc Interface

This interface provides methods for setting and retrieving properties on the DV Video Encoder filter.

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDVEnc methods | Description
get_IFormatResolution | Retrieves the encoding resolution.
put_IFormatResolution | Sets the encoding resolution.

IDVEnc::get_IFormatResolution

IDVEnc Interface

Retrieves the encoding resolution.

Syntax

HRESULT get_IFormatResolution(
    int *VideoFormat,
    int *DVFormat,
    int *Resolution,
    BYTE fDVInfo,
    DVINFO *sDVInfo
);

Parameters

VideoFormat
[out] Pointer to a variable that receives a member of the DVENCODERVIDEOFORMAT enumeration, specifying the video standard in use (NTSC or PAL).
DVFormat
[out] Pointer to a variable that receives a member of the DVENCODERFORMAT enumeration, specifying the digital video (DV) format.
Resolution
[out] Pointer to a variable that receives a member of the DVENCODERRESOLUTION enumeration, specifying the video resolution.
fDVInfo
[in] Boolean value specifying whether to retrieve the DVINFO structure that specifies the stream format. If TRUE, the stream format is returned in the sDVInfo parameter.
sDVInfo
[out] Pointer to a variable that receives a DVINFO structure containing the stream format. (If fDVInfo is FALSE, this parameter is ignored.)

Return Value

Returns S_OK if successful. Otherwise, returns E_FAIL or another error code.

IDVEnc::put_IFormatResolution

IDVEnc Interface

Sets the encoding resolution.

Syntax

HRESULT put_IFormatResolution(
    int VideoFormat,
    int DVFormat,
    int Resolution,
    BYTE fDVInfo,
    DVINFO *sDVInfo
);

Parameters

VideoFormat
[in] Member of the DVENCODERVIDEOFORMAT enumeration, specifying the video standard to use (NTSC or PAL).
DVFormat
[in] Member of the DVENCODERFORMAT enumeration, specifying the DV format.
Resolution
[in] Member of the DVENCODERRESOLUTION enumeration, specifying the video resolution.
fDVInfo
[in] Boolean value specifying whether the sDVInfo parameter contains a valid DVINFO structure. To set the stream format, set this parameter to TRUE and specify the format chunk with the sDVInfo parameter.
sDVInfo
[in] If fDVInfo is TRUE, must point to a DVINFO structure that describes the stream format.

Return Value

Returns S_OK if successful. Otherwise, returns E_FAIL or another error code.


IDVSplitter Interface

Downgrades the frame rate on a digital video (DV) stream. The DV Splitter filter exposes this interface.

Applications can use this interface to reduce the frame rate on a DV stream, before the stream reaches the DV Video Decoder filter. This can be helpful for processor-intensive tasks, such as real-time transcoding.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDVSplitter methods | Description
DiscardAlternateVideoFrames | Discards half of the frames in the video stream.

IDVSplitter::DiscardAlternateVideoFrames

IDVSplitter Interface

Discards half of the frames in the video stream. For NTSC, the frame rate is reduced from 30 frames per second (fps) to 15 fps. For PAL, the frame rate is reduced from 25 fps to 12.5 fps.

Syntax

HRESULT DiscardAlternateVideoFrames(
    int nDiscard
);

Parameters

nDiscard
[in] Flag that specifies whether to discard frames. If the value is non-zero, the filter discards alternate frames. If the value is zero, the filter delivers every frame.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_UNEXPECTED | Filter is paused or running.


IEnumFilters Interface

The IFilterGraph::EnumFilters method returns this interface, which provides access to a standard Component Object Model (COM) collection object that contains the filters currently in the filter graph. For more information on COM collections, see the IEnumXXXX topic in the Platform SDK. For more information on enumerating filters, see Enumerating Objects in a Filter Graph.

If the set of filters in the graph changes, some methods on this interface return VFW_E_ENUM_OUT_OF_SYNC. Call the Reset method to resynchronize the enumerator.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IEnumFilters methods | Description
Next | Retrieves the specified number of filters in the enumeration sequence.
Skip | Skips over a specified number of filters.
Reset | Resets the enumeration sequence to the beginning.
Clone | Makes a copy of the enumerator with the same enumeration state.

IEnumFilters::Clone

IEnumFilters Interface

Makes a copy of the enumerator with the same enumeration state.

Syntax

HRESULT Clone(
    IEnumFilters **ppEnum
);

Parameters

ppEnum
[out] Address of a variable that receives a pointer to the IEnumFilters interface of the new enumerator.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

IEnumFilters::Next

IEnumFilters Interface

Retrieves the specified number of filters in the enumeration sequence.

Syntax

HRESULT Next(
    ULONG cFilters,
    IBaseFilter **ppFilter,
    ULONG *pcFetched
);

Parameters

cFilters
[in] Number of filters to retrieve.
ppFilter
[out] Array of size cFilters that is filled with IBaseFilter pointers.
pcFetched
[out] Pointer to a variable that receives the number of filters retrieved. Can be NULL if cFilters is 1.

Return Value

Returns one of the following HRESULT values.

S_FALSE | Did not retrieve as many filters as requested.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The graph has changed and is now inconsistent with the enumerator.

Remarks

If the method succeeds, the IBaseFilter pointers all have outstanding reference counts. Be sure to release them when you are done.

If the filter graph changes (for example, the application removes a filter), the enumerator is no longer be consistent with the graph, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the Reset method. You can then call the Next method safely.

IEnumFilters::Reset

IEnumFilters Interface

Resets the enumeration sequence to the beginning.

Syntax

HRESULT Reset(void);

Return Value

Returns S_OK, which indicates success.

IEnumFilters::Skip

IEnumFilters Interface

Skips over a specified number of filters.

Syntax

HRESULT Skip(
    ULONG cFilter
);

Parameters

cFilter
[in] Number of filters to skip.

Return Value

Returns one of the following HRESULT values.

S_FALSE | Skipped past the end of the sequence.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The graph has changed and is now inconsistent with the enumerator.

Remarks

If the filter graph changes (for example, the application removes a filter), the enumerator is no longer be consistent with the graph, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the Reset method. You can then call the Skip method safely.


IEnumMediaTypes Interface

Enumerates the preferred media types for a pin.

The IPin::EnumMediaTypes method returns this interface. It is based on the standard Component Object Model (COM) enumerators. For more information, see the IEnumXXXX topic in the Platform SDK.

Pins use this interface when they connect to other pins. Applications can also use it to examine a pin's preferred media types. For more information, see Enumerating Objects in a Filter Graph.

If a pin's set of preferred media types changes, some methods on this interface return VFW_E_ENUM_OUT_OF_SYNC. Call the Reset method to resynchronize the enumerator.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IEnumMediaTypes methods | Description
Next | Retrieves a specified number of media types.
Skip | Skips over a specified number of media types.
Reset | Resets the enumeration sequence to the beginning.
Clone | Makes a copy of the enumerator with the same enumeration state.

IEnumMediaTypes::Clone

IEnumMediaTypes Interface

Makes a copy of the enumerator with the same enumeration state.

Syntax

HRESULT Clone(
    IEnumMediaTypes **ppEnum
);

Parameters

ppEnum
[out] Address of a variable that receives a pointer to the IEnumMediaTypes interface of the new enumerator.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.

Remarks

If the set of media types changes, the enumerator is no longer consistent with the pin, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the Reset method. You can then call the Clone method safely.

IEnumMediaTypes::Next

IEnumMediaTypes Interface

Retrieves a specified number of media types.

Syntax

HRESULT Next(
    ULONG cMediaTypes,
    AM_MEDIA_TYPE **ppMediaTypes,
    ULONG *pcFetched
);

Parameters

cMediaTypes
[in] Number of media types to retrieve.
ppMediaTypes
[out] Array of pointers to AM_MEDIA_TYPE structures, of size cPins.
pcFetched
[out] Pointer to a variable that receives the number of media types the method returned. Can be NULL if cMediaTypes is 1.

Return Value

Returns one of the following HRESULT values.

S_FALSE | Did not retrieve as many media types as requested.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.

Remarks

If the method succeeds, the array specified by ppMediaTypes contains pointers to AM_MEDIA_TYPE structures. The number of structures is equal to *pcFetched. Free each media type by calling the DeleteMediaType function.

If the set of media types changes, the enumerator is no longer consistent with the pin, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the Reset method. You can then call the Next method safely.

IEnumMediaTypes::Reset

IEnumMediaTypes Interface

Resets the enumeration sequence to the beginning.

Syntax

HRESULT Reset(void);

Return Value

Returns S_OK.

IEnumMediaTypes::Skip

IEnumMediaTypes Interface

Skips over a specified number of media types.

Syntax

HRESULT Skip(
    ULONG cMediaTypes);

Parameters

cMediaTypes
[in] Number of media types to skip.

Return Value

Returns one of the following HRESULT values.

S_FALSE | Skipped past the end of the sequence.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.

Remarks

If the set of media types changes, the enumerator is no longer consistent with the pin, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the Reset method. You can then call the Skip method safely.


IEnumPIDMap

Microsoft DirectX 8.0

IEnumPIDMap Interface

This interface is implemented on a standard COM collection of Packet ID (PID) maps that have been created by a call to the IMPEG2PIDMap::MapPID method on an output pin of the MPEG-2 Demultiplexer. To obtain a pointer to this interface, use the IMPEG2PIDMap::EnumPIDMap method. Typically, output pins for audio and video streams will only have a single PID mapped at any given time. This collection represents a snapshot of the PIDs mapped at the time the collection is created. The collection is not updated automatically.

MethodName | Description
Clone | Creates a new copy of the collection and all its sub-objects.
Next | Retrieves the next n elements in the collection.
Reset | Moves the iterator to the beginning of the collection.
Skip | Skips over the specified element in the collection.

IEnumPIDMap::Clone

IEnumPIDMap Interface

Copy the collection.

Syntax

HRESULT Clone(
    IEnumPIDMap** ppIEnumPIDMap
    );

Parameters

ppIEnumPIDMap
[out] Address of an IEnumPIDMap interface pointer that will be set to the returned collection object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumPIDMap::Next

IEnumPIDMap Interface

Retrieves the next n elements in the collection.

Syntax

HRESULT Next(
    ULONG cRequest,
    PID_MAP* pPIDMap,
    ULONG* pcReceived
    );

Parameters

cRequest
[in] The number of elements to retrieve.
pPIDMap
[in, out, size_is (cRequest)] Address of a caller-allocated array containing cRequest elements that will receive the retrieved PID_MAP structures.
pcReceived
[out] Pointer to a variable of type ULONG that receives the number of elements actually retrieved.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Return Value

If cRequest> = 0 and pcReceived is not NULL, upon return pcReceived contains the number of PID maps remaining in the collection.

IEnumPIDMap::Reset

IEnumPIDMap Interface

Moves the iterator to the beginning of the collection.

Syntax

HRESULT Reset();

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumPIDMap::Skip

IEnumPIDMap Interface

Skip the element at the specified index.

Syntax

HRESULT Skip(
    ULONG cRecords
    );

Parameters

cRecords
[in] Index of the element to skip.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IEnumPins Interface

Enumerates pins on a filter.

The IBaseFilter::EnumPins method returns this interface. It is based on the standard Component Object Model (COM) enumerators. For more information, see the IEnumXXXX topic in the Platform SDK.

The filter graph manager uses this interface when it connects filters. Applications can use it to retrieve pins on a filter. For more information, see Enumerating Objects in a Filter Graph.

If the number of pins on the filter changes, some methods on this interface return VFW_E_ENUM_OUT_OF_SYNC. Call the Reset method to resynchronize the enumerator.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IEnumPins methods | Description
Next | Retrieves a specified number of pins.
Skip | Skips over a specified number of pins.
Reset | Resets the enumeration sequence to the beginning.
Clone | Makes a copy of the enumerator with the same enumeration state.

IEnumPins::Clone

IEnumPins Interface

Makes a copy of the enumerator with the same enumeration state.

Syntax

HRESULT Clone(
    IEnumPins **ppEnum
);

Parameters

ppEnum
[out] Address of a variable that receives a pointer to the IEnumPins interface of the new enumerator.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.

Remarks

If the number of pins changes, the enumerator is no longer consistent with the filter, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the Reset method. You can then call the Clone method safely.

IEnumPins::Next

IEnumPins Interface

Retrieves a specified number of pins in the enumeration sequence.

Syntax

HRESULT Next(
    ULONG cPins,
    IPin **ppPins,
    ULONG *pcFetched
);

Parameters

cPins
[in] Number of pins to retrieve.
ppPins
[out] Array of size cPins that is filled with IPin pointers.
pcFetched
[out] Pointer to a variable that receives the number of pins retrieved. Can be NULL if cPins is 1.

Return Value

Returns one of the following HRESULT values.

S_FALSE | Did not retrieve as many pins as requested.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.

Remarks

This method retrieves pointers to the specified number of pins, starting at the current position in the enumeration, and places them in the specified array.

If the method succeeds, the IPin pointers all have outstanding reference counts. Be sure to release them when you are done.

If the number of pins changes, the enumerator is no longer consistent with the filter, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the Reset method. You can then call the Next method safely.

IEnumPins::Reset

IEnumPins Interface

Resets the enumeration sequence to the beginning.

Syntax

HRESULT Reset(void);

Return Value

Returns S_OK.

IEnumPins::Skip

IEnumPins Interface

Skips over a specified number of pins.

Syntax

HRESULT Skip(
    ULONG cPins
);

Parameters

cPins
[in] Number of pins to skip.

Return Value

Returns one of the following HRESULT values.

S_FALSE | Skipped past the end of the sequence.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.

Remarks

If the number of pins changes, the enumerator is no longer consistent with the filter, and the method returns VFW_E_ENUM_OUT_OF_SYNC. Discard any data obtained from previous calls to the enumerator, because it might be invalid. Update the enumerator by calling the Reset method. You can then call the Skip method safely.


IEnumStreamIdMap

Microsoft DirectX 8.0

IEnumStreamIdMap Interface

This interface is implemented on a standard COM collection of Stream ID maps that have been created by the MPEG-2 Demultiplexer's IMPEG2StreamIdMap::MapStreamID method. To obtain a pointer to this interface, use the IMPEG2StreamIdMap::EnumStreamIdMap method. Typically, an output pin will never have more than one stream ID mapped to it at any given time. This collection represents a snapshot of the Stream IDs mapped at the time the the collection is created. The collection is not updated automatically.

MethodName | Description
Clone | Creates a new copy of the collection and all its sub-objects.
Next | Retrieves the next n elements in the collection.
Reset | Moves the iterator to the beginning of the collection.
Skip | Skips over the specified element in the collection.

IEnumStreamIdMap::Clone

IEnumStreamIdMap Interface

Copy the collection.

Syntax

HRESULT Clone(
    IEnumStreamIdMap** ppIEnumStreamIdMap
    );

Parameters

ppIEnumStreamIdMap
[out] Address of an IEnumStreamIdMap interface pointer that will be set to the returned collection object.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumStreamIdMap::Next

IEnumStreamIdMap Interface

Retrieves the next n elements in the collection.

Syntax

HRESULT Next(
    ULONG cRequest,
    STREAM_ID_MAP* pStreamIdMap,
    ULONG* pcReceived
    );

Parameters

cRequest
[in] The number of elements to retrieve.
pStreamIdMap
[in, out, size_is (cRequest)] Address of a user-allocated array containing cRequest elements that will receive the retrieved STREAM_ID_MAP structures.
pcReceived
[out] Pointer to a variable of type ULONG that receives the number of elements actually retrieved.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

If cRequest> = 0 and pcReceived is not NULL, upon return pcReceived contains the number of stream ID maps remaining in the collection.

IEnumStreamIdMap::Reset

IEnumStreamIdMap Interface

Moves the iterator to the beginning of the collection.

Syntax

HRESULT Reset();

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

IEnumStreamIdMap::Skip

IEnumStreamIdMap Interface

Skip the element at the specified index.

Syntax

HRESULT Skip(
    ULONG cRecords
    );

Parameters

cRecords
[in] Index of the element to skip.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IFileSinkFilter Interface

The IFileSinkFilter interface is implemented on filters that write media streams to a file. A file sink filter in a video capture filter graph, for instance, writes the output of the video compression filter to a file. Typically, the application running this filter graph should enable the user to enter the name of the file to be written to. This interface enables the communication of this information.

IFileSinkFilter2 replaces this interface unless you need to maintain backward compatibility with Microsoft® ActiveMovie® 1.0.

If a filter needs the name of an output file, it should expose this interface to allow an application to set the file name. Note that there is currently no base class implementation of this interface.

Any application that must set the name of the file into which the file sink filter will write should use this interface to get and set the file name.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IFileSinkFilter methods | Description
SetFileName | Sets the name of the file into which media samples will be written.
GetCurFile | Retrieves the name of the current file into which media samples will be written (the sink file).

IFileSinkFilter::GetCurFile

IFileSinkFilter Interface

Retrieves the name of the current file into which media samples will be written (the sink file).

Syntax

HRESULT GetCurFile(
    LPOLESTR *ppszFileName,
    AM_MEDIA_TYPE *pmt
);

Parameters

ppszFileName
[out] Address of a pointer to the name of the file set to receive media samples.
pmt
[out] Pointer to the type of media samples to be written to the file.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

If a file name is not assigned, this method returns E_FAIL.

IFileSinkFilter::SetFileName

IFileSinkFilter Interface

Sets the name of the file into which media samples will be written.

Syntax

HRESULT SetFileName(
    LPCOLESTR pszFileName,
    const AM_MEDIA_TYPE *pmt
);

Parameters

pszFileName
[in] Pointer to the name of the file to receive the media samples.
pmt
[in] Pointer to the type of media samples to be written to the file, and the media type of the sink filter's input pin.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

If the pszFileName parameter names a nonexistent file, the file will be created. If it names an existing file, the sink filter will overwrite the file without first deleting it.


IFileSinkFilter2 Interface

The IFileSinkFilter2 interface derives from the IFileSinkFilter interface and replaces it unless you need backward compatibility with Microsoft® ActiveMovie® 1.0. Like IFileSinkFilter, filters that write media streams to a file implement this interface. A file sink filter in a video capture filter graph, for instance, saves the output of the video compression filter to a file. Typically, the application running this filter graph should allow the user to enter the name of the file to which to save the data. This interface enables you to communicate this information. IFileSinkFilter2 adds the option to determine whether the file it writes should destroy an existing file of the same name. In the video capture case, do not destroy a file you've already created, because preallocating file space takes valuable time. By default, the new file does not destroy the old one. Otherwise, destroy the original file to make sure the file you author doesn't contain garbage.

A filter should implement this interface when it needs the name of an output file or needs to set options for that file. Implement the older IFileSinkFilter interface if you need to make your filter compatible with ActiveMovie 1.0. Note that there is currently no base class implementation of this interface.

When an application must set the name of the file into which the file sink filter will write, it should use this interface to get and set the file name or change options. Use the older IFileSinkFilter interface if you need to make your application compatible with ActiveMovie 1.0.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IFileSinkFilter methods | Description
SetFileName | Sets the name of the file into which media samples will be written.
GetCurFile | Retrieves the name of the current file into which media samples will be written (the sink file).
IFileSinkFilter2 methods | Description
SetMode | Determines whether the file writer destroys the file when it creates the new one.
GetMode | Retrieves whether the file writer destroys the file when it creates the new one.

IFileSinkFilter2::GetMode

IFileSinkFilter2 Interface

Retrieves whether the file writer destroys the file when it creates the new one.

Syntax

HRESULT GetMode(
    DWORD *dwFlags
);

Parameters

dwFlags
[out] Pointer to the retrieved flags. Currently, the only defined flag is AM_FILE_OVERWRITE, which indicates that the file should be destroyed; zero indicates that the file will be left alone.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IFileSinkFilter2::SetMode

IFileSinkFilter2 Interface

Determines whether the file writer destroys the file when it creates the new one.

Syntax

HRESULT SetMode(
    DWORD dwFlags
);

Parameters

dwFlags
[in] Currently, the only defined flag is AM_FILE_OVERWRITE, which indicates that the file writer should destroy the file. Specify zero for dwFlags to leave the file alone.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.


IFileSourceFilter Interface

The IFileSourceFilter interface is exposed by source filters to set the file name and media type of the media file that they are to render. It is an abbreviated version of the COM IPersistFile interface. If the file has a type that can be determined by the algorithm described in Registering a Custom File Type, the recommended file source filter CLSID is used when the filter graph manager attempts to render the filter graph.

If a filter needs the name of a file to open, it should expose this interface to allow an application to set the file name. Note that there is no base class implementation of this interface.

An application that inserts file source filters directly must query for this interface and set the file name. Normally, the filter graph manager uses this interface when an application calls IGraphBuilder::RenderFile. The Graphedt.exe tool queries for the IFileSourceFilter interface and prompts for a file name if it finds it.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IFileSourceFilter methods | Description
Load | Loads the source filter with the file.
GetCurfile | Retrieves the current file.

IFileSourceFilter::GetCurfile

IFileSourceFilter Interface

Collects information about the file to open.

Syntax

HRESULT GetCurfile(
  LPOLESTR *ppszFileName,
  AM_MEDIA_TYPE *pmt
  );

Parameters

ppszFileName
[out] Address of a pointer to the path to the loaded file.
pmt
[out] Pointer to the media type.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

IFileSourceFilter::Load

IFileSourceFilter Interface

Loads a media file.

Syntax

HRESULT Load(
  LPCOLESTR pszFileName,
  const AM_MEDIA_TYPE *pmt
  );

Parameters

pszFileName
[in] Pointer to the absolute path of the file to open.
pmt
[in] Pointer to the media type of the file. This can be NULL.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This is an initialization method for the interface. It is not designed to load multiple files, and any calls to this method after the first call will fail.

You should implement this method to load the file specified by pszFileName.

The name in pszFileName need not actually be a disk file name (that is, one you could pass to the Microsoft® Win32® CreateFile function, for example). It could also be a URL name. The URL moniker filter uses IFileSourceFilter to retrieve its URL name, and IGraphBuilder::AddSourceFilter (and hence IGraphBuilder::RenderFile) handles this correctly. IGraphBuilder::AddSourceFilter returns a specific error (ERROR_FILE_NOT_FOUND) upon not finding the file, which indicates that the file specified does not exist and not that the filter does not exist.


IFilterChain Interface

This interface provides methods for starting, stopping, or removing chains of filters in a filter graph. The filter graph manager exposes this interface.

A filter chain is a sequence of filters, each with at most one connected input pin and one connected output pin, that forms an unbroken line of filters. A filter chain is defined by the filter at the start of the chain and the filter at the end of the chain. (These can be the same filter, making a chain of one filter.) By definition, there is a single stream path going from the start of the chain downstream to the end of the chain.

The methods on this interface are useful in situations where an entire stream of data can appear or disappear, such as a video conferencing application that receives multiple streams over a network. For more information, see Dynamic Graph Building. To control individual streams on a capture filter, use the IAMStreamControl interface instead.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IFilterChain methods | Description
StartChain | Switches all the filters in a filter chain into a running state.
StopChain | Switches all the filters in a filter chain into a stopped state.
RemoveChain | Removes every filter in a filter chain from the filter graph.
PauseChain | Switches all the filters in a filter chain into a paused state.

IFilterChain::PauseChain

IFilterChain Interface

Switches all the filters in a filter chain into a paused state.

Syntax

HRESULT PauseChain(
    IBaseFilter *pStartFilter,
    IBaseFilter *pEndFilter
);

Parameters

pStartFilter
[in] Pointer to the filter at the start of the chain.
pEndFilter
[in] Pointer to the filter at the end of the chain. If this parameter is NULL, the method uses the longest possible filter chain that extends downstream from the start filter.

Return Value

Returns S_OK if successful. If the method fails, the return value may be VFW_E_NOT_PAUSED or another HRESULT value.

Remarks

If this method cannot switch a given filter into a paused state, it stops all of the filters in chain. The filter graph must be paused when you call this method.

IFilterChain::RemoveChain

IFilterChain Interface

Removes every filter in a filter chain from the filter graph.

Syntax

HRESULT RemoveChain(
    IBaseFilter *pStartFilter,
    IBaseFilter *pEndFilter
);

Parameters

pStartFilter
[in] Pointer to the filter at the start of the chain.
pEndFilter
[in] Pointer to the filter at the end of the chain. If this parameter is NULL, the method uses the longest possible filter chain that extends downstream from the start filter.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure otherwise.

Remarks

You can call this method while the graph is running; the method stops the filters in the chain before removing them from the graph.

IFilterChain::StartChain

IFilterChain Interface

Switches all the filters in a filter chain into a running state.

Syntax

HRESULT StartChain(
    IBaseFilter *pStartFilter,
    IBaseFilter *pEndFilter
);

Parameters

pStartFilter
[in] Pointer to the filter at the start of the chain.
pEndFilter
[in] Pointer to the filter at the end of the chain. If this parameter is NULL, the method uses the longest possible filter chain that extends downstream from the start filter.

Return Value

Returns S_OK if successful. If the method fails, the return value may be VFW_E_NOT_RUNNING or another HRESULT value.

Remarks

If this method cannot switch a given filter into a running state, it leaves all the filters in a stopped state. The filter graph must be running when you call this method.

IFilterChain::StopChain

IFilterChain Interface

Switches all the filters in a filter chain into a stopped state.

Syntax

HRESULT StopChain(
    IBaseFilter *pStartFilter,
    IBaseFilter *pEndFilter
);

Parameters

pStartFilter
[in] Pointer to the filter at the start of the chain.
pEndFilter
[in] Pointer to the filter at the end of the chain. If this parameter is NULL, the method uses the longest possible filter chain that extends downstream from the start filter.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure otherwise.


IFilterGraph Interface

This interface provides methods for building a filter graph. An application can use it to add filters to the graph, connect or disconnect filters, remove filters, and perform other basic operations. However, the IGraphBuilder interface inherits from this interface and provides additional methods that are more sophisticated. Therefore, applications should use IGraphBuilder rather than using IFilterGraph directly.

The filter graph manager implements this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IFilterGraph methods | Description
AddFilter | Adds a filter to the graph and gives it a name.
RemoveFilter | Removes a filter from the graph.
EnumFilters | Provides an enumerator for all filters in the graph.
FindFilterByName | Finds a filter that was added with a specified name.
ConnectDirect | Connects two pins directly (without intervening filters).
Reconnect | Breaks the existing pin connection and reconnects it to the same pin.
Disconnect | Disconnects a specified pin.
SetDefaultSyncSource | Sets the default synchronization source (a clock).

IFilterGraph::AddFilter

IFilterGraph Interface

Adds a filter to the graph and gives it a name.

Syntax

HRESULT AddFilter(
    IBaseFilter *pFilter,
    LPCWSTR pName
);

Parameters

pFilter
[in] Pointer to the filter to add to the graph.
pName
[in] Pointer to the name of the filter.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
VFW_S_DUPLICATE_NAME | Successfully added a filter with a duplicate name.
E_FAIL | Failure.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | Null pointer argument.
VFW_E_CERTIFICATION_FAILURE | Use of this filter is restricted by a software key.
VFW_E_DUPLICATE_NAME | Failed to add a filter with a duplicate name.

Remarks

The name of the filter can be NULL, in which case the filter graph manager will generate a name. If the name is not NULL and is not unique, this method will modify the name in an attempt to generate a new unique name. If this is successful, this method returns VFW_S_DUPLICATE_NAME. If it cannot generate a unique name, it returns VFW_E_DUPLICATE_NAME.

AddFilter calls the filter's IBaseFilter::JoinFilterGraph method to inform the filter that it has been added. AddFilter must be called before attempting to use the IGraphBuilder::Connect, IFilterGraph::ConnectDirect, or IGraphBuilder::Render method to connect or render pins belonging to the added filter.

IFilterGraph::ConnectDirect

IFilterGraph Interface

Connects the two pins directly (without intervening filters).

Syntax

HRESULT ConnectDirect(
    IPin *ppinOut,
    IPin *ppinIn,
    const AM_MEDIA_TYPE *pmt
);

Parameters

ppinOut
[in] Pointer to the output pin.
ppinIn
[in] Pointer to the input pin.
pmt
[in] Pointer to the media type to use for the connection (optional; that is, can be NULL).

Return Value

Returns one of the following values, or an error value returned by IPin::Connect.

S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_NOT_IN_GRAPH | One of the specified pins is not in the graph.
VFW_E_CIRCULAR_GRAPH | The input pin is upstream of the output pin, which would result in a circular graph.

IFilterGraph::Disconnect

IFilterGraph Interface

Disconnects this pin.

Syntax

HRESULT Disconnect(
    IPin *ppin
);

Parameters

ppin
[in] Pointer to the pin to disconnect.

Return Value

Returns one of the following values.

S_OK | Success.
S_FALSE | Pin was not connected. No error.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_STOPPED | The filter is not stopped, but does not support reconnection while in a running state.

Remarks

This method does not completely break the connection. To completely break the connection, both ends must be disconnected.

IFilterGraph::EnumFilters

IFilterGraph Interface

Provides an enumerator for all filters in the graph.

Syntax

HRESULT EnumFilters(
    IEnumFilters **ppEnum
);

Parameters

ppEnum
[out] Address of a pointer to the enumerator.

Return Value

Returns one of the following values.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory to create the enumerator.
E_POINTER | Null pointer argument.

Remarks

The interface returned by this method has had its reference count incremented. Be sure to use IUnknown::Release on the interface to decrement the reference count when you have finished using the interface.

IFilterGraph::FindFilterByName

IFilterGraph Interface

Finds a filter that was added to the filter graph with a specific name.

Syntax

HRESULT FindFilterByName(
    LPCWSTR pName,
    IBaseFilter **ppFilter
);

Parameters

pName
[in, string] Pointer to the name to search for.
ppFilter
[out] Address of a pointer to an IBaseFilter interface on the found filter.

Return Value

Returns one of the following values.

S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_NOT_FOUND | No filter was found with the specified name.

Remarks

If no filter is found, the method returns a NULL pointer in the ppFilter parameter.

IFilterGraph::Reconnect

IFilterGraph Interface

Disconnects this and the pin to which it connects and then reconnects it to the same pin. This enables the details of the connection, such as media type and allocator, to be renegotiated.

Syntax

HRESULT Reconnect(
    IPin *ppin
);

Parameters

ppin
[in] Pointer to the pin to disconnect and reconnect.

Return Value

Returns one of the following values.

S_OK | Success.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | Pin is not connected.
VFW_E_WRONG_STATE | Filter is not stopped.

Remarks

This method performs its operation on a separate thread that will not hold any relevant locks. It can be called by a pin or filter to enable renegotiation of the connection. When a transform filter has its input connected, it must agree upon some media type. When the output is connected, it might discover that, to please both its upstream and downstream connections, it would have been better to have chosen a different media type for the upstream connection. The solution is to reconnect the input pin. The caller of this method should ensure (for example, by calling IPin::QueryAccept) that the resulting renegotiation will succeed, because the reconnection process is performed asynchronously and there is no mechanism for reporting or correcting errors.

IFilterGraph::RemoveFilter

IFilterGraph Interface

Removes a filter from the graph.

Syntax

HRESULT RemoveFilter(
    IBaseFilter *pFilter
);

Parameters

pFilter
[in] Pointer to the filter to be removed from the graph.

Return Value

Returns one of the following values.

S_OK | Success.
E_FAIL | Failure.
E_POINTER | Null pointer argument.

Remarks

The filter graph implementation informs the filter that it is being removed by calling the IBaseFilter::JoinFilterGraph method with a NULL argument. It is not necessary to disconnect the filter's pins before calling RemoveFilter, but the filter graph should be in the Stopped state. If the filters are not stopped, RemoveFilter may fail to disconnect the pins and then fail to remove the filter from the graph. IGraphConfig::RemoveFilterEx enables an application to remove a filter without disconnecting the pins automatically, which improves performance if you want to move groups of connected filters into a new graph.

IFilterGraph::SetDefaultSyncSource

IFilterGraph Interface

Sets the default source of synchronization.

Syntax

HRESULT SetDefaultSyncSource(void);

Return Value

Returns S_OK if successful. Otherwise, returns VFW_E_NOT_STOPPED (indicating that the graph is not in a stopped state) or another error value.

Remarks

This method is used when no clock has been given to the filter graph, and the filter graph manager must find a clock to use as the synchronization source. The filter graph manager tries all connected filters, starting with renderers, and selects the first one that provides an IReferenceClock interface. If no connected filters are found, the filter graph manager will select an unconnected filter that exports a clock. Typically, this will be the audio rendering filter. If no unconnected filter exports a clock, the filter graph manager creates a system clock.


IFilterGraph2 Interface

This interface extends the IFilterGraph and IGraphBuilder interfaces, which contain methods for building filter graphs.

The filter graph manager implements this interface. Applications can use it when building graphs, to take advantage of the additional methods it provides.

IFilterGraph2 adds two methods to IFilterGraph and IGraphBuilder.

  • The AddSourceFilterForMoniker method creates a source filter based on a moniker, and adds it to the graph.
  • The ReconnectEx method improves the IFilterGraph::Reconnect method by specifying a media type for the reconnection.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IFilterGraph methods | Description
AddFilter | Adds a filter to the graph and gives it a name.
RemoveFilter | Removes a filter from the graph.
EnumFilters | Provides an enumerator for all filters in the graph.
FindFilterByName | Finds a filter that was added with a specified name.
ConnectDirect | Connects two pins directly (without intervening filters).
Reconnect | Breaks the existing pin connection and reconnects it to the same pin.
Disconnect | Disconnects a specified pin.
SetDefaultSyncSource | Sets the default synchronization source (a clock).
IGraphBuilder methods | Description
Connect | Connects two pins. If they do not connect directly, this method connects them with intervening transforms.
Render | Adds a chain of filters to a specified output pin to render it.
RenderFile | Builds a filter graph that renders the specified file.
AddSourceFilter | Adds a source filter to the filter graph for a specific file. The IGraphBuilder::RenderFile method calls this to find the source filter.
SetLogFile | Sets the file for logging actions taken when attempting to perform an operation.
Abort | Requests that the graph builder return as soon as possible from its current task.
ShouldOperationContinue | Queries whether the current operation should continue.
IFilterGraph2 methods | Description
AddSourceFilterForMoniker | Adds a source filter based on a moniker.
ReconnectEx | Breaks the existing pin connection and reconnects it to the same pin, using a specified media type.

IFilterGraph2::AddSourceFilterForMoniker

IFilterGraph2 Interface

Adds a source filter based on a moniker. For example, you can obtain a moniker for a system device, such as a video capture device, and add a video capture filter for that device. (For more information about system device monikers, see ICreateDevEnum.)

Syntax

HRESULT AddSourceFilterForMoniker(
  IMoniker *pMoniker,
  IBindCtx *pCtx,
  LPCWSTR lpcwstrFilterName,
  IBaseFilter **ppFilter );

Parameters

pMoniker
[in] Pointer to an IMoniker interface.
pCtx
[in] Pointer to an IBindCtx bind context interface.
lpcwstrFilterName
[in] Pointer to the filter's name.
ppFilter
[out] Address of a pointer to an IBaseFilter interface.

Return Value

If the method succeeds, the return value is one of the following values.

S_OK | Success.
VFW_S_DUPLICATE_NAME | Successfully added a filter with a duplicate name.

If the method fails, the return value may be one of the following error values.

E_FAIL | Failure.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_DUPLICATE_NAME | Failed to add a filter with a duplicate name.
VFW_E_CANNOT_LOAD_SOURCE_FILTER | The source filter for could not be loaded.
VFW_E_UNKNOWN_FILE_TYPE | The media type of this file is not recognized.

Remarks

When adding a source filter for the given moniker to the graph, the COM IMoniker::BindToStorage member function will query for an IStream interface. If this fails, IMoniker::BindToObject will try to retrieve an IBaseFilter interface.

IFilterGraph2::ReconnectEx

IFilterGraph2 Interface

Breaks the existing pin connection and reconnects it to the same pin, using a specified media type.

Syntax

HRESULT ReconnectEx(

  IPin *ppin,

  const AM_MEDIA_TYPE *pmt );

Parameters

ppin
[in] Pointer to the pin to disconnect and reconnect.
pmt
[in] Pointer to the media type to reconnect with. Specify NULL to use the existing media type.

Return Value

S_OK | Success.
S_FALSE | Pin was not connected. No error.

If the method fails, the return value may be one of the following error values.

E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_STOPPED | The filter is not stopped, but it does not support reconnection while in a running state.

Remarks

Like the IFilterGraph::Reconnect method, the ReconnectEx method schedules a reconnection of the pin with the pin it is currently connected to. By specifying a media type when this method is called, the pins don't have to check what type they were originally connected with or enumerate possible new types. This makes the reconnection more likely to succeed.

See Also

IFilterGraph::Reconnect


IFilterInfo Interface

The IFilterInfo interface manages information about a filter and provides access to the filter and to the IPinInfo interfaces representing the pins on the filter. It is essentially an IBaseFilter interface that can be accessed through Automation. This was created to provide access to the IBaseFilter methods from Microsoft® Visual Basic® applications without incurring the overhead of Automation in the IBaseFilter interface itself.

This interface is implemented by the filter graph manager for use by Automation client applications, such as Microsoft Visual Basic.

Use this interface from an application to retrieve information about a filter and to retrieve individual pin objects in the filter or a collection of all pin objects belonging to the filter. This can be used when adding filters to a filter graph and connecting pins together.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether there is type information available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returned successfully.
GetIDsOfNames | Converts text names of properties and methods (including arguments) to their corresponding DISPIDs.
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IFilterInfo methods | Description
FindPin | Locates a pin and returns an IPinInfo interface.
get_Name | Retrieves the filter name.
get_VendorInfo | Retrieves a string containing optional information supplied by a vendor about the specified filter.
get_Filter | Retrieves the IBaseFilter interface for the filter.
get_Pins | Retrieves an IAMCollection interface which provides access to the IPinInfo interfaces for this filter.
get_IsFileSource | Determines if the filter is a file source filter.
get_Filename | Retrieves the file name associated with the source filter.
put_Filename | Sets the file name containing the media source.

IFilterInfo::FindPin

IFilterInfo Interface

Locates a pin, given an identifier, and returns an IPinInfo interface.

Syntax

HRESULT FindPin(
    BSTR strPinID,
    IDispatch **ppUnk
);

Parameters

strPinID
[in] String pin identifier.
ppUnk
[out] Address of a pointer to an IPinInfo interface.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values can include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method corresponds to the IBaseFilter::FindPin method. This method is exposed for use by Automation clients and is not expected to be used by C or C++ applications because of performance limitations.

IFilterInfo::get_Filename

IFilterInfo Interface

Retrieves the file name associated with the source filter.

Syntax

HRESULT get_Filename(
    BSTR *pstrFilename
);

Parameters

pstrFilename
[out, retval] Pointer to the name of the file containing the source media.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values can include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method is exposed for use by Automation clients and is not expected to be used by C or C++ applications because of performance limitations.

IFilterInfo::get_Filter

IFilterInfo Interface

Retrieves the IBaseFilter interface of the filter.

Syntax

HRESULT get_Filter(
    IUnknown **ppUnk
);

Parameters

ppUnk
[out, retval] Address of a pointer to the IBaseFilter interface of the filter represented by IFilterInfo.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values can include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

The object that implements IFilterInfo is a wrapper and is not the same COM object as the filter itself. Thus a call to IFilterInfo::QueryInterface for IBaseFilter will fail. The IFilterInfo::get_Filter method enables an application to obtain the filter object itself. This method is exposed for use by Automation clients and is not expected to be used by C or C++ applications because of performance limitations.

IFilterInfo::get_IsFileSource

IFilterInfo Interface

Determines if the filter is a file source filter.

Syntax

HRESULT get_IsFileSource(
    LONG *pbIsSource
);

Parameters

pbIsSource
[out, retval] Pointer to the returned value indicating whether the filter is a file source filter. Returns OATRUE if it is; otherwise, returns OAFALSE.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values can include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method is exposed for use by Automation clients and is not expected to be used by C or C++ applications because of performance limitations.

IFilterInfo::get_Name

IFilterInfo Interface

Retrieves the filter name.

Syntax

HRESULT get_Name(
    BSTR *strName
);

Parameters

strName
[out, retval] Pointer to the name of the filter.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values can include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method is exposed for use by Automation clients and is not expected to be used by C or C++ applications because of performance limitations.

IFilterInfo::get_Pins

IFilterInfo Interface

Retrieves an IAMCollection interface, which provides access to the IPinInfo interfaces for the pins on this filter.

Syntax

HRESULT get_Pins(
    IDispatch **ppUnk
);

Parameters

ppUnk
[out, retval] Address of a pointer to the IAMCollection interface.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values can include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method is exposed for use by Automation clients and is not expected to be used by C or C++ applications because of performance limitations. Visual Basic applications can enumerate the IPinInfo interfaces in the returned IAMCollection object by using the For Each ...Next syntax.

IFilterInfo::get_VendorInfo

IFilterInfo Interface

Retrieves a string containing optional information supplied by a vendor about the specified filter.

Syntax

HRESULT get_VendorInfo(
    BSTR *strVendorInfo
);

Parameters

strVendorInfo
[out, retval] Pointer to a string containing vendor information.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values can include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method is exposed for use by Automation clients and is not expected to be used by C or C++ applications because of performance limitations.

IFilterInfo::put_Filename

IFilterInfo Interface

Sets the file name containing the media source.

Syntax

HRESULT put_Filename(
    BSTR strFilename
);

Parameters

strFilename
[in] Name of the file for the source filter to read from.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values can include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

This method is exposed for use by Automation clients and is not expected to be used by C or C++ applications because of performance limitations.


IFilterMapper2 Interface

Registers and unregisters filters, and locates filters in the registry. The Filter Mapper helper object implements this interface.

Filters use this interface to register and unregister themselves. When the filter graph manager builds a filter graph, it uses this interface to look up filters and determine their characteristics. Applications can also use this interface to look up filters. For more information, see Using the Filter Mapper and How to Register DirectShow Filters.

Note This interface replaces the IFilterMapper interface. IFilterMapper2 adds support for filter categories, pin mediums, and pin categories. In addition, it combines filter registration into one method call.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IFilterMapper2 methods | Description
CreateCategory | Adds a new filter category to the registry.
UnregisterFilter | Removes filter information from the registry.
RegisterFilter | Adds filter information to the registry.
EnumMatchingFilters | Enumerates registered filters that meet specified requirements.

IFilterMapper2::CreateCategory

IFilterMapper2 Interface

Adds a new filter category to the registry.

Syntax

HRESULT CreateCategory(
    REFCLSID clsidCategory,
    DWORD dwCategoryMerit,
    LPCWSTR Description
);

Parameters

clsidCategory
[in] Class identifier (CLSID) of the new filter category.
dwCategoryMerit
[in] Merit value of the category. Categories with higher merit are enumerated first.
Description
[in] Descriptive name for the category.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

The filter graph manager initially skips all categories with a merit value less than or equal to MERIT_DO_NOT_USE, to speed up the graph-building process. Filter categories that should not be considered for playback should have a merit of MERIT_DO_NOT_USE or less.

A filter can appear in one or more categories (for example, Video Compressors) to restrict the search space.

IFilterMapper2::EnumMatchingFilters

IFilterMapper2 Interface

Enumerates registered filters that meet specified requirements.

Syntax

HRESULT EnumMatchingFilters(
    IEnumMoniker **ppEnum,
    DWORD dwFlags,
    BOOL bExactMatch,
    DWORD dwMerit,
    BOOL bInputNeeded,
    DWORD cInputTypes,
    const GUID *pInputTypes,
    const REGPINMEDIUM *pMedIn,
    const CLSID *pPinCategoryIn,
    BOOL bRender,
    BOOL bOutputNeeded,
    DWORD cOutputTypes,
    const GUID *pOutputTypes,
    const REGPINMEDIUM *pMedOut,
    const CLSID *pPinCategoryOut
);

Parameters

ppEnum
[out] Address of a pointer that receives the IEnumMoniker interface. If the method succeeds, use this interface pointer to retrieve filter monikers from the enumeration. Be sure to release the interface when you are done.
dwFlags
[in] Reserved, must be zero.
bExactMatch
[in] Boolean value indicating whether an exact match is required. See Remarks for more information.
dwMerit
[in] Minimum merit value.
bInputNeeded
[in] Boolean value indicating whether the filter must have an input pin. If the value is TRUE, the filter must have at least one input pin.
cInputTypes
[in] Number of input media types specified in pInputTypes.
pInputTypes
[in] Pointer to an array of GUID pairs that specify major types and subtypes, for the input pins to match. The size of the array is 2 * cInputTypes. The array can be NULL. Individual array members can be GUID_NULL, which matches any type.
pMedIn
[in] Pointer to a REGPINMEDIUM structure specifying the medium for the input pins. Set to NULL if not needed.
pPinCategoryIn
[in] Pointer to a GUID that specifies the input pin category. Set to NULL if not needed.
bRender
[in] Boolean value that specifies whether the filter must render its input. If TRUE, the specified filter must render input.
bOutputNeeded
[in] Boolean value specifying whether the filter must have an output pin. If TRUE, the filter must have at least one output pin.
cOutputTypes
[in] Number of input media types specified in pOutputTypes.
pOutputTypes
[in] Pointer to an array of GUID pairs that specify major types and subtypes, for the output pins to match. The size of the array is 2 * cOutputTypes. The array can be NULL. Individual array members can be GUID_NULL, which matches any type.
pMedOut
[in] Pointer to a REGPINMEDIUM structure specifying the medium for the output pins. Set to NULL if not needed.
pPinCategoryOut
[in] Pointer to a GUID that specifies the output pin category. Set to NULL if not needed.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success
E_FAIL | Failure
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

To find filters whose input pins match a given set of media types, declare an array with major-type GUIDs and subtype GUIDs ordered in pairs. Pass the array address in the pInputTypes parameter, and set the cInputTypes parameter equal to the number of pairs (that is, half the array size):

GUID arrayInTypes[2];
arrayInTypes[0] = MEDIATYPE_Video;
arrayInTypes[1] = GUID_NULL;

DWORD cInTypes = 1;

For output pins, pass a similar array in the pOutputTypes parameter, and specify the number of GUID pairs in the cOutputTypes parameter.

If the value of the bExactMatch parameter is TRUE, this method looks for filters that exactly match the values you specify for media type, pin category, and pin medium. If the value is FALSE, filters that register a value of NULL for any of these items are considered a match. (In effect, a NULL value in the registry acts as a wildcard.)

If you specify NULL for media type, pin category, or pin medium, any filter is considered a match for that parameter.

If a pin did not register any media types, this method will not consider it a match for the media type.

IFilterMapper2::RegisterFilter

IFilterMapper2 Interface

Adds filter information to the registry.

Syntax

HRESULT RegisterFilter(
    REFCLSID clsidFilter,
    LPCWSTR Name,
    IMoniker **ppMoniker,
    const CLSID *pclsidCategory,
    const OLECHAR *szInstance,
    const REGFILTER2 *prf2
);

Parameters

clsidFilter
[in] Class identifier (CLSID) of the filter.
Name
[in] Descriptive name for the filter.
ppMoniker
[in, out] Address of a pointer to a device moniker that determines where this filter's data will be written. Can be NULL.
pclsidCategory
[in] Pointer to the filter category of the filter. If NULL, the default category is CLSID_ActiveMovieFilters.
szInstance
[in] Instance data for constructing the device moniker's display name. Can be the friendly name, or the string representation of the filter CLSID. If NULL, defaults to the filter CLSID.
prf2
[in] Pointer to a REGFILTER2 structure containing filter information.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_BAD_KEY | Could not get registry key.

Remarks

This method adds information about the filter to the registry, under the registry entry for the specified filter category. It does not register the in-process server that creates the filter (usually a DLL). To register the server, you can call the AMovieDllRegisterServer2 function.

For the ppMoniker parameter, use one of the following:

  • The address of an IMoniker interface pointer for an existing device moniker
  • The address of a NULL IMoniker interface pointer
  • NULL

If you are registering a filter for a Windows Driver Model (WDM) or Plug and Play device, pass the address of the existing device moniker. The filter will be registered using this moniker. When the method returns, *ppMoniker is set to NULL.

Otherwise, the method creates a new moniker. If ppMoniker is non-NULL, the method sets *ppMoniker to point to the new moniker. The application can use this moniker to write additional private values in the property bag. Be sure to release the interface.

Set ppMoniker to NULL if you don't want to provide or receive the moniker.

IFilterMapper2::UnregisterFilter

IFilterMapper2 Interface

Removes filter information from the registry.

Syntax

HRESULT UnregisterFilter(
    const CLSID *pclsidCategory,
    const OLECHAR *szInstance,
    REFCLSID Filter
);

Parameters

pclsidCategory
[in] Pointer to the filter category from which to remove the filter.
szInstance
[in] Instance data used to construct the device moniker's display name. Use the value that was originally passed to the RegisterFilter method.
Filter
[in] Class identifier (CLSID) of the filter.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

If the filter was not registered, the method might return an error.


IFullScreenVideo Interface

The IFullScreenVideo interface is implemented on the Full Screen Renderer filter. The filter graph manager uses the Full Screen Renderer to render full-screen video on systems with older graphics cards that can not quickly stretch a 320x240 video to 1024x768. To overcome this hardware limitation, the Full Screen Renderer simply switches the graphics display card into 320x240 mode. Newer video cards can stretch the display quickly enough to permit the Video Renderer filter to be used for both windowed and full-screen modes. The display goes into full-screen mode when an application calls IVideoWindow::put_FullScreenMode and returns to normal window playback when the user presses the Escape key.

When connected, the Full Screen Renderer loads the display modes that are available. This number of modes available can be obtained through IFullScreenVideo::CountModes. Information on each individual mode is then available by calling IFullScreenVideo::GetModeInfo and IFullScreenVideo::IsModeAvailable. An application can enable and disable any mode by calling the IFullScreenVideo::SetEnabled method. The current value can be queried by calling IFullScreenVideo::IsModeEnabled. An application can enable or disable any mode by calling the IFullScreenVideo::SetEnabled flag with OATRUE or OAFALSE (not C/C++ TRUE and FALSE values).

The Full Screen Renderer can function only when it is the foreground active window. If the user tries to switch to another application while in full-screen mode, the video will be hidden. The Full Screen Renderer does this by minimizing the window it is actually drawing the video in (although the use of a window is transparent to the user). Maximizing the window restores the video.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IFullScreenVideo methods | Description
CountModes | Retrieves the number of modes available on the Full Screen Renderer.
GetModeInfo | Retrieves information about a specified mode.
GetCurrentMode | Retrieves the video mode currently in effect.
IsModeAvailable | Determines if a specified video mode is available.
IsModeEnabled | Determines if a specified video mode is enabled.
SetEnabled | Enables and disables video modes.
GetClipFactor | Retrieves the current clip loss factor setting.
SetClipFactor | Specifies the video mode based on the maximum image area that will be lost.
SetMessageDrain | Specifies a window that will receive window messages sent to the renderer.
GetMessageDrain | Retrieves the window set to receive window messages sent to the renderer.
SetMonitor | Sets the monitor in use (for use with multiple-monitor implementations).
GetMonitor | Retrieves the monitor in use.
HideOnDeactivate | Hides the window when it is deactivated.
IsHideOnDeactivate | Retrieves the state of the HideOnDeactivate property.
SetCaption | Sets the caption associated with the full-screen window.
GetCaption | Retrieves the caption associated with the full-screen window.
SetDefault | Sets the default for all full-screen video renderer properties.

IFullScreenVideo::CountModes

IFullScreenVideo Interface

Retrieves the number of modes available on the Full Screen Renderer.

Syntax

HRESULT CountModes(
    long *pModes
);

Parameters

pModes
[out] Pointer to the returned mode count.

Return Value

Returns an HRESULT value.

Remarks

The DirectShow Full Screen Renderer supports eight modes (320 × 200 × 8/16 bit, 320 × 240 × 8/16, 640 × 400 × 8/16, and 640 × 480 × 8/16). The lower-resolution modes are always chosen over the higher modes. An application can enable and disable specific modes to more accurately specify which ones are available for use. A slightly less fine-grained mechanism to affect the selected mode is available through the clip loss factor.

IFullScreenVideo::GetCaption

IFullScreenVideo Interface

Retrieves the caption associated with the full-screen window.

Syntax

HRESULT GetCaption(
    BSTR *pstrCaption
);

Parameters

pstrCaption
[out] Pointer to the retrieved caption.

Return Value

Returns an HRESULT value.

Remarks

The DirectShow Full Screen Renderer will show itself as an icon when it is deactivated (you can deactivate it by pressing ALT+TAB to switch away from it). The text caption for the icon can be set through this method. If the renderer is supposed to hide itself when deactivated, this method will succeed, although it will have no use because the window will never be shown as an icon.

IFullScreenVideo::GetClipFactor

IFullScreenVideo Interface

Retrieves the current clip loss factor setting.

Syntax

HRESULT GetClipFactor(
    long *pClipFactor
);

Parameters

pClipFactor
[out] Pointer to the maximum allowable amount of the image to lose.

Return Value

Returns an HRESULT value.

Remarks

For a description of the clip loss factor setting, see IFullScreenVideo::SetClipFactor.

IFullScreenVideo::GetCurrentMode

IFullScreenVideo Interface

Retrieves the video mode currently in effect.

Syntax

HRESULT GetCurrentMode(
    long *pMode
);

Parameters

pMode
[out] Pointer to the retrieved full-screen video mode.

Return Value

Returns an HRESULT value.

Remarks

When the full-screen video renderer is connected, it chooses a display mode to use for video playback. The selected mode can be retrieved through this method. The details for that mode can then be retrieved by using IFullScreenVideo::GetModeInfo.

For a list of available modes for the DirectShow full-screen video renderer, see IFullScreenVideo::SetEnabled.

IFullScreenVideo::GetMessageDrain

IFullScreenVideo Interface

Retrieves the window set to receive window messages sent to the renderer.

Syntax

HRESULT GetMessageDrain(
    HWND *hwnd
);

Parameters

hwnd
[out] Pointer to the window handle of the window specified as the message drain.

Return Value

Returns an HRESULT value.

Remarks

The full-screen video renderer posts all mouse and keyboard messages it receives to the window designated as a message drain, with the message parameters untranslated. The exact list of messages passed is the same as for IVideoWindow::put_MessageDrain. An application can use this to implement hot-key support for full-screen video. For example, it might watch for the CTRL+P key combination as a cue to pause the video.

IFullScreenVideo::GetModeInfo

IFullScreenVideo Interface

Retrieves information about a specified mode.

Syntax

HRESULT GetModeInfo(
    long Mode,
    long *pWidth,
    long *pHeight,
    long *pDepth
);

Parameters

Mode
[in] Specified mode for which to retrieve information.
pWidth
[out] Pointer to the width, in pixels, of the mode's image display.
pHeight
[out] Pointer to the height, in pixels, of the mode's image display.
pDepth
[out] Pointer to the number of color bits per pixel.

Return Value

Returns an HRESULT value.

Remarks

This method returns the height, width, and color depth for a given mode that the renderer has available. The number of display modes available can be retrieved through IFullScreenVideo::CountModes.

For a list of modes available to the DirectShow full-screen video renderer, see IFullScreenVideo::SetEnabled.

IFullScreenVideo::GetMonitor

IFullScreenVideo Interface

Retrieves the monitor type in use.

Syntax

HRESULT GetMonitor(
    long *Monitor
);

Parameters

Monitor
[out] Pointer to the monitor currently in use.

Return Value

Returns NOERROR.

Remarks

The DirectShow Full Screen Renderer always returns zero (the primary monitor).

IFullScreenVideo::HideOnDeactivate

IFullScreenVideo Interface

Hides the window icon when the full-screen window is deactivated.

Syntax

HRESULT HideOnDeactivate(
    long Hide
);

Parameters

Hide
[in] Value specifying whether to hide the video window icon when the full-screen window is deactivated. Set to OATRUE to hide the icon; set to OAFALSE to display the icon.

Return Value

Returns NOERROR if successful and E_INVALIDARG if Hide is invalid.

Remarks

The default setting for the DirectShow Full Screen Renderer is OATRUE.

The Full Screen Renderer can function only when it is the foreground active window. If the user tries to switch to another application while in full-screen mode, the video will be hidden. The renderer does this by minimizing the window it is actually drawing the video in (although the use of a window is transparent to the user). Maximizing the window restores the video. If this property is set, the window will be hidden rather than minimized.

IFullScreenVideo::IsHideOnDeactivate

IFullScreenVideo Interface

Retrieves the state of the IFullScreenVideo::HideOnDeactivate property.

Syntax

HRESULT IsHideOnDeactivate(void);

Return Value

Returns S_OK if HideOnDeactivate is set to OATRUE or S_FALSE if it is set to OAFALSE.

IFullScreenVideo::IsModeAvailable

IFullScreenVideo Interface

Determines if a specified video mode is available.

Syntax

HRESULT IsModeAvailable(
    long Mode
);

Parameters

Mode
[in] Full-screen mode to check.

Return Value

Returns S_OK if the video mode is available or S_FALSE if it isn't.

Remarks

The display modes supported by the Full Screen Renderer are different than the actual modes available on any given display card. The application should call this method only when the renderer is connected, because until then the renderer might not have allocated the resources it needs to make this information available. Even if a mode is available, it will not necessarily be used for video playback; the mode must also be compatible with the filters in the filter graph.

IFullScreenVideo::IsModeEnabled

IFullScreenVideo Interface

Determines if a specified mode is enabled.

Syntax

HRESULT IsModeEnabled(
    long Mode
);

Parameters

Mode
[in] Full-screen video mode to check.

Return Value

Returns S_OK if the video mode is enabled or S_FALSE if it isn't.

Remarks

You can use this method to enable and disable specific display modes supported by the renderer. Even if a mode is enabled, it will not necessarily be used for video playback; the mode must also be compatible with the filters in the filter graph.

For a list of available modes for the DirectShow full-screen video renderer, see IFullScreenVideo::SetEnabled.

See Also

IFullScreenVideo::IsModeAvailable

IFullScreenVideo::SetCaption

IFullScreenVideo Interface

Sets the title associated with the full-screen window.

Syntax

HRESULT SetCaption(
    BSTR strCaption
);

Parameters

strCaption
[in] String containing the caption.

Return Value

Returns an HRESULT value.

IFullScreenVideo::SetClipFactor

IFullScreenVideo Interface

Specifies the video mode based on the maximum data that will be lost.

Syntax

HRESULT SetClipFactor(
    long ClipFactor
);

Parameters

ClipFactor
[in] Maximum allowable amount of the image to lose.

Return Value

Returns an HRESULT value.

Remarks

Clip loss factor is a means of enabling full-screen modes that is more generic and easier for applications to use. This method defines the amount of video that can be lost when deciding which display mode to use. For example, assuming the decoder cannot compress the video, playing an MPEG file (say 352 × 288 pixels) into a 320 × 200 display will lose about 25 percent of the image. The clip loss factor specifies the upper range permissible. To allow typical QCIF-sized MPEG video (352 × 288 pixels) to be played in a 320 × 200 display mode, it defaults to 25 percent.

IFullScreenVideo::SetDefault

IFullScreenVideo Interface

Sets the default full-screen video renderer settings.

Syntax

HRESULT SetDefault(void);

Return Value

Returns an HRESULT value.

Remarks

The properties set through this interface apply only to the current renderer instance. They can, however, be made the global default by calling this interface method.

IFullScreenVideo::SetEnabled

IFullScreenVideo Interface

Enables and disables video modes.

Syntax

HRESULT SetEnabled(
    long Mode,
    long bEnabled
);

Parameters

Mode
[in] Mode to be enabled or disabled (see the following table).
bEnabled
[out] Can be set to one of the following values.
OATRUE | Enable mode.
OAFALSE | Disable mode.

Return Value

Returns an HRESULT value.

Remarks

Available DirectShow modes are defined as follows. The ordering of these modes is subject to change, so use IFullScreenVideo::CountModes and IFullScreenVideo::GetModeInfo interface methods to enumerate modes.
Mode | Width | Height | RGB depth (in bits)
0 | 320 | 200 | 16
1 | 320 | 200 | 8
2 | 320 | 240 | 16
3 | 320 | 240 | 8
4 | 640 | 400 | 16
5 | 640 | 400 | 8
6 | 640 | 480 | 16
7 | 640 | 480 | 8
8 | 800 | 600 | 16
9 | 800 | 600 | 8
10 | 1024 | 768 | 16
11 | 1024 | 768 | 8
12 | 1152 | 864 | 16
13 | 1152 | 864 | 8
14 | 1280 | 1024 | 16
15 | 1280 | 1024 | 8

IFullScreenVideo::SetMessageDrain

IFullScreenVideo Interface

Specifies a window that will receive window messages sent to the renderer.

Syntax

HRESULT SetMessageDrain(
    HWND hwnd
);

Parameters

hwnd
[in] Window handle of the message drain window.

Return Value

Returns an HRESULT value.

Remarks

The full-screen video renderer posts all mouse and keyboard messages it receives to the window designated as a message drain, with the message parameters untranslated. The exact list of messages passed is the same as for IVideoWindow::put_MessageDrain. An application can use this to implement hot-key support for full-screen video. For example, it might watch for the CTRL+P key combination as a cue to pause the video.

IFullScreenVideo::SetMonitor

IFullScreenVideo Interface

Sets the monitor type in use.

Syntax

HRESULT SetMonitor(
    long Monitor
);

Parameters

Monitor
[in] Monitor currently in use.

Return Value

Returns an HRESULT value.

Remarks

Setting this method to anything but the primary display (0) will return an error. In future versions of DirectShow, the renderer might allow applications to select the monitor on which to play back the full-screen video.


IGraphBuilder Interface

This interface provides methods that enable an application to build a filter graph. The filter graph manager implements this interface.

IGraphBuilder inherits from the IFilterGraph interface. IFilterGraph provides basic operations, such as adding a filter to the graph or connecting two pins. IGraphBuilder adds further methods that construct graphs from partial information. For example, the RenderFile method builds a graph for file playback, given the name of the file. The Render method renders data from an output pin by connecting new filters to the pin.

Using these methods, an application does not need to specify every filter and every pin connection in the graph. Instead, the filter graph manager selects filters that are registered on the user's system, introduces them into the graph, and connects them. Internally, it uses the filter mapper to look up filters in the registry. For more information, see IFilterMapper2.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IFilterGraph methods | Description
AddFilter | Adds a filter to the graph and gives it a name.
RemoveFilter | Removes a filter from the graph.
EnumFilters | Provides an enumerator for all filters in the graph.
FindFilterByName | Finds a filter that was added with a specified name.
ConnectDirect | Connects two pins directly (without intervening filters).
Reconnect | Breaks the existing pin connection and reconnects it to the same pin.
Disconnect | Disconnects a specified pin.
SetDefaultSyncSource | Sets the default synchronization source (a clock).
IGraphBuilder methods | Description
Connect | Connects two pins. If they will not connect directly, this method connects them with intervening transforms.
Render | Adds a chain of filters to a specified output pin to render it.
RenderFile | Builds a filter graph that renders the specified file.
AddSourceFilter | Adds a source filter to the filter graph for a specific file.
SetLogFile | Sets the file for logging actions taken when attempting to perform an operation.
Abort | Requests that the graph builder return as soon as possible from its current task.
ShouldOperationContinue | Queries whether the current operation should continue.

IGraphBuilder::Abort

IGraphBuilder Interface

Requests that the graph builder return as soon as possible from its current task.

The current task may or may not fail to complete. It is possible that the fastest way for the graph builder to return from its current task is to complete it.

Syntax

HRESULT Abort(void);

Return Value

Returns S_OK.

IGraphBuilder::AddSourceFilter

IGraphBuilder Interface

Adds a source filter to the filter graph for a specific file. The IGraphBuilder::RenderFile method calls this to find the source filter.

Syntax

HRESULT AddSourceFilter(
    LPCWSTR lpwstrFileName,
    LPCWSTR lpwstrFilterName,
    IBaseFilter **ppFilter
);

Parameters

lpwstrFileName
[in] Pointer to the file.
lpwstrFilterName
[in] Pointer to the name to give the source filter when it is added.
ppFilter
[out] Address of a pointer to an IBaseFilter interface on the filter that was added.

Return Value

Returns an HRESULT. Possible values include the following.

S_OK | Success.
E_NOINTERFACE | Source filter does not support IFileSourceFilter interface.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_CANNOT_LOAD_SOURCE_FILTER | The source filter for this file could not be loaded.
VFW_E_NOT_FOUND | An object or name was not found.
VFW_E_UNKNOWN_FILE_TYPE | The media type of this file is not recognized.

Remarks

This method enables you to obtain and retain more control over building the rest of the graph. For example, you can use the IFilterGraph::AddFilter method to add a renderer of your choice, and then use the IGraphBuilder::Connect method to connect the two filters. The IBaseFilter interface exposed by the source filter is returned in the ppFilter parameter, and the reference is already added by the IUnknown::AddRef method. The lpwstrFilterName parameter is used to allow the filter to be identified by this name in this filter graph. For more information, see FindFilterByName.

It is the application's responsibility to find the output pin of the added source filter in order to build the rest of the filter graph, which can be done by calling IGraphBuilder::Render on the output pin, to build the entire filter graph automatically, or by adding and connecting filters individually. When adding filters individually, the asynchronous file reader source filter and the URL moniker source filter do not parse the data, so the output pins of these source filters can be connected only to a parser filter, such as the MPEG splitter filter.

The IGraphBuilder::RenderFile method adds the same source filter.

IGraphBuilder::Connect

IGraphBuilder Interface

Connects the two pins, using intermediates if necessary.

Syntax

HRESULT Connect(
    IPin *ppinOut,
    IPin *ppinIn
);

Parameters

ppinOut
[in] Pointer to the output pin.
ppinIn
[in] Pointer to the input pin.

Return Value

Returns an HRESULT. Possible values include the following.

S_OK | Success.
VFW_S_PARTIAL_RENDER | Some of the streams in this movie are in an unsupported format.
E_ABORT | Operation aborted.
E_POINTER | NULL pointer argument.
VFW_E_CANNOT_CONNECT | No combination of intermediate filters could be found to make the connection.
VFW_E_NOT_IN_GRAPH | Cannot perform the requested function on an object that is not in the filter graph.

Remarks

This method connects these two pins directly or indirectly, using transform filters if necessary. The method either succeeds or leaves the filter graph unchanged. The filter graph manager attempts a direct connection. If that fails, it attempts to use any available transforms provided by filters that are already in the filter graph. (It enumerates these in an arbitrary order.) If that fails, it attempts to find filters from the registry to provide a transform. These will be tried in order of merit.

During the connection process, the filter graph manager ignores pins on intermediate filters if the pin name begins with a tilde (~). For more information, see PIN_INFO.

IGraphBuilder::Render

IGraphBuilder Interface

Builds a filter graph that renders the data from this output pin.

Syntax

HRESULT Render(
    IPin *ppinOut
);

Parameters

ppinOut
[in] Pointer to the output pin.

Return Value

Returns an HRESULT. Possible values include the following.

S_OK | Success.
VFW_S_AUDIO_NOT_RENDERED | Cannot play back the audio stream: could not find a suitable renderer.
VFW_S_DUPLICATE_NAME | An attempt to add a filter with a duplicate name succeeded with a modified name.
VFW_S_PARTIAL_RENDER | Some of the streams in this movie are in an unsupported format.
VFW_S_VIDEO_NOT_RENDERED | Cannot play back the video stream: could not find a suitable renderer.
E_ABORT | Operation aborted.
E_POINTER | NULL pointer argument.
VFW_E_CANNOT_CONNECT | No combination of intermediate filters could be found to make the connection.
VFW_E_CANNOT_RENDER | No combination of filters could be found to render the stream.
VFW_E_NO_ACCEPTABLE_TYPES | There is no common media type between these pins.
VFW_E_NOT_IN_GRAPH | Cannot perform the requested function on an object that is not in the filter graph.

Remarks

This method connects this output pin directly or indirectly to a filter or filters that will render it, using transform filters as intermediary filters if necessary. Filters are tried in the same order as for the IGraphBuilder::Connect method.

During the connection process, the filter graph manager ignores pins on intermediate filters if the pin name begins with a tilde (~). For more information, see PIN_INFO.

IGraphBuilder::RenderFile

IGraphBuilder Interface

Builds a filter graph that renders the specified file.

Syntax

HRESULT RenderFile(
    LPCWSTR lpwstrFile,
    LPCWSTR lpwstrPlayList
);

Parameters

lpwstrFile
[in] Pointer to the name of the file, or the moniker of a capture device, containing the data to be rendered.
lpwstrPlayList
[in] Reserved. Must be NULL.

Return Value

Returns an HRESULT. Possible values include the following.

S_OK | Success.
VFW_S_AUDIO_NOT_RENDERED | Cannot play back the audio stream: could not find a suitable renderer.
VFW_S_DUPLICATE_NAME | An attempt to add a filter with a duplicate name succeeded with a modified name.
VFW_S_PARTIAL_RENDER | Some of the streams in this movie are in an unsupported format.
VFW_S_VIDEO_NOT_RENDERED | Cannot play back the video stream: could not find a suitable renderer.
E_ABORT | Operation aborted.
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_CANNOT_CONNECT | No combination of intermediate filters could be found to make the connection.
VFW_E_CANNOT_LOAD_SOURCE_FILTER | The source filter for this file could not be loaded.
VFW_E_CANNOT_RENDER | No combination of filters could be found to render the stream.
VFW_E_INVALID_FILE_FORMAT | The file format is invalid.
VFW_E_NOT_FOUND | An object or name was not found.
VFW_E_NOT_IN_GRAPH | Cannot perform the requested function on an object that is not in the filter graph.
VFW_E_UNKNOWN_FILE_TYPE | The media type of this file is not recognized.
VFW_E_UNSUPPORTED_STREAM | Cannot play back the file: the format is not supported.

Remarks

This method adds a source filter that can handle the specified file. Then it renders the output pins on the source filter, adding intermediate filters if necessary. Filters are tried in the same order as for the IGraphBuilder::Connect method.

During the connection process, the filter graph manager ignores pins on intermediate filters if the pin name begins with a tilde (~). For more information, see PIN_INFO.

To determine the media type and compression scheme of the specified file, the Filter Graph Manager reads the first few bytes of the file, looking for file signatures as documented in the Registering a Custom File Type article.

The lpwstrFile parameter can specify a GraphEdit (.grf) file. The filter graph manager loads the graph from the .grf file.

The lpwstrFile parameter can also specify a device moniker for a capture device such as a USB camera or a DV camcorder. The filter graph manager creates a simple preview graph.

IGraphBuilder::SetLogFile

IGraphBuilder Interface

Sets the file for logging actions taken when attempting to perform an operation.

Syntax

HRESULT SetLogFile(
    HANDLE hFile
);

Parameters

hFile
Handle to the log file.

Return Value

Returns S_OK.

Remarks

This method is for use in debugging; it is intended to help you determine the cause of any failure to automatically build a filter graph.

The hFile parameter must be an open file handle. Your application is responsible for opening the file and for closing it when you are done logging. Before closing the file handle, call SetLogFile with a NULL file handle. This will ensure that the component does not attempt to use the file handle after you have closed it.

IGraphBuilder::ShouldOperationContinue

IGraphBuilder Interface

Queries whether the current operation should continue. A filters that is performing some operation at the request of the graph can call this method to determine whether it should continue. Applications will not normally call this method.

Syntax

HRESULT ShouldOperationContinue(void);

Return Value

Returns an HRESULT. Possible values include the following.

S_OK | The current operation should continue.
S_FALSE | The current operation should not continue.
E_UNEXPECTED | Unexpected error.


IGraphConfig Interface

The Filter Graph Manager exposes IGraphConfig to support dynamic graph building. This interface enables applications and filters to reconfigure the filter graph while the graph is in a running state, and without losing data from the stream.

The most straightforward way to rebuild the graph dynamically is to call the Reconnect method. This method handles most of the details of dynamically rebuilding the graph. If a situation ever arises where you want to implement your own technique, IGraphConfig also provides the Reconfigure method. This method obtains a lock on the filter graph and then calls a callback function in your application, which reconfigures the graph. With this method, most of the work is shifted to your application. For more information, see Dynamic Graph Building.

To optimize the process of adding and removing filters, the filter graph maintains a cache of filters. During a call to the Reconnect method, you can specify that any filters removed from the graph get added to the cache. You can also add a filter to the cache directly, if you know it is likely to be needed, by calling AddFilterToCache. The IGraphBuilder::Render, IGraphBuilder::RenderFile, and IGraphBuilder::Connect methods automatically try to use filters in the cache before using other filters. Also, in the Reconnect method you can specify that only cached filters will be used for the reconnection. Note that filters held in the cache are not actually part of the graph. They are disconnected from any pins and are kept in a stopped state.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IGraphConfig methods | Description
Reconnect | Performs a dynamic reconnection between two pins.
Reconfigure | Locks the filter graph and calls a callback function in the application or filter to perform a dynamic reconfiguration.
AddFilterToCache | Adds a filter to the filter cache.
RemoveFilterFromCache | Removes a filter from the filter cache.
EnumCacheFilter | Enumerates the filters in the filter cache.
GetStartTime | Retrieves the reference time used when the filter graph was last put into a running state.
PushThroughData | Pushes data through the filter graph to the specified pin.
SetFilterFlags | Sets a filter's configuration information.
GetFilterFlags | Retrieves a filter's configuration information.
RemoveFilterEx | Removes a filter from the filter graph.

IGraphConfig::AddFilterToCache

IGraphConfig Interface

Adds a filter to the filter cache.

Syntax

HRESULT AddFilterToCache(
    IBaseFilter *pFilter
);

Parameters

pFilter
[in] Pointer to the IBaseFilter interface of the filter.

Return Value

Returns one of the following HRESULT values.

E_FAIL | Failure.
E_POINTER | Null pointer argument.
S_FALSE | Filter is already in the cache.
S_OK | Filter was added to the cache.

Remarks

You must disconnect all of the filter's pins before calling this method, or the method will fail. If the filter is in the filter graph, this method will remove it. This method will also put the filter into a stopped state, if it is not already.

IGraphConfig::EnumCacheFilter

IGraphConfig Interface

Enumerates the filters in the filter cache.

Syntax

HRESULT EnumCacheFilter(
    IEnumFilters **pEnum
);

Parameters

pEnum
[out] Address of a pointer to the IEnumFilters interface on the filter enumerator.

Return Value

Returns one of the following HRESULT values.

E_OUTOFMEMORY | Failed to allocate necessary memory.
E_POINTER | Null pointer argument.
S_OK | Success.

IGraphConfig::GetFilterFlags

IGraphConfig Interface

Retrieves a filter's configuration information.

Syntax

HRESULT GetFilterFlags(
    IBaseFilter *pFilter,
    DWORD *pdwFlags
);

Parameters

pFilter
[in] Pointer to a filter in the filter graph.
pdwFlags
[out] Pointer to a variable of type DWORD that receives the current configuration flags.

Return Value

Returns one of the following HRESULT values.

E_POINTER | Null pointer argument.
S_OK | Success.
VFW_E_NOT_IN_GRAPH | The filter is not in the graph.

See Also

SetFilterFlags

IGraphConfig::GetStartTime

IGraphConfig Interface

Retrieves the reference time that was used when the filter graph was last put into a running state.

Syntax

HRESULT GetStartTime(
    REFERENCE_TIME *prtStart
);

Parameters

prtStart
[out] Pointer to a variable that receives the start time.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
VFW_E_WRONG_STATE | Filter graph is not in a running state.

Remarks

The filter graph must currently be in a running state or this method will fail.

IGraphConfig::PushThroughData

IGraphConfig Interface

Pushes data through the filter graph to the specified pin.

Syntax

HRESULT PushThroughData(
    IPin *pOutputPin,
    IPinConnection *pConnection,
    HANDLE hEventAbort
);

Parameters

pOutputPin
[in] Pointer to an output pin in the filter graph.
pConnection
[in] Pointer to an input pin in the filter graph, or NULL.
hEventAbort
[in] Handle to an event. If the caller is a filter calling on one of its data processing threads, this parameter should be a handle to an event that will be signaled when the filter is put into a stopped state. Otherwise, this parameter can be NULL. For more information, see Remarks.

Return Value

Returns S_OK if successful. Otherwise, returns an error code that may be one of the following values, or others not listed.

E_OUTOFMEMORY | Failed to allocate necessary memory.
VFW_E_NOT_FOUND | Could not find a candidate input pin.
VFW_E_STATE_CHANGED | Filter state changed during the operation.

Remarks

This method pushes through any pending data, from a specified output pin down to a specified input pin. Optionally, you can leave the input pin unspecified and let the method search the filter graph for the best candidate. Do not call this method from the thread that is pushing data.

If a filter calls this method on one of its own data processing threads, it creates the potential for a deadlock. The method obtains a lock on the filter graph, which can block the filter from stopping on receiving a call to IMediaFilter::Stop. To prevent this situation, the method takes a handle to an event object provided by the filter. The filter should signal the event if it receives a call to its Stop method.

IGraphConfig::Reconfigure

IGraphConfig Interface

Locks the filter graph and calls a callback function in the application or filter to perform a dynamic reconfiguration.

Syntax

HRESULT Reconfigure(
    IGraphConfigCallback *pCallback,
    PVOID pvContext,
    DWORD dwFlags,
    HANDLE hAbortEvent
);

Parameters

pCallback
[in] Pointer to the IGraphConfigCallback callback interface on the application or filter.
pvContext
[in] Pointer to a variable of type PVOID that is passed to the callback routine.
dwFlags
[in] Application-defined flags that are passed to the callback routine.
hAbortEvent
[in] Handle to an event. If the caller is a filter calling on one of its data processing threads, this parameter should be a handle to an event that will be signaled when the filter is put into a stopped state. Otherwise, this parameter can be NULL. For more information, see Remarks.

Return Value

Returns S_OK if successful, or an error code otherwise. Possible errors include VFW_E_WRONG_STATE, if the method could not obtain a lock on the filter graph; whatever HRESULT was returned by the callback routine; or an error code indicating that the graph could not put the filters into a running state.

Remarks

This method is provided so that an application or filter can implement specialized dynamic graph building. In most cases, however, the IGraphConfig::Reconnect method is adequate, and should be preferred because it handles most of the implementation details.

Before calling this method, block any streams as needed and push the data through the graph (see IPinFlowControl::Block and IGraphConfig::PushThroughData). If the callback method succeeds, IGraphConfig::Reconfigure attempts to put all the filters into a running state. (The caller must then unblock the data flow.) Otherwise, it returns whatever error code the callback method returned.

If a filter calls this method on one of its own data processing threads, it creates the potential for a deadlock. The method obtains a lock on the filter graph, which can block the filter from stopping on receiving a call to IMediaFilter::Stop. To prevent this situation, the method takes a handle to an event object provided by filter. The filter should signal the event if it receives a call to its Stop method.

IGraphConfig::Reconnect

IGraphConfig Interface

Performs a dynamic reconnection between two pins.

Syntax

HRESULT Reconnect(
    IPin *pOutputPin,
    IPin *pInputPin,
    const AM_MEDIA_TYPE *pmtFirstConnection,
    IBaseFilter *pUsingFilter,
    HANDLE hAbortEvent,
    DWORD dwFlags
);

Parameters

pOutputPin
[in] Pointer to an output pin. Can be NULL, in which case pInputPin must not be NULL.
pInputPin
[in] Pointer to an input pin. Can be NULL, in which case pOutputPin must not be NULL.
pmtFirstConnection
[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type for the first pin connection made during the reconnection. If this parameter is NULL, the first connection can have any media type.
pUsingFilter
[in] Pointer to an optional filter to use in the reconnection. The filter must already be in the graph. Can be NULL.
hAbortEvent
[in] Handle to an event. If the caller is a filter calling on one of its data processing threads, this parameter should be a handle to an event that will be signaled when the filter is put into a stopped state. Otherwise, this parameter can be NULL. For more information, see Remarks.
dwFlags
[in] Combination of flags from the AM_GRAPH_CONFIG_RECONNECT_FLAGS enumeration, specifying how to perform the reconnection.

Return Value

Returns S_OK if successful. Otherwise, returns an error code that may be one of the following values, or others not listed.

E_INVALIDARG | Invalid argument. (For example, both pInputPin and pOutputPin are NULL.)
E_NOINTERFACE | Input pin does not support IPinConnection.
VFW_E_CANNOT_CONNECT | Unable to connect filter.
VFW_E_STATE_CHANGED | The state of the filter changed. Unable to complete the operation.

Remarks

If you specify only one pin, the method will search for the other pin. By default, however, the search fails if it reaches a filter that was added to the graph by means of the IFilterGraph::AddFilter method. To override this behavior, call IGraphConfig::SetFilterFlags and set the AM_FILTER_FLAGS_REMOVABLE flag on the filter.

The reconnection process involves several steps, most of them handled inside this method:

  1. First, before calling the method, make sure to block the flow of data along the path that is being reconfigured. Applications should call the IPinFlowControl::Block method to do this. If the caller is a filter, rather than an application, possibly the filter can control the data flow internally.
  2. The specified output and input pins define the starting and ending points for the reconnection. The input pin must support the IPinConnection interface. If you leave one of these pins unspecified (by passing a NULL parameter), the method searches the filter graph to find a candidate pin for reconnection. (To find an input pin, it searches downstream from the output pin; to find an output pin, it searches upstream from the input pin.)
  3. The method pushes any pending data through the filter graph (through an internal call to PushThroughData).
  4. If you have specified a filter to insert into the graph, the method connects the starting output pin to the filter's input pin, and connects the filter's output pin to the final input pin. If you do not specify a filter, the method simply connects the output pin to the input pin. In either case, the method inserts any transform filters required to complete the connections. (However, you can override this behavior by setting the appropriate flag; for more information see the description of the dwFlags parameter.)
  5. Finally, the method places the new filters into a running state. It is up to the caller to restart the data flow. Applications can do this by calling IPinFlowControl::Block with no flags.

If a filter calls this method on one of its own data processing threads, it creates the potential for a deadlock. The method obtains a lock on the filter graph, which can block the filter from stopping on receiving a call to IMediaFilter::Stop. To prevent this situation, the method takes a handle to an event object provided by filter. The filter should signal the event if it receives a call to its Stop method.

IGraphConfig::RemoveFilterEx

IGraphConfig Interface

Removes a filter from the filter graph.

Syntax

HRESULT RemoveFilterEx(
    IBaseFilter *pFilter,
    DWORD Flags
);

Parameters

pFilter
[in] Pointer to the filter to remove from the graph.
Flags
[in] Combination of flags from the REM_FILTER_FLAGS enumerated type.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

This method extends the IFilterGraph::RemoveFilter method by accepting a flag that specifies the behavior of the method. This flag enables an application to remove a filter without disconnecting the pins automatically, which improves performance when moving groups of connected filters into a new graph.

By default, this method disconnects the filter before removing it from the graph. Use the REMFILTERF_LEAVECONNECTED flag to leave the filter connected.

RemoveFilterEx

IGraphConfig::RemoveFilterFromCache

IGraphConfig Interface

Removes a filter from the filter cache.

Syntax

HRESULT RemoveFilterFromCache(
    IBaseFilter *pFilter
);

Parameters

pFilter
[in] Pointer to the filter to remove from the cache.

Return Value

Returns one of the following HRESULT values.

E_POINTER | Null pointer argument.
S_FALSE | Filter was not in the cache.
S_OK | Filter was successfully removed from the cache.

IGraphConfig::SetFilterFlags

IGraphConfig Interface

Sets a filter's configuration information.

Syntax

HRESULT SetFilterFlags(
    IBaseFilter *pFilter,
    DWORD dwFlags
);

Parameters

pFilter
[in] Pointer to a filter in the filter graph.
dwFlags
[in] Value specifying the new configuration flags. Must be one of the following values.
Zero | No flags set.
AM_FILTER_FLAGS_REMOVABLE | The filter is removable during a dynamic reconnection. For more information, see Remarks.

Return Value

Returns one of the following HRESULT values.

E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_IN_GRAPH | The filter is not in the graph.

Remarks

The AM_FILTER_FLAGS_REMOVABLE flag changes the behavior of the IGraphConfig::Reconnect method. The Reconnect method performs a dynamic reconnection between two pins. If the caller specifies one pin, but leaves the other pin unspecified, Reconnect searches upstream or downstream from the specified pin to find a suitable match. By default, however, the search fails if it reaches a filter that was added to the graph by means of the IFilterGraph::AddFilter method. To override this behavior, call SetFilterFlags and set the AM_FILTER_FLAGS_REMOVABLE flag on the filter.


IGraphConfigCallback Interface

The IGraphConfigCallback interface contains the callback method passed to IGraphConfig::Reconfigure. The caller (an application or filter) implements this interface. For more information, see IGraphConfig.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IGraphConfigCallback methods | Description
Reconfigure | Callback method passed to IGraphConfig::Reconfigure.

IGraphConfigCallback::Reconfigure

IGraphConfigCallback Interface

Callback method passed to IGraphConfig::Reconfigure.

Syntax

HRESULT Reconfigure(
    PVOID pvContext,
    DWORD dwFlags
);

Parameters

pvContext
Value passed in the IGraphConfig::Reconfigure method's pvContext parameter.
dwFlags
Value passed in the IGraphConfig::Reconfigure method's dwFlags parameter.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

If your application or filter calls IGraphConfig::Reconfigure, you must implement this method and pass it as a callback. The IGraphConfig::Reconfigure method obtains a lock on the filter graph before calling your Reconfigure method. Your method then handles all the other details of dynamic graph building.

If this method succeeds, IGraphConfig::Reconfigure tries to put all the filters in the graph back into a running state. If the method fails, IGraphConfig::Reconfigure returns whatever error code this method returned.

This method allows for specialized graph rebuilding. For a more straightforward approach to dynamic graph building, see IGraphConfig::Reconnect.


IGraphVersion Interface

The IGraphVersion interface is implemented on the filter graph manager to provide a way for plug-in distributors and applications to know when the graph has changed. If the graph has changed, and the application or plug-in distributor has an interface on a particular filter or pin, it should requery the graph to see if its pointers are still valid, or if there are new ones it should use.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IGraphVersion methods | Description
QueryVersion | Retrieves the current graph version number.

IGraphVersion::QueryVersion

IGraphVersion Interface

Retrieves the current graph version number.

Syntax

HRESULT QueryVersion(
    LONG *pVersion
    );

Parameters

pVersion
Pointer to the current graph version.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

The version number is incremented every time there is a change in the set of filters in the graph or in their connections. If the version number has changed since the last enumeration, the graph must be re-enumerated.


IIPDVDec Interface

This interface provides methods for setting and retrieving properties on the DV Video Decoder filter.

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IIPDVDec methods | Description
get_IPDisplay | Retrieves the decoding resolution.
put_IPDisplay | Sets the decoding resolution.

IIPDVDec::get_IPDisplay

IIPDVDec Interface

Retrieves the decoding resolution.

Syntax

HRESULT get_IPDisplay(
    int *displayPix
);

Parameters

displayPix
Pointer to a variable that receives a member of the DVDECODERRESOLUTION enumerated type, specifying the decoding resolution.

Return Value

Returns S_OK.

IIPDVDec::put_IPDisplay

IIPDVDec Interface

Sets the decoding resolution.

Syntax

HRESULT put_IPDisplay(
    int displayPix
);

Parameters

displayPix
[in] Member of the DVDECODERRESOLUTION enumerated type, specifying the decoding resolution. The meaning of this value depends on whether the current format is NTSC or PAL. The filter determines at run time which format applies, based on the media type.

Return Value

Returns S_OK if successful; otherwise, returns E_FAIL or another error code.

Remarks

This method will fail if the filter is already streaming media data.


IKsPropertySet Interface

The IKsPropertySet interface was originally designed as an efficient way to set and retrieve device properties on WDM drivers, using KSProxy to translate the user-mode COM method calls into kernel-mode "property sets" used by WDM streaming class drivers. This interface is now also used to pass information strictly between software components. In some cases, software components must implement this interface. For example, if you are writing a software MPEG-2 decoder for use with the Microsoft® DVD Navigator, you must implement this interface and also support the DVD-related property sets that the Navigator will send to the decoder using the IKsPropertySet::Get and IKsPropertySet::Set methods. Pins may support this interface in order to allow other pins or filters to set or retrieve its properties.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IKsPropertySet methods | Description
Set | Sets a property identified by a property set GUID and a property ID.
Get | Retrieves a property identified by a property set GUID and a property ID.
QuerySupported | Determines whether an object supports a specified property set.

IKsPropertySet::Get

IKsPropertySet Interface

Retrieves a property identified by a property set GUID and a property ID.

Syntax

HRESULT Get(
  REFGUID guidPropSet,
  DWORD dwPropID,
  LPVOID pInstanceData,
  DWORD cbInstanceData,
  LPVOID pPropData,
  DWORD cbPropData,
  DWORD *pcbReturned
  );

Parameters

guidPropSet
[in] Property set GUID.
dwPropID
[in] Identifier of the property within the property set.
pInstanceData
[out, size_is(cbInstanceData)] Pointer to instance data for the property.
cbInstanceData
[in] Number of bytes in the buffer to which pInstanceData points.
pPropData
[out, size_is(cbPropData)] Pointer to the retrieved buffer, which contains the value of the property.
cbPropData
[in] Number of bytes in the buffer to which pPropData points.
pcbReturned
[out] Pointer to the number of bytes returned in the buffer to which pPropData points.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The current Microsoft® DirectShow® implementation returns E_PROP_SET_UNSUPPORTED if the property set is not supported or E_PROP_ID_UNSUPPORTED if the property ID is not supported for the specified property set.

Remarks

To retrieve a property, allocate a buffer which this method will then fill in. To determine the necessary buffer size, specify NULL for pPropData and zero (0) for cbPropData. This method returns the necessary buffer size in pcbReturned.

IKsPropertySet::QuerySupported

IKsPropertySet Interface

Determines whether an object supports a specified property set.

Syntax

HRESULT QuerySupported(
  REFGUID guidPropSet,
  DWORD dwPropID,
  DWORD *pTypeSupport
  );

Parameters

guidPropSet
[in] Property set GUID.
dwPropID
[in] Identifier of the property within the property set.
pTypeSupport
[out] Pointer to a value in which to store flags indicating the support provided by the driver. Supported flags include the following:
KSPROPERTY_SUPPORT_GET | You can retrieve the property by calling the IKsPropertySet::Get method.
KSPROPERTY_SUPPORT_SET | You can change the property by calling IKsPropertySet::Set.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The return values for the current DirectShow implementation include the following:
E_NOTIMPL | Property set is not supported.
E_PROP_ID_UNSUPPORTED | Property ID is not supported for the specified property set.
E_PROP_SET_UNSUPPORTED | Property set is not supported.
S_OK | Specified property set and property ID combination is supported.

IKsPropertySet::Set

IKsPropertySet Interface

Sets a property identified by a property set GUID and a property ID.

Syntax

HRESULT Set(
  REFGUID guidPropSet,
  DWORD dwPropID,
  LPVOID pInstanceData,
  DWORD cbInstanceData,
  LPVOID pPropData,
  DWORD cbPropData
  );

Parameters

guidPropSet
[in] Property set GUID.
dwPropID
[in] Identifier of the property within the property set.
pInstanceData
[out, size_is(cbInstanceData)] Pointer to instance data for the property.
cbInstanceData
[in] Number of bytes in the buffer to which pInstanceData points.
pPropData
[out, size_is(cbPropData)] Pointer to the retrieved buffer, which contains the value of the property.
cbPropData
[in] Number of bytes in the buffer to which pPropData points.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

The current DirectShow implementation returns E_PROP_SET_UNSUPPORTED if the property set is not supported or E_PROP_ID_UNSUPPORTED if the property ID is not supported for the specified property set.


IMediaControl Interface

This interface provides methods for controlling the flow of data through the filter graph. It includes methods for running, pausing, and stopping the graph. The filter graph manager implements this interface. For more information on filter graph states, see Data Flow in the Filter Graph.

IMediaControl also provides Automation-compatible methods for building graphs. Applications written in Microsoft® Visual Basic® can use these methods to construct filter graphs or retrieve information about the graph. Applications written in C or C++ should use the methods in IGraphBuilder and IFilterGraph2 instead, because they are more efficient.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether type information is available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returns successfully.
GetIDsOfNames | Converts text names of properties and methods, including arguments, to their corresponding dispatch identifiers (DISPIDs).
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IMediaControl methods | Description
Run | Runs all the filters in the filter graph.
Pause | Pauses all filters in the filter graph.
Stop | Stops all the filters in the filter graph.
StopWhenReady | Pauses the filter graph, allowing filters to queue data, and then stops the filter graph.
GetState | Retrieves the state of the filter graph.
RenderFile | Used by Visual Basic applications to build a filter graph that renders the specified file.
AddSourceFilter | Used by Visual Basic applications to add to the graph the source filter that can read the given file name.
get_FilterCollection | Used by Visual Basic applications to build a filter graph that renders the specified file to retrieve a collection of IFilterInfo interfaces that represent the filters in the graph.
get_RegFilterCollection | Used by Visual Basic applications to retrieve a collection of IRegFilterInfo interfaces that represent the registered filters available on the local system.

IMediaControl::AddSourceFilter

IMediaControl Interface

Used by Visual Basic applications to add to the graph the source filter that can read the given file name.

Syntax

HRESULT AddSourceFilter(
    BSTR strFilename,
    IDispatch **ppUnk
);

Parameters

strFilename
[in] Name of the file containing the source video.
ppUnk
[out] Address of a pointer that will receive the IFilterInfo interface on the filter.

Return Values

Returns an HRESULT value. Possible values include the following.

Success.
S_OK
E_OUTOFMEMORY | Insufficient memory.
VFW_E_CANNOT_LOAD_SOURCE_FILTER | The source filter for this file could not be loaded.
VFW_E_NOT_FOUND | An object or name was not found.
VFW_E_UNKNOWN_FILE_TYPE | The media type of this file is not recognized.

Remarks

This method is primarily for use by Automation clients because it returns an IDispatch interface pointer. C and C++ applications should call the IGraphBuilder::AddSourceFilter method to perform this operation for maximum efficiency.

IMediaControl::get_FilterCollection

IMediaControl Interface

Used by Visual Basic applications to build a filter graph that renders the specified file to retrieve a collection of IFilterInfo interfaces that represent the filters in the graph.

Syntax

HRESULT get_FilterCollection(
    IDispatch **ppUnk
);

Parameters

ppUnk
[out, retval] Address of a pointer that will receive the IAMCollection interface on a collection of IFilterInfo objects.

Return Values

Returns an HRESULT value. Possible values include the following.

Success.
S_OK
E_OUTOFMEMORY Insufficient memory.

Remarks

This method is primarily for use by Automation clients because it returns an IDispatch interface pointer. C and C++ applications should call the IFilterGraph::EnumFilters method to perform this operation for maximum efficiency.

IMediaControl::get_RegFilterCollection

IMediaControl Interface

Used by Visual Basic applications to retrieve a collection of IRegFilterInfo interfaces that represent the registered filters available on the local system.

Syntax

HRESULT get_RegFilterCollection(
    IDispatch **ppUnk
);

Parameters

ppUnk
[out, retval] Address of a pointer that will receive the IDispatch interface of the IAMCollection object.

Return Values

Returns an HRESULT value. Possible values include the following.

Success.
S_OK
E_OUTOFMEMORY Insufficient memory.

Remarks

This method is primarily for use by Automation clients because it returns an IDispatch interface pointer. C and C++ applications should call the IFilterMapper::EnumMatchingFilters method to perform this operation for maximum efficiency.

IMediaControl::GetState

IMediaControl Interface

Retrieves the state of the filter graph—paused, running, or stopped.

State transitions are not necessarily synchronous. Therefore, when you call this method, the filter graph might be in transition to a new state. In that case, the method blocks until the transition completes or until the specified time-out elapses.

Syntax

HRESULT GetState(
    LONG msTimeout,
    OAFilterState *pfs
);

Parameters

msTimeout
[in] Duration of the time-out, in milliseconds, or INFINITE to specify an infinite time-out.
pfs
[out] Pointer to a variable that receives a member of the FILTER_STATE enumeration.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
VFW_S_STATE_INTERMEDIATE | The filter graph is still in transition to the indicated state.
VFW_S_CANT_CUE | The filter graph is paused, but cannot cue data.
E_FAIL | Failure.

Remarks

Applications can use this method to determine whether playback has started after a call to IMediaControl::Run. Generally, applications should have their own mechanism for tracking which state they have put the filter graph into. Applications typically use the current state to determine which user interface controls are enabled or disabled. For example, once the graph goes into the running state, the application might disable a "Play" button and enable "Stop" and "Pause" buttons.

If the filter graph is in a transition to a new state, the returned state is the new state, not the previous state.

This method returns an error if there is a call on another thread to change the state while this method is blocked.

Avoid specifying a time-out of INFINITE, because threads cannot process messages while waiting in GetState. If you call GetState from the thread that processes Windows messages, specify small wait times on the call in order to remain responsive to user input. This is especially important when the source is streaming over a network or from the Internet because state transitions in these environments can take significantly more time to complete.

For more information about filter graph states, see Data Flow in the Filter Graph.

IMediaControl::Pause

IMediaControl Interface

Pauses all the filters in the filter graph.

Pausing the filter graph cues the graph for immediate rendering when the graph is next run. While the graph is paused, filters process data but do not render it. Data is pushed through the graph and processed by transform filters as far as buffering permits, but renderer filters do not render the data. However, video renderers display a static poster frame of the first sample.

Syntax

HRESULT Pause(void);

Return Values

Returns an HRESULT value. Possible values include the following.

S_FALSE | The graph paused successfully, but some filters have not completed the state transition.
S_OK | All filters in the graph completed the transition to a paused state.

Remarks

If the method returns S_FALSE, call the GetState method to wait for the state transition to complete, or to check if the transition has completed.

If the method fails, it stops the graph before returning.

IMediaControl::RenderFile

IMediaControl Interface

Used by Visual Basic applications to build a filter graph that renders the specified file.

Syntax

HRESULT RenderFile(
    BSTR strFilename
);

Parameters

strFilename
Name of the file to render.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
VFW_S_AUDIO_NOT_RENDERED | Cannot play the audio stream: could not find a suitable renderer.
VFW_S_DUPLICATE_NAME | An attempt to add a filter with a duplicate name succeeded with a modified name.
VFW_S_PARTIAL_RENDER | Some streams in this movie are in an unsupported format.
VFW_S_VIDEO_NOT_RENDERED | Cannot play the video stream: could not find a suitable renderer.
E_ABORT | Operation aborted.
VFW_E_CANNOT_CONNECT | No combination of intermediate filters could be found to make the connection.
VFW_E_CANNOT_LOAD_SOURCE_FILTER | The source filter for this file could not be loaded.
VFW_E_CANNOT_RENDER | No combination of filters could be found to render the stream.
VFW_E_INVALID_FILE_FORMAT | The file format is invalid.
VFW_E_NOT_FOUND | An object or name was not found.
VFW_E_NOT_IN_GRAPH | Cannot perform the requested function on an object that is not in the filter graph.
VFW_E_UNKNOWN_FILE_TYPE | The media type of this file is not recognized.
VFW_E_UNSUPPORTED_STREAM | Cannot play the file: the format is not supported.

Remarks

This method allows an application to pass the name of a media file that it wants rendered to the filter graph manager. The filter graph manager will build a graph of the filters needed to play back this file. This method is Automation-compatible and is equivalent to the IGraphBuilder::RenderFile method, which should be used by C and C++ applications.

IMediaControl::Run

IMediaControl Interface

Runs all the filters in the filter graph. While the graph is running, data moves through the graph and is rendered.

Syntax

HRESULT Run(void);

Return Values

Returns an HRESULT value. Possible values include the following.

S_FALSE | The graph is preparing to run, but some filters have not completed the transition to a running state.
S_OK | All filters in the graph completed the transition to a running state.

Remarks

If the filter graph is stopped, this method pauses the graph before running. If the graph is already running, the method returns S_OK but has no effect.

The graph runs until the IMediaControl::Pause or IMediaControl::Stop method is called. When playback reaches the end of the stream, the graph continues to run, although the filters do not stream any more data. At that point, the application can pause or stop the graph. For information about the end-of-stream event, see IMediaEvent and EC_COMPLETE.

This method does not seek to the beginning of the stream. If you run the graph, pause it, and then run it again, playback resumes from the paused position. If you run the graph after it reached end-of-stream, there is no effect. To seek the graph, use the IMediaSeeking interface.

If the return value is S_FALSE, you can wait for the transition to complete by calling the GetState method. If the method fails, some filters might be in a running state. In a multistream graph, entire streams might be playing successfully. The application must determine whether to stop the graph.

IMediaControl::Stop

IMediaControl Interface

Stops all the filters in the graph.

Syntax

HRESULT Stop(void);

Return Values

Returns S_OK if successful, or an HRESULT value that indicates the cause of the error.

Remarks

If the graph is running, this method pauses the graph before stopping it. While paused, video renderers can copy the current frame to display as a poster frame.

This method does not seek to the beginning of the stream. If you call this method and then call the IMediaControl::Run method, playback resumes from the stopped position. To seek, use the IMediaSeeking interface.

The filter graph manager pauses all the filters in the graph, and then calls the IMediaFilter::Stop method on all filters, without waiting for the pause operations to complete. Therefore, some filters might have their Stop method called before they complete their pause operation. If you develop a custom rendering filter, you might need to handle this case by pausing the filter if it receives a stop command while in a running state. However, most filters do not need to take any special action in this regard.

See Also

StopWhenReady

IMediaControl::StopWhenReady

IMediaControl Interface

Pauses the filter graph, allowing filters to queue data, and then stops the filter graph.

Syntax

HRESULT StopWhenReady(void);

Return Values

Returns S_OK if successful, or an HRESULT value that indicates the cause of the error.

Remarks

This method is useful if you want to seek the filter graph while the graph is stopped. As long as the filter graph is stopped, changes in the current position do not repaint the video window with a new frame. Therefore, calling IMediaSeeking::SetPositions does not update the video window. To update the window after the seek operation, call StopWhenReady. This method transitions the graph to a paused state, waits for the pause operation to complete, and then transitions the graph back to stopped. The pause operation queues data in the graph, so that the video renderer receives and displays the new frame.

This method is asynchronous. It waits on a separate thread for the pause to complete. The calling thread does not block, which enables the application to respond to user input. When the method returns, the logical state of the graph is stopped, even before the pause operation completes. If you call the GetState method at this point, it returns State_Stopped.

If the application issues another state-change command (such as pause, run, or seek) before the pause operation completes, the new command cancels the pending stop command. The pause operation completes, but the graph does not stop.


IMediaEvent Interface

This interface contains methods for retrieving event notifications and for overriding the filter graph's default handling of events. The IMediaEventEx interface inherits this interface and extends it.

The filter graph manager implements this interface. Applications can use it to respond to events that occur in the filter graph, such as the end of a stream or a rendering error. Filters post events to the filter graph using the IMediaEventSink interface.

For more information about event notification, see Event Notification in DirectShow. For a list of system-defined event notifications, see Event Notification Codes.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether there is type information available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returned successfully.
GetIDsOfNames | Converts text names of properties and methods (including arguments) to their corresponding DISPIDs.
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IMediaEvent methods | Description
GetEventHandle | Retrieves a handle to a manual-reset event that remains signaled while the queue contains event notifications.
GetEvent | Retrieves the next event notification from the event queue.
WaitForCompletion | Waits for the filter graph to render all available data.
CancelDefaultHandling | Cancels the filter graph manager's default handling of a specified event.
RestoreDefaultHandling | Restores the filter graph manager's default handling of a specified event.
FreeEventParams | Frees resources associated with the parameters of an event.

IMediaEvent::CancelDefaultHandling

IMediaEvent Interface

Cancels the filter graph manager's default handling of a specified event. The event notification is passed to the application.

Syntax

HRESULT CancelDefaultHandling(
    long lEvCode
);

Parameters

lEvCode
Event code for which to cancel default handling.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.
S_OK | Success.
E_INVALIDARG | No default handling for this event.

Remarks

To restore the default handling for an event, call the RestoreDefaultHandling method with the event code.

IMediaEvent::FreeEventParams

IMediaEvent Interface

Frees resources associated with the parameters of an event.

Syntax

HRESULT FreeEventParams(
    long lEventCode,
    long lParam1,
    long lParam2
);

Parameters

lEventCode
[in] Event code.
lParam1
[in] First event parameter.
lParam2
[in] Second event parameter.

Return Value

Returns S_OK.

Remarks

After you call the IMediaEvent::GetEvent method to retrieve an event notification, you must call FreeEventParams. This method frees any resources that were allocated for the event parameters. Pass in the same variables used for the GetEvent call, as shown in the following example:

hr = pEvent->GetEvent(&evCode, &param1, &param2, 0);
// Handle the event (not shown).
hr = pEvent->FreeEventParams(evCode, param1, param2);

IMediaEvent::GetEvent

IMediaEvent Interface

Retrieves the next event notification from the event queue.

Syntax

HRESULT GetEvent(
    long *lEventCode,
    long *lParam1,
    long *lParam2,
    long msTimeout
);

Parameters

IEventCode
[out] Pointer to a variable that receives the event code.
lParam1
[out] Pointer to a variable that receives the first event parameter.
lParam2
[out] Pointer to a variable that receives the second event parameter.
msTimeout
[in] Time-out interval, in milliseconds. Use INFINITE to block until there is an event.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_ABORT | Timeout expired.

Remarks

Applications should avoid using a time-out interval of INFINITE, because threads cannot process any messages while waiting in GetEvent. If you call GetEvent from the same thread that processes Windows messages, specify only small wait times, in order to remain responsive to user input. This is most important when streaming data from a source such as the Internet, because state transitions can take significantly more time to complete.

After calling GetEvent, call the FreeEventParams method to release any resources allocated for the event parameters.

For a list of notification codes and event parameter values, see Event Notification Codes.

IMediaEvent::GetEventHandle

IMediaEvent Interface

Retrieves a handle to a manual-reset event that remains signaled while the queue contains event notifications.

Syntax

HRESULT GetEventHandle(
    OAEVENT *hEvent
);

Parameters

hEvent
[out] Pointer to a variable that receives the event handle.

Return Value

Returns S_OK.

Remarks

The filter graph manager keeps a manual-reset event that reflects the state of the event queue. If the queue contains event notifications, the manual-reset event is signaled. If the queue is empty, the IMediaEvent::GetEvent method resets the event.

An application can use this event to determine the state of the queue. First call GetEventHandle to obtain a handle to the event. Wait for the event to be signaled, using a Microsoft® Windows® function such as WaitForSingleObject. When the event is signaled, call the GetEvent method to retrieve the next event notification from the queue. The filter graph manager keeps the event signaled until the queue is empty; then it resets the event.

Note For Automation compatibility, this method takes a pointer to an OAEVENT variable. In C++, declare a variable of type HANDLE and cast it to type OAEVENT, as follows:
HANDLE hEvent;
GetEventHandle( (OAEVENT*) &hEvent );

Another way for applications to monitor the event queue is by calling the IMediaEventEx::SetNotifyWindow method.

IMediaEvent::RestoreDefaultHandling

IMediaEvent Interface

Restores the filter graph manager's default handling of a specified event.

Syntax

HRESULT RestoreDefaultHandling(
    long lEvCode
);

Parameters

lEvCode
[in] Event code for which to restore default handling.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | No default handling for this event.

Remarks

By default, the filter graph manager handles some events (such as EC_REPAINT) without passing them to the application. If you call the CancelDefaultHandling method to override the default handling for an event, you can restore the default behavior by calling RestoreDefaultHandling with the same event code.

IMediaEvent::WaitForCompletion

IMediaEvent Interface

Waits for the filter graph to render all available data. The filter graph must be running or the method fails.

Syntax

HRESULT WaitForCompletion(
    long msTimeout,
    long *pEvCode
);

Parameters

msTimeout
[in] Time-out interval, in milliseconds. Pass zero to return immediately. Pass the value INFINITE to block indefinitely.
pEvCode
[out] Pointer to a variable that receives an event code. See Remarks for more information.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_ABORT | Time-out expired.
VFW_E_WRONG_STATE | The filter graph is not running.

Remarks

This method blocks until the time-out expires, or one of the following events occurs:

  • EC_COMPLETE
  • EC_ERRORABORT
  • EC_USERABORT

During the wait, the method discards all other event notifications.

If the return value is S_OK, the pEvCode parameter receives the event code that ended the wait. When the method returns, the filter graph is still running. The application can pause or stop the graph, as appropriate.


IMediaEventEx Interface

This interface inherits the IMediaEvent interface, which contains methods for retrieving event notifications and for overriding the filter graph's default handling of events. IMediaEventEx adds methods that enable an application window to receive messages when events occur. Unlike IMediaEvent, this interface is not available through Automation, and therefore cannot be called directly from Microsoft® Visual Basic®.

The filter graph manager implements this interface.

For more information about event notification, see Event Notification in DirectShow. For a list of system-defined event notifications, see Event Notification Codes.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether there is type information available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returned successfully.
GetIDsOfNames | Converts text names of properties and methods (including arguments) to their corresponding DISPIDs.
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IMediaEvent methods | Description
GetEventHandle | Retrieves a handle to a manual-reset event that remains signaled while the queue contains event notifications.
GetEvent | Retrieves the next event notification from the event queue.
WaitForCompletion | Waits for the filter graph to render all available data.
CancelDefaultHandling | Cancels the filter graph manager's default handling of a specified event.
RestoreDefaultHandling | Restores the filter graph manager's default handling of a specified event.
FreeEventParams | Frees resources associated with the parameters of an event.
IMediaEventEx methods | Description
SetNotifyWindow | Registers a window to process event notifications.
SetNotifyFlags | Enables or disables event notifications.
GetNotifyFlags | Determines whether event notifications are enabled.

IMediaEventEx::GetNotifyFlags

IMediaEventEx Interface

Determines whether event notifications are enabled.

Syntax

HRESULT GetNotifyFlags(
    long *lplNoNotifyFlags
);

Parameters

lplNoNotifyFlags
[out] Pointer to a variable that receives one of the following values:
  • Zero: Event notifications are enabled.
  • AM_MEDIAEVENT_NONOTIFY: Event notifications are disabled.

Return Value

Returns S_OK if successful, or E_POINTER if the lplNoNotifyFlags parameter is NULL.

Remarks

By default, the filter graph manager posts event notifications for the application. To disable event notification, call the SetNotifyFlags method with the value AM_MEDIAEVENT_NONOTIFY.

If event notifications are disabled, the handle returned by the GetEventHandle method is signaled at the end of each stream—that is, whenever the filter graph manager receives an EC_COMPLETE event.

IMediaEventEx::SetNotifyFlags

IMediaEventEx Interface

Enables or disables event notifications.

Syntax

HRESULT SetNotifyFlags(
    long lNoNotifyFlags
);

Parameters

lNoNotifyFlags
[in] Value indicating whether to enable or disable event notifications. Must be one of the following values:
  • Zero: Enable event notifications.
  • AM_MEDIAEVENT_NONOTIFY: Disable event notifications.

Return Value

Returns S_OK if successful, or E_INVALIDARG if the lNoNotifyFlags parameter is invalid.

Remarks

By default, the filter graph manager posts event notifications for the application. If the lNoNotifyFlags parameter is AM_MEDIAEVENT_NONOTIFY, the filter graph manager clears any pending event notifications from the queue, and does not post any new ones.

If event notifications are disabled, the handle returned by the GetEventHandle method is signaled at the end of each stream—that is, whenever the filter graph manager receives an EC_COMPLETE event.

IMediaEventEx::SetNotifyWindow

IMediaEventEx Interface

Registers a window to process event notifications.

Syntax

HRESULT SetNotifyWindow(
    OAHWND hwnd,
    long lMsg,
    long lInstanceData
);

Parameters

hwnd
[in] Handle to the window, or NULL to stop receiving event messages.
lMsg
[in] Window message to be passed as the notification.
lInstanceData
[in] Value to be passed as the lParam parameter for the lMsg message.

Return Value

Returns S_OK if successful or E_INVALIDARG if the hwnd parameter is not a valid handle to a window.

Remarks

This method designates a window that will process event notifications. Whenever the filter graph manager puts an event in the event queue, it will also post a message to the designated window. The hwnd parameter specifies the window, and the lMsg parameter specifies the message. The application should define a private window message for this purpose. The message's lParam parameter is set to the value of lInstanceData, and the wParam parameter is set to zero.

When the window receives the message, it should call the GetEvent method to retrieve the event. Events are asynchronous, so the queue might contain several events (or none). Call GetEvent repeatedly, until it returns an error code.


IMediaEventSink Interface

Notifies the filter graph manager of events that occur within the filter graph. Filters use this interface to report events. The filter graph manager exposes this interface.

Applications do not use IMediaEventSink. To retrieve events, applications use the IMediaEventEx interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaEventSink methods | Description
Notify | Notifies the filter graph manager of an event.

IMediaEventSink::Notify

IMediaEventSink Interface

Notifies the filter graph manager of an event.

Syntax

HRESULT Notify(
long EventCode,
LONG_PTR EventParam1,
LONG_PTR EventParam2
);

Parameters

EventCode
[in] Identifier of the event.
EventParam1
[in] First event parameter.
EventParam2
[in] Second event parameter.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

The event is queued but not delivered to the application on this thread. For a list of notification codes and event parameter values, see Event Notification Codes.


IMediaFilter Interface

Controls the streaming state of a filter.

All Microsoft® DirectShow® filters implement this interface. It provides methods for switching the filter between states (stopped, paused, and running); for retrieving the filter's current state; and for setting a reference clock. The filter graph manager also exposes this interface. It distributes the method calls to the filters in the filter graph.

This interface provides low-level control of the graph. Applications should use the IMediaControl interface instead, because it provides control of the graph at a higher level.

IMediaFilter inherits the IPersist interface. The IBaseFilter interface inherits from IMediaFilter.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaFilter methods | Description
Stop | Stops the filter.
Pause | Pauses the filter.
Run | Runs the filter.
GetState | Retrieves the filter's state (running, stopped, or paused).
SetSyncSource | Sets a reference clock for the filter.
GetSyncSource | Retrieves the reference clock that the filter is using.

IMediaFilter::GetState

IMediaFilter Interface

Retrieves the filters's state (running, stopped, or paused).

Syntax

HRESULT GetState(
    DWORD dwMilliSecsTimeout,
    FILTER_STATE *State
);

Parameters

dwMilliSecsTimeout
[in] Time-out interval, in milliseconds. To block indefinitely, use the value INFINITE.
State
[out] Pointer to a variable that receives a member of the FILTER_STATE enumerated type, indicating the filter's state.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_S_STATE_INTERMEDIATE | Intermediate state.
VFW_S_CANT_CUE | The filter is active, but cannot deliver data.

Remarks

State transitions can be asynchronous. If the filter is transitioning to a new state, and the method times out before the transition completes, the method returns VFW_S_STATE_INTERMEDIATE.

If a filter cannot deliver data for some reason, it returns VFW_S_CANT_CUE. Live capture filters return this value while paused, because they do not deliver data in the paused state.

For more information, see Data Flow in the Filter Graph.

IMediaFilter::GetSyncSource

IMediaFilter Interface

Retrieves the reference clock that the filter is using.

Syntax

HRESULT GetSyncSource(

  IReferenceClock **pClock

  );

Parameters

pClock
[out] Address of a variable that receives a pointer to the clock's IReferenceClock interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success
E_POINTER | NULL pointer argument

Remarks

If the filter is not using a reference clock, *pClock is set to NULL. When the method returns, if *pClock is non-NULL, the IReferenceClock interface has an outstanding reference count. Be sure to release it when you are done.

IMediaFilter::Pause

IMediaFilter Interface

Pauses the filter.

Syntax

HRESULT Pause(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | Transition is not complete.
S_OK | Success. Transition is complete.

Remarks

When a filter is paused, it can receive, process, and deliver samples. However, a renderer filter will only accept one sample while paused. Therefore, when the filter graph is paused, samples move through the graph until the first sample reaches the renderer. At that point, streaming is paused until the Run method is called. Video renderers display the first sample as a still frame.

Live capture filters do not deliver any samples while paused, only while running.

The state transition might be asynchronous. If the method returns before the transition completes, the return value is S_FALSE. Renderer filters do not complete the state transition until they receive one sample.

IMediaFilter::Run

IMediaFilter Interface

Runs the filter.

Syntax

HRESULT Run(
    REFERENCE_TIME tStart
);

Parameters

tStart
Reference time corresponding to stream time 0.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | Transition is not complete.
S_OK | Success. Transition is complete.

Remarks

When a filter is running, it can receive, process, and deliver samples. Source filters generate new samples, and renderer filters render them.

The state transition might be asynchronous. If the method returns before the transition completes, the return value is S_FALSE.

Stream time is calculated as the current reference time minus tStart. To calculate when a media sample should be rendered, the renderer compares the time stamp with the current stream time. Thus, a media sample with a time stamp of zero should be rendered at time tStart. For more information, see Time and Clocks in DirectShow.

When an application calls the IMediaControl::Run method, the filter graph manager calls IMediaFilter::Run on each filter. It sets the value of tStart slightly in the future, to account for graph latency.

IMediaFilter::SetSyncSource

IMediaFilter Interface

Sets a reference clock for the filter.

Syntax

HRESULT SetSyncSource(
    IReferenceClock *pClock
);

Parameters

pClock
[in] Pointer to the clock's IReferenceClock interface, or NULL.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

If the pClock parameter is NULL, the filter does not use a reference clock. Renderer filters use the reference clock to schedule when samples get rendered. If there is no reference clock, a renderer filter renders every sample as soon as it arrives.

All the filters in the filter graph should share the same reference clock, in order to stay synchronized. Normally the filter graph manager selects the reference clock. An application can override the default clock by calling the IMediaFilter::SetSyncSource method on the filter graph manager. Only do this if you have a particular reason to prefer another clock.

IMediaFilter::Stop

IMediaFilter Interface

Stops the filter.

Syntax

HRESULT Stop(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | Transition is not complete.
S_OK | Success. Transition is complete.

Remarks

When a filter is stopped, it does not process or deliver any samples, and it rejects samples from upstream filters.

The state transition might be asynchronous. If the method returns before the transition completes, the return value is S_FALSE.


IMediaPosition Interface

Contains methods for seeking to a position within a stream.

The IMediaSeeking interface improves on this interface. Applications written in C/C++ should use IMediaSeeking instead of IMediaPosition. However, IMediaSeeking is not compatible with Automation, so applications written in Microsoft® Visual Basic® must use IMediaPosition instead.

This interface is exposed by the filter graph manager as well as by individual filters. Applications should obtain an IMediaPosition interface pointer from the filter graph manager, not from a filter. The filter graph manager distributes method calls to all of the renderer filters. The renderer filters propagate the calls upstream to the source filters. This sequence of events ensures that all streams remain synchronized.

If one of the distributed calls returns an error, the filter graph manager returns the first error value it received. Some of the distributed calls may have succeeded in this case. However, the filter graph does not return E_NOTIMPL unless all the distributed calls return E_NOTIMPL. If at least one filter in the graph implements the method, the filter graph manager does not return E_NOTIMPL.

Filter developers: Do not implement this method. Implement IMediaSeeking instead. If your filter supports IMediaSeeking, the filter graph manager automatically handles calls to IMediaPosition.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Retrieves the number of type information interfaces the object provides.
GetTypeInfo | Retrieves the type information for the object, which can then be used to get the type information for an interface.
GetIDsOfNames | Maps a set of names to a corresponding set of DISPIDs.
Invoke | Provides access to properties and methods exposed by the object.
IMediaPosition methods | Description
get_Duration | Retrieves the duration of the stream.
put_CurrentPosition | Sets the current position, relative to the total duration of the stream.
get_CurrentPosition | Retrieves the current position, relative to the total duration of the stream.
get_StopTime | Retrieves the time at which the playback will stop, relative to the duration of the stream.
put_StopTime | Sets the time at which the playback will stop, relative to the duration of the stream.
get_PrerollTime | Retrieves the amount of data that will be queued before the start position.
put_PrerollTime | Sets the amount of data that will be queued before the start position.
put_Rate | Sets the playback rate.
get_Rate | Retrieves the playback rate.
CanSeekForward | Determines whether the filter graph can seek forward in the stream.
CanSeekBackward | Determines whether the filter graph can seek backward in the stream.

IMediaPosition::CanSeekBackward

IMediaPosition Interface

Determines whether the filter graph can seek backward in the stream.

Syntax

HRESULT CanSeekBackward(
    LONG *pCanSeekBackward
);

Parameters

pCanSeekBackward
[out] Pointer to a variable that receives the value OATRUE if the graph can seek backward, or OAFALSE otherwise.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

IMediaPosition::CanSeekForward

IMediaPosition Interface

Determines whether the filter graph can seek forward in the stream.

Syntax

HRESULT CanSeekForward(
    LONG *pCanSeekForward
);

Parameters

pCanSeekForward
[out] Pointer to a variable that receives the value OATRUE if the graph can seek forward, or OAFALSE otherwise.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

IMediaPosition::get_CurrentPosition

IMediaPosition Interface

Retrieves the current position, relative to the total duration of the stream.

Syntax

HRESULT get_CurrentPosition(
    REFTIME *pllTime
);

Parameters

pllTime
[out] Pointer to a variable that receives the current position, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

This method returns the current position that playback has reached. The value ignores the playback rate and start time. For example, if you set the rate to 2.0 and the start time to five seconds, running the graph for four seconds yields a current position of 9.0 seconds (5 + 4 × 2.0).

If the graph is paused or stopped, the current position is the point at which playback will resume.

IMediaPosition::get_Duration

IMediaPosition Interface

Retrieves the duration of the stream.

Syntax

HRESULT get_Duration(
    REFTIME *plength
);

Parameters

plength
[out] Pointer to a variable that receives the total stream length, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

This method retrieves the duration of the stream at normal playback speed. Changing the playback rate does not affect the duration.

IMediaPosition::get_PrerollTime

IMediaPosition Interface

Retrieves the amount of data that will be queued before the start position.

Syntax

HRESULT get_PrerollTime(
    REFTIME *pllTime
);

Parameters

pllTime
[out] Pointer to a variable that receives the preroll time, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

The preroll is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.

If no filter in the graph implements this method, the filter graph manager sets the value of *pllTime to zero and returns S_OK.

IMediaPosition::get_Rate

IMediaPosition Interface

Retrieves the playback rate.

Syntax

HRESULT get_Rate(
    double *pdRate
);

Parameters

pdRate
[out] Pointer to a variable that receives the playback rate.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

The playback rate is expressed as a ratio of the normal speed. Thus, 1.0 is normal playback speed, 0.5 is half speed, and 2.0 is twice speed.

IMediaPosition::get_StopTime

IMediaPosition Interface

Retrieves the time at which the playback will stop, relative to the duration of the stream.

Syntax

HRESULT get_StopTime(
    REFTIME *pllTime
);

Parameters

pllTime
[out] Pointer to a variable that receives the stop time, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

The playback rate does not affect the value returned by this method.

IMediaPosition::put_CurrentPosition

IMediaPosition Interface

Sets the current position, relative to the total duration of the stream.

Syntax

HRESULT put_CurrentPosition(
    REFTIME llTime
);

Parameters

llTime
[in] New position, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following:

S_FALSE | Graph was paused and is in transition back to a running state.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

Remarks

The position specified by the llTime parameter is relative to the total duration, ignoring playback rate. For example, if a source file is 10 seconds long, setting the position to 5.0 causes the graph to seek to the middle of the file, regardless of playback rate.

If the filter graph is running, the filter graph manager pauses the graph, issues the seek command, and then runs the graph again. If the method returns while the graph is still transitioning to a running state, the return value is S_FALSE.

If a filter is paused when it receives a seek command, it must flush existing data before it introduces the data from the new position. See IPin::BeginFlush and IPin::EndFlush.

IMediaPosition::put_PrerollTime

IMediaPosition Interface

Sets the amount of data that will be queued before the start position.

Syntax

HRESULT put_PrerollTime(
    REFTIME llTime
);

Parameters

llTime
[in] Preroll time, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Not implemented.

Remarks

The preroll is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.

IMediaPosition::put_Rate

IMediaPosition Interface

Sets the playback rate.

Syntax

HRESULT put_Rate(
    double dRate
);

Parameters

dRate
[in] Playback rate. Must not be zero.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

Remarks

The playback rate is expressed as a ratio of the normal speed. Thus, 1.0 is normal playback speed, 0.5 is half speed, and 2.0 is twice speed. For audio streams, changing the rate also changes the pitch.

For more information, see the remarks in IMediaSeeking::SetRate.

IMediaPosition::put_StopTime

IMediaPosition Interface

Sets the time at which the playback will stop, relative to the duration of the stream.

Syntax

HRESULT put_StopTime(
    REFTIME llTime
);

Parameters

llTime
[in] Stop time, in seconds.

Return Values

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

Remarks

The stop time ignores the start time and the playback rate. For example, if the start time is 2 seconds, the stop time is 12 seconds, and the playback rate is 2.0, playback will stop after 5 seconds (real time).


IMediaPropertyBag Interface

The IMediaPropertyBag interface is exposed by the media property bag. The media property bag is a specialized version of the standard COM property bag, designed for setting and retrieving INFO and DISP chunks in Audio-Video Interleaved (AVI) files.

An INFO chunk contains meta-information about a file, such as author and copyright information. A DISP chunk contains data in Clipboard format. For more information, refer to the resource interchange file format (RIFF) specification.

The media property bag stores the chunks as name/value pairs, as follows:

  • INFO chunks: The name is a string with the form INFO/XXXX, where XXXX is the four-character code that defines the type of meta-information—for example, ICOP for copyright information and IART for author name. The value is any string.
  • DISP chunks: The name is a string with the form DISP/0000000000, where 0000000000 is the 10-character decimal equivalent of a standard Clipboard format—for example, 0000000008 for CF_DIB. The value is an array of bytes that contains the display data.

This interface inherits the IPropertyBag interface. Use this interface with the IPersistMediaPropertyBag interface to retrieve INFO and DISP chunks from an AVI file.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaPropertyBag methods | Description
EnumProperty | Retrieves a property/value pair.

IMediaPropertyBag::EnumProperty

IMediaPropertyBag Interface

Retrieves a property/value pair.

Syntax

HRESULT EnumProperty(
    ULONG iProperty,
    VARIANT *pvarPropertyName,
    VARIANT *pvarPropertyValue
);

Parameters

iProperty
[in] Index value of the pair.
pvarPropertyName
[in, out] Pointer to a VARIANT that receives the property's name.
pvarPropertyValue
[in, out] Pointer to a VARIANT that receives the property's value.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS) | Index out of range.

Remarks

The name is always a string. Set the variant type of the pvarPropertyName parameter to VT_EMPTY or VT_BSTR before calling this method.

The value can be a string (for INFO chunks) or an array of bytes (for DISP chunks). Set the variant type of the pvarPropertyName parameter to VT_EMPTY, VT_BSTR, or (VT_ARRAY | VT_UI1).


IMediaSample Interface

Sets and retrieves properties on media samples. A media sample is a COM object that contains a block of media data. Media samples support the use of shared memory buffers among filters.

Typically, applications do not call methods on this interface. Filters use this interface to set properties on samples, and deliver the samples to a downstream filter. The downstream filter uses the interface to retrieve the properties and read the data. The filter can modify the data in place, or it can copy the sample, modify the copy, and pass the copy downstream.

The IMediaSample2 interface inherits this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaSample methods | Description
GetPointer | Retrieves a read/write pointer to this buffer's memory.
GetSize | Retrieves the size of the buffer.
GetTime | Retrieves the stream times at which this sample should begin and finish.
SetTime | Sets the stream time when this sample should begin and finish.
IsSyncPoint | Determines if the beginning of this sample is a synchronization point.
SetSyncPoint | Specifies whether the beginning of this sample is a synchronization point.
IsPreroll | Determines if this sample is a preroll sample.
SetPreroll | Specifies whether this sample is a preroll sample.
GetActualDataLength | Retrieves the length of the valid data in the buffer.
SetActualDataLength | Sets the length of the valid data in the buffer.
GetMediaType | Retrieves the media type, if the media type differs from the previous sample.
SetMediaType | Sets the media type for the sample.
IsDiscontinuity | Determines if this sample represents a break in the data stream.
SetDiscontinuity | Specifies whether this sample represents a break in the data stream.
GetMediaTime | Retrieves the media times for this sample.
SetMediaTime | Sets the media times for this sample.

IMediaSample::GetActualDataLength

IMediaSample Interface

Retrieves the length of the valid data in the buffer.

Syntax

LONG GetActualDataLength(void);

Return Value

Returns the length of the valid data, in bytes.

IMediaSample::GetMediaTime

IMediaSample Interface

Retrieves the media times for this sample.

Syntax

HRESULT GetMediaTime(
    LONGLONG *pTimeStart,
    LONGLONG *pTimeEnd
);

Parameters

pTimeStart
[out] Pointer to a variable that receives the media start time.
pTimeEnd
[out] Pointer to a variable that receives the media stop time.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_MEDIA_TIME_NOT_SET | Media times are not set on this sample.

Remarks

For more information about media times, see Time and Clocks in DirectShow.

IMediaSample::GetMediaType

IMediaSample Interface

Retrieves the media type, if the media type differs from the previous sample.

Syntax

HRESULT GetMediaType(
    AM_MEDIA_TYPE **ppMediaType
);

Parameters

ppMediaType
Address of a variable that receives a pointer to an AM_MEDIA_TYPE structure. If the media type has not changed from the previous sample, *ppMediaType is set to NULL.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | The media type has not changed from the previous sample.
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.

Remarks

This method enables a filter to make limited changes to the media type, such as changing the palette. To make a significant change to the media type, the pins might need to reconnect and renegotiate the media type.

When you are done with the media type, free the memory block by calling the DeleteMediaType utility function.

IMediaSample::GetPointer

IMediaSample Interface

Retrieves a read/write pointer to this buffer's memory.

Syntax

HRESULT GetPointer(
    BYTE **ppBuffer
);

Parameters

ppBuffer
[out] Address of a pointer to the buffer.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

IMediaSample::GetSize

IMediaSample Interface

Retrieves the size of the buffer.

Syntax

long GetSize(void);

Return Value

Returns the size of the buffer, in bytes.

IMediaSample::GetTime

IMediaSample Interface

Retrieves the stream times at which this sample should begin and finish.

Syntax

HRESULT GetTime(
    REFERENCE_TIME *pTimeStart,
    REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart
[out] Pointer to a variable that receives the beginning stream time.
pTimeEnd
[out] Pointer to a variable that receives the ending stream time. If the sample has no stop time, the value is set to the start time plus one.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success. The sample has valid start and stop times.
VFW_S_NO_STOP_TIME | The sample has a valid start time, but no stop time.
VFW_E_SAMPLE_TIME_NOT_SET | The sample is not time-stamped.

Remarks

For more information about stream times, see Time and Clocks in DirectShow.

IMediaSample::IsDiscontinuity

IMediaSample Interface

Determines if this sample represents a break in the data stream.

Syntax

HRESULT IsDiscontinuity(void);

Return Value

Returns S_OK if the sample is a break in the data stream. Otherwise, returns S_FALSE.

Remarks

A discontinuity occurs when a filter seeks to a different place in the stream, or when a filter drops samples for quality control.

IMediaSample::IsPreroll

IMediaSample Interface

Determines if this sample is a preroll sample. A preroll sample should not be displayed.

Syntax

HRESULT IsPreroll(void);

Return Value

Returns S_OK if the sample is a preroll sample. Otherwise, returns S_FALSE.

Remarks

Preroll samples are processed but not displayed. They are located in the media stream before the displayable samples.

IMediaSample::IsSyncPoint

IMediaSample Interface

Determines if the beginning of this sample is a synchronization point.

Syntax

HRESULT IsSyncPoint(void);

Return Value

Returns S_OK if the sample is a synchronization point. Otherwise, returns S_FALSE.

Remarks

A filter can begin a stream at any synchronization point. With some compression types, streaming can begin only at certain points in the stream; for example, on key frames. If the bTemporalCompression member of the AM_MEDIA_TYPE structure is FALSE, all samples are synchronization points.

IMediaSample::SetActualDataLength

IMediaSample Interface

Sets the length of the valid data in the buffer.

Syntax

HRESULT SetActualDataLength(
    long lLen
);

Parameters

lLen
Length of the data in the media sample, in bytes.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_BUFFER_OVERFLOW. | Length specified in lLen is larger than the buffer size.

IMediaSample::SetDiscontinuity

IMediaSample Interface

Specifies whether this sample represents a break in the data stream.

Syntax

HRESULT SetDiscontinuity(
    BOOL bIsDiscontinuity
);

Parameters

bIsDiscontinuity
[in] Boolean value that specifies whether this sample is a discontinuity. If TRUE, the media sample is discontinuous with the previous sample.

Return Value

Returns S_OK, or an HRESULT value indicating the cause of the error.

See Also

IMediaSample::IsDiscontinuity

IMediaSample::SetMediaTime

IMediaSample Interface

Sets the media times for this sample.

Syntax

HRESULT SetMediaTime(
    LONGLONG *pTimeStart,
    LONGLONG *pTimeEnd
);

Parameters

pTimeStart
[in] Pointer to the beginning media time.
pTimeEnd
[in] Pointer to the ending media time.

Return Value

Returns S_OK, or an HRESULT value indicating the cause of the error.

Remarks

To invalidate the media time, set pTimeStart and pTimeEnd to NULL. This will cause the IMediaSample::GetMediaTime method to return VFW_E_MEDIA_TIME_NOT_SET.

For more information about media times, see Time and Clocks in DirectShow.

IMediaSample::SetMediaType

IMediaSample Interface

Sets the media type for the sample.

Syntax

HRESULT SetMediaType(
    AM_MEDIA_TYPE *pMediaType
);

Parameters

pMediaType
Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success
E_OUTOFMEMORY | Insufficient memory

Remarks

By default, every sample has the same media type as the previous sample. (The pin connection determines the original media type.) Call this method to make limited changes to the media type, such as changing the palette. To make a significant change to the media type, the pins might need to reconnect and renegotiate the media type.

IMediaSample::SetPreroll

IMediaSample Interface

Specifies whether this sample is a preroll sample.

Syntax

HRESULT SetPreroll(
    BOOL bIsPreroll
);

Parameters

bIsPreroll
Boolean value that specifies whether this is a preroll sample. If TRUE, this is a preroll sample.

Return Value

Returns S_OK, or an HRESULT value indicating the cause of the error.

See Also

IMediaSample::IsPreroll

IMediaSample::SetSyncPoint

IMediaSample Interface

Specifies whether the beginning of this sample is a synchronization point.

Syntax

HRESULT SetSyncPoint(
    BOOL bIsSyncPoint
);

Parameters

bIsSyncPoint
[in] Boolean value that specifies whether this is a synchronization point. If TRUE, this is a synchronization point.

Return Value

Returns S_OK or an HRESULT value indicating the cause of the error.

See Also

IMediaSample::IsSyncPoint

IMediaSample::SetTime

IMediaSample Interface

Sets the stream times when this sample should begin and finish.

Syntax

HRESULT SetTime(
    REFERENCE_TIME *pTimeStart,
    REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart
[in] Pointer to the stream time at which the sample begins, in 100-nanosecond units.
pTimeEnd
[in] Pointer to the stream time at which the sample ends, in 100-nanosecond units.

Return Value

Returns S_OK, or HRESULT value indicating the cause of the error.

Remarks

To invalidate the stream times, set pTimeStart and pTimeEnd to NULL. This will cause the IMediaSample::GetTime method to return VFW_E_SAMPLE_TIME_NOT_SET.

For more information about stream times, see Time and Clocks in DirectShow.


IMediaSample2 Interface

Sets and retrieves properties on media samples. This interface inherits the IMediaSample interface. The IMediaSample interface requires separate method calls for each sample property. The IMediaSample2 interface adds methods that set or retrieve multiple properties at once.

Media samples are not guaranteed to support IMediaSample2. However, if an allocator does create samples that support IMediaSample2, all of the samples it generates must support the interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaSample methods | Description
GetPointer | Retrieves a read/write pointer to this buffer's memory.
GetSize | Retrieves the size of the buffer.
GetTime | Retrieves the stream times at which this sample should begin and finish.
SetTime | Sets the stream time when this sample should begin and finish.
IsSyncPoint | Determines if the beginning of this sample is a synchronization point.
SetSyncPoint | Specifies whether the beginning of this sample is a synchronization point.
IsPreroll | Determines if this sample is a preroll sample.
SetPreroll | Specifies whether this sample is a preroll sample.
GetActualDataLength | Retrieves the length of the valid data in the buffer.
SetActualDataLength | Sets the length of the valid data in the buffer.
GetMediaType | Retrieves the media type, if the media type differs from the previous sample.
SetMediaType | Sets the media type for the sample.
IsDiscontinuity | Determines if this sample represents a break in the data stream.
SetDiscontinuity | Specifies whether this sample represents a break in the data stream.
GetMediaTime | Retrieves the media times for this sample.
SetMediaTime | Sets the media times for this sample.
IMediaSample2 methods | Description
GetProperties | Retrieves the properties of a media sample.
SetProperties | Sets the properties of a media sample.

IMediaSample2::GetProperties

IMediaSample2 Interface

Retrieves the properties of a media sample.

Syntax

HRESULT GetProperties(
    DWORD cbProperties,
    BYTE *pbProperties
);

Parameters

cbProperties
[in] Length of property data to retrieve, in bytes.
pbProperties
[out] Pointer to a buffer of size cbProperties.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

The retrieved data conforms to the format of the AM_SAMPLE2_PROPERTIES structure. You can retrieve a subset of the sample properties by setting cbProperties to a value less than the size of the AM_SAMPLE2_PROPERTIES structure.

For efficiency, the pMediaType member returned in AM_SAMPLE2_PROPERTIES is a pointer to the data stored in the media sample, not a copy of that data. The pointer may become invalid after the sample is passed to another filter, or after the input pin's IMemInputPin::Receive method has completed. Also, do not free the pointer or delete the media type.

IMediaSample2::SetProperties

IMediaSample2 Interface

Sets the properties of a media sample.

Syntax

HRESULT SetProperties(
    DWORD cbProperties,
    const BYTE *pbProperties
);

Parameters

cbProperties
[in] Length of property data to set, in bytes.
pbProperties
[in] Pointer to a buffer of size cbProperties.

Return Value

Returns an HRESULT value. Possible values include the following.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

The data contained in pbProperties must conform to the format of the AM_SAMPLE2_PROPERTIES structure. You can specify a subset of the sample properties by setting cbProperties to a value less than the size of the AM_SAMPLE2_PROPERTIES structure.


IMediaSeeking Interface

Contains methods for seeking to a position within a stream, and for setting the playback rate.

The filter graph manager exposes this interface, as do individual filters. Applications should obtain this interface from the filter graph manager, not from a filter. The filter graph manager distributes method calls to all of the renderer filters. The renderer filters send the calls upstream to the source filters. This sequence of events ensures that all streams remain synchronized.

If any of the distributed calls returns an error, the filter graph manager returns the first error value it received, even if some of the distributed calls succeed. An exception is E_NOTIMPL: the filter graph manager does not return E_NOTIMPL unless it was returned by all of the distributed calls.

An application can seek the graph while the graph is in any state (running, paused or stopped). If the graph is running, the filter graph manager pauses the graph before it issues the seek command. Then it runs the graph again. All seeking operations are independent of the current playback rate. Seeking operations cause any pending media data to be flushed from the graph.

This interface improves on the IMediaPosition interface. The IMediaPosition methods require time parameters in fractions of seconds, whereas the IMediaSeeking methods can accept arbitrary formats, such as frames, bytes, or 100-nanosecond units. Also, IMediaSeeking uses 64-bit integers (LONGLONG), providing for greater accuracy. On the other hand, IMediaSeeking is not compatible with Automation, so applications written in Microsoft® Visual Basic® must use IMediaPosition.

For all IMediaSeeking parameters that specify time, the unit of time depends on the current time format. To set the time format, call the IMediaSeeking::SetTimeFormat method. Time formats are globally unique identifiers (GUIDs) defined in uuids.h. For more information, see Time Format GUIDs.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaSeeking methods | Description
GetCapabilities | Retrieves all the seeking capabilities of the stream.
CheckCapabilities | Queries whether a stream has specified seeking capabilities.
IsFormatSupported | Determines whether a specified time format is supported.
QueryPreferredFormat | Retrieves the preferred time format for the stream.
GetTimeFormat | Retrieves the current time format.
IsUsingTimeFormat | Determines whether a specified time format is the format currently in use.
SetTimeFormat | Sets the time format.
GetDuration | Retrieves the duration of the stream.
GetStopPosition | Retrieves the time at which the playback will stop, relative to the duration of the stream.
GetCurrentPosition | Retrieves the current position, relative to the total duration of the stream.
ConvertTimeFormat | Converts from one time format to another.
SetPositions | Sets the current position and the stop position.
GetPositions | Retrieves the current position and the stop position, relative to the total duration of the stream.
GetAvailable | Retrieves the range of times in which seeking is efficient.
SetRate | Sets the playback rate.
GetRate | Retrieves the playback rate.
GetPreroll | Retrieves the amount of data that will be queued before the start position.

IMediaSeeking::CheckCapabilities

IMediaSeeking Interface

Queries whether a stream has specified seeking capabilities.

Syntax

HRESULT CheckCapabilities(
    DWORD *pCapabilities
);

Parameters

pCapabilities
[in, out] Pointer to a bitwise combination of one or more AM_SEEKING_SEEKING_CAPABILITIES attributes. When the method returns, the value indicates which of those attributes are available.

Return Value

Returns an HRESULT value. Possible values include the following.

S_FALSE | Not all of the capabilities in pCapabilities are present.
S_OK | All capabilities in pCapabilities are present.
E_FAIL | No capabilities in pCapabilities are present.
E_POINTER | NULL pointer argument.

Remarks

If you are only interested in a few specific capabilities, calling this method is more efficient than calling GetCapabilities, which checks all the stream's seeking capabilities.

Declare a DWORD value equal to the bitwise-OR combination of the AM_SEEKING_SEEKING_CAPABILITIES attributes that you want to test. Pass a pointer to this value in the pCapabilities parameter. When the method returns, pCapabilities contains a subset of the original bits, indicating which capabilities are present. The return value indicates whether some, none, or all of the requested capabilities are present.

The following code example shows how to find out whether the stream supports forward seeking, backward seeking, and absolute seeking.

// Set flags for the capabilities you want to check.
DWORD dwCaps = AM_SEEKING_CanSeekAbsolute |
             AM_SEEKING_CanSeekForwards |
             AM_SEEKING_CanSeekBackwards;

HRESULT hr = pMediaSeeking->CheckCapabilities(&dwCaps);
if(FAILED(hr))
{
    // The stream cannot seek.
}
else if (hr == S_OK)
{
    // The stream can seek forward, backward, and to an absolute position.
}
else if (hr == S_FALSE) // The stream might have some of the capabilities.
{
    if (dwCaps & AM_SEEKING_CanSeekAbsolute)
        // The stream can seek to an absolute position.
    if dwCaps & AM_SEEKING_CanSeekAbsolute)
        // The stream can seek forward.
    if (dwCaps & AM_SEEKING_CanSeekBackwards)
        // The stream can seek backward.
}

IMediaSeeking::ConvertTimeFormat

IMediaSeeking Interface

Converts from one time format to another.

Syntax

HRESULT ConvertTimeFormat(
    LONGLONG *pTarget,
    const GUID *pTargetFormat,
    LONGLONG Source,
    const GUID *pSourceFormat
);

Parameters

pTarget
[out] Pointer to a variable that receives the converted time.
pTargetFormat
[in] Pointer to the time format GUID of the target format. If NULL, the current format is used.
Source
[in] Time value to be converted.
pSourceFormat
[in] Pointer to the time format GUID of the format to convert. If NULL, the current format is used.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | Conversion between these types is not supported.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

IMediaSeeking::GetAvailable

IMediaSeeking Interface

Retrieves the range of times in which seeking is efficient.

Syntax

HRESULT GetAvailable(
    LONGLONG *pEarliest,
    LONGLONG *pLatest
);

Parameters

pEarliest
[out] Pointer to a variable that receives the earliest time for efficient seeking.
pLatest
[out] Pointer to a variable that receives the latest time for efficient seeking.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

This method is intended primarily for seeking in media streams that might have excessive latency, such as streams being sent over a network. The returned values indicate cached data that has already arrived, which can be easily seeked. It is assumed that seeking to values beyond these returned parameters will cause a delay while the application waits for the data to arrive.

IMediaSeeking::GetCapabilities

IMediaSeeking Interface

Retrieves all the seeking capabilities of the stream.

Syntax

HRESULT GetCapabilities(
    DWORD *pCapabilities
);

Parameters

pCapabilities
[out] Pointer to a variable that receives a bitwise combination of AM_SEEKING_SEEKING_CAPABILITIES flags.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

This method returns information on all the seeking capabilities of the stream. Examine pCapabilities by performing a separate bitwise-AND operation on each AM_SEEKING_SEEKING_CAPABILITIES value you are interested in.

DWORD dwCaps = 0;
pMediaSeeking->GetCapabilities(&dwCaps);

if (dwCaps & AM_SEEKING_CanGetCurrentPos)
{
    // The stream can seek to the current position.
}
if (dwCaps & AM_SEEKING_CanPlayBackwards)
{
    // The stream can play backward.
}

IMediaSeeking::GetCurrentPosition

IMediaSeeking Interface

Retrieves the current position, relative to the total duration of the stream.

Syntax

HRESULT GetCurrentPosition(
    LONGLONG *pCurrent
);

Parameters

pCurrent
[out] Pointer to a variable that receives the current position, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

This method returns the current position that playback has reached. The value ignores the playback rate and start time. For example, if you set the rate to 2.0 and the start time to five seconds, running the graph for four seconds yields a current position of nine seconds (5 + 4 × 2.0). The returned value is expressed in units of the current time format. To determine the current time format, call the GetTimeFormat method.

If the graph is paused or stopped, the current position is the point at which playback will resume.

The filter graph manager calculates the position from the current stream time; it does not query the filters in the graph. For file playback, this yields an accurate result, because playback is synchronized to the stream time. For file writing, the results are not accurate. To get the current position in a file-writing graph, query the multiplexer filter. (Position is not relevant for live capture, however.)

IMediaSeeking::GetDuration

IMediaSeeking Interface

Retrieves the duration of the stream.

Syntax

HRESULT GetDuration(
    LONGLONG *pDuration
);

Parameters

pDuration
[out] Pointer to a variable that receives the duration, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

This method retrieves the duration of the stream at normal playback speed. Changing the playback rate does not affect the duration. The returned value is expressed in units of the current time format. To determine the current time format, call the GetTimeFormat method.

IMediaSeeking::GetPositions

IMediaSeeking Interface

Retrieves the current position and the stop position, relative to the total duration of the stream.

Syntax

HRESULT GetPositions(
    LONGLONG *pCurrent,
    LONGLONG *pStop
);

Parameters

pCurrent
[out] Pointer to a variable that receives the current position, in units of the current time format.
pStop
[out] Pointer to a variable that receives the stop position, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

The current position and the stop position are both relative to the original stream, and are independent of the playback rate.

The returned values are expressed in units of the current time format. To determine the current time format, call the GetTimeFormat method.

IMediaSeeking::GetPreroll

IMediaSeeking Interface

Retrieves the amount of data that will be queued before the start position.

Syntax

HRESULT GetPreroll(
    LONGLONG *pllPreroll
);

Parameters

pllPreroll
[out] Pointer to a variable that receives the preroll time, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

The preroll is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.

IMediaSeeking::GetRate

IMediaSeeking Interface

Retrieves the playback rate.

Syntax

HRESULT GetRate(
    double *dRate
);

Parameters

dRate
[out] Pointer to a variable that receives the playback rate.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

The playback rate is expressed as a ratio of the normal speed. Thus, 1.0 is normal playback speed, 0.5 is half speed, and 2.0 is twice speed.

IMediaSeeking::GetStopPosition

IMediaSeeking Interface

Retrieves the time at which the playback will stop, relative to the duration of the stream.

Syntax

HRESULT GetStopPosition(
    LONGLONG *pStop
);

Parameters

pStop
[out] Pointer to a variable that receives the stop time, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

The playback rate does not affect the value returned by this method. The returned values are expressed in units of the current time format. To determine the current time format, call the GetTimeFormat method.

IMediaSeeking::GetTimeFormat

IMediaSeeking Interface

Retrieves the current time format.

Syntax

HRESULT GetTimeFormat(
    GUID *pFormat
);

Parameters

pFormat
[out] Pointer to a variable that receives a time format GUID.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_POINTER | NULL pointer argument.

IMediaSeeking::IsFormatSupported

IMediaSeeking Interface

Determines whether a specified time format is supported.

Syntax

HRESULT IsFormatSupported(
    const GUID *pFormat
);

Parameters

pFormat
[in] Pointer to a time format GUID.

Return Value

Returns an HRESULT value. Possible values include the following.

S_FALSE | The format is not supported.
S_OK | The format is supported.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

IMediaSeeking::IsUsingTimeFormat

IMediaSeeking Interface

Determines whether a specified time format is the format currently in use.

Syntax

HRESULT IsUsingTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat
[in] Pointer to a time format GUID.

Return Value

Returns an HRESULT value. Possible values include the following.

S_FALSE | The specified format is not the current format.
S_OK | The specified format is the current format.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

This method is more efficient than the IMediaSeeking::GetTimeFormat method, because it does not require copying the GUID.

IMediaSeeking::QueryPreferredFormat

IMediaSeeking Interface

Retrieves the preferred time format for the stream.

Syntax

HRESULT QueryPreferredFormat(
    GUID *pFormat
);

Parameters

pFormat
[out] Pointer to a variable that receives a time format GUID.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.

Remarks

If the returned format is not satisfactory, call the IsFormatSupported method to query for other supported time formats.

IMediaSeeking::SetPositions

IMediaSeeking Interface

Sets the current position and the stop position.

Syntax

HRESULT SetPositions(
    LONGLONG *pCurrent,
    DWORD dwCurrentFlags,
    LONGLONG *pStop,
    DWORD dwStopFlags
);

Parameters

pCurrent
[in,out] Pointer to a variable that specifies the current position, in units of the current time format.
dwCurrentFlags
[in] Bitwise combination of flags. See Remarks.
pStop
[in,out] Pointer to a variable that specifies the stop time, in units of the current time format.
dwStopFlags
[in] Bitwise combination of flags. See Remarks.

Return Value

Returns an HRESULT value. Possible values include the following.

S_FALSE | No position change. (Both flags specify no seeking.)
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

The dwCurrentFlags and dwStopFlags parameters define the type of seek. The following flags are defined:

Positioning Flags
AM_SEEKING_NoPositioning | No change in position. (The time parameter can be NULL.)
AM_SEEKING_AbsolutePositioning | The specified position is absolute.
AM_SEEKING_RelativePositioning | The specified position is relative to the previous value.
AM_SEEKING_IncrementalPositioning | The stop position (pStop) is relative to the current position (pCurrent).
Modifier Flags
AM_SEEKING_SeekToKeyFrame | Seek to the nearest key frame. This might be faster, but less accurate.
AM_SEEKING_ReturnTime | Return the equivalent reference times.
AM_SEEKING_Segment | Use segment seeking.
AM_SEEKING_NoFlush | Do not flush.

For each parameter, use one positioning flag. Optionally, include one or more modifier flags.

If the AM_SEEKING_ReturnTime flag is specified, the method converts the position value to a reference time and returns it in the pCurrent or pStop variable. This flag is useful if you are using another time format, such as frames.

The AM_SEEKING_Segment and AM_SEEKING_NoFlush flags support seamless looping:

  • If the AM_SEEKING_Segment flag is present, the source filter sends an EC_END_OF_SEGMENT event when it reaches the stop position, instead of calling IPin::EndOfStream. The application can wait for this event and then issue another seek command.
  • If the AM_SEEKING_NoFlush flag is present, the graph does not flush data during the seek. Use this flag with AM_SEEKING_Segment.

To perform looping, the graph must report AM_SEEKING_CanDoSegments in the GetCapabilities method. Currently, only the WAVE Parser filter supports this feature.

IMediaSeeking::SetRate

IMediaSeeking Interface

Sets the playback rate.

Syntax

HRESULT SetRate(
    double dRate
);

Parameters

dRate
[in] Playback rate. Must not be zero.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | The specified rate was zero or a negative value. (See Remarks.)
E_NOTIMPL | Not implemented.
E_POINTER | NULL pointer argument.
VFW_E_UNSUPPORTED_AUDIO | Audio device or filter does not support this rate.

Remarks

The playback rate is expressed as a ratio of the normal speed. Thus, 1.0 is normal playback speed, 0.5 is half speed, and 2.0 is twice speed. For audio streams, changing the rate also changes the pitch.

Negative values indicate reverse playback. Most filters do not support negative playback, but instead return an error code if the dRate parameter is negative.

When an application calls this method on the filter graph manager, the filter graph manager does the following:

  1. Calls the GetCurrentPosition method. This call returns the current position as calculated by the filter graph manager.
  2. Stops the filter graph (if the graph is paused or running).
  3. Calls the SetPositions method on the filters, with the current position as the start time. This has the effect of resetting the stream time to zero.
  4. Calls the SetRate method on the filters, with the new rate.
  5. Resumes the filter graph, if it was paused or running.

If an error occurs in step 4, the filter graph manager tries to restore the previous rate.

Filters should repond to rate changes as follows:

Parser and source filters: The filter that originates the time stamps responds to the SetRate call. This is usually a parser filter, such as the AVI Splitter, but it might be a source filter. After any seek or rate change, the filter should call the IPin::NewSegment method with the new settings. After a rate change, it should adjust its time stamps accordingly. Because a rate change is preceded by a seek, time stamps restart from zero, so the filter can simply divide by the rate to calculate the new time stamps.

Decoder filters: Decoders should not act on SetRate calls other than to pass them upstream. Instead, they should respond to the NewSegment call that the upstream parser issues. When a decoder filter receives new segment information, it should store the values and pass the NewSegment call downstream. Some decoders need to generate extra time stamps by interpolating their input; they should take rate changes into account when doing so.

Renderers: Video renderers can typically ignore rate changes, because the incoming frames already have the correct time stamp. Audio renderers must modify their playback rate, because audio decoders typically do not make rate-change conversions.

IMediaSeeking::SetTimeFormat

IMediaSeeking Interface

Sets the time format.

Syntax

HRESULT SetTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat
[in] Pointer to a time format GUID.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.
VFW_E_WRONG_STATE | Filter graph is not stopped.

Remarks

This method specifies the time units used by other IMediaSeeking methods, such as GetPositions and SetPositions. To determine what formats are supported, call the IsFormatSupported method. To retrieve the current time format, call the GetTimeFormat method. To determine the preferred time format, call the QueryPreferredFormat method.

Only one time format can be set on the filter graph at any one time.


IMediaTypeInfo Interface

This interface provides Automation-compatible methods for retrieving the media type of a pin connection.

Microsoft® Visual Basic® applications can use this interface to retrieve the media type of a pin connection. The IPinInfo::get_ConnectionMediaType method returns an object that supports this interface. The major type and minor type GUIDs are retrieved as properties on the object.

C/C++ applications should call the IPin::ConnectionMediaType method instead.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether there is type information available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returned successfully.
GetIDsOfNames | Converts text names of properties and methods (including arguments) to their corresponding DISPIDs.
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IMediaTypeInfo methods | Description
get_Type | Retrieves the GUID as a string.
get_Subtype | Retrieves the subtype GUID as a string.

IMediaTypeInfo::get_Subtype

IMediaTypeInfo Interface

Retrieves the subtype GUID as a string.

Syntax

HRESULT get_Subtype(
    BSTR *strType
);

Parameters

strType
[out, retval] Pointer to a string containing the subtype GUID.

Return Value

Returns an HRESULT value.

IMediaTypeInfo::get_Type

IMediaTypeInfo Interface

Retrieves the major type GUID as a string.

Syntax

HRESULT get_Type(
    BSTR *strType
);

Parameters

strType
[out, retval] Pointer to a string containing the major type GUID.

Return Value

Returns an HRESULT value.


IMemAllocator Interface

Allocates media samples, for moving data between pins.

This interface is used by pins that share allocators, when the input pin exposes the IMemInputPin interface. The pins negotiate which pin will provide the allocator. The allocator is used to allocate memory buffers, retrieve empty buffers, and release buffers. Not every filter creates its own allocator, so one allocator might be used by several filters. For more information, see Connection Model.

Applications typically do not use this interface.

To use an allocator, perform the following steps:

  1. Call the IMemAllocator::SetProperties method to specify the buffer requirements, including the number of buffers and the size of each buffer.
  2. Call the IMemAllocator::Commit method to allocate the buffers.
  3. Call the IMemAllocator::GetBuffer method to retrieve media samples. This method blocks until the next sample becomes available.
  4. When you are done with each sample, call the IUnknown::Release method on the sample. The sample is not deleted when its reference count reaches zero. Instead, the sample returns to the allocator's free list.
  5. When you are done using the allocator, call the IMemAllocator::Decommit method to free the memory for the buffers.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMemAllocator methods | Description
SetProperties | Specifies the number of buffers to allocate and the size of each buffer.
GetProperties | Retrieves the number of buffers that the allocator will create, and the buffer properties.
Commit | Allocates the buffer memory.
Decommit | Releases the memory for the buffers.
GetBuffer | Retrieves a media sample that contains an empty buffer.
ReleaseBuffer | Releases a media sample.

IMemAllocator::Commit

IMemAllocator Interface

Allocates the buffer memory.

Syntax

HRESULT Commit(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_SIZENOTSET | Buffer requirements were not set.

Remarks

Before calling this method, call the IMemAllocator::SetProperties method to specify the buffer requirements.

You must call this method before calling the IMemAllocator::GetBuffer method.

IMemAllocator::Decommit

IMemAllocator Interface

Releases the memory for the buffers.

Syntax

HRESULT Decommit(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

Any threads waiting in the IMemAllocator::GetBuffer method return with an error. Further calls to GetBuffer fail, until the IMemAllocator::Commit method is called.

IMemAllocator::GetBuffer

IMemAllocator Interface

Retrieves a media sample that contains an empty buffer.

Syntax

HRESULT GetBuffer(
    IMediaSample **ppBuffer,
    REFERENCE_TIME *pStartTime,
    REFERENCE_TIME *pEndTime,
    DWORD dwFlags
);

Parameters

ppBuffer
[out] Address of a variable that receives a pointer to the buffer's IMediaSample interface.
pStartTime
[in] Pointer to the start time of the sample, or NULL.
pEndTime
[in] Pointer to the ending time of the sample, or NULL.
dwFlags
[in] Bitwise combination of zero or more of the following flags.
  • AM_GBF_NOTASYNCPOINT: This sample is not a synchronization point. Dynamic format changes are not allowed on this sample.
  • AM_GBF_PREVFRAMESKIPPED: This sample is the first after a discontinuity. (Only the video renderer uses this flag.)
  • AM_GBF_NOWAIT: Do not wait for a buffer to become available.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_NOT_COMMITTED | Allocator is decommitted.
VFW_E_TIMEOUT | Timed out.

Remarks

By default, this method blocks until a free sample is available or the allocator is decommitted. If the caller specifies the AM_GBF_NOWAIT flag and no sample is available, the allocator can return immediately with a return value of VFW_E_TIMEOUT. However, allocators are not required to support this flag.

The sample returned in ppBuffer has a valid buffer pointer. The caller is responsible for setting any other properties on the sample, such as the time stamps, the media times, or the sync-point property. (For more information, see IMediaSample.)

The pStartTime and pEndTime parameters are not applied to the sample. The allocator might use these values to determine which buffer it retrieves. For example, the Video Renderer filter uses these values to synchronize switching between Microsoft® DirectDraw® surfaces. To set the time stamp on the sample, call the IMediaSample::SetTime method.

You must call the IMemAllocator::Commit method before calling this method. This method fails after the IMemAllocator::Decommit method is called. If the method succeeds, the IMediaSample interface that it returns has an outstanding reference count. Be sure to release the interface when you are done using it.

IMemAllocator::GetProperties

IMemAllocator Interface

Retrieves the number of buffers that the allocator will create, and the buffer properties.

Syntax

HRESULT GetProperties(
    ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps
[out] Pointer to an ALLOCATOR_PROPERTIES structure that receives the allocator properties.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

Calls to this method might not succeed until the IMemAllocator::Commit method is called.

IMemAllocator::ReleaseBuffer

IMemAllocator Interface

Releases a media sample.

Syntax

HRESULT ReleaseBuffer(
    IMediaSample *pBuffer
);

Parameters

pBuffer
[in] Pointer to the media sample's IMediaSample interface.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

When a media sample's reference count reaches zero, it calls this method with itself as the pBuffer parameter. This method releases the sample back to the allocator's list of available samples.

IMemAllocator::SetProperties

IMemAllocator Interface

Specifies the number of buffers to allocate and the size of each buffer.

Syntax

HRESULT SetProperties(
    ALLOCATOR_PROPERTIES *pRequest,
    ALLOCATOR_PROPERTIES *pActual
);

Parameters

pRequest
Pointer to an ALLOCATOR_PROPERTIES structure that contains the buffer requirements.
pActual
Pointer to an ALLOCATOR_PROPERTIES structure that receives the actual buffer properties.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_ALREADY_COMMITTED | Cannot change allocated memory while the filter is active.
VFW_E_BADALIGN | An invalid alignment was specified.
VFW_E_BUFFERS_OUTSTANDING | One or more buffers are still active.

Remarks

This method specifies the buffer requirements, but does not allocate any buffers. Call the IMemAllocator::Commit method to allocate buffers.

The caller allocates two ALLOCATOR_PROPERTIES structures. The pRequest parameter contains the caller's buffer requirements, including the number of buffers and the size of each buffer. When the method returns, the pActual parameter contains the actual buffer properties, as set by the allocator.

When this method is called, the allocator must not be committed or have outstanding buffers.


IMemInputPin Interface

Delivers media data to an input pin. Input pins expose this interface if they use the IMemAllocator interface to allocate buffers. When an output pin connects to an input pin, the output pin uses this interface to negotiate allocator requirements and deliver samples to the input pin.

Applications typically do use this interface.

Filter developers: The CBaseInputPin class implements this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMemInputPin methods | Description
GetAllocator | Retrieves the memory allocator proposed by this pin.
NotifyAllocator | Specifies an allocator for the connection.
GetAllocatorRequirements | Retrieves allocator properties that are requested by the input pin.
Receive | Receives the next media sample in the stream.
ReceiveMultiple | Receives multiple samples in the stream.
ReceiveCanBlock | Determines whether calls to the Receive method might block.

IMemInputPin::GetAllocator

IMemInputPin Interface

Retrieves the memory allocator proposed by this pin.

Syntax

HRESULT GetAllocator(
IMemAllocator **ppAllocator
);

Parameters

ppAllocator
[out] Address of a variable that receives a pointer to the allocator's IMemAllocator interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_NO_ALLOCATOR | No allocator is available.

Remarks

When an output pin connects to an input pin, it negotiates with the input pin to decide on a memory allocator. The output pin calls this method to retrieve the input pin's proposed allocator. It calls the NotifyAllocator method to specify which allocator it selected.

If this method succeeds, the IMemAllocator interface has an outstanding reference count. Be sure to release it when you are done.

IMemInputPin::GetAllocatorRequirements

IMemInputPin Interface

Retrieves the allocator properties requested by the input pin.

Syntax

HRESULT GetAllocatorRequirements(
    ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps
[in] Pointer to an ALLOCATOR_PROPERTIES structure, which is filled in with the requirements.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success
E_NOTIMPL | Not implemented
E_POINTER | NULL pointer argument

Remarks

When an output pin initializes a memory allocator, it can call this method to determine whether the input pin has any buffer requirements. The input pin is not required to implement this method. If the filter has specific alignment or prefix requirements, it should implement this method.

IMemInputPin::NotifyAllocator

IMemInputPin Interface

Specifies an allocator for the connection.

Syntax

HRESULT NotifyAllocator(
    IMemAllocator *pAllocator,
    BOOL bReadOnly
);

Parameters

pAllocator
[in] Pointer to the allocator's IMemAllocator interface.
bReadOnly
[out] Flag that specifies whether samples from this allocator are read-only. If TRUE, samples are read-only.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

During the pin connection, the output pin chooses an allocator and calls this method to notify the input pin. The output pin might use the allocator that the input pin proposed in the IMemInputPin::GetAllocator method, or it might provide its own allocator.

If the bReadOnly parameter is TRUE, all samples in the allocator are read-only. The filter must copy them to modify the data.

IMemInputPin::Receive

IMemInputPin Interface

Receives the next media sample in the stream.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample
[in] Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
S_FALSE | Pin is currently flushing; sample was rejected.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

This method is synchronous and possibly blocking. The pin does one of the following:

  • Rejects the sample.
  • Returns immediately and processes the sample in a worker thread.
  • Processes the sample before returning.

In the last case, the method might block indefinitely. If this might happen, the ReceiveCanBlock method returns S_OK.

If the pin uses a worker thread to process the sample, it holds a reference count on the sample. In any case, the output pin cannot directly re-use this sample. It must call the IMemAllocator::GetBuffer method to obtain a new sample.

IMemInputPin::ReceiveCanBlock

IMemInputPin Interface

Determines whether calls to the Receive method might block.

Syntax

HRESULT ReceiveCanBlock(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | The pin will not block on a call to Receive
S_OK | The pin might block on a call to Receive.

Remarks

If this method returns S_FALSE, calls to the Receive method are guaranteed not to block. Otherwise, they might block. An upstream filter can use this method to determine its threading strategy. If calls to Receive can block, the upstream filter might decide to use a worker thread that buffers data.

IMemInputPin::ReceiveMultiple

IMemInputPin Interface

Receives multiple samples in the stream.

Syntax

HRESULT ReceiveMultiple(
    IMediaSample **pSamples,
    long nSamples,
    long *nSamplesProcessed
);

Parameters

pSamples
[in] Address of an array of IMediaSample pointers, of size nSamples.
nSamples
[in] Number of samples to process.
nSamplesProcessed
[out] Pointer to a variable that receives the number of samples that were processed.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
S_FALSE | Pin is currently flushing; sample was rejected.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

This method behaves like the Receive method, but receives an array of samples.


IMixerPinConfig Interface

The IMixerPinConfig interface is exposed on the input pins of the Overlay Mixer filter and contains methods that manipulate video streams in various ways. The Overlay Mixer contains multiple input pins that are dynamically created as video input streams are added. The video stream on the first pin is known as the primary stream and subsequent streams are known as secondary streams.

Use this interface to manipulate the parameters involved in mixing various video streams. These parameters include getting and setting position, z-order, blending and transparency levels, aspect ratio correction, and color keys of streams.

When setting the position of video streams in the display window, the default relative position of all secondary streams is {0, 0, 0, 0}. Therefore, use the SetRelativePosition method on secondary streams to ensure that all video streams are placed properly.

Applications use this interface to get and set attributes when mixing multiple video streams.

Requirements

Requires Mpconfig.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMixerPinConfig methods | Description
SetRelativePosition | Sets the position of the stream in the display window.
GetRelativePosition | Retrieves the position of the stream in the display window.
SetZOrder | Sets the z-order of a particular video stream.
GetZOrder | Retrieves the z-order of a particular video stream.
SetColorKey | Sets the color key being used by a video stream.
GetColorKey | Retrieves the color key being used by a video stream.
SetBlendingParameter | Sets the blending parameter that defines how a secondary stream is blended with a primary stream.
GetBlendingParameter | Retrieves the value of the blending parameter that defines how a secondary stream is blended with a primary stream.
SetAspectRatioMode | Sets the aspect ratio correction mode for window resizing.
GetAspectRatioMode | Retrieves the aspect ratio correction mode for window resizing.
SetStreamTransparent | Sets the stream to transparent.
SetStreamTransparent | Determines whether a stream is transparent.

IMixerPinConfig::GetAspectRatioMode

IMixerPinConfig Interface

Retrieves the aspect ratio correction mode for window resizing.

Syntax

HRESULT GetAspectRatioMode(
    AM_ASPECT_RATIO_MODE *pamAspectRatioMode
    ) PURE;

Parameters

pamAspectRatioMode
[out] Pointer to an AM_ASPECT_RATIO_MODE enumerated type member.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current DirectShow implementation return values include:
E_NOTIMPL | Method called on secondary stream.
E_INVALIDARG | Value invalid or NULL.
NOERROR | No error.

See Also

IMixerPinConfig::SetAspectRatioMode

IMixerPinConfig::GetBlendingParameter

IMixerPinConfig Interface

Retrieves the value of the blending parameter that defines how a secondary stream is blended with a primary stream.

Syntax

HRESULT GetBlendingParameter(
    DWORD *pdwBlendingParameter
    ) PURE;

Parameters

pdwBlendingParameter
[out] Pointer to a value between 0 and 255 that indicates the amount of blending between a primary stream and a secondary stream.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current DirectShow implementation return values include:
E_UNEXPECTED | Method called on primary stream.
E_INVALIDARG | Value outside of possible range (0-255).
NOERROR | No error.

Remarks

A value of zero indicates that the secondary stream is invisible; a value of 255 indicates the primary stream is invisible in the area that the secondary stream occupies.

See Also

IMixerPinConfig::SetBlendingParameter

IMixerPinConfig::GetColorKey

IMixerPinConfig Interface

Retrieves the color key being used by a video stream.

Syntax

HRESULT GetColorKey(
    COLORKEY *pColorKey,
    DWORD *pColor ) PURE;

Parameters

pColorKey
[out] Pointer to a COLORKEY structure that contains the key type and a palette index.
pColor
[out] Pointer to a value indicating the 8-bit palette index of the COLORKEY returned if the current display mode is 8-bit palettized. Otherwise it is a value representing the color key in the pixel format of the current display mode.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current DirectShow implementation return values include:
E_INVALIDARG | Invalid arguments, both parameters are NULL.
E_FAIL | GetColorKey failed because the color key isn't known.
NOERROR | No error.

Remarks

Getting the value on the primary stream will retrieve the destination color key being used by the overlay surface. Getting this value on the secondary pin returns the color key being used by that particular stream.

Current DirectShow implementation of this interface can return NULL for either the pColorKey or the pColor parameters; however, the method will fail and return E_INVALIDARG if both parameters are NULL.

Note The DWORD value returned by the pColor parameter is the actual color being used. So, if the bit depth of the display is 8, 16, 24, 32 the last 8, 16, 24 or 32 bits of the DWORD specify the actual value of the color key.

See Also

IMixerPinConfig::SetColorKey

IMixerPinConfig::GetStreamTransparent

IMixerPinConfig Interface

Determines whether a stream is transparent.

Syntax

HRESULT GetStreamTransparent(
    BOOL *pbStreamTransparent
    ) PURE;

Parameters

pbStreamTransparent
[out] Pointer to a value indicating whether the stream is transparent. TRUE indicates transparent stream; FALSE indicates not a transparent stream.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_NOTIMPL | Method is not supported.
NOERROR | No error.

See Also

IMixerPinConfig::SetStreamTransparent

IMixerPinConfig::GetRelativePosition

IMixerPinConfig Interface

Retrieves the position of the stream in the display window.

Syntax

HRESULT GetRelativePosition(
    DWORD *pdwLeft,
    DWORD *pdwTop,
    DWORD *pdwRight,
    DWORD *pdwBottom ) PURE;

Parameters

pdwLeft
[out] Pointer to a value indicating the x-coordinate in the top-left corner of the display window.
pdwTop
[out] Pointer to a value indicating the y-coordinate in the top-left corner of the display window.
pdwRight
[out] Pointer to a value indicating the x-coordinate in the bottom-right corner of the display window.
pdwBottom
[out] Pointer to a value indicating the y-coordinate in the bottom-right corner of the display window.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current DirectShow implementation return values include:
E_INVALIDARG | Coordinates not in the {0, 0, 10,000, 10,000} range.
NOERROR | No error.

Remarks

This method assumes window coordinates of {0, 0, 10,000, 10,000}. If the video stream is being rendered in the bottom right quarter of the display window, this method would return {5,000, 5,000, 10,000, 10,000}.

See Also

IMixerPinConfig::SetRelativePosition

IMixerPinConfig::GetZOrder

IMixerPinConfig Interface

Retrieves the z-order of a particular video stream.

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT GetZOrder(
    DWORD *pdwZOrder
    ) PURE;

Parameters

pdwZOrder
[out] Pointer to a value indicating the order in which streams will clip each other.

Return Value

Returns E_NOTIMPL.

Remarks

Images with larger z-values are always in front of images with smaller z-values.

See Also

IMixerPinConfig::SetZOrder

IMixerPinConfig::SetAspectRatioMode

IMixerPinConfig Interface

Sets the aspect ratio correction mode for window resizing.

Syntax

HRESULT SetAspectRatioMode(
    AM_ASPECT_RATIO_MODE amAspectRatioMode
    ) PURE;

Parameters

amAspectRatioMode
[in] Value specifying one of the AM_ASPECT_RATIO_MODE enumerated type members.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current DirectShow implementation return values include:
E_NOTIMPL | Method called on secondary stream.
E_INVALIDARG | Invalid argument.
NOERROR | No error.

Remarks

Currently this function is implemented only on the primary pin of the Overlay Mixer filter. Calling it on a secondary pin will result in an error.

See Also

IMixerPinConfig::GetAspectRatioMode

IMixerPinConfig::SetBlendingParameter

IMixerPinConfig Interface

Sets the blending parameter that defines how a secondary stream is blended with a primary stream.

Syntax

HRESULT SetBlendingParameter(
    DWORD dwBlendingParameter
    ) PURE;

Parameters

dwBlendingParameter
[in] Value between 0 and 255 that indicates the amount of blending between a primary stream and a secondary stream.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current DirectShow implementation return values include:
E_UNEXPECTED | Method called on primary stream.
E_INVALIDARG | Value outside of possible range (0 to 255).
NOERROR | No error.

Remarks

The value of the dwBlendingParameter parameter must be between 0 and 255, where 0 makes the secondary stream invisible and 255 makes the primary stream invisible in the area that the secondary stream occupies. If no value is set the default is 255.

This method is not intended to be called on the primary stream.

Note Current DirectShow implementation of this interface allows only values of 0 or 255 for the dwBlendingParameter parameter. Any other values are invalid.

See Also

IMixerPinConfig::GetBlendingParameter

IMixerPinConfig::SetColorKey

IMixerPinConfig Interface

Sets the color key being used by a video stream.

Syntax

HRESULT SetColorKey(
    COLORKEY *pColorKey
) PURE;

Parameters

pColorKey
[in] Pointer to a COLORKEY structure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The term color key has different meanings depending on which stream it is referring to. The color key of the primary stream refers to the destination color key being used by the overlay surface. The color key of the secondary stream refers to the source color key used, when blitting from an offscreen surface to the primary surface.

Applications should set the color key of the primary pin to an obscure color (some color which, in all probability, will not be present on the desktop). Overlay mixer filters will try to pick an obscure color, but if the application knows that the specified color is part of some other content, then the application should change it.

Setting the color key on the secondary stream can be used to make the stream transparent and enable nonrectangular images. For example, if the secondary stream is closed-captioned text, then the closed-captioned text decoder should paint a solid color in the background and then set the color key on the corresponding pin to that color. This ensures that all pixels are transferred except those specified by the color key. If possible, applications should set the color key of the secondary stream to the same as that of the primary stream to give a slight performance advantage.

Setting this value on the primary stream sets the destination color key being used by the overlay surface. By default, the destination color key is used as the color key for all transparent (secondary) streams.

Valid arguments for the pColorKey parameter include CK_INDEX when video display mode is set to 256 colors, and CK_RGB when video display mode is set to a higher color depth such as hi-color, 24-bit, or 32-bit. The CK_RGB flag must be specified along with the CK_INDEX. If CK_INDEX flag is set then the index will be used as palette index in 256 color mode. But you must provide a COLORREF with a valid true color so that if the display mode is changed on the fly, DirectShow can switch to using the specified true color. This is because a number of true colors can be mapped to a single palette index, but going the other way from the palette index to a true color is not one-to-one.

Note Currently, this method is implemented only for the primary input pin.

See Also

IMixerPinConfig::GetColorKey

IMixerPinConfig::SetStreamTransparent

IMixerPinConfig Interface

Sets the stream to transparent.

Syntax

HRESULT SetStreamTransparent(
    BOOL bStreamTransparent
    ) PURE;

Parameters

bStreamTransparent
[in] Value specifying the transparency of the stream. Pass in TRUE to indicate stream is transparent; FALSE to indicate not a transparent stream.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_NOTIMPL | Method is not supported.
NOERROR | No error.

See Also

IMixerPinConfig::GetStreamTransparent

IMixerPinConfig::SetRelativePosition

IMixerPinConfig Interface

Sets the position of the stream in the display window.

Syntax

HRESULT SetRelativePosition(
    DWORD dwLeft,
    DWORD dwTop,
    DWORD dwRight,
    DWORD dwBottom ) PURE;

Parameters

dwLeft
[in] Value specifying the x-coordinate in the upper-left corner of the display window.
dwTop
[in] Value specifying the y-coordinate in the upper-left corner of the display window.
dwRight
[in] Value specifying the x-coordinate in the bottom-right corner of the display window.
dwBottom
[in] Value specifying the y-coordinate in the bottom-right corner of the display window.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Current DirectShow implementation return values include:
E_INVALIDARG | Coordinates not in the {0, 0, 10,000, 10,000} range.
NOERROR | No error.

Remarks

This method assumes window coordinates of {0, 0, 10,000, 10,000}. Therefore, if you want your video stream to be rendered in the bottom right quarter of the display window, you would call this method with the parameters {5,000, 5,000, 10,000, 10,000}.

Note Values greater than 10,000 are invalid and will cause an error.

See Also

IMixerPinConfig::GetRelativePosition

IMixerPinConfig::SetZOrder

IMixerPinConfig Interface

Sets the z-order of a particular video stream.

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT SetZOrder(
  DWORD dwZOrder
) PURE;

Parameters

dwZOrder
[in] Value indicating the order in which streams will clip each other.

Return Value

Returns E_NOTIMPL.

Remarks

The z-order indicates which streams can clip other streams. Images with larger z-values are always in front of images with smaller z-values.

The relative order of multiple streams is significant only if the video images overlap.

Specifying the same z-order for two overlapping streams can cause strange video artifacts.

See Also

IMixerPinConfig::GetZOrder


IMixerPinConfig2 Interface

The IMixerPinConfig2 interface is exposed on the input pins of the Overlay Mixer and contains methods that manipulate video color controls, if the VGA chip supports it.

This interface derives from the IMixerPinConfig interface.

Applications use this interface to get and set video color controls when mixing multiple video streams.

Requirements

Requires Mpconfig.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMixerPinConfig2 methods | Description
SetOverlaySurfaceColorControls | Sets the color control settings associated with the specified overlay surface.
GetOverlaySurfaceColorControls | Retrieves the color control settings currently associated with the specified overlay surface.

IMixerPinConfig2::GetOverlaySurfaceColorControls

IMixerPinConfig2 Interface

Retrieves the color control settings associated with the specified overlay surface.

Syntax

HRESULT GetOverlaySurfaceColorControls(
    LPDDCOLORCONTROL pColorControl
    ) PURE;

Parameters

pColorControl
[out] Address of a pointer to the DDCOLORCONTROL structure containing the color values currently applied to the specified surface.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. If the allocator on the pin is not using an overlay surface, E_FAIL is returned.

IMixerPinConfig2::SetOverlaySurfaceColorControls

IMixerPinConfig2 Interface

Sets the color control settings associated with the specified overlay surface.

Syntax

HRESULT SetOverlaySurfaceColorControls(
    LPDDCOLORCONTROL pColorControl
    ) PURE;

Parameters

pColorControl
[in] Address of a pointer to the DDCOLORCONTROL structure containing the new values to be applied to the specified surface.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. If the allocator on the pin is not using an overlay surface, E_FAIL is returned.


IMpeg2Demultiplexer

Microsoft DirectX 8.0

IMpeg2Demultiplexer Interface

This interface is implemented on the MPEG-2 Demultiplexer filter (Demux) and is used in both program stream mode and transport stream mode. It is called by applications or other filters to create, configure and delete output pins on the Demux.

MethodName | Description
CreateOutputPin | Creates a new output pin on the Demux.
SetOutputPinMediaType | Updates the media type of the specified output pin. (Not implemented in DirectX® 8.)
DeleteOutputPin | Deletes the specified output pin.

IMpeg2Demultiplexer::CreateOutputPin

IMpeg2Demultiplexer Interface

Creates a new output pin on the Demux.

Syntax

HRESULT CreateOutputPin(
    AM_MEDIA_TYPE* pMediaType,
     LPWSTR pszPinName,
      IPin** ppIPin
    );

Parameters

pMediaType
[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type information for the new pin.
pszPinName
[in] Pointer to a wide character string that specifies the application-defined friendly name for the new pin.
ppIPin
[out] Pointer that will be set to the new pin's IPin interface.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Duplicate pin names are not allowed. The returned IPin interface can be used to query the new pin for either an IMPEG2StreamIdMap interface (for program streams) or an IMPEG2PIDMap interface (for transport streams). Based on which interface is queried for on the first output pin, the Demux will configure itself for either transport or program stream mode. Once the Demux is configured, a call to QueryInterface to retrieve the other interface will fail.

IMpeg2Demultiplexer::SetOutputPinMediaType

IMpeg2Demultiplexer Interface

Updates the media type of the specified output pin. (Not implemented in DirectX® 8.)

Syntax

HRESULT SetOutputPinMediaType(
    LPWSTR pszPinName,
    AM_MEDIA_TYPE* pMediaType
    );

Parameters

pszPinName
[in] The friendly name of the pin as specified when the pin was created in a call to CreateOutputPin.
pMediaType
in] Pointer to an AM_MEDIA_TYPE structure that specifies the new media type information for the pin.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

For DirectX 8, the pin must be assigned the media type at the time it is created. The media type cannot be modified later.

Pins can be reconfigured at any time with a new media type. If no connection exists, the media type is simply updated. If the pin is connected, the success or failure of the call will depend on the downstream input pin's acceptance or rejection of the specified media type.

The media type is not interpreted in any way by the Demux. It is used only during connection negotiation by the output pin. It has no effect on the content of the media samples. Media sample content is defined when a PID is mapped via the MEDIA_SAMPLE_CONTENT parameter in the IMPEG2PIDMap::MapPID method, or via the defined values in an IMPEG2StreamId::MapStreamId call.

IMpeg2Demultiplexer::DeleteOutputPin

IMpeg2Demultiplexer Interface

Deletes the specified output pin.

Syntax

HRESULT DeleteOutputPin(
    LPWSTR pszPinName
    );

Parameters

pszPinName
[in] The friendly name of the pin as specified when the pin was created in a call to CreateOutputPin.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Call this method only when you need to delete a pin while keeping the filter alive. When the filter is released, it will perform all necessary cleanup on the output pins.


IMPEG2PIDMap

Microsoft DirectX 8.0

IMPEG2PIDMap Interface

This interface is implemented on each output pin of the MPEG-2 Demultiplexer filter (Demux) and is used in transport stream mode only. It is called by applications or other filters to associate the pin with one or more Packet IDs (PID). Once a PID has been mapped, the Demux will deliver all packets with that ID to the output pin.

For program streams, use the IMPEG2StreamIdMap interface.

MethodName | Description
MapPID | Maps the packets of a specified PID to the pin.
UnmapPID | Unmaps the PID mapping created in a previous call to MapPID.
EnumPIDMap | Returns a collection of all the currently mapped PIDs on this pin.

IMPEG2PIDMap::MapPID

IMPEG2PIDMap Interface

Maps the packets of a specified PID to the pin.

Syntax

HRESULT MapPID(
    ULONG culPID,
    ULONG* pulPID,
    MEDIA_SAMPLE_CONTENT MediaSampleContent
);

Parameters

culPID
[in] Variable of type ULONG that specifies the number of elements in the pulPID array.
pulPID
[in] Pointer to a variable of type ULONG that specifies the PID to map.
MediaSampleContent
[in] Variable of type MEDIA_SAMPLE_CONTENT that specifies the contents of the stream.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

There may be no more than 255 distinct PIDs mapped at any given time. This includes the PIDs that the Demux maps internally for its own use; this number varies depending on the transport stream. This limitation should never present a problem because applications will typically map no more than 10-12 PIDs on any given transport stream.

IMPEG2PIDMap::UnmapPID

IMPEG2PIDMap Interface

Unmaps the PID mapping created in a previous call to MapPID.

Syntax

HRESULT UnmapPID(
    ULONG culPID,
    ULONG* pulPID
);

Parameters

culPID
[in] Variable of type ULONG that specifies the number of elements in the pulPID array.
pulPID
[in] Array of PIDs mapped for this pin.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

On output pins for audio and video streams, there will typically be only one PID mapped at any given time. On an output pin such as one delivering the PSI stream to the Transport Information Filter, there may be multiple PIDs mapped to a single pin. Use the IEnumPIDMap methods to determine which PIDs are mapped to the pin, and then fill in the pulPID array with those values.

IMPEG2PIDMap::EnumPIDMap

IMPEG2PIDMap Interface

Returns a collection of all the currently mapped PIDs on this pin.

Syntax

HRESULT EnumPIDMap(
    IEnumPIDMap** ppIEnumPIDMap
);

Parameters

ppIEnumPIDMap
[in] IEnumPIDMap interface pointer that will be set to the returned collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.


IMPEG2StreamIdMap

Microsoft DirectX 8.0

IMPEG2StreamIdMap Interface

This interface is implemented on each output pin of the MPEG-2 Demultiplexer filter (Demux) and is used in program stream mode only. It is called by applications or other filters to associate the pin with a specified Stream ID and to inform the pin whether substream filtering is required on the stream.

For transport streams, use the IMPEG2PIDMap interface.

MethodName | Description
MapStreamId | Maps the Stream ID of an elementary stream within an MPEG-2 program stream to a media content type and substream filtering information.
UnmapStreamId | Unmaps the Stream ID mapping created in a previous call to MapStreamId.
EnumStreamIdMap | Returns a collection of all the mapped Stream IDs on this pin.

IMPEG2StreamIdMap::MapStreamId

IMPEG2StreamIdMap Interface

Maps the Stream ID of an elementary stream within an MPEG-2 program stream to a media content type and substream filtering information.

Syntax

HRESULT MapStreamId(
    ULONG ulStreamId,
    DWORD MediaSampleContent,
    ULONG ulSubstreamFilterValue,
    int iDataOffset
);

Parameters

ulStreamId
[in] Variable of type ULONG that specifies the stream ID of the PES stream.
MediaSampleContent
[in] Variable of type ULONG that specifies the contents of the stream. Currently the only value supported is MPEG2_PROGRAM_ELEMENTARY_STREAM (defined as 0x00000001 in axextend.idl).
ulSubstreamFilterValue
[in] Variable of type ULONG that specifies which substream within this elementary stream to pass on to the downstream decoder. Only the low-order byte can contain a valid filter value. If iDataOffset = 0, this parameter is ignored.
iDataOffset
[in] Variable of type int that specifies the byte offset into the payload at which the substream begins.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

The Stream ID mapped by this method is the stream ID in the PES header. Substream filtering is most commonly used to provide multiple channels on a single audio stream.

IMPEG2StreamIdMap::UnmapStreamId

IMPEG2StreamIdMap Interface

Unmaps the Stream ID mapping created in a previous call to MapStreamId.

Syntax

HRESULT UnmapStreamId(
    ULONG culStreamId,
    ULONG* pulStreamID
);

Parameters

culStreamId
[in] Variable of type ULONG that specifies the number of elements in the pulStreamID array.
pulStreamID
[in] Array of Stream IDs mapped for this pin.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

There is typically only one stream ID mapped to a given pin, therefore pulStreamID will typically contain a single element.

IMPEG2StreamIdMap::EnumStreamIdMap

IMPEG2StreamIdMap Interface

Returns a collection of all the mapped Stream IDs on this pin.

Syntax

HRESULT EnumStreamIdMap(
    IEnumStreamIdMap** ppIEnumStreamIdMap
);

Parameters

ppIEnumStreamIdMap
[in] IEnumStreamIdMap interface pointer that will be set to the returned collection.

Return Value

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

Remarks

Currently, there is only one stream ID mapped to a given pin, therefore this collection will contain a single item.


IOverlay Interface

The IOverlay interface provides information so that a filter can write directly to video memory while placing the video in the correct window position. It is implemented on the input pin of the video renderer and communicates with an upstream filter (typically a video decompressor) by calling that filter's IOverlayNotify methods to notify it of changes to the video window.

This interface has no relationship to the DirectDraw® overlay capability. The Microsoft video renderer draws data it receives through the IMemInputPin interface, using DirectDraw overlays when available. This interface, used in place of IMemInputPin, is intended to provide notification support for any upstream filter that bypasses the renderer's drawing capabilities, but needs notifications of other display properties.

See the IOverlayNotify interface for more information on how the IOverlay and IOverlayNotify interfaces work together.

See the IOverlayNotify2 interface for more information on asynchronous notifications of changes to the rendering window.

This interface is implemented on the Microsoft® DirectShow® video renderer filter. It can also be implemented on replacement video renderer filters if desired. If doing so, implement this interface so that filters writing directly to the frame buffer or trying to position an overlay know where to display their video. To implement this interface, the renderer must be prepared to use methods on the IOverlayNotify interface or the IOverlayNotify2 interface of the filter doing the drawing, with notifications of video property changes.

The window-based renderer in DirectShow supports both IMemInputPin and IOverlay interfaces. These two interfaces are mutually exclusive. A filter chooses to use the IOverlay transport interface by providing a media type during connection that has a subtype of MEDIASUBTYPE_Overlay. After connection, it will be able to get and use successfully the IOverlay interface. If it connects with any other video formats (such as MEDIASUBTYPE_RGB8), trying to call through IOverlay returns VFW_E_NOT_OVERLAY_CONNECTION.

Use the methods on this function from an upstream filter that must control video overlay properties and intends to handle the displaying of the video data itself. This typically is used by hardware video decoders that have an alternate connection to the video hardware.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IOverlay methods | Description
GetPalette | Retrieves the current palette.
SetPalette | Sets the palette.
GetDefaultColorKey | Retrieves the default color key.
GetColorKey | Returns the identifier of the currently active color key.
SetColorKey | Changes the color key.
GetWindowHandle | Returns the window handle.
GetClipList | Retrieves the clipping list.
GetVideoPosition | Retrieves the current video source and destination rectangles.
Advise | Sets up an advise link for the overlay events.
Unadvise | Terminates the advise link.

IOverlay::Advise

IOverlay Interface

Sets up an advise link for the overlay events specified by the dwInterests parameter.

Syntax

HRESULT Advise(

  IOverlayNotify *pOverlayNotify,

  DWORD dwInterests

  );

Parameters

pOverlayNotify
[in] Pointer to the notification interface.
dwInterests
[in] Callbacks of interest, which can be any subset of the following events.
ADVISE_NONE | No changes.
ADVISE_CLIPPING | Change in clipping region (synchronized with the window).
ADVISE_PALETTE | Change in palette.
ADVISE_COLORKEY | Change of chroma key value.
ADVISE_POSITION | Change in position of video window (not synchronized with the window).
ADVISE_DISPLAY_CHANGE | Called on WM_DISPLAYCHANGE. The WM_DISPLAYCHANGE message is sent to all windows when the display resolution has changed.
ADVISE_ALL2 | All of the above.

Return Value

No return value.

Remarks

This method sets up an advise link for the IOverlayNotify interface to receive notifications. If one of these events occurs, the appropriate entry point in the pOverlayNotify parameter passed in is called (IOverlayNotify::OnClipChange, IOverlayNotify::OnColorKeyChange, IOverlayNotify::OnPaletteChange, or IOverlayNotify::OnPositionChange).

Only one advise link can be set on any given IOverlay interface. Trying to set another notification interface on second and subsequent calls returns VFW_E_ADVISE_ALREADY_SET. You can cancel an advise link by using IOverlay::Unadvise.

IOverlay::GetClipList

IOverlay Interface

Retrieves the clipping list.

Syntax

HRESULT GetClipList(

  RECT *pSourceRect,

  RECT *pDestinationRect,

  RGNDATA **ppRgnData

  );

Parameters

pSourceRect
[out] Pointer to the bounding client rectangle.
pDestinationRect
[in] Pointer to the destination rectangle.
ppRgnData
[out] Address of a pointer to the header and data describing clipping. If successful, the Microsoft® Win32® CoTaskMemFree function should free memory.

Return Value

No return value.

Remarks

The IOverlay implementation allocates the memory for the clipping rectangles, because it can vary in length. The filter calling this method should free the memory (using CoTaskMemFree) when it is finished with it.

IOverlay::GetColorKey

IOverlay Interface

Retrieves the current color key used for chroma keying.

Syntax

HRESULT GetColorKey(

  COLORKEY *pColorKey

  );

Parameters

pColorKey
[out] Pointer to where the current color key for chroma keying is copied.

Return Value

No return value.

Remarks

If you change the color key by using the IOverlay::SetColorKey method, all the advise links receive an IOverlayNotify::OnColorKeyChange callback method with the new color.

If no color key is currently being used, this method returns VFW_E_NO_COLOR_KEY_SET.

IOverlay::GetDefaultColorKey

IOverlay Interface

Retrieves the default color key used for a chroma key overlay.

Syntax

HRESULT GetDefaultColorKey(

  COLORKEY *pColorKey

  );

Parameters

pColorKey
[out] Pointer to where the default color key is copied.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

A filter using color keys can get a default color from the video renderer. The default color key can then be installed into the window using IOverlay::SetColorKey. The colors returned through this method vary depending on the current display mode. If the colors are 8-bit palettized, they will be bright system colors (such as magenta). If the display is in a true-color mode, they will be shades of black.

The IOverlay interface ensures that separate instances of the renderer on the same computer get different color keys so that overlays do not conflict.

IOverlay::GetPalette

IOverlay Interface

Retrieves the current system palette.

Syntax

HRESULT GetPalette(

  DWORD *pdwColors,

  PALETTEENTRY **ppPalette

  );

Parameters

pdwColors
[out] Pointer to the number of colors present.
ppPalette
[out] Address of a pointer to the retrieved palette structure.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

IOverlay::GetVideoPosition

IOverlay Interface

Retrieves the current video source and destination rectangles.

Syntax

HRESULT GetVideoPosition(
  [out] RECT *pSourceRect,
  [out] RECT *pDestinationRect
  );

Parameters

pSourceRect
[out] Pointer to the bounding video client rectangle.
pDestinationRect
[in] Pointer to the destination video rectangle.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

IOverlay::GetWindowHandle

IOverlay Interface

Retrieves the current window handle.

Syntax

HRESULT GetWindowHandle(
  HWND *pHwnd
  );

Parameters

pHwnd
[out] Pointer to the window handle.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

IOverlay::SetColorKey

IOverlay Interface

Changes the color key.

Syntax

HRESULT SetColorKey(

  COLORKEY *pColorKey

  );

Parameters

pColorKey
[out] Pointer to the color key value to be set. If successful, the actual color key value selected is copied to this parameter.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

If you change the color key by using the IOverlay::SetColorKey method, all the advise links will receive an IOverlayNotify::OnColorKeyChange callback method with the new color.

When using IOverlay on a palettized display, a filter can either install a color key (using IOverlay::SetColorKey) or install a palette (using IOverlay::SetPalette), but not both. This is because color keys in this mode require a palette to be realized that would conflict with SetPalette. Color keys can be uninstalled by requesting a color key with the CK_NOCOLORKEY flag. Likewise, any palette installed through SetPalette can be uninstalled by calling SetPalette and passing in null parameters (that is, SetPalette(0,NULL)).

Trying to set a palette when a color key is installed returns a VFW_E_PALETTE_SET error. Trying to set a color key when a palette is installed returns VFW_E_COLOR_KEY_SET.

IOverlay::SetPalette

IOverlay Interface

Sets the palette.

Syntax

HRESULT SetPalette(

  DWORD dwColors,

  PALETTEENTRY *pPalette

  );

Parameters

dwColors
[in] Number of colors present.
pPalette
[in] Pointer to colors to use for the palette.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method sets a logical palette for the window. The window is not guaranteed to always have the colors requested in the actual system device palette. The Microsoft® Windows® operating system only guarantees those colors when the window is the foreground active window. The current device palette can be obtained by calling IOverlay::GetPalette.

If the device does not have a palette, it returns VFW_E_NO_DISPLAY_PALETTE.

The Overlay Mixer filter returns E_NOTIMPL.

IOverlay::Unadvise

IOverlay Interface

Terminates the advise link established with the IOverlayNotify interface.

Syntax

HRESULT Unadvise(void);

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method terminates the advise link established by using the IOverlay::Advise method. Only one advise link can be maintained at any one time.


IOverlayNotify Interface

The IOverlayNotify interface provides an upstream filter, such as a decoder, with notifications of changes to the rendering window. This includes notifications of changes to the palette, color key, and window position, and visible region (clipping) changes.

Most software video decoders let the video renderer draw the decompressed images they produce by passing the media samples to the IMemInputPin interface on the renderer's input pin.

However, some video decoding filters (typically hardware decompression boards) handle the drawing of the images themselves, perhaps by using a VGA connector. These filters do not need to use IMemInputPin, but can instead use the IOverlay interface provided by the renderer input pin. Through this interface, the decoder can be notified when the window position or size changes, or when the current system palette changes in order to install and change color keys and palettes.

To get notifications of when the window size or position changes, when the current system palette changes, or when a different color key is used, decoders that do their own drawing should implement an IOverlayNotify interface. A pointer to this interface can then be passed to the IOverlay interface on the renderer's input pin, through the method, to set up an advise link (essentially a callback mechanism). After the advise link is established, the renderer calls the decoder's IOverlayNotify methods when the appropriate events occur. An advise link can be canceled by calling IOverlay::Unadvise.

The video renderer is the only filter that calls the methods on this interface. This is done automatically by the default video renderer. If you are writing a replacement video renderer, you will need to use the methods on this interface if your filter supports IOverlay and this interface is passed to your filter in an IOverlay::Advise call.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IOverlayNotify methods | Description
OnPaletteChange | Provides notification that the palette of the window has changed.
OnClipChange | Provides notification that the window's visible region has changed.
OnColorKeyChange | Provides notification that the chroma key has changed.
OnPositionChange | Provides notification that the position has changed.

IOverlayNotify::OnClipChange

IOverlayNotify Interface

Provides notification that the window's visible region has changed. It is essential that any overlay hardware be updated to reflect the change to the visible region before returning from this method.

Syntax

HRESULT OnClipChange(
  RECT *pSourceRect,
  RECT *pDestinationRect,
  RGNDATA *pRgnData
  );

Parameters

pSourceRect
[in] Pointer to the region of the video to use.
pDestinationRect
[in] Pointer to the video destination.
pRgnData
[in] Pointer to the clipping information.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

The calls to OnClipChange happen in synchronization with the window. It is called with an empty clip list to freeze the video before the window moves, and then called again when the window has stabilized with the new clip list.

If the window rectangle is all zeros, the window is invisible. As is the case for AVI decoders, the decoder should save the image if it relies on the current image to decode the next one.

IOverlayNotify::OnColorKeyChange

IOverlayNotify Interface

Provides notification that the window's color key has changed.

Syntax

HRESULT OnColorKeyChange(

  COLORKEY *pColorKey

  );

Parameters

pColorKey
[in] Pointer to the new chroma key.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

IOverlayNotify::OnPaletteChange

IOverlayNotify Interface

Provides notification that the palette of the window has changed.

Syntax

HRESULT OnPaletteChange(

  DWORD dwColors,

  const PALETTEENTRY *pPalette

  );

Parameters

dwColors
[in] Number of colors present.
pPalette
[in] Pointer to the array of palette colors.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

Before returning, the filter should copy the array of RGBQUAD values, if necessary.

IOverlayNotify::OnPositionChange

IOverlayNotify Interface

Provides notification that the position has changed.

Syntax

HRESULT OnPositionChange(
  const RECT *pSourceRect,
  const RECT *pDestinationRect
  );

Parameters

pSourceRect
[in] Pointer to the source video rectangle.
pDestinationRect
[in] Pointer to the destination video rectangle. Note that this is not clipped to the visible display area.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method is a callback intended for use by hardware overlay cards that do not want the expense of synchronous clipping updates, and just want to know when the source or destination video positions change.

Unlike the IOverlayNotify::OnClipChange method, this method is not called in synchronization with the window changing but, rather, at some point after the window has changed (basically in time with WM_SIZE messages received). This is therefore suitable for overlay cards that do not inlay their data to the frame buffer.


IOverlayNotify2 Interface

The IOverlayNotify2 interface derives from the IOverlayNotify interface. IOverlayNotify2 gives asynchronous notifications of changes to the rendering window, identifying changes to the exposed window area. The advise link optionally supports this for the purpose of accepting IOverlayNotify2::OnDisplayChange notification.

To get notifications that the exposed window area has changed, decoders that do their own drawing should implement an IOverlayNotify2 interface.

The video renderer is the only filter that calls the method on this interface. This is done automatically by the default video renderer.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IOverlayNotify methods | Description
OnPaletteChange | Provides notification that the palette of the window has changed.
OnClipChange | Provides notification that the visible region of the window has changed.
OnColorKeyChange | Provides notification that the chroma key has changed.
OnPositionChange | Provides notification that the position has changed.
IOverlayNotify2 method | Description
OnDisplayChange | Provides notification that the exposed window area has changed.

IOverlayNotify2::OnDisplayChange

IOverlayNotify2 Interface

Provides notification that the exposed window area has changed.

Syntax

HRESULT OnDisplayChange(
    HMONITOR hMonitor
);

Parameters

hMonitor
[in] Handle to the monitor used for displaying the overlay.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.


IPersistMediaPropertyBag Interface

The IPersistMediaPropertyBag interface sets and retrieves INFO and DISP chunks in Audio-Video Interleaved (AVI) streams. It uses the IMediaPropertyBag interface to store the chunks as name/value pairs.

The AVI Splitter filter and the WAV Parser filter support this interface for reading INFO and DISP chunks from an AVI or WAV file. The AVI MUX filter supports the interface for writing these chunks into a file.

IPersistMediaPropertyBag is modeled after, but does not inherit from, the IPersistPropertyBag interface. For more information on IPersistPropertyBag, see the Platform SDK.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IPersistMediaPropertyBag methods | Description
InitNew | Initializes a new property bag that will hold the media file header information.
Load | Retrieves the properties from the media file and stores them in the property bag.
Save | Saves the media file properties.

IPersistMediaPropertyBag::InitNew

IPersistMediaPropertyBag Interface

Initializes the object to receive new properties.

Syntax

HRESULT InitNew(void);

Return Value

Returns S_OK.

Remarks

Calling this method on the AVI Mux filter clears any properties that were previously set using the Load method.

Calling this method on the AVI Splitter filter or the WAV Parser has no effect.

IPersistMediaPropertyBag::Load

IPersistMediaPropertyBag Interface

Loads properties from the media property bag into the filter.

Syntax

HRESULT Load(
    IMediaPropertyBag *pPropBag
    IErrorLog *pErrorLog
);

Parameters

pPropBag
[in] Pointer to the IMediaPropertyBag interface of a media property bag created by the caller.
pErrorLog
[in] Reserved. Set the value to NULL.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_POINTER | NULL pointer argument.
STG_E_ACCESSDENIED | Access denied.
VFW_E_WRONG_STATE | Filter graph is not in a stopped state.

Remarks

Call this method on the AVI Mux filter to write the properties into the AVI stream. The following code example writes an IART (author name) INFO chunk to the stream.

IPersistMediaPropertyBag *pPersist = NULL;
IMediaPropertyBag *pBag = NULL;
VARIANT val;

// Query the AVI Mux filter for IPersistMediaPropertyBag (not shown).

CoCreateInstance(CLSID_MediaPropertyBag, NULL, CLSCTX_INPROC,
        IID_IMediaPropertyBag, (LPVOID *)&pBag);

val.vt = VT_BSTR;
val.bstrVal = SysAllocString(L"Author Name");
pBag->Write(L"INFO/IART", &val);
pPersist->Load(pBag, NULL);
VariantClear(&val);

The AVI Splitter filter and the WAV Parser do not support this method.

IPersistMediaPropertyBag::Save

IPersistMediaPropertyBag Interface

Saves properties from the filter into the media property bag.

Syntax

HRESULT Save(
    IMediaPropertyBag *pPropBag
    BOOL fClearDirty
    BOOL fSaveAllProperties
);

Parameters

pPropBag
[in] Pointer to the IMediaPropertyBag interface of a media property bag created by the caller.
fClearDirty
[in] Reserved. Can be any value.
fSaveAllProperties
[in] Reserved. Can be any value.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_NOTIMPL | Not implemented.
E_OUTOFMEMORY | Insufficient memory.
HRESULT_FROM_WIN32(ERROR_INVALID_DATA) | Invalid data.

Remarks

If you call this method on the AVI Splitter filter or the WAV Parser, the filter reads any INFO and DISP chunks from the file and stores them in the media property bag. You can use the IMediaPropertyBag::Read or IMediaPropertyBag::EnumProperty method to retrieve the chunks.

The AVI Mux filter does not implement this method.


IPin Interface

This interface is exposed by all input and output pins.

The filter graph manager uses this interface to connect pins and perform flushing operations. Applications can use this interface to query the pin for information. Applications should never call IPin methods that change a pin's state, such as Connect, Disconnect, BeginFlush, or EndFlush. To connect pins, an application must use the methods in IGraphBuilder.

Filter developers: The CBasePin, CBaseInputPin, and CBaseOutputPin classes implement this interface. Other base classes derive from these three classes.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IPin methods | Description
Connect | Connects the pin to another pin.
ReceiveConnection | Accepts a connection from another pin.
Disconnect | Breaks the current pin connection.
ConnectedTo | Retrieves the pin connected to this pin.
ConnectionMediaType | Retrieves the media type for the current pin connection.
QueryPinInfo | Retrieves information about the pin, such as the name, the owning filter, and the direction.
QueryId | Retrieves the pin identifier.
QueryAccept | Determines whether the pin accepts a specified media type.
EnumMediaTypes | Enumerates the pin's preferred media types.
QueryInternalConnections | Retrieves the pins that are connected internally to this pin (within the filter).
EndOfStream | Notifies the pin that no additional data is expected.
BeginFlush | Begins a flush operation.
EndFlush | Ends a flush operation.
NewSegment | Notifies the pin that media samples received after this call are grouped as a segment.
QueryDirection | Retrieves the direction of the pin (input or output).

IPin::BeginFlush

IPin Interface

Begins a flush operation.

Syntax

HRESULT BeginFlush(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

In a flush operation, a filter discards whatever data it was processing. It rejects new data until the flush is completed. The flush is completed when the upstream pin calls the IPin::EndFlush method. Flushing enables the filter graph to be more responsive when events alter the normal data flow. For example, flushing occurs during a seek.

When BeginFlush is called, the filter performs the following steps:

  1. Passes the IPin::BeginFlush call downstream.
  2. Sets an internal flag that causes all data-streaming methods to fail, such as IMemInputPin::Receive.
  3. Returns from any blocked calls to the Receive method.

When the BeginFlush notification reaches a renderer filter, the renderer frees any samples that it holds.

After BeginFlush is called, the pin rejects all samples from upstream, with a return value of S_FALSE, until the IPin::EndFlush method is called.

See Also

Data Flow In The Filter Graph

IPin::Connect

IPin Interface

Connects the pin to another pin.

Syntax

HRESULT Connect(
    IPin *pReceivePin,
    const AM_MEDIA_TYPE *pmt
);

Parameters

pReceivePin
[in] Pointer to the receiving pin's IPin interface.
pmt
[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type for the connection. Can be NULL.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
VFW_E_ALREADY_CONNECTED | The pin is already connected.
VFW_E_NO_ACCEPTABLE_TYPES | Could not find an acceptable media type.
VFW_E_NOT_STOPPED | The filter is active and the pin does not support dynamic reconnection.
VFW_E_TYPE_NOT_ACCEPTED | The specified media type is not acceptable.

Remarks

The pmt parameter can be NULL. It can also specify a partial media type, with a value of GUID_NULL for the major type, subtype, or format.

This method verifies that the connection is possible. If the pin rejects the connection, the method fails. The connecting pin proposes media types by calling IPin::ReceiveConnection on the receiving pin.

IPin::ConnectedTo

IPin Interface

Retrieves a pointer to the connected pin, if any.

Syntax

HRESULT ConnectedTo(
    IPin **ppPin
);

Parameters

ppPin
[out] Address of a variable that receives a pointer to the IPin interface of the other pin. Cannot be NULL.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

If the method succeeds, the IPin interface that it returns has an outstanding reference count. Be sure to release it when you are done.

IPin::ConnectionMediaType

IPin Interface

Retrieves the media type for the current pin connection, if any.

Syntax

HRESULT ConnectionMediaType(
    AM_MEDIA_TYPE *pmt
);

Parameters

pmt
[out] Pointer to an AM_MEDIA_TYPE structure that receives the media type.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

If the pin is connected, this method copies the media type into the AM_MEDIA_TYPE structure specified by pmt. The caller must free the media type's format block. You can use the Microsoft® Win32® CoTaskMemFree function, or the FreeMediaType helper function.

If the pin is not connected, this method clears the media type specified by pmt and returns an error code.

IPin::Disconnect

IPin Interface

Breaks the current pin connection.

Syntax

HRESULT Disconnect(void);

Return Value

Returns an HRESULT value. Possible values include the following.

S_FALSE | The pin was not connected.
S_OK | Success.
VFW_E_NOT_STOPPED | The filter is active.

Remarks

This method fails if the filter is paused or running. If the pin supports the IPinConnection interface, call IPinConnection::DynamicDisconnect to disconnect the pin when the filter is paused or running.

A pin should never use this method to disconnect from its peer.

IPin::EndFlush

IPin Interface

Ends a flush operation.

Syntax

HRESULT EndFlush(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

When this method is called, the filter performs the following actions:

  1. Waits for all queued samples to be discarded.
  2. Frees any buffered data.
  3. Clears any pending EC_COMPLETE notifications.
  4. Calls EndFlush downstream.

When the method returns, the pin can accept new samples.

See Also

Data Flow In The Filter Graph

IPin::EndOfStream

IPin Interface

Notifies the pin that no additional data is expected, until a new run command is issued to the filter.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_UNEXPECTED | Pin does not support this method.

Remarks

Call this method only on input pins. Output pins return E_UNEXPECTED.

This method sends an end-of-stream notification to the pin. The pin delivers the notification downstream. It must serialize end-of-stream notifications with IMemInputPin::Receive calls. If the pin queues media samples for delivery, it should queue end-of-stream notifications as well. The IPin::BeginFlush method flushes any queued end-of-stream notifications.

IPin::EnumMediaTypes

IPin Interface

Enumerates the pin's preferred media types.

Syntax

HRESULT EnumMediaTypes(
    IEnumMediaTypes **ppEnum
);

Parameters

ppEnum
[out] Address of a variable that receives a pointer to the IEnumMediaTypes interface.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

The IEnumMediaTypes interface works like a standard COM enumerator. For more information, see Enumerating Objects in a Filter Graph. If the method succeeds, the IEnumMediaTypes interface has an outstanding reference count. Be sure to release it when you are done.

IPin::NewSegment

IPin Interface

Notifies the pin that media samples received after this call are grouped as a segment, with a common start time, stop time, and rate.

Syntax

HRESULT NewSegment(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop,
    double dRate
);

Parameters

tStart
Start time of the segment, relative to the original source, in 100-nanosecond units.
tStop
End time of the segment, relative to the original source, in 100-nanosecond units.
dRate
Rate at which this segment should be processed, as a percentage of the original rate.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

A source filter (or parser filter) calls this method at the start of each new stream and after each seek operation. It calls the method on the input pin of the downstream filter, after delivering the previous batch of data and before calling IMemInputPin::Receive with any new data. The downstream filter propagates the NewSegment call downstream.

Filters can use segment information to process samples. For example, with some formats it is impossible to reconstruct a delta frame without the next key frame. Therefore, if the stop time occurs on a delta frame, the source filter must send some additional frames. The decoder filter determines the final frame based on the segment information. The segment rate is used to render continuous data sources, such as audio data. For example, the audio renderer uses the sampling rate and the segment rate to render the audio data correctly.

IPin::QueryAccept

IPin Interface

Determines whether the pin accepts a specified media type.

Syntax

HRESULT QueryAccept(
    const AM_MEDIA_TYPE *pmt
);

Parameters

pmt
[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns S_TRUE if the media type is acceptable. Otherwise, returns S_FALSE.

Remarks

A return value of S_OK does not guarantee that the pin can switch to the specified format while the filter is running. If you need to switch formats while the filter is running, and the pin supports the IPinConnection interface, call the IPinConnection::DynamicQueryAccept method.

IPin::QueryDirection

IPin Interface

Retrieves the direction of the pin (input or output).

Syntax

HRESULT QueryDirection(
    PIN_DIRECTION *pPinDir
);

Parameters

pPinDir
[out] Pointer to a variable that receives a member of the PIN_DIRECTION enumerated type.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_POINTER | Null pointer argument.

IPin::QueryId

IPin Interface

Retrieves an identifier for the pin.

Syntax

HRESULT QueryId(
    LPWSTR *Id
);

Parameters

Id
[out] Address of a variable that receives a string containing the pin identifier.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | Null pointer argument.

Remarks

This method supports graph persistence. Use this method to save a pin's state, and the IBaseFilter::FindPin method to restore the state. The pin's identifier string is defined by the filter implementation. The identifier must be unique within the filter.

Note The pin identifier is not necessarily the same as the pin name that the QueryPinInfo method returns.

The filter allocates the returned string using the Microsoft® Win32® CoTaskMemAlloc function. The caller must free it using CoTaskMemFree.

IPin::QueryInternalConnections

IPin Interface

Retrieves the pins that are connected internally to this pin (within the filter).

Syntax

HRESULT QueryInternalConnections(
    IPin **apPin,
    ULONG *nPin
);

Parameters

apPin
[out] Address of an array of IPin pointers.
nPin
[in, out] On input, specifies the size of the array. When the method returns, the value is set to the number of pointers returned in the array.

Return Value

Returns one of the following HRESULT values.

S_FALSE | Insufficient array size.
S_OK | Success.
E_FAIL | Failure.
E_NOTIMPL | Not implemented.

Remarks

On some filters, input pins correspond to particular output pins. For each pin, this method fills an array with pointers to the corresponding pins. If every input pin provides data for every output pin, the pin returns E_NOTIMPL.

If the method succeeds and returns a value of *nPin greater than zero, the array contains pointers to IPin interfaces. Be sure to release each interface pointer when you are done.

IPin::QueryPinInfo

IPin Interface

Retrieves information about the pin.

Syntax

HRESULT QueryPinInfo(
    PIN_INFO *pInfo
);

Parameters

pInfo
[out] Pointer to a PIN_INFO structure that receives the pin information.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_POINTER | Null pointer argument.

Remarks

When the method returns, if the pFilter member of the PIN_INFO structure is non-NULL, it has an outstanding reference count. Be sure to release the interface when you are done.

IPin::ReceiveConnection

IPin Interface

Accepts a connection from another pin.

Syntax

HRESULT ReceiveConnection(
    IPin *pConnector,
    AM_MEDIA_TYPE *pmt
);

Parameters

pConnector
[in] Pointer to the connecting pin's IPin interface.
pmt
[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type for the connection.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_ALREADY_CONNECTED | The pin is already connected.
VFW_E_NOT_STOPPED | Cannot connect while filter is active.
VFW_E_TYPE_NOT_ACCEPTED | The specified media type is not acceptable.

Remarks

The pin that initiates the connection calls this method on the receiving pin. If the receiving pin returns an error code, the connection fails.


IPinConnection Interface

This interface provides methods for reconnecting an input pin while the filter is still running. The filter graph calls methods on this interface when it performs dynamic reconnections (see the IGraphConfig interface). For more information, see Dynamic Graph Building.

Filter developers: Implement this interface on any input pin that allows dynamic reconnection or dynamic changes in format.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IPinConnection methods | Description
DynamicQueryAccept | Queries whether the pin can accept the specified media type while the graph is running with the current connection to this pin.
NotifyEndOfStream | Requests notification from the pin when the next end-of-stream condition occurs.
IsEndPin | Indicates whether a reconnection search should end at this pin.
DynamicDisconnect | Disconnects the pin when the filter is running.

IPinConnection::DynamicDisconnect

IPinConnection Interface

Disconnects the pin when the filter is active (paused or running). Call this method instead of IPin::Disconnect to disconnect a pin on an active filter.

Syntax

HRESULT DynamicDisconnect(void)

Return Value

If the pin was connected and the method succeeds, the return value is S_OK. If the pin was not connected, the return value is S_FALSE.

If the method fails, it returns an HRESULT value indicating the cause of the error.

IPinConnection::DynamicQueryAccept

IPinConnection Interface

Queries whether the pin can accept the specified media type while the graph is running with the current connection to this pin.

Syntax

HRESULT DynamicQueryAccept(
    const AM_MEDIA_TYPE *pmt
);

Parameters

pmt
[in] Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns one of the following HRESULT values.

S_OK | Media type is acceptable.
VFW_E_TYPE_NOT_ACCEPTED | Media type is not acceptable.

Remarks

If this method succeeds, the pin can accept the media type on the next sample or in a call to IPin::ReceiveConnection.

An application or filter can call this method to determine whether the filter graph must be reconfigured. If the pin can accept the specified media type, there is no need to reconfigure the graph.

Although the IPin::QueryAccept method also determines whether a pin can accept a format type, it does not guarantee that the pin can switch to that format while the filter is running. If you need to switch formats while the filter is running, call DynamicQueryAccept instead.

IPinConnection::IsEndPin

IPinConnection Interface

Indicates whether a reconnection search should end at this pin.

Syntax

HRESULT IsEndPin(void);

Return Value

If successful, returns one of the following HRESULT values.

S_FALSE | Media type is not acceptable.
S_OK | Media type is acceptable.

Otherwise, returns an error code indicating the error that occurred.

Remarks

A filter or application can call this method to determine whether the pin is a candidate for dynamic reconnection.

Generally, a sink filter or a filter that splits or merges data should return S_OK. Other filters (for example, simple transform filters) should return S_FALSE.

IPinConnection::NotifyEndOfStream

IPinConnection Interface

Requests notification from the pin when the next end-of-stream condition occurs.

Syntax

HRESULT NotifyEndOfStream(
    HANDLE hNotifyEvent
);

Parameters

hNotifyEvent
[in] Handle to an event object that the pin will signal.

Return Value

Returns one of the following HRESULT values if successful.

S_FALSE | Event handle was NULL, but there was no existing event handle to reset.
S_OK | Event handle was set. (If event handle was NULL, event notification was canceled.)

Otherwise, returns an error code indicating the error that occurred.

Remarks

This method enables the caller to push data through a portion of the filter graph ending with this pin.

For example, suppose the caller is pushing data from an output pin called "A" on one filter, to an input pin called "B" on another filter, possibly with intermediate filters connecting them. The following sequence of events would take place.

  1. The caller blocks the data flow at pin A.
  2. It calls IPinConnection::NotifyEndOfStream on pin B.
  3. It calls IPin::EndOfStream on the input pin connected to pin A.
  4. As the remaining data travels downstream through any intermediate filters, those filters propagate the end-of-stream notification.
  5. When pin B receives the end-of-stream notification, it signals the event given in the hNotifyEvent parameter. At that point, the caller can safely reconfigure the graph between pin A and pin B.

Because the purpose of this method is to enable the caller to rebuild the graph dynamically and then restart the connection, the end-of-stream notification does not represent the actual end of the stream. Therefore, pin B does not propagate the end-of-stream condition or signal EC_COMPLETE. This is an exception to the usual rules for data flow in the filter graph.

It is the caller's responsibility to cancel notification by calling this method again with a NULL event handle.

The filter graph calls this method inside the IGraphConfig::Reconnect method. If an application or filter does any specialized dynamic reconfiguration to the graph (using the IGraphConfig::Reconfigure method), it might call this method first in order to push data through the portion of the graph that is being reconfigured.


IPinFlowControl Interface

Blocks data flow from an active output pin. This interface is exposed by output pins that can reconnect dynamically. Use this interface to start a dynamic reconnection within the filter graph. For more information, see Dynamic Graph Building.

Filter developers: Parser and capture filters that support dynamic reconnection should support this interface on their output pins. Generally, other types of filters do not need to implement this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IPinFlowControl methods | Description
Block | Blocks or unblocks the flow of data from the pin.

IPinFlowControl::Block

IPinFlowControl Interface

Blocks or unblocks the flow of data from the pin.

Syntax

HRESULT Block(
    DWORD dwBlockFlags,
    HANDLE hEvent,
);

Parameters

dwBlockFlags
[in] Flag that indicates whether to block or unblock the pin. Must be one of the following values:
  • Zero: Unblock data flow from the pin.
  • AM_PIN_FLOW_CONTROL_BLOCK: Block data flow from the pin.
hEvent
[in] Handle to an event object, or NULL. If this parameter is non-NULL, the method is asynchronous and returns immediately. The event is signaled when the operation completes. If this parameter is NULL, the method is synchronous and does not complete until the pin is blocked. If dwBlockFlags is zero, this parameter must be NULL.

Return Value

Returns an HRESULT value. Possible values include the following.

S_FALSE | Pin is already unblocked.
S_OK | Success.
VFW_E_PIN_ALREADY_BLOCKED | Pin is already blocked on another thread.
VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD | Pin is already blocked on the calling thread.

Remarks

This method can be synchronous or asynchronous:

  • To call it asynchronously, use the CreateEvent function to create an event object. Pass the event handle in the hEvent parameter. The method returns immediately and signals the event when the operation has completed. Call a wait function such as WaitForSingleObject to wait for the event.
  • To call this method synchronously, set the hEvent parameter to NULL. The method blocks until it completes. The method might not complete until the pin is ready to deliver a sample. If the filter is paused, the method might block indefinitely. Therefore, you should not call this method synchronously from your main application thread.


IPinInfo Interface

This interface provides Automation-compatible methods for retrieving information about a pin, and for connecting pins. The filter graph manager exposes this interface.

Microsoft® Visual Basic® applications can use this interface to retrieve information about a pin, such as the media type and the pin direction. They can also use it to connect pins, using intermediate filters if necessary.

C/C++ applications should use the IGraphBuilder and IPin interfaces rather than this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether there is type information available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returned successfully.
GetIDsOfNames | Converts text names of properties and methods (including arguments) to their corresponding DISPIDs.
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IPinInfo methods | Description
get_Pin | Retrieves the pin object that supports the IPin interface.
get_ConnectedTo | Retrieves the IPinInfo object for the corresponding pin to which this pin is connected.
get_ConnectionMediaType | Retrieves the media type on this connection.
get_FilterInfo | Retrieves the IFilterInfo object for the filter to which this pin belongs.
get_Name | Retrieves the name of this pin.
get_Direction | Retrieves the pin direction.
get_PinID | Retrieves the pin identifier.
get_MediaTypes | Retrieves an IAMCollection interface providing access to the preferred media types supported by this pin.
Connect | Connects to the specified pin.
ConnectDirect | Connects directly to the specified pin.
ConnectWithType | Connects directly to the specified pin using only the specified media type.
Disconnect | Disconnects this pin from its connected pin.
Render | Creates a filter graph capable of rendering the pin's media type.

IPinInfo::Connect

IPinInfo Interface

Connects to the specified pin using other transform filters as necessary.

Syntax

HRESULT Connect(
    IUnknown *pPin
    );

Parameters

pPin
[in] Pointer to the pin to connect with.

Return Value

Returns an HRESULT value.

Remarks

The pPin parameter can be either an IPin or an IPinInfo object. This method uses the graph builder to determine the required transform filters to enable the connection of this pin with the specified pin. For example, if the pin is an output pin of a source filter, and the requested connection is the input pin of a video renderer, this method will insert a decompressor filter of the appropriate media type to make this a valid filter graph. This method is essentially an Automation wrapper for the IGraphBuilder::Connect method.

IPinInfo::ConnectDirect

IPinInfo Interface

Connects directly to the given pin, not using any intermediate filters.

Syntax

HRESULT ConnectDirect(
  IUnknown *pPin
  );

Parameters

pPin
[in] Pointer to the pin to connect directly to.

Return Value

Returns an HRESULT value.

Remarks

This method will return an error if a common media type for the connecting pins cannot be agreed on. This method is essentially an Automation wrapper for the IFilterGraph::ConnectDirect method.

IPinInfo::ConnectWithType

IPinInfo Interface

Connects directly to the specified pin by using the specified media type.

Syntax

HRESULT ConnectWithType(
  IUnknown *pPin,
  IDispatch *pMediaType
  );

Parameters

pPin
[in] Pointer to the pin to connect to; pPin is an object that must support either the IPin or the IPinInfo interface.
pMediaType
[in] Pointer to the media type the pin is connecting with; pMediaType must support the IMediaTypeInfo interface.

Return Value

Returns an HRESULT value.

Remarks

This method enables you to determine which media type you want the connection to be made with, rather than letting the pins decide the media type upon connection.

IPinInfo::Disconnect

IPinInfo Interface

Disconnects this pin from its connected pin.

Syntax

HRESULT Disconnect(void);

Return Value

Returns an HRESULT value.

Remarks

This method calls IPin::Disconnect on both pins.

IPinInfo::get_ConnectedTo

IPinInfo Interface

Retrieves the IPinInfo interface for the connected pin.

Syntax

HRESULT get_ConnectedTo(
  IDispatch **ppUnk
  );

Parameters

ppUnk
[out, retval] Address of a pointer to the IPinInfo interface for the pin.

Return Value

Returns an HRESULT value.

Remarks

This method is essentially an Automation wrapper for the IPin::ConnectedTo method.

IPinInfo::get_ConnectionMediaType

IPinInfo Interface

Retrieves the IMediaTypeInfo object containing the connection information.

Syntax

HRESULT get_ConnectionMediaType(
  IDispatch **ppUnk
  );

Parameters

ppUnk
[out, retval] Address of a pointer to the returned IMediaTypeInfo interface.

Return Value

Returns an HRESULT value.

Remarks

This method is essentially an Automation wrapper for the IPin::ConnectionMediaType method.

IPinInfo::get_Direction

IPinInfo Interface

Retrieves the pin direction.

Syntax

HRESULT get_Direction(
  LONG *ppDirection
  );

Parameters

ppDirection
[out, retval] Address of a pointer to the pin direction; either PINDIR_INPUT or PINDIR_OUTPUT.

Return Value

Returns an HRESULT value.

IPinInfo::get_FilterInfo

IPinInfo Interface

Retrieves the IFilterInfo interface for the filter to which this pin belongs.

Syntax

HRESULT get_FilterInfo(
  IDispatch **ppUnk
  );

Parameters

ppUnk
[out, retval] Address of a pointer to the retrieved IFilterInfo interface.

Return Value

Returns an HRESULT value.

IPinInfo::get_MediaTypes

IPinInfo Interface

Retrieves an IAMCollection interface providing access to the preferred media types supported by this pin.

Syntax

HRESULT get_MediaTypes(
  IDispatch **ppUnk
  );

Parameters

ppUnk
[out, retval] Address of a pointer to the IAMCollection interface containing the preferred media types as IMediaTypeInfo objects.

Return Value

Returns an HRESULT value.

Remarks

This method is essentially an Automation wrapper for the IPin::EnumMediaTypes method.

IPinInfo::get_Name

IPinInfo Interface

Retrieves the name of this pin.

Syntax

HRESULT get_Name(
  BSTR **ppUnk
  );

Parameters

ppUnk
[out, retval] Address of a pointer to the name of the pin.

Return Value

Returns an HRESULT value.

IPinInfo::get_Pin

IPinInfo Interface

Retrieves the pin object that supports the IPin interface.

Syntax

HRESULT get_Pin(
  IUnknown **ppUnk
  );

Parameters

ppUnk
[out, retval] Address of a pointer to the IUnknown object that supports IPin.

Return Value

Returns an HRESULT value.

Remarks

The IPinInfo interface is implemented by a wrapper COM object, so QueryInterface for IPin on this object will fail. The IPinInfo::get_Pin method returns the pin object, on which the IPin interface is supported.

IPinInfo::get_PinID

IPinInfo Interface

Retrieves the pin identifier.

Syntax

HRESULT get_PinID(
  BSTR *strPinID
  );

Parameters

strPinID
[out, retval] Pointer to the pin identifier string.

Return Value

Returns an HRESULT value.

Remarks

The returned strPinID string can be passed to IFilterInfo::FindPin. This is often the same as the name of the pin, but might be some other value. This identifier can be written to persistent storage and used later to identify the same pin in a different instance of the filter.

IPinInfo::Render

IPinInfo Interface

Connects filters together as necessary in order to render the output of this pin, using any necessary transform and rendering filters.

Syntax

HRESULT Render(void);

Return Value

Returns an HRESULT value.

Remarks

This method is essentially an Automation wrapper for the IGraphBuilder::Render method. This method is valid only on output pins.


IQualityControl Interface

This interface provides support for quality control. An object exposes this interface if it can generate or receive quality-control messages. This includes renderer filters (which typically generate quality control messages), pins (which receive them), and external quality managers (which also receive them).

A renderer filter generates a quality-control message by calling the IQualityControl::Notify method on the output pin of the upstream filter. The upstream filter either handles the message or passes it upstream.

An application can implement its own quality-control manager. Call IQualityControl::SetSink on the renderer to designate the quality-control manager as the recipient for quality-control messages. Calling this method overrides the default handling of quality-control messages.

However, most applications will not implement their own quality-control managers; and aside from this special case, applications typically do not use this interface. For more information, see Quality-Control Management

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IQualityControl methods | Description
Notify | Notifies the recipient that a quality change is requested.
SetSink | Sets the IQualityControl object that will receive quality messages.

IQualityControl::Notify

IQualityControl Interface

Notifies the filter that a quality change is requested.

Syntax

HRESULT Notify(
    IBaseFilter *pSelf,
    Quality q
);

Parameters

pSelf
[in] Pointer to the filter that is sending the quality notification.
q
[in] Quality notification structure.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

IQualityControl::SetSink

IQualityControl Interface

Sets the IQualityControl object that will receive quality messages.

Syntax

HRESULT SetSink(
    IQualityControl *piqc
);

Parameters

piqc
Pointer to the IQualityControl object to which the notifications should be sent.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

The filter that receives a call to this method should record the piqc but should not add a reference count to it. The object pointed to will be a quality manager and will be a part of the filter graph (for example, a plug-in distributor). Adding a reference count to this could cause circular reference problems.

The reference to the object specified in piqc is guaranteed to be valid until this method is called with a null value.


IQualProp Interface

This interface provides methods for retrieving performance information from video renderers. The values returned through the interface are reset each time the filter is stopped. The Video Renderer filter and the Full Screen Renderer filter expose this interface.

Applications can use this interface to retrieve video performance information.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IQualProp methods | Description
get_AvgFrameRate | Retrieves the average frame rate achieved.
get_AvgSyncOffset | Retrieves the average time difference between when a frame was due for rendering and when rendering actually began (this is returned as a value in milliseconds).
get_DevSyncOffset | Retrieves the average time difference between when a frame was due for rendering and when rendering actually began (this is returned as a standard deviation).
get_FramesDrawn | Retrieves the number of frames drawn since streaming started.
get_FramesDroppedInRenderer | Retrieves the number of frames dropped by the renderer.
get_Jitter | Expresses the average time between successive frames delivered to the video renderer.

IQualProp::get_AvgFrameRate

IQualProp Interface

Retrieves the average frame rate since streaming started.

Syntax

HRESULT get_AvgFrameRate(
    int *piAvgFrameRate
    ) PURE;

Parameters

piAvgFrameRate
Pointer to the number of frames per second (fps) since the streaming began.

Return Value

Returns an HRESULT value.

IQualProp::get_AvgSyncOffset

IQualProp Interface

Retrieves the average time difference between when the video frames should have been displayed and when they actually were.

Syntax

HRESULT get_AvgSyncOffset(
    int *piAvg
    );

Parameters

piAvg
Pointer to the time difference, expressed in milliseconds.

Return Value

Returns an HRESULT value.

IQualProp::get_DevSyncOffset

IQualProp Interface

Retrieves the average time difference between when the video frames should have been displayed and when they actually were. This method is the same as the IQualProp::get_AvgSyncOffset method except that the value returned is calculated as a standard deviation rather than as a simple average.

Syntax

HRESULT get_DevSyncOffset(
    int *piDev
    );

Parameters

piDev
Pointer to a value denoting the accuracy of the video frames displayed.

Return Value

Returns an HRESULT value.

Remarks

When playing video from networks, the presentation can often be disrupted by network glitches. For this reason, expressing the accuracy of video frames by a simple average is inappropriate. Looking at a standard deviation provides a better idea of the overall accuracy.

IQualProp::get_FramesDrawn

IQualProp Interface

Retrieves the number of frames drawn since streaming started.

Syntax

HRESULT get_FramesDrawn(
    int *pcFramesDrawn
    );

Parameters

pcFramesDrawn
Pointer to the number of frames drawn since streaming started.

Return Value

Returns an HRESULT value.

IQualProp::get_FramesDroppedInRenderer

IQualProp Interface

Retrieves the number of frames dropped by the renderer.

Syntax

HRESULT get_FramesDroppedInRenderer(
    int *pcFrames
    );

Parameters

pcFrames
Pointer to the number of frames dropped by the renderer.

Return Value

Returns an HRESULT value.

Remarks

The property page uses this method to retrieve data from the renderer.

IQualProp::get_Jitter

IQualProp Interface

Expresses the average time between successive frames delivered to the video renderer.

Syntax

HRESULT get_Jitter(
    int *piJitter
    );

Parameters

piJitter
Pointer to the standard deviation of the interframe time, in milliseconds.

Return Value

Returns an HRESULT value.


IQueueCommand Interface

Queues a command for processing at a designated time. The filter graph manager exposes this interface. Applications can use it to queue graph-control commands in advance.

The methods in IQueueCommand are modeled after the IDispatch::InvokeAt method. The application specifies an interface, a method on the interface, parameters to the method, and a reference time. The filter graph manager queues this information and then invokes the method at the specified time. The requested interface must inherit IDispatch and must be exposed by the filter graph manager. Examples include IMediaControl, IMediaEventEx, and IMediaPosition.

When the command is queued, the filter graph manager returns a pointer to the IDeferredCommand interface. The application can use this interface to cancel or modify the command.

Note The two methods in IQueueCommand are InvokeAtStreamTime and InvokeAtPresentationTime. In the context of the filter graph manager, stream time and presentation time are identical, so there is no functional difference between the two methods. Other objects could implement IQueueCommand differently. For more information about stream time and presentation time, see Time and Clocks in DirectShow.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IQueueCommand methods | Description
InvokeAtStreamTime | Queues a method to be invoked at the specified stream time.
InvokeAtPresentationTime | Queues a method to be invoked at the specified presentation time.

IQueueCommand::InvokeAtPresentationTime

IQueueCommand Interface

Queues a method to be invoked at the specified stream time.

Syntax

HRESULT InvokeAtPresentationTime(
    IDeferredCommand **pCmd,
    REFTIME time,
    GUID *iid,
    long dispidMember,
    short wFlags,
    long cArgs,
    VARIANT *pDispParams,
    VARIANT *pvarResult,
    short *puArgErr
);

Parameters

pCmd
[out] Address of a variable that receives an IDeferredCommand interface pointer.
time
[in] Time at which to invoke the command.
iid
[in] Pointer to the interface identifier (IID) of interface.
dispidMember
[in] Dispatch identifier (DISPID) of a method or property on the interface. Equivalent to the dispIdMember parameter of the IDispatch::InvokeAt method.
wFlags
[in] Flags describing the context of the call. Equivalent to the wFlags parameter of the IDispatch::InvokeAt method.
cArgs
[in] Number of arguments in pDispParams. Equivalent to the cArgs member of the DISPPARAMS structure.
pDispParams
[in] Pointer to an array that contains the arguments. Equivalent to the rgvarg member of the DISPPARAMS structure.
pvarResult
[in, out] Pointer a VARIANT that receives the result. Equivalent to the pVarResult parameter of the IDispatch::InvokeAt method.
puArgErr
[out] Pointer to a variable that receives the index of the first argument that has an error. Equivalent to the puArgErr parameter of the IDispatch::InvokeAt method.

Return Value

Returns an HRESULT value.

Remarks

Use the IDispatch::GetIDsOfNames method to retrieve the DISPID for the dispidMember parameter.

IQueueCommand::InvokeAtStreamTime

IQueueCommand Interface

Queues a method or property change for execution at a specified stream time (that is, presentation time relative to the current stream time offset).

Syntax

HRESULT InvokeAtStreamTime(
    IDeferredCommand **pCmd,
    REFTIME time,
    GUID *iid,
    long dispidMember,
    short wFlags,
    long cArgs,
    VARIANT *pDispParams,
    VARIANT *pvarResult,
    short *puArgErr
);

Parameters

pCmd
[out] Address of a variable that receives an IDeferredCommand interface pointer.
time
[in] Time at which to invoke the command.
iid
[in] Pointer to the interface identifier (IID) of interface.
dispidMember
[in] Dispatch identifier (DISPID) of a method or property on the interface. Equivalent to the dispIdMember parameter of the IDispatch::InvokeAt method.
wFlags
[in] Flags describing the context of the call. Equivalent to the wFlags parameter of the IDispatch::InvokeAt method.
cArgs
[in] Number of arguments in pDispParams. Equivalent to the cArgs member of the DISPPARAMS structure.
pDispParams
[in] Pointer to an array that contains the arguments. Equivalent to the rgvarg member of the DISPPARAMS structure.
pvarResult
[in, out] Pointer to a VARIANT that receives the result. Equivalent to the pVarResult parameter of the IDispatch::InvokeAt method.
puArgErr
[out] Pointer to a variable that receives the index of the first argument that has an error. Equivalent to the puArgErr parameter of the IDispatch::InvokeAt method.

Return Value

Returns an HRESULT value.

Remarks

Use the IDispatch::GetIDsOfNames method to retrieve the DISPID for the dispidMember parameter.


IReferenceClock Interface

Provides the reference time for the filter graph.

Filters that can act as a reference clock can expose this interface. It is also exposed by the system reference clock. The filter graph manager uses this interface to synchronize the filter graph. Applications can use this interface to retrieve the current reference time, or to request notification of an elapsed time.

For more information, see Time and Clocks in DirectShow.

Filter developers: Implement this interface if you are writing a filter that generates reliable clock times. For example, the Audio Renderer filter implements this interface, because audio sound boards usually contain a reference clock. Use the CBaseReferenceClock class to implement this interface.

To increase the chances that a non-rendering filter will be selected by the Filter Graph Manager as the reference close, follow these steps:

  1. Implement IReferenceClock in the filter.
  2. Implement IAMFilterMiscFlags in the filter.
  3. Return AM_FILTER_MISC_FLAGS_IS_SOURCE from IAMFilterMiscFlags::GetMiscFlags.
  4. Implement IAMPushSource on all output pins.
  5. Return (* pFlags) = 0 from IAMPushSource::GetPushSourceFlags.
  6. You may return E_NOTIMPL from all other IAMPushSource methods.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IReferenceClock methods | Description
GetTime | Retrieves the current reference time.
AdviseTime | Creates a one-shot advise request.
AdvisePeriodic | Creates a periodic advise request.
Unadvise | Removes a pending advise request.

IReferenceClock::AdvisePeriodic

IReferenceClock Interface

Creates a periodic advise request.

Syntax

HRESULT AdvisePeriodic(
    REFERENCE_TIME rtStartTime,
    REFERENCE_TIME rtPeriodTime,
    HSEMAPHORE hSemaphore,
    DWORD *pdwAdviseCookie
);

Parameters

rtStartTime
[in] Time of the first notification, in 100-nanosecond units. Must be greater than zero and less than MAX_TIME.
rtPeriodTime
[in] Time between notifications, in 100-nanosecond units. Must be greater than zero.
hSemaphore
[in] Handle to a semaphore, created by the caller.
pdwAdviseCookie
[out] Pointer to a variable that receives an identifier for the advise request.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | Invalid time values.
E_OUTOFMEMORY | Failure.
E_POINTER | NULL pointer argument.

Remarks

At each notification time, the clock releases the semaphore specified in the hSemaphore parameter. When no further notifications are required, call Unadvise and pass the pdwAdviseToken value returned from this call.

The following code example creates an advise request that signals five seconds from the time it is created, and again every second thereafter.

IReferenceClock *pRefClock = NULL;
// Get an IReferenceClock pointer (not shown).

DWORD          dwAdviseToken;
HANDLE         hSemaphore = CreateSemaphore(NULL, 0, 0x7FFFFFFF, NULL);
REFERENCE_TIME rtPeriodTime = 10000000; // A one-second interval
REFERENCE_TIME rtNow;

pRefClock->GetTime(&rtNow);
pRefClock->AdvisePeriodic(rtNow + (5 * rtPeriodTime),
                          rtPeriodTime,
                          hSemaphore,
                          &dwAdviseToken);
...

pRefClock->Unadvise(dwAdviseToken);

IReferenceClock::AdviseTime

IReferenceClock Interface

Creates a one-shot advise request.

Syntax

HRESULT AdviseTime(
    REFERENCE_TIME rtBaseTime,
    REFERENCE_TIME rtStreamTime,
    HEVENT hEvent,
    DWORD *pdwAdviseCookie
);

Parameters

rtBaseTime
[in] Base reference time, in 100-nanosecond units. See Remarks.
rtStreamTime
[in] Stream offset time, in 100-nanosecond units. See Remarks.
hEvent
[in] Handle to an event, created by the caller.
pdwAdviseCookie
[out] Pointer to a variable that receives an identifier for the advise request.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | Invalid time values.
E_OUTOFMEMORY | Failure.
E_POINTER | NULL pointer argument.

Remarks

This method creates a one-shot advise request for the reference time baseTime + streamTime. The sum must be greater than zero and less than MAX_TIME, or the method returns E_INVALIDARG. At the requested time, the clock signals the event specified in the hEvent parameter.

To cancel the notification before the time is reached, call the Unadvise method and pass the pdwAdviseToken value returned from this call. After the notification has occurred, the clock automatically clears it, so it is not necessary to call Unadvise. However, it is not an error to do so.

IReferenceClock::GetTime

IReferenceClock Interface

Retrieves the current reference time.

Syntax

HRESULT GetTime(
    REFERENCE_TIME *pTime
);

Parameters

pTime
[out] Pointer to a variable that receives the current time, in 100-nanosecond units.

Return Value

Returns an HRESULT value. Possible values include the following.

E_POINTER | NULL pointer argument.
S_FALSE | Returned time is the same as the previous value.
S_OK | Success.

IReferenceClock::Unadvise

IReferenceClock Interface

Removes a pending advise request.

Syntax

HRESULT Unadvise(
    DWORD dwAdviseCookie
);

Parameters

dwAdviseCookie
[in] Identifier of the request to remove. Use the value returned by AdviseTime or AdvisePeriodic in the pdwAdviseToken parameter.

Return Value

Returns an HRESULT value. Possible values include the following.

S_FALSE | Not found.
S_OK | Success.


IRegFilterInfo Interface

Provides access to filters in the Windows® Registry, and adds registered filters to the filter graph.

The filter graph manager implements this interface for use by applications written in Microsoft® Visual Basic®. C/C++ applications should use the IFilterMapper2 interface instead.

The IMediaControl::get_RegFilterCollection method returns a collection of IRegFilterInfo interfaces. Use the interface to query the names of filters in the collection and add desired filters to the filter graph.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether there is type information available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returned successfully.
GetIDsOfNames | Converts text names of properties and methods (including arguments) to their corresponding DISPIDs.
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IRegFilterInfo methods | Description
get_Name | Retrieves the name of the filter.
Filter | Creates an instance of this filter and adds it to the filter graph.

IRegFilterInfo::Filter

IRegFilterInfo Interface

Creates an instance of this filter and adds it to the filter graph.

Syntax

HRESULT Filter(

  IDispatch **ppUnk

  );

Parameters

ppUnk
[out] Address of a pointer to the IFilterInfo interface for the added filter.

Return Value

Returns an HRESULT value.

Remarks

Use the IRegFilterInfo::get_Name method (Name property in Visual Basic) to find the filter by comparing names in a collection of IRegFilterInfo interfaces.

IRegFilterInfo::get_Name

IRegFilterInfo Interface

Retrieves the name of the filter.

Syntax

HRESULT get_Name(

  BSTR *strName

  );

Parameters

strName
[out, retval] Pointer to the name of the filter.

Return Value

Returns an HRESULT value.

Remarks

Typically, a Visual Basic application will use the For Each...Next syntax on a collection of IRegFilterInfo interfaces and check the name of each filter in the registry until it finds the one it wants to add. It can then add the filter to the filter graph by using the IRegFilterInfo::Filter method.


IResourceConsumer Interface

Provides a callback mechanism for objects using the IResourceManager interface.

An object must implement IResourceConsumer if it uses the IResourceManager interface to request resources from the filter graph manager. The filter graph manager calls methods on IResourceConsumer to notify the object when a resource becomes available, or when the object should release a resource that it acquired.

Applications typically do not use or implement this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Returns pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IResourceManager methods | Description
AcquireResource | Notifies the resource consumer that a resource might be acquired.
ReleaseResource | Requests the resource consumer to release the specified resource.

IResourceConsumer::AcquireResource

IResourceConsumer Interface

Notifies the resource consumer that a resource might be acquired.

Syntax

HRESULT AcquireResource(
  LONG idResource
  );

Parameters

idResource
[in] Resource identifier of the resource to be acquired.

Return Value

Returns one of the following values.
S_OK | Consumer has successfully acquired the resource.
S_FALSE | Consumer has not acquired the resource but will use IResourceManager::NotifyAcquire when it does.
VFW_S_RESOURCE_NOT_NEEDED | Consumer no longer needs the resource.
Error Value | Consumer tried to acquire the resource but failed.

IResourceConsumer::ReleaseResource

IResourceConsumer Interface

Requests the resource consumer to release the specified resource.

Syntax

HRESULT ReleaseResource(
  LONG idResource
  );

Parameters

idResource
[in] Resource identifier to be released.

Return Value

Returns S_OK if the consumer has released it and requires it again when it becomes available, or S_FALSE if the consumer has not released it but will use IResourceManager::NotifyRelease when it does.


IResourceManager Interface

Resolves contentions for system resources.

The filter graph manager exposes this interface. Filters can use this interface to request resources that other objects are likely to use. For example, the Audio Renderer filter uses this interface to resolve contentions for the wave-output device, to enable sound to follow focus.

Applications will typically not use this interface.

An object can use this interface to resolve possible contentions between existing resources. The object registers the resource with the interface and then requests it whenever needed. The object should notify the filter graph manager whenever the user focus changes. The filter graph manager can then switch contended resources to the objects that have the focus of the user.

An object that uses this interface must implement the IResourceConsumer interface. IResourceConsumer provides a callback mechanism for the filter graph manager to notify the object when a resource becomes available, or when the object should release a resource that it acquired.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IResourceManager methods | Description
Register | Registers a single named resource with the resource manager.
RegisterGroup | Registers a named resource group with the resource manager.
RequestResource | Requests the use of a given registered resource.
NotifyAcquire | Notifies the resource manager that an attempt to acquire a resource has completed.
NotifyRelease | Notifies the resource manager that a resource consumer has released a resource.
CancelRequest | Cancels the request for a resource.
SetFocus | Notifies the resource manager that a specified object has been given the focus of the user.
ReleaseFocus | Sets the focus object to NULL in the resource manager if the object of the current focus object is the one specified in this method.

IResourceManager::CancelRequest

IResourceManager Interface

Cancels the request for a resource.

Syntax

HRESULT CancelRequest(
    LONG idResource,
    IResourceConsumer *pConsumer
);

Parameters

idResource
[in] Resource identifier of a pending request.
pConsumer
[in] Pointer to the IResourceConsumer interface that made the request.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method should be called when the IResourceConsumer object that requested the resource has not received it and no longer requires it. If it has already received the resource, it should use the IResourceManager::NotifyRelease method.

IResourceManager::NotifyAcquire

IResourceManager Interface

Notifies the resource manager that an attempt to acquire a resource has completed.

Syntax

HRESULT NotifyAcquire(
    LONG idResource,
    IResourceConsumer *pConsumer,
    HRESULT hr
);

Parameters

idResource
[in] Token for the registered resource.
pConsumer
[in] Pointer to the IResourceConsumer interface of the object requesting the resource.
hr
[in] Value indicating the success of the acquisition; S_OK if the resource was acquired, or an error value if not.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

Use this method after an IResourceConsumer::AcquireResource method returns an S_FALSE value, indicating that the acquisition will be asynchronous (that is, handled by a callback mechanism). If the hr parameter is S_OK, the resource manager will assume that the resource is now held by the caller. If the hr parameter is anything other than S_OK, the resource manager will assume that the attempt to acquire the resource failed and will reassign the resource elsewhere.

IResourceManager::NotifyRelease

IResourceManager Interface

Notifies the resource manager that IResourceConsumer has released a resource.

Syntax

HRESULT NotifyRelease LONG idResource,
    IResourceConsumer *pConsumer,
    BOOL bStillWant
);

Parameters

idResource
[in] Resource token.
pConsumer
[in] Pointer to the object releasing the resource.
bStillWant
[in] Flag that specifies whether the resource is still required. Set to TRUE to indicate that you still want the resource when it is next available, or FALSE if you no longer want the resource.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

Use this method in response to an IResourceConsumer::ReleaseResource method, or when you have finished using the resource.

IResourceManager::Register

IResourceManager Interface

Registers a single named resource with the resource manager.

Syntax

HRESULT Register(
    LPCWSTR pName,
    LONG cResource,
    LONG *plToken
);

Parameters

pName
[in] Named resource.
cResource
[in] Number of resources.
plToken
[out] Pointer to the returned token identifying the resource to be used in additional calls.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method registers a named resource, which can contain a number of resources, and returns a token to be used when requesting this resource. It is not an error if the resource is already registered; if the number in the cResource parameter is less than what is already registered, resources will be deallocated to the new count. To unregister the resource, pass a count of zero in cResource.

IResourceManager::RegisterGroup

IResourceManager Interface

Registers a named resource group with the resource manager.

Syntax

HRESULT RegisterGroup(
    LPCWSTR pName,
    LONG cResource,
    LONG *palTokens,
    LONG *plToken
);

Parameters

pName
[in] Named resource group.
cResource
[in] Number of resources in the group.
palTokens
[in, size_is(cResource)] Pointer to an array of resources in the group.
plToken
[out] Pointer to the returned group resource identifier.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

IResourceManager::ReleaseFocus

IResourceManager Interface

Sets the focus object to NULL in the resource manager if the current focus object is the one specified in this method.

Syntax

HRESULT ReleaseFocus(
    IUnknown *pFocusObject
);

Parameters

pFocusObject
[in] Pointer to the focus object.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

Use this method when the object of focus is about to be destroyed to ensure that the focus is not still being referenced.

IResourceManager::RequestResource

IResourceManager Interface

Requests the use of a given registered resource.

Syntax

HRESULT RequestResource(
    LONG idResource,
    IUnknown *pFocusObject,
    IResourceConsumer *pConsumer
);

Parameters

idResource
[in] Resource token retrieved when the resource was registered.
pFocusObject
[in] Pointer to the IUnknown interface of a focus object associated with a request (typically the filter's IUnknown interface).
pConsumer
[in] Pointer to the IResourceConsumer interface on the object requesting the resource.

Return Value

Returns an HRESULT value. Returns S_OK if the requested resource is returned, or S_FALSE if the resource is not available, in which case the resource manager will call the requesting object back when the resource becomes available. Any other return is an error.

Remarks

When there is more than one request for the resource, the resource manager will decide the priority by using the object of focus passed with each request and comparing it to the object of focus passed in the most recent IResourceManager::SetFocus method.

Requests will be filled in the following order of priority.

  1. Requests made with exactly the same object of focus as the last SetFocus method.
  2. Requests whose object of focus shares a common source filter.
  3. Requests whose object of focus shares a common filter graph.
  4. Requests in the same process as the focus.

While checking this priority, the resource manager will use QueryInterface on the focus object for IID_IFilter. If found, the resource manager will use IBaseFilter methods to check the filter graph and look for common source filters with the current focus object.

A filter should pass the IUnknown interface of the filter in the pFocusObject parameter. The filter graph manager matches filters to the filter graph and will attempt to trace filters to common source filters when checking objects of focus.

The focus object must be valid for the entire lifetime of the request—until either the IResourceManager::CancelRequest method is called, or the IResourceManager::NotifyRelease method is called with the bStillWant parameter set to FALSE.

IResourceManager::SetFocus

IResourceManager Interface

Notifies the resource manager that a specified object has been given the focus of the user.

Syntax

HRESULT SetFocus(
    IUnknown *pFocusObject
);

Parameters

pFocusObject
[in] Pointer to the object that has been given the user's focus.

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

In DirectShow, the object given the user's focus is typically a video renderer whose window has received the focus. The resource manager gives priority to requests for resources in the following order.

  1. Requests made with the focus object specified in the pFocusObject parameter.
  2. Requests whose focus object shares a common source filter.
  3. Requests whose focus object shares a common filter graph.
  4. Requests in the same process as the focus.

After a focus has been set, the resource manager must maintain a focus object until ReleaseFocus is called. That is, after calling this method, you must use ReleaseFocus before the IUnknown interface of the focus object becomes invalid, unless you can guarantee that SetFocus is called by a different object in the meantime. No reference count is held on the focus object.

The resource manager will hold this pointer until replaced or canceled, and will use it to resolve resource contention. It will use QueryInterface for the IBaseFilter interface at least and, if found, will use methods on that interface. It calls methods on IBaseFilter to decide which audio renderer to use if there are two (it will choose the one with a source filter common to the focus object), and also to determine if the two objects are within the same filter graph.


ISampleGrabber Interface

This interface provides methods for retrieving individual media samples as they move through the filter graph.

The Sample Grabber filter exposes this interface. Applications can call methods on this interface to retrieve media samples. For more information, see Grabbing Media Samples.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
ISampleGrabber methods | Description
SetOneShot | Specifies whether the filter should stop the graph after receiving one sample.
SetMediaType | Specifies the media type for the connection on the Sample Grabber's input pin.
GetConnectedMediaType | Retrieves the media type for the connection on the Sample Grabber's input pin.
SetBufferSamples | Specifies whether to copy sample data into a buffer as it goes through the filter.
GetCurrentBuffer | Retrieves a copy of the sample that the filter received most recently.
GetCurrentSample | Not currently implemented.
SetCallback | Specifies a callback method to call on incoming samples.

ISampleGrabber::GetConnectedMediaType

ISampleGrabber Interface

Retrieves the media type for the connection on the Sample Grabber's input pin.

Syntax

HRESULT GetConnectedMediaType(
    AM_MEDIA_TYPE *pType
);

Parameters

pType
Pointer to a variable that receives an AM_MEDIA_TYPE structure.

Return Value

Returns one of the following values.

E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | Filter is not connected.

ISampleGrabber::GetCurrentBuffer

ISampleGrabber Interface

Retrieves a copy of the buffer associated with the most recent sample.

Syntax

HRESULT GetCurrentBuffer(
    long *pBufferSize,
    long *pBuffer
);

Parameters

pBufferSize
[in, out] Pointer to the size of the buffer. If pBuffer is NULL, this parameter receives the required size. If pBuffer is not NULL, this parameter specifies the buffer size.
pBuffer
[out] Pointer to a buffer to receive a copy of the sample, or NULL.

Return Value

Returns one of the following values.

E_INVALIDARG | Samples are not being buffered.
E_POINTER | NULL pointer argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | Filter is not connected.
VFW_E_WRONG_STATE | The filter is in the wrong state.

Remarks

To activate buffering, call SetBufferSamples with a value of TRUE.

ISampleGrabber::GetCurrentSample

ISampleGrabber Interface

Not currently implemented.

Syntax

HRESULT GetCurrentSample(
    IMediaSample **ppSample
);

ISampleGrabber::SetBufferSamples

ISampleGrabber Interface

Specifies whether to copy sample data into a buffer as it goes through the filter.

Syntax

HRESULT SetBufferSamples(
    BOOL BufferThem
);

Parameters

BufferThem
Boolean value specifying whether to buffer sample data. If TRUE, the filter copies sample data into an internal buffer.

Return Value

Returns S_OK.

ISampleGrabber::SetCallback

ISampleGrabber Interface

Specifies a callback method to call on incoming samples.

Syntax

HRESULT SetCallback(
    ISampleGrabberCB *pCallback,
    long WhichMethodToCallback
);

Parameters

pCallback
Pointer to an ISampleGrabberCB interface containing the callback method, or NULL to cancel the callback.
WhichMethodToCallback
Index specifying the callback method. Must be one of the following values.
0 | Call the ISampleGrabberCB::SampleCB method.
1 | Call the ISampleGrabberCB::BufferCB method.

Return Value

Returns one of the following values.

E_INVALIDARG | Samples are not being buffered.
S_OK | Success.

Remarks

If the sample is a Microsoft® DirectDraw® surface, the surface is locked during the callback. The Win16 lock (also called Win16Mutex) might be locked as well. Both of these locks create the potential for deadlock. If the callback thread waits for a thread that is trying to call a DirectDraw API, it can cause deadlock. In addition, if the Win16 lock is being held, deadlock can result if the callback holds a critical section or waits for another thread to complete any activity.

Therefore, the callback should not perform any actions with the potential to block, such as holding a critical section or waiting on another thread. Also, do not call any GDI or USER32.DLL APIs that might cause a window to move. For more information about the Win16 lock, see Knowledge Base article Q125867, Understanding Win16Mutex (http://support.microsoft.com/support/kb/articles/Q125/8/67.asp).

The data processing thread blocks until the callback method returns. If the callback does not return quickly, it can interfere with playback.

ISampleGrabber::SetMediaType

ISampleGrabber Interface

Specifies the media type for the connection on the Sample Grabber's input pin.

Syntax

HRESULT SetMediaType(
    const AM_MEDIA_TYPE *pType
);

Parameters

pType
Pointer to a variable of type AM_MEDIA_TYPE that specifies the media type. It is not necessary to set all the structure members. This parameter can specify just the major type; specify the major type and the subtype; or specify the major type, subtype, and format type. The other structure members are ignored.

Return Value

Returns S_OK.

Remarks

By default, the Sample Grabber has no preferred media type. To ensure that the Sample Grabber connects to the correct filter, call this method before rendering the graph.

ISampleGrabber::SetOneShot

ISampleGrabber Interface

Specifies whether the filter should stop the graph after receiving one sample.

Syntax

HRESULT SetOneShot(
    BOOL OneShot
);

Parameters

OneShot
Boolean value specifying whether the filter should stop the graph after receiving one sample. If TRUE, the filter stops upon receiving the first sample and signals EC_COMPLETE. If FALSE, the filter continues to run normally.

Return Value

Returns S_OK.

Remarks

You can retrieve a sample at a particular time by calling this method with a value of TRUE, seeking to the desired time, and running the graph.


ISampleGrabberCB Interface

This interface provides callback methods for the ISampleGrabber::SetCallback method. If your application calls that method, it must implement this interface. For more information, see ISampleGrabber.

Requirements

Requires Qedit.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
ISampleGrabberCB methods | Description
SampleCB | Callback method that receives a pointer to the media sample.
BufferCB | Callback method that receives a pointer to the sample buffer.

ISampleGrabberCB::BufferCB

ISampleGrabberCB Interface

Callback method that receives a pointer to the sample buffer.

Syntax

HRESULT BufferCB(
    double SampleTime,
    BYTE *pBuffer,
    long BufferLen
);

Parameters

SampleTime
Starting time of the sample, in seconds.
pBuffer
Pointer to a buffer that contains the sample data.
BufferLen
Length of the buffer pointed to by pBuffer, in bytes.

Return Value

Returns S_OK if successful, or an HRESULT error code otherwise.

Remarks

Call the ISampleGrabber::SetBufferSamples method to activate sample buffering. Otherwise, the buffer will be empty.

ISampleGrabberCB::SampleCB

ISampleGrabberCB Interface

Callback method that receives a pointer to the media sample.

Syntax

HRESULT SampleCB(
    double SampleTime,
    IMediaSample *pSample
);

Parameters

SampleTime
Starting time of the sample, in seconds.
pSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns S_OK if successful, or an HRESULT error code otherwise.


ISeekingPassThru Interface

Initializes a helper object that implements seeking for one-input filters. The SeekingPassThru helper object exposes the interface. Filters with one input pin can use this interface to implement the IMediaSeeking and IMediaPosition interfaces. For more information, see CSeekingPassThru.

Applications do not use this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
ISeekingPassThru methods | Description
Init | Initializes the seeking helper object.

ISeekingPassThru::Init

ISeekingPassThru Interface

Initializes the seeking helper object.

Syntax

HRESULT Init(
    BOOL bSupportRendering,
    IPin *pPin
);

Parameters

bSupportRendering
[in] Boolean value that specifies whether the filter is a renderer. Use the value TRUE if the filter is a renderer, or FALSE otherwise.
pPin
[in] Pointer to the IPin interface on the filter's input pin..

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_FAIL | Object was already initialized.
E_OUTOFMEMORY | Not enough memory to create the object.


IStreamBuilder Interface

Enables an output pin to notify the filter graph manager that the pin itself will build the downstream section of the filter graph. Output pins with special connection needs can implement this interface to override the default pin connection process used by the filter graph manager.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IStreamBuilder methods | Description
Render | Completes rendering of the stream originating with this pin. This can involve adding filters to the filter graph and connecting them.
Backout | Undoes steps taken in Render. This includes disconnecting and removing any filters that were added inside Render.

IStreamBuilder::Backout

IStreamBuilder Interface

Undoes steps taken in Render. This includes disconnecting and removing any filters that were added inside Render.

Syntax

HRESULT Backout(
   IPin *ppinOut
   IGraphBuilder *pGraph
)

Parameters

ppinOut
[in] Pointer to this pin's IPin interface.
pGraph
[in] Pointer to the filter graph manager's IGraphBuilder interface.

Return Value

Returns an HRESULT value. A return code of S_OK indicates to the graph builder that the disconnect was successful.

Remarks

The following code illustrates how to implement this method on an output pin.

STDMETHODIMP CMyOutputPin::BackOut(IPin *pOutputPin, IGraphBuilder *pBuilder)
{
    HRESULT hr = S_OK;
    if (m_Connected != NULL) {
        FILTER_INFO fi;

        // Find the filter pointer for the pin connected to my pin.
        hr = m_Connected->QueryFilterInfo(&fi);
        if (SUCCEEDED(hr)) {
            if (fi.pFilter != NULL) {
                //  Disconnect
                pBuilder->Disconnect(m_Connected);
                pBuilder->Disconnect(pOutputPin);
                // Remove the filter we added from the graph.
                pBuilder->RemoveFilter(fi.pFilter);
                fi.pFilter->Release();
            } else {
                hr = E_UNEXPECTED;
            }
        }
    }
    return hr;
}

IStreamBuilder::Render

IStreamBuilder Interface

Completes rendering of the stream originating with this pin. This can involve adding filters to the filter graph and connecting them.

Syntax

HRESULT Render(
    IPin *ppinOut
    IGraphBuilder *pGraph
);

Parameters

ppinOut
[in] Pointer to this pin's IPin interface.
pGraph
[in] Pointer to the filter graph manager's IGraphBuilder interface.

Return Value

Returns an HRESULT value. A return code of S_OK indicates that the stream was successfully rendered.

Remarks

The following code illustrates how to implement this method on an output pin.

STDMETHODIMP CMyOutputPin::Render(IPin *pOutputPin, IGraphBuilder *pBuilder)
{
    // This filter needs my special renderer connected to it.
    IBaseFilter *pMyRenderer = NULL;
    IPin *pMyRendererInputPin = NULL;
    bool bAddedToGraph = false;

    // Create my renderer.
    HRESULT hr = CoCreateInstance(CLSID_MyRenderer, NULL, CLSCTX_INPROC, IID_IBaseFilter, (void **)&pMyRenderer);
    if (SUCCEEDED(hr)) {
        // Add my renderer to the filter graph.
        hr = pBuilder->AddFilter(pMyRenderer, L"My Renderer");
    }
    // Find my renderer's input pin.

    if (SUCCEEDED(hr)) {
            bAddedToGraph = true;
            IEnumPins *pEnumPins;
            hr = pMyRenderer->EnumPins(&pEnumPins);
            if (SUCCEEDED(hr)) {
                DWORD nPins;
                if (S_OK != pEnumPins->Next(1, &pMyRendererInputPin, &nPins)) {
                    hr = E_UNEXPECTED;
                }
            }
    }
    if (SUCCEEDED(hr)) {
        // Connect my renderer to my output pin.
        hr = pBuilder->ConnectDirect(pOutputPin, pMyRendererInputPin);
    }
    if (FAILED(hr)) {
        if (bAddedToGraph) {
            pBuilder->RemoveFilter(pMyRenderer);
        }
        pMyRenderer->Release();
    }
    if (NULL != pMyRendererOutputPin) {
        pMyRendererInputPin->Release();
    }
    return hr;
}


IUnknown Interface

Manages the lifetime of a Component Object Model (COM) component and queries the component for other COM interfaces. All other COM interfaces inherit IUnknown.

This interface and its methods are fully described in the COM documentation and are included here only for quick reference.

If you implement an interface, you must implement IUnknown as well. The CUnknown base class provides a convenient way to implement IUnknown, but you can write your own implementation if you prefer. For more information, see How to Implement IUnknown.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.

IUnknown::AddRef

IUnknown Interface

Increments the reference count for the calling interface on an object. It should be called for every new copy of a pointer to an interface on a given object.

Syntax

ULONG AddRef(void);

Return Value

Returns an integer from 1 to n, the value of the new reference count. This information is meant to be used for diagnostic/testing purposes only, because, in certain situations, the value might be unstable.

IUnknown::QueryInterface

IUnknown Interface

Retrieves a pointer to a specified interface on a component to which a client currently holds an interface pointer. This method must use IUnknown::AddRef on the pointer it returns.

Syntax

HRESULT QueryInterface(

  REFIID iid,

  void **ppvObject

  );

Parameters

iid
[in] Value specifying the IID of the interface being requested.
ppvObject
[out] Address of a pointer to the object on return. If the object doesn't support the interface specified in iid, ppvObject is set to NULL.

Return Value

Returns S_OK if the interface is supported, E_NOINTERFACE if not.

IUnknown::Release

IUnknown Interface

Decrements the reference count for the calling interface on an object. If the reference count on the object falls to zero, the object is freed from memory.

Syntax

ULONG Release(void);

Return Value

Returns the resulting value of the reference count, which is used for diagnostic/testing purposes only. If you need to know that resources have been freed, use an interface with higher-level semantics.


IVideoFrameStep Interface

Steps through a video stream. This interface enables Microsoft® DirectShow® applications, including DVD players, to step through a video stream as slowly as one frame at a time. Obtain the interface through the filter graph manager, which controls the frame stepping process in conjunction with the Overlay Mixer filter or the Video Renderer filter. Backward frame stepping is not supported.

Note For frame stepping to work with a hardware decoder, the decoder must support the AM_KSPROPSETID_FrameStep property set.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IVideoFrameStep methods | Description
Step | Causes the filter graph to step forward by the specified number of frames.
CanStep | Determines the stepping capabilities of the specified filter.
CancelStep | Cancels the previous step operation.

IVideoFrameStep::CancelStep

IVideoFrameStep Interface

Cancels the previous Step operation.

Syntax

HRESULT CancelStep();

Return Value

Returns S_OK if the Step operation was successfully canceled, or E_FAIL otherwise.

IVideoFrameStep::CanStep

IVideoFrameStep Interface

Determines the stepping capabilities of the specified filter.

Syntax

HRESULT CanStep(
   long bMultiple,
   IUnknown *pStepObject
);

Parameters

bMultiple
If bMultiple is specified as 0 and the method returns S_OK, it means the object can step one frame at a time. If bMultiple if greater than 0, and the method returns S_OK, it means that pStepObject can step bMultiple frames at a time.
pStepObject
Pointer to an interface on the filter that will control the stepping operation. Specify NULL to instruct the Filter Graph Manager to perform frame stepping using the renderer filter for that particular filter graph. If the graph includes a custom filter that implements the frame stepping, then pStepObject should point to that filter's IBaseFilter interface.

Return Value

Returns S_OK if the object can step or E_INVALIDARG if pStepObject is invalid.

Remarks

The frames step in real time, which means that if the movie is playing at 30 frames per second, calling Step with bMultiple set to 60 would take 2 seconds to execute. All methods in this interface are asynchronous, so control returns to the application immediately.

IVideoFrameStep::Step

IVideoFrameStep Interface

Causes the filter graph to step forward by the specified number of frames.

Syntax

HRESULT Step(
   DWORD dwFrames,
   IUnknown *pStepObject
);

Parameters

dwFrames
Variable of type DWORD specifying the number of frames to skip. If dwFrames is 1, it means step one frame forward. If dwFrames == n and n is greater than 1, it means to skip n - 1 frames and show the nth frame.
pStepObject
Pointer to an interface on the filter that will control the stepping operation. Specify NULL to instruct the Filter Graph Manager to perform frame stepping using the renderer filter for that particular filter graph. If the graph includes a custom filter that implements the frame stepping, then pStepObject should point to that filter's IBaseFilter interface.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
VFW_E_FRAME_STEP_UNSUPPORTED | Frame stepping is not supported.
E_INVALIDARG | The pStepObject parameter is invalid.

Remarks

When the step operation is complete, this method sends an EC_STEP_COMPLETE event notification to the filter graph manager, which will pass it to the application's event loop and set the filter graph to a paused state.


IVideoWindow Interface

The IVideoWindow interface is implemented on the video renderer filter supplied with Microsoft® DirectShow® and exposed to applications through the filter-graph manager. (Note: C++ developers: Always obtain this interface by calling QueryInterface on the filter graph manager. Never obtain it directly from the video renderer.) IVideoWindow is a dual interface accessible to applications written in Microsoft® Visual Basic® as well as Visual C++®. IVideoWindow provides methods and properties for controlling the window in which video is displayed.

The methods require only that the video renderer be connected. If it is not connected, all the interface functions return VFW_E_NOT_CONNECTED. Properties set on a video renderer persist between successive connections and disconnections. All applications should ensure that they reset the renderer properties before starting a presentation.

Because this interface is Automation-compatible, there are two important aspects to remember about parameters accepted by these methods. First, all Boolean returns are OAFALSE (0) or OATRUE (–1), which is different from the C or C++ definition. Second, all strings are defined as being of type BSTR. All strings sent to the interface should be allocated through the Automation SysAllocString function, and similarly all strings returned from the interface should be freed by using the Automation SysFreeString function.

Implement this interface if you are writing a replacement video renderer filter. You can use the CBaseVideoWindow class, which handles the IDispatch implementation for Automation, to help implement this interface. Note: MFC applications in which the video renderer is in a child window must have an empty WM_ERASEBKGND message handler in order for the video display area to repaint correctly.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDispatch methods | Description
GetTypeInfoCount | Determines whether there is type information available for this dispinterface.
GetTypeInfo | Retrieves the type information for this dispinterface if GetTypeInfoCount returned successfully.
GetIDsOfNames | Converts text names of properties and methods (including arguments) to their corresponding DISPIDs.
Invoke | Calls a method or accesses a property in this dispinterface if given a DISPID and any other necessary parameters.
IVideoWindow methods | Description
put_Caption | Sets the text caption on the playback window.
get_Caption | Retrieves the text caption on the playback window.
put_WindowStyle | Sets the playback window style.
get_WindowStyle | Retrieves the window style of the video window.
put_WindowStyleEx | Sets the style of the control window.
get_WindowStyleEx | Retrieves the extended style of the video window.
put_AutoShow | Specifies if the window will be automatically shown on the first state change.
get_AutoShow | Retrieves information about whether the window will be automatically shown.
put_WindowState | Sets the current window state (such as visible or minimized).
get_WindowState | Retrieves the current window state (such as visible or minimized).
put_BackgroundPalette | Informs the renderer to realize its palette in the background.
get_BackgroundPalette | Retrieves information about whether any palette required will be realized in the background.
put_Visible | Sets the visibility of the window.
get_Visible | Retrieves the visibility of the window.
put_Left | Sets the x-axis coordinate for the video window.
get_Left | Retrieves the x-axis coordinate for the video window.
put_Width | Sets the width of the video window.
get_Width | Retrieves the width of the video window.
put_Top | Sets the y-axis coordinates for the video window.
get_Top | Retrieves the y-axis coordinates for the video window.
put_Height | Sets the height of the video window.
get_Height | Retrieves the height of the video window.
put_Owner | Sets the owning parent window for the video playback window.
get_Owner | Retrieves the owning parent window for the video playback window.
put_MessageDrain | Specifies a window to which the video window will post messages.
get_MessageDrain | Retrieves the window set to receive messages from the video window.
get_BorderColor | Retrieves the border color for the video window.
put_BorderColor | Sets the border color for the video window.
get_FullScreenMode | Retrieves the full-screen rendering mode of the video renderer filter supporting this interface.
put_FullScreenMode | Sets the full-screen mode for the video renderer filter supporting this interface.
SetWindowForeground | Tells the renderer filter to become the foreground window.
NotifyOwnerMessage | Forwards messages that have been received by a parent window to a child window owned by a filter.
SetWindowPosition | Sets the video window position on the display.
GetWindowPosition | Retrieves the video window position.
GetMinIdealImageSize | Retrieves the ideal minimum image size for the video image playback (client) area.
GetMaxIdealImageSize | Retrieves the ideal maximum image size for the video image playback (client) area.
GetRestorePosition | Retrieves the normal restored window dimensions.
HideCursor | Hides the cursor.
IsCursorHidden | Determines if the cursor is hidden or showing.

IVideoWindow::get_AutoShow

IVideoWindow Interface

Retrieves information about whether the window will be automatically shown.

Syntax

HRESULT get_AutoShow(
    long *AutoShow
);

Parameters

AutoShow
[out] Pointer to a value indicating whether the window will be automatically shown. OATRUE indicates that the window will be made visible when the state is changed to the paused or running state.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::get_BackgroundPalette

IVideoWindow Interface

Retrieves information about whether any palette required will be realized in the background.

Syntax

HRESULT get_BackgroundPalette(
    long *pBackgroundPalette
);

Parameters

pBackgroundPalette
[out] Pointer to a value indicating whether the palette will be realized in the background; OATRUE indicates that it will.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::get_BorderColor

IVideoWindow Interface

Retrieves the border color for the video window.

Syntax

HRESULT get_BorderColor(
    long *pColor
);

Parameters

pColor
[out] Pointer to the retrieved border color as a Microsoft Win32® COLORREF value.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::get_Caption

IVideoWindow Interface

Retrieves the textual title string for the video window.

Syntax

HRESULT get_Caption(
    BSTR *strCaption
);

Parameters

strCaption
[out] Pointer to the retrieved window title caption.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::get_FullScreenMode

IVideoWindow Interface

Retrieves the full-screen rendering capabilities of the renderer filter supporting this interface.

Syntax

HRESULT get_FullScreenMode(
    long *FullScreenMode
);

Parameters

FullScreenMode
[out] Pointer to a value indicating whether the renderer has full-screen capabilities; OATRUE if it supports full-screen video, or OAFALSE if not.

Return Value

Possible return values include the following:

E_NOTIMPL | Filter does not support full-screen mode.
E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

This method is called by the filter graph manager when asked to render the video to full-screen size. If the renderer does not have inherent support for full-screen playback, it should return E_NOTIMPL. Otherwise, it should return NOERROR. If the renderer does support full-screen playback, this method determines if it is currently switched on or off.

IVideoWindow::get_Height

IVideoWindow Interface

Retrieves the height of the video window.

Syntax

HRESULT get_Height(
    long *pHeight
);

Parameters

pHeight
[out] Pointer to the retrieved vertical dimension of the video window.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::get_Left

IVideoWindow Interface

Retrieves the x-axis coordinate for the video window.

Syntax

HRESULT get_Left(
    long *pLeft
);

Parameters

pLeft
[out] Pointer to the x-axis coordinate to be retrieved.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::GetMaxIdealImageSize

IVideoWindow Interface

Retrieves the ideal maximum image size for the video image playback (client) area.

Syntax

HRESULT GetMaxIdealImageSize(
    long *pWidth,
    long *pHeight
);

Parameters

pWidth
[out] Pointer to the image width, in pixels.
pHeight
[out] Pointer to the image height, in pixels.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_FALSE | Could not retrieve a minimum image size.
S_OK | Success.
VFW_E_WRONG_STATE | Filter is stopped.

Remarks

This method returns S_FALSE under various circumstances:

  • The filter is using an IOverlay transport.
  • UseWhenFullScreen mode is on. (See IDirectDrawVideo::UseWhenFullScreen.)
  • The video surface has no maximum overlay stretch. (The dwMaxOverlayStretch member of the DDCAPS structure is zero. See IDirectDrawVideo::GetCaps.)

IVideoWindow::get_MessageDrain

IVideoWindow Interface

Retrieves the window set to receive messages from the video window.

Syntax

HRESULT get_MessageDrain(
    OAHWND *Drain
);

Parameters

Drain
[in] Pointer to the window currently assigned to receive messages from the video window.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

The IVideoWindow::put_MessageDrain description contains a list of the Microsoft Win32® messages passed to the window that is specified as a message drain.

IVideoWindow::GetMinIdealImageSize

IVideoWindow Interface

Retrieves the ideal minimum image size for the video image playback (client) area.

Syntax

HRESULT GetMinIdealImageSize(
    long *pWidth,
    long *pHeight
);

Parameters

pWidth
[out] Pointer to the image width, in pixels.
pHeight
[out] Pointer to the image height, in pixels.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_FALSE | Could not retrieve a minimum image size.
S_OK | Success.
VFW_E_WRONG_STATE | Filter is stopped.

Remarks

This method returns S_FALSE under various circumstances:

  • The filter is using an IOverlay transport.
  • UseWhenFullScreen mode is on. (See IDirectDrawVideo::UseWhenFullScreen.)
  • Video playback is using a stretchable offscreen surface. (The dwCaps member of the DDCAPS structure includes the DDCAPS_BLTSTRETCH flag. See IDirectDrawVideo::GetCaps.)
  • The video surface has no minimum overlay stretch. (The dwMinOverlayStretch member of the DDCAPS structure is zero. See IDirectDrawVideo::GetCaps.)

IVideoWindow::get_Owner

IVideoWindow Interface

Retrieves the owning parent for the video window.

Syntax

HRESULT get_Owner(
    OAHWND *pOwner
);

Parameters

pOwner
[out] Pointer to the retrieved window handle.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::GetRestorePosition

IVideoWindow Interface

Retrieves the normal restored window dimensions.

Syntax

HRESULT GetRestorePosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft
[out] Pointer to the left x-axis coordinate of the window.
pTop
[out] Pointer to the top y-axis coordinate of the window.
pWidth
[out] Pointer to the width of the window, in pixels.
pHeight
[out] Pointer to the height of the window, in pixels.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

When the window is maximized or minimized, the window position methods return the actual window size. This method returns the dimensions that the window would be when restored. It is useful for applications that want to save a window state while the window is maximized or minimized.

IVideoWindow::get_Top

IVideoWindow Interface

Retrieves the y-axis coordinate of the video window.

Syntax

HRESULT get_Top(
    long *pTop
);

Parameters

pTop
[out] Pointer to the y-axis origin to be retrieved.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::get_Visible

IVideoWindow Interface

Retrieves the visibility of the video window.

Syntax

HRESULT get_Visible(
    long *pVisible
);

Parameters

pVisible
[out] Pointer to a value indicating whether the window is shown. OATRUE if it is; otherwise, the window is hidden.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::get_Width

IVideoWindow Interface

Retrieves the width of the video window.

Syntax

HRESULT get_Width(
    long *pWidth
);

Parameters

pWidth
[out] Pointer to the width to be retrieved.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::GetWindowPosition

IVideoWindow Interface

Retrieves the current window rectangle (not the client rectangle), in device coordinates.

Syntax

HRESULT GetWindowPosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft
[out] Pointer to the x-axis origin of the window.
pTop
[out] Pointer to the y-axis origin of the window.
pWidth
[out] Pointer to the width of the window, in pixels.
pHeight
[out] Pointer to the height of the window, in pixels.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

This method has the same effect as individually calling the IVideoWindow::get_Left, IVideoWindow::get_Top, IVideoWindow::get_Width, and IVideoWindow::get_Height methods.

IVideoWindow::get_WindowState

IVideoWindow Interface

Returns the state of the video window.

Syntax

HRESULT get_WindowState(
    long *WindowState
);

Parameters

WindowState
[out] Pointer to flags indicating the state of the video window.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

This method retrieves a subset of the properties of the window state, specifically SW_MINIMIZE, SW_MAXIMIZE, SW_SHOW, or SW_HIDE. These have the same definitions as the Win32 ShowWindow function.

IVideoWindow::get_WindowStyle

IVideoWindow Interface

Retrieves the window style of the video window.

Syntax

HRESULT get_WindowStyle(
    long *pWindowStyle
);

Parameters

pWindowStyle
[out] Pointer to a set of flags that matches a subset of the flags that can be set by the GWL_STYLE value of the Win32 GetWindowLong function.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

For a complete list of window styles, see the CreateWindow function in the Platform Software Development Kit (SDK).

IVideoWindow::get_WindowStyleEx

IVideoWindow Interface

Retrieves the extended window style of the video window.

Syntax

HRESULT get_WindowStyleEx(
    long *pWindowStyleEx
);

Parameters

pWindowStyleEx
[out, retval] Pointer to a set of flags that matches a subset of the flags that can be set by the GWL_STYLE value of the Win32 GetWindowLong function.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

This method uses extended window styles. For a complete list of window styles, see the CreateWindow function in the Platform SDK.

IVideoWindow::HideCursor

IVideoWindow Interface

Hides the cursor.

Syntax

HRESULT HideCursor(
    long HideCursor
);

Parameters

HideCursor
[in] Value specifying whether to hide the cursor. If OATRUE, do not display the cursor; if OAFALSE, display the cursor.

Return Value

Possible return values include the following:

E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

This method is typically used when the video renderer is in full-screen mode, where cursor display might be unwanted.

IVideoWindow::IsCursorHidden

IVideoWindow Interface

Determines if the cursor is hidden or showing.

Syntax

HRESULT IsCursorHidden(
    long *CursorHidden
);

Parameters

CursorHidden
[out] Pointer to a value indicating whether the cursor is hidden; if OATRUE, cursor is hidden; if OAFALSE, cursor is displayed.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

This method is typically used when the video renderer is in full-screen mode, where cursor display might be unwanted.

IVideoWindow::NotifyOwnerMessage

IVideoWindow Interface

Forwards messages that have been received by a parent window to a child window owned by a filter.

Syntax

HRESULT NotifyOwnerMessage(
    long hwnd,
    long uMsg,
    long wParam,
    long lParam
    );

Parameters

hwnd
[in] Window handle.
uMsg
[in] Message being sent.
wParam
[in] Message's wParam passed in.
lParam
[in] Message's lParam passed in.

Return Value

Possible return values include the following:

S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

This method should be used by windows that make a renderer window a child window. It forwards significant messages to the child window that the child window would not otherwise receive. This includes the following messages.

  • WM_ACTIVATEAPP
  • WM_DEVMODECHANGE
  • WM_DISPLAYCHANGE
  • WM_PALETTECHANGED
  • WM_PALETTEISCHANGING
  • WM_QUERYNEWPALETTE
  • WM_SYSCOLORCHANGE

IVideoWindow::put_AutoShow

IVideoWindow Interface

Determines whether the window will be automatically shown.

Syntax

HRESULT put_AutoShow(
    long AutoShow
);

Parameters

AutoShow
[in] Value specifying whether the window will be automatically shown. OATRUE (–1) means the window will be visible when the state changes; OAFALSE (0) means the window remains hidden until explicitly shown.

Return Value

Possible return values include the following:

E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

Many simple applications require a displayed window when a filter graph is set to the running state. AutoShow defaults to OATRUE so that when the graph changes state to paused or running, the window is visible (it also is set as the foreground window). It will remain visible on all subsequent state changes to paused or running. If you close the window while the stream is running, the window will not automatically reappear. If you stop and restart the stream, however, the window will automatically reappear.

See Also

IVideoWindow::put_Visible

IVideoWindow::put_BackgroundPalette

IVideoWindow Interface

Determines whether any palette required will be realized in the background.

Syntax

HRESULT put_BackgroundPalette(
    long BackgroundPalette
);

Parameters

BackgroundPalette
[in] Value specifying whether the palette will be realized in the background. Set to OATRUE (–1) to realize the palette in the background; otherwise, set to OAFALSE.

Return Value

Possible return values include the following:

E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

If BackgroundPalette is OATRUE, any palette required by the video is realized by the renderer in the background. This means that any colors the palette uses will change to their closest match in the display palette prior to drawing. This ensures that an application will not have its palette disturbed when playing a video. It does, however, impose severe performance penalties on the video and should not be used unless absolutely necessary. The default value for this property is OAFALSE.

IVideoWindow::put_BorderColor

IVideoWindow Interface

Sets the border color for the video window.

Syntax

HRESULT put_BorderColor(
    long Color
);

Parameters

Color
[in] New border color as a COLORREF type.

Return Value

Possible return values include the following:

S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

When a destination rectangle that is set differs from the visible client area of the window, a border is exposed around the edge. This method allows an application to change the border color. It is set to black by default. Any nonsystem color passed in is converted to its closest match according to the current palette before being used (this is not an issue on true color devices). Setting this causes the window border to be repainted in the new color automatically.

IVideoWindow::put_Caption

IVideoWindow Interface

Sets the textual title string for the video window.

Syntax

HRESULT put_Caption(
    BSTR strCaption
);

Parameters

strCaption
[in] Window title caption.

Return Value

Possible return values include the following:

E_POINTER | NULL pointer.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::put_FullScreenMode

IVideoWindow Interface

Sets the full-screen mode for the video renderer filter supporting this interface.

Syntax

HRESULT put_FullScreenMode(
    long FullScreenMode
);

Parameters

FullScreenMode
[in] Value specifying whether the video renderer filter supports full-screen mode; set to OATRUE if supporting full-screen video, or OAFALSE if not.

Return Value

Possible return values include the following:

E_NOTIMPL | Filter does not support full-screen mode.
S_FALSE | Filter is already in the requested mode.
S_OK | Success.

Remarks

This method enables an application to switch a full-screen renderer into and out of full-screen mode. The renderer's behavior when switched out of full-screen mode is implementation-dependent. The Microsoft full-screen renderer, for example, switches back to a window.

The IVideoWindow plug-in distributor in the filter graph manager implements full-screen renderer switching. It looks to see if any renderer in the graph supports a full-screen mode and, if not, will temporarily replace the renderer with the default DirectShow full-screen renderer. It calls IVideoWindow::GetMaxIdealImageSize to determine if a window can be made a topmost window and resized to the entire display. This is preferred to swapping renderers, because the filter graph might be using DirectDraw® overlays or a hardware decoder filter.

IVideoWindow::put_Height

IVideoWindow Interface

Sets the height of the video window.

Syntax

HRESULT put_Height(
    long Height
);

Parameters

Height
[in] New vertical dimension of the video window.

Return Value

Possible return values include the following:

E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

Calling this method does not affect the y-axis coordinate of the video window.

IVideoWindow::put_Left

IVideoWindow Interface

Sets the x-axis coordinate for the video window.

Syntax

HRESULT put_Left(
    long Left
);

Parameters

Left
[in] The x-axis coordinate to be set.

Return Value

Possible return values include the following:

E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

Calling this method does not affect the video window's width.

IVideoWindow::put_MessageDrain

IVideoWindow Interface

Specifies a window to which the video window will post messages.

Syntax

HRESULT put_MessageDrain(
    OAHWND Drain
);

Parameters

Drain
[in] Window to which messages will be posted.

Return Value

Possible return values include the following:

S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

The video renderer passes messages to the specified message drain by calling the Win32 PostMessage function. These messages allow you to write applications that include user interaction, such as applications that require mouse clicks on specific areas of the video display. An application can have a close relationship with the video window and know at certain time points to look for user interaction. When the renderer passes a message to the drain, it sends the parameters, such as the client-area coordinates, exactly as generated.

DirectShow passes the following messages to the window specified by the Drain parameter, if and when the application generates them.

  • WM_KEYDOWN
  • WM_KEYUP
  • WM_LBUTTONDBLCLK
  • WM_LBUTTONDOWN
  • WM_LBUTTONUP
  • WM_MBUTTONDBLCLK
  • WM_MBUTTONDOWN
  • WM_MBUTTONUP
  • WM_MOUSEACTIVATE
  • WM_MOUSEMOVE
  • WM_NCLBUTTONDBLCLK
  • WM_NCLBUTTONDOWN
  • WM_NCLBUTTONUP
  • WM_NCMBUTTONDBLCLK
  • WM_NCMBUTTONDOWN
  • WM_NCMBUTTONUP
  • WM_NCMOUSEMOVE
  • WM_NCRBUTTONDBLCLK
  • WM_NCRBUTTONDOWN
  • WM_NCRBUTTONUP
  • WM_RBUTTONDBLCLK
  • WM_RBUTTONDOWN
  • WM_RBUTTONUP

Because this member function does not make the message drain window a child window, applications with full-screen capabilities can use it.

IVideoWindow::put_Owner

IVideoWindow Interface

Sets an owning parent for the video window.

Syntax

HRESULT put_Owner(
    OAHWND Owner
);

Parameters

Owner
[in] Handle of new owner window.

Return Value

Possible return values include the following:

S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

This method offers a way for applications to set the owner of the video window. This is often used when playing videos in compound documents. This method changes the parent of the renderer window and sets the WS_CHILD style for the video window.

To forward video window messages to the parent window, use the IVideoWindow::put_MessageDrain method, supplying the window handle of the parent window. This method does not post messages automatically.

After using this method to set the owner of a video window, you must reset the owner to NULL (by calling put_Owner(NULL)) before releasing the filter graph. Otherwise, messages will continue to be sent to this window and errors will likely occur when the application is terminated.

IVideoWindow::put_Top

IVideoWindow Interface

Sets the y-axis coordinate of the video window.

Syntax

HRESULT put_Top(
    long Top
);

Parameters

Top
[in] The y-axis origin of the video window.

Return Value

Possible return values include the following:

E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

Calling this method does not affect the height of the video window.

IVideoWindow::put_Visible

IVideoWindow Interface

Changes the visibility of the video window.

Syntax

HRESULT put_Visible(
    long Visible
);

Parameters

Visible
[in] Boolean flag that is compatible with Automation.

Return Value

Possible return values include the following:

E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

If the Visible parameter is set to OATRUE (–1), the window is shown. If it is set to OAFALSE (0), the window is hidden.

IVideoWindow::put_Width

IVideoWindow Interface

Sets the video window's width.

Syntax

HRESULT put_Width(
    long Width
);

Parameters

Width
[in] Width to be set, in pixels.

Return Value

Possible return values include the following:

E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

Calling this method does not affect the video window's x-axis coordinate.

IVideoWindow::put_WindowState

IVideoWindow Interface

Sets the video window's state.

Syntax

HRESULT put_WindowState(
    long WindowState
);

Parameters

WindowState
[in] Describes the video window's state.

Return Value

Possible return values include the following:

S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

This method is a wrapper for the Microsoft Win32 ShowWindow function. IVideoWindow::put_WindowState passes the WindowState parameter on to CBaseWindow::DoShowWindow, which in turn passes it on to ShowWindow. Hence, WindowState can be any value that is valid for ShowWindow.

IVideoWindow::put_WindowStyle

IVideoWindow Interface

Changes the style parameters for the video window.

Syntax

HRESULT put_WindowStyle(
    long WindowStyle
);

Parameters

WindowStyle
[in] Set of flags that matches a subset of the flags that can be set by the GWL_STYLE value of the Microsoft Win32 GetWindowLong function.

Return Value

Possible return values include the following:

S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

Use this property to change the overall style of the video window; for example, to remove the border and caption areas of the video window. It is a fairly thin wrapper on top of setting the GWL_STYLE value of the Microsoft Win32 GetWindowLong function and therefore must be treated with care. In particular, ensure that the current styles are first retrieved, and then the necessary bit fields are added or removed. With some exceptions (noted here), the acceptable flags are the same as those allowed by the Win32 CreateWindow function.

Do not use this method to affect the window size. For example, if the window is minimized, do not set the WS_MAXIMIZE style; doing so causes unpredictable results. Instead, use the IVideoWindow::put_WindowState method for maximizing or minimizing the window.

Any of the following styles return E_INVALIDARG.

  • WS_DISABLED
  • WS_HSCROLL
  • WS_ICONIC
  • WS_MAXIMIZE
  • WS_MINIMIZE
  • WS_VSCROLL

IVideoWindow::put_WindowStyleEx

IVideoWindow Interface

Sets the style of the control window.

Syntax

HRESULT put_WindowStyleEx(
    long WindowStyleEx
);

Parameters

WindowStyleEx
[in] Value that specifies the style of the control window.

Return Value

Possible return values include the following:

S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

This method uses extended window styles. For a complete list of extended window styles, see the CreateWindowEx function in the Platform SDK.

Use this property to change the overall style of the video window; for example, to remove the border and caption areas of the video window. It is a fairly thin wrapper on top of setting the GWL_STYLE value of the Microsoft Win32 GetWindowLong function and therefore must be treated with care. In particular, ensure that the current styles are first retrieved, and then the necessary bit fields are added or removed.

Do not use the following window styles because they are not validated.

  • WS_DISABLED
  • WS_HSCROLL
  • WS_ICONIC
  • WS_MAXIMIZE
  • WS_MINIMIZE
  • WS_VSCROLL

With some exceptions (noted here), the acceptable flags are the same as those allowed by the Win32 CreateWindow function.

IVideoWindow::SetWindowForeground

IVideoWindow Interface

Moves the video window to the foreground and optionally gives it focus.

Syntax

HRESULT SetWindowForeground(
    long Focus
);

Parameters

Focus
Value that specifies whether the video window will get focus. A value of –1 gives the window focus and 0 does not.

Return Value

Possible return values include the following:

E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

IVideoWindow::SetWindowPosition

IVideoWindow Interface

Sets the position of the video window (not the client rectangle position) in device coordinates.

Syntax

HRESULT SetWindowPosition(
    long Left,
    long Top,
    long Width,
    long Height
);

Parameters

Left
[in] The x-axis origin of the window.
Top
[in] The y-axis origin of the window.
Width
[in] Width of the window, in pixels.
Height
[in] Height of the window, in pixels.

Return Value

Possible return values include the following:

E_INVALIDARG | Invalid argument.
S_OK | Success.
VFW_E_NOT_CONNECTED | The pins are not connected.

Remarks

This method has the same effect as individually calling the IVideoWindow::put_Left, IVideoWindow::put_Top, IVideoWindow::put_Width, and IVideoWindow::put_Height methods.

Specify, in window coordinates, where the video should appear. For example, setting a destination of (100,50,200,400) positions the video playback at an origin of 100 pixels from the left of the client area and 50 pixels from the top, with an overall size of 200 × 400 pixels. If the video is smaller than this (or a source rectangle has been specified that is smaller than the video), it will be stretched appropriately. Similarly, if the video is larger than the destination rectangle, the video is compressed into the visible rectangle. There are fairly severe performance penalties if an application does not keep the source and destination rectangles the same size.

Under typical circumstances, when no destination rectangle has been set, the video fills the entire visible client window area (regardless of how much the user has stretched the window). Also, the destination rectangle properties correctly return the size of the video window client area.


IVPBaseConfig Interface

IVPBaseConfig is implemented on a filter that wraps a hardware device such as a decoder, if that device has a video port to the graphics adapter. This interface allows the video port to communicate with the Overlay Mixer regarding configuration information. The IVPConfig interface derives from this interface. See also IVPBaseNotify and IVPNotify.

Applications never use this interface.

Requirements

Requires Dvp.h, Vptype.h, Vpconfig.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IVPBaseConfig methods | Description
GetConnectInfo | Retrieves connection information structures.
SetConnectInfo | Sets the index for the current video port connection information.
GetVPDataInfo | Retrieves the current video port data information.
GetMaxPixelRate | Retrieves the maximum pixels per second rate for a given width and height.
InformVPInputFormats | Informs the device what video formats the video port supports.
GetVideoFormats | Retrieves the video formats the decoder supports.
SetVideoFormat | Sets the format that the video will use.
SetInvertPolarity | Reverses the current polarity the decoder uses.
GetOverlaySurface | Determines whether the overlay mixer should use the driver's overlay surface and if so retrieves a pointer to the surface.
SetDirectDrawKernelHandle | Sets the Microsoft® DirectDraw® kernel handle for the decoder's minidriver to use.
SetVideoPortID | Sets the port ID that the video will use.
SetDDSurfaceKernelHandle | Sets the kernel handle that the DirectDraw surface will use.
SetSurfaceParameters | Tells the capture driver about the surface created on its behalf by the Overlay Mixer or VBI surface filter.

IVPBaseConfig::GetConnectInfo

IVPBaseConfig Interface

Retrieves connection information structures.

Syntax

HRESULT GetConnectInfo(
    LPDWORD pdwNumConnectInfo,
    LPDDVIDEOPORTCONNECT pddVPConnectInfo
    );

Parameters

pdwNumConnectInfo
[in, out] Pointer to a buffer that contains the number of DDVIDEOPORTCONNECT structures provided by the pddVPConnectInfo parameter. Contains the actual number of structures returned on output. If pddVPConnectInfo is NULL, this method updates this parameter with the number of structures supported by the driver.
pddVPConnectInfo
[in, out] Pointer to an array of DDVIDEOPORTCONNECT structures that the driver fills in. Specify NULL to retrieve the total number of formats supported.

Return Value

Returns NOERROR if the count or structures were retrieved, or a driver error.

Remarks

This method retrieves the various connection information structures such as GUID and port width structures, in an array of structures specified by pddVPConnectInfo. The callee must allocate the correct amount of space for the number of structures requested.

Set the index for connection information by using the IVPBaseConfig::SetConnectInfo method.

IVPBaseConfig::GetMaxPixelRate

IVPBaseConfig Interface

Retrieves the maximum pixels per second rate for a given width and height.

Syntax

HRESULT GetMaxPixelRate(
    LPAMVPSIZE pamvpSize,
    LPDWORD pdwMaxPixelsPerSecond
    );

Parameters

pamvpSize
[in, out] Pointer to an AMVPSIZE structure containing the desired width and height. The structure receives the final dimensions upon return.
pdwMaxPixelsPerSecond
[out] Pointer to the retrieved maximum pixels per second rate.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | NULL pointer argument.
E_INVALIDARG | Invalid argument.
NOERROR | The maximum pixel rate was retrieved.

Remarks

This method retrieves the maximum pixels per second rate expected for a given format and a given scaling factor. If the decoder does not support those scaling factors, then it returns the rate and the nearest scaling factors it supports.

IVPBaseConfig::GetOverlaySurface

IVPBaseConfig Interface

Determines whether the overlay mixer should use the driver's overlay surface and if so retrieves a pointer to the surface.

Syntax

HRESULT GetOverlaySurface(
    LPDIRECTDRAWSURFACE *ppddOverlaySurface
    );

Parameters

ppddOverlaySurface
[out] Address of a pointer to the retrieved DirectDraw® overlay surface object.

Return Value

Returns NOERROR if the overlay surface object was returned. (Default implementation sets the surface to NULL and returns NOERROR.)

Remarks

The Overlay Mixer uses this function to determine if the driver requires the Overlay Mixer to use its overlay surface and if so to get a pointer to it. If this function returns NULL, then the Overlay Mixer allocates its own surface.

IVPBaseConfig::GetVideoFormats

IVPBaseConfig Interface

Retrieves the video formats the decoder supports.

Syntax

HRESULT GetVideoFormats(
    LPDWORD pdwNumFormats,
    LPDDPIXELFORMAT pddPixelFormats
    );

Parameters

pdwNumFormats
[in, out] Pointer to the number of DDPIXELFORMAT structures provided by the pddPixelFormats parameter. When called, this method updates this parameter with the actual number of structures retrieved. If pddPixelFormats is NULL, this method updates this parameter with the total number of formats the driver supports.
pddPixelFormats
[in, out] Pointer to an array of DDPIXELFORMAT structures that the driver fills. Specify NULL to retrieve only the count of supported formats in pdwNumFormats.

Return Value

Returns NOERROR if the count or structures were returned, or a driver error otherwise.

Remarks

This method queries for either the number of DDPIXELFORMAT structures supported by the driver, or retrieves as many structures as can fit into the provided buffer space.

The callee must allocate the correct amount of space for the number of structures requested.

Set the video format by using IVPBaseConfig::SetVideoFormat.

IVPBaseConfig::GetVPDataInfo

IVPBaseConfig Interface

Retrieves the current video port data information.

Syntax

HRESULT GetVPDataInfo(
    LPAMVPDATAINFO pamvpDataInfo
    );

Parameters

pamvpDataInfo
[in, out] Pointer to the AMVPDATAINFO data information structure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | NULL pointer argument.
E_INVALIDARG | Invalid argument.
NOERROR | The video port data information was retrieved.

IVPBaseConfig::InformVPInputFormats

IVPBaseConfig Interface

Informs the device what video formats the video port supports.

Syntax

HRESULT InformVPInputFormats(
    DWORD dwNumFormats,
    LPDDPIXELFORMAT pDDPixelFormats
    );

Parameters

dwNumFormats
[in] Number of video formats contained in the pDDPixelFormats parameter.
pDDPixelFormats
[in] Pointer to an array of pixel format structures (DDPIXELFORMAT) to send to the device.

Return Value

Returns S_FALSE if failure, or NOERROR otherwise.

Remarks

The supplied array of supported video port formats might determine what formats the device, in turn, proposes.

IVPBaseConfig::SetConnectInfo

IVPBaseConfig Interface

Sets the index for the current video port connection information.

Syntax

HRESULT SetConnectInfo(
    DWORD dwChosenEntry
    );

Parameters

dwChosenEntry
[in] Index of new video port connect information (zero-based) to pass to the driver.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
NOERROR | The video port connect information was set.

Remarks

Retrieve connection information by using IVPBaseConfig::GetConnectInfo.

IVPBaseConfig::SetDDSurfaceKernelHandle

IVPBaseConfig Interface

Sets the kernel handle to be used by the DirectDraw surface.

Syntax

HRESULT SetDDSurfaceKernelHandle(
    DWORD dwDDKernelHandle
    );

Parameters

dwDDKernelHandle
[in] DirectDraw surface handle for kernel mode, passed as a DWORD value.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
NOERROR | The specified handle is set successfully.

Remarks

This method sets the DirectDraw handle on the mini driver to enable it to communicate with the video port directly.

IVPBaseConfig::SetDirectDrawKernelHandle

IVPBaseConfig Interface

Sets the DirectDraw® kernel handle for the decoder's minidriver to use.

Syntax

HRESULT SetDirectDrawKernelHandle(
    DWORD dwDDKernelHandle
    );

Parameters

dwDDKernelHandle
[in] DirectDraw kernel level handle passed as a DWORD value.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
NOERROR | The specified handle was set successfully.

IVPBaseConfig::SetInvertPolarity

IVPBaseConfig Interface

Reverses the current polarity the decoder uses.

Syntax

HRESULT SetInvertPolarity(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
NOERROR | The polarity was reversed.

Remarks

Reversing polarity means asking the decoder to treat even fields like odd fields and vice versa.

IVPBaseConfig::SetSurfaceParameters

IVPBaseConfig Interface

Tells the capture driver about the surface created on its behalf by the Overlay Mixer or VBI surface filter.

Syntax

HRESULT SetSurfaceParameters(
    DWORD dwPitch,
    DWORD dwXOrigin,
    DWORD dwYOrigin ) PURE;

Parameters

dwPitch
[in] Pitch of the surface. Distance (or pitch) in pixels between the start pixels of two consecutive lines of the surface.
dwXOrigin
[in] X-value of the pixel at which valid data starts.
dwYOrigin
[in] Y-value of the pixel at which valid data starts.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current default implementation returns NOERROR if the call completed successfully, or E_NOTIMPL if the method is not implemented.

IVPBaseConfig::SetVideoFormat

IVPBaseConfig Interface

Sets the format to be used by the video.

Syntax

HRESULT SetVideoFormat(
    DWORD dwChosenEntry
    );

Parameters

dwChosenEntry
[in] Value specifying the index (zero-based) of the video pixel format to use.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
NOERROR | The new video format was set.

Remarks

Retrieve the video formats by using IVPBaseConfig::GetVideoFormats.

IVPBaseConfig::SetVideoPortID

IVPBaseConfig Interface

Sets the port ID which the video will use.

Syntax

HRESULT SetVideoPortID (
    DWORD dwVideoPortID
    );

Parameters

dwVideoPortID
[in] DirectDraw video port ID.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
NOERROR | The specified port ID is set successfully.

Remarks

This method sets the DirectDraw video port ID on the mini driver to enable it to communicate with the video port directly.


IVPBaseNotify Interface

Enables the Overlay Mixer to control the properties of a hardware device such as a decoder that uses a video port. The IVPNotify interface derives from this interface. See also IVPBaseConfig and IVPConfig.

Applications should never use this interface.

Requirements

Requires Vptype.h, Vpnotify.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IVPBaseNotify methods | Description
RenegotiateVPParameters | Initializes the connection to the decoder.

IVPBaseNotify::RenegotiateVPParameters

IVPBaseNotify Interface

Initializes the connection to the decoder.

Syntax

HRESULT RenegotiateVPParameters(void) PURE;

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | NULL pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
NOERROR | No error.

Remarks

The Overlay Mixer filter negotiates various parameters (by using the IVPBaseConfig interface) with the decoder or driver. Call this method if any of those parameters (such as the video format or size) change. Currently, the Overlay Mixer repeats the whole connection process. You can call this method even while the graph is playing.


IVPConfig Interface

IVPConfig must be implemented by any filter that wraps a hardware decoder with a video port. This enables the Overlay Mixer, through its IVPNotify interface, to set and retrieve configuration information on the video port regarding the video memory on the display adapter. This interface derives from IVPBaseConfig. See also IVPBaseNotify and IVPNotify2.

Applications never use this interface.

Requirements

Requires Dvp.h, Vptype.h, Vpconfig.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IVPBaseConfig methods | Description
GetConnectInfo | Retrieves connection information structures.
SetConnectInfo | Sets the index for the current video port connection information.
GetVPDataInfo | Retrieves the current video port data information.
GetMaxPixelRate | Retrieves the maximum pixels per second rate for a given width and height.
InformVPInputFormats | Informs the device what video formats the video port supports.
GetVideoFormats | Retrieves the video formats the decoder supports.
SetVideoFormat | Sets the format that the video will use.
SetInvertPolarity | Reverses the current polarity the decoder uses.
GetOverlaySurface | Determines whether the overlay mixer should use the driver's overlay surface and if so retrieves a pointer to the surface.
SetDirectDrawKernelHandle | Sets the DirectDraw® kernel handle for the decoder's minidriver to use.
SetVideoPortID | Sets the port ID that the video will use.
SetDDSurfaceKernelHandle | Sets the kernel handle that the DirectDraw surface will use.
SetSurfaceParameters | Tells the capture driver about the surface created on its behalf by the Overlay Mixer or VBI surface filter.
IVPConfig methods | Description
IsVPDecimationAllowed | Given the context, retrieves whether scaling at the video port is possible.
SetScalingFactors | Sets the factors by which the decoder should scale the video stream.

IVPConfig::IsVPDecimationAllowed

IVPConfig Interface

Given the context, retrieves whether scaling at the video port is possible.

Syntax

HRESULT IsVPDecimationAllowed(
    AMVP_CONTEXT amvpContext,
    LPBOOL pbIsDecimationAllowed
    );

Parameters

amvpContext
[in] Context (video or VBI) in which to query the VP decimation capability.
pbIsDecimationAllowed
[out] Pointer to the retrieved value indicating whether decimation is allowed.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | NULL pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method is not supported.
NOERROR | No error.

Remarks

The Overlay Mixer filter uses this function to determine whether the driver needs the mixer to decimate video data at its own discretion. This function can be especially useful in a capture with preview situation in which you would not want the VP mixer filter to perform any scaling at the video port.

IVPConfig::SetScalingFactors

IVPConfig Interface

Sets the factors by which the decoder should scale the video stream.

Syntax

HRESULT SetScalingFactors(
    LPAMVPSIZE pamvpSize
    );

Parameters

pamvpSize
[in] Pointer to the new scaling size structure (AMVPSIZE) to use to specify the width and height.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
NOERROR | The new scaling factors were set.

Remarks

If the decoder does not support the specified scaling factors, then it sets the values to the nearest factors it can support.


IVPNotify Interface

Supports a private communication mechanism between the Overlay Mixer filter and a VPE decoder filter that represents a hardware decoder. This interface derives from IVPBaseNotify. See also IVPBaseConfig and IVPConfig.

Only the Overlay Mixer filter implements this interface. Applications should never use it.

Requirements

Requires Vptype.h, Vpnotify.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IVPBaseNotify methods | Description
RenegotiateVPParameters | Initializes the connection to the decoder.
IVPNotify methods | Description
SetDeinterlaceMode | Sets the deinterlacing mode (such as bob or weave).
GetDeinterlaceMode | Retrieves the deinterlacing mode (such as bob or weave).

IVPNotify::GetDeinterlaceMode

IVPNotify Interface

Retrieves the mode (such as bob or weave).

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT GetDeinterlaceMode(
  AMVP_MODE *pmode
) PURE;

Parameters

pmode
[out] Pointer to the retrieved mode. This value is a member of the AMVP_MODE enumerated data type.

Return Value

Returns E_NOTIMPL.

IVPNotify::SetDeinterlaceMode

IVPNotify Interface

Sets the mode (such as bob or weave).

Syntax

HRESULT SetDeinterlaceMode(
    AMVP_MODE mode
    ) PURE;

Parameters

mode
[in] Specified mode. This value is a member of the AMVP_MODE enumerated data type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.


IVPNotify2 Interface

The IVPNotify2 interface inherits from IVPNotify and is implemented only by the Overlay Mixer filter. This interface enables the Overlay Mixer to communicate with a video port (on a hardware device such as a decoder) that implements IVPConfig.

Applications should never use this interface.

Requirements

Requires Vptype.h, Vpnotify.h.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IVPNotify2 methods | Description
SetVPSyncMaster | Sets whether the video port controls vertical synchronization of the VGA.
GetVPSyncMaster | Checks whether the video port controls the synchronization of the VGA.

IVPNotify2::GetVPSyncMaster

IVPNotify2 Interface

Checks whether the video port controls the synchronization of the VGA.

Syntax

HRESULT GetVPSyncMaster(
    BOOL *pbVPSyncMaster
) PURE;

Parameters

pbVPSyncMaster
[out] Pointer to a value indicating whether the video port controls the vertical synchronization of the VGA monitor. TRUE if the port controls the monitor's synchronization; FALSE otherwise.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

IVPNotify2::SetVPSyncMaster

IVPNotify2 Interface

Sets whether the video port controls vertical synchronization of the VGA.

Syntax

HRESULT GetVPSyncMaster(
    BOOL bVPSyncMaster
) PURE;

Parameters

bVPSyncMaster
[in] Value specifying whether the video port controls the vertical synchronization of the VGA monitor. TRUE if the port controls the monitor's synchronization; FALSE otherwise.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.


Structures

This section describes the Microsoft® DirectShow® structures.

Structure | Description
ALLOCATOR_PROPERTIES | Contains the allocator's count, size, alignment, and prefix properties.
AM_DVD_RENDERSTATUS | Contains codes indicating the status of DVD-Video playback. These codes are used in the IDvdGraphBuilder::RenderDvdVideoVolume method.
AM_MEDIA_TYPE | Describes a media sample type.
AM_SAMPLE2_PROPERTIES | Describes the properties of a generic media sample.
AMOVIESETUP_FILTER | Contains filter information for registering a filter.
AMOVIESETUP_MEDIATYPE | Contains media type information for registering a filter.
AMOVIESETUP_PIN | Contains pin information for registering a filter.
AM_STREAM_INFO | Contains start and stop information given to a pin.
AMVABeginFrameInfo | Specifies information needed to begin processing the frame.
AMVABUFFERINFO | Describes buffer information.
AMVACompBufferInfo | Describes the allocated surfaces and compressed buffer information.
AMVAEndFrameInfo | Specifies information to finish processing the frame.
AMVAInternalMemInfo | Specifies the amount of scratch memory the hardware abstraction layer (HAL) will allocate for its private use.
AMVAUncompBufferInfo | Describes the surfaces to be allocated.
AMVAUncompDataInfo | Specifies the pixel format and dimensional characteristics of the data input stream.
AMVPDATAINFO | Specifies the data-specific characteristics of the VP input stream.
AMVPDIMINFO | Specifies the dimensional characteristics of the VP input stream.
AMVPSIZE | Specifies the width and height for a VP image.
DVD_ATR | Specifies DVD attributes.
DVD_DECODER_CAPS | Contains information about the audio decoder's capabilities.
DVD_HMSF_TIMECODE | Encapsulates timecode information in a more convenient manner than the older DVD_TIMECODE structure. Use DVD_HMSF_TIMECODE with the new DVD2 interfaces.
DVD_KaraokeAttributes | Contains information about karaoke audio streams on a DVD disc.
DVD_MenuAttributes | Contains information about the menus on a DVD disc.
DVD_MUA_Coeff | Contains information about surround sound mixing coefficients for multichannel audio on DVD.
DVD_MUA_MixingInfo | Contains information about surround sound mixing information on a DVD disc.
DVD_MultichannelAudioAttributes | Contains information about multichannel audio streams on a DVD disc.
DVD_PLAYBACK_LOCATION | Contains the DVD playback location.
DVD_PLAYBACK_LOCATION2 | Contains the DVD playback location; for use with the new DVD2 interfaces.
DVD_SubpictureAttributes | Contains information about a subpicture stream on a DVD disc.
DVD_TIMECODE | Contains DVD timecode in hours, minutes, seconds, and frames.
DVD_TitleAttributes | Contains information about a title on a DVD disc.
DVD_VideoAttributes | Contains information about the video stream on a DVD disc.
FILTER_INFO | Contains information about a filter.
PIN_INFO | Contains information about a pin.
Quality | Describes a quality message by indicating Flood or Famine in the renderer and specifying the percentage of frames to drop or add to optimize the renderer's performance.
REGFILTER | Describes a filter in the registry.
REGFILTER2 | Describes a filter for registration through the IFilterMapper2 interface.
REGFILTERPINS | Contains pin information for registering a filter.
REGFILTERPINS2 | Contains information for registering a filter through the IFilterMapper2 interface.
REGPINMEDIUM | Describes a pin medium (as defined in the Microsoft Windows® NT DDK) for registration through the IFilterMapper2 interface.
REGPINTYPES | Contains media type information for registering a filter.
STREAM_ID_MAP | Contains information about an elementary stream within an MPEG-2 program stream.

The following structure maintains information about graphics device interface (GDI) bitmaps and device-independent bitmaps (DIBs). This is used solely by the CImageAllocator, CImageSample, and CDrawImage window utility classes.

Structure | Description
DIBDATA | Contains information about each DIB.

The following structures maintain information about video, as well as video capture and compression.

Structure | Description
TRUECOLORINFO | Maintains color information.
ANALOGVIDEOINFO | Maintains information about the format of the analog video signal.
AUDIO_STREAM_CONFIG_CAPS | Contains information about all possible audio formats supported.
COLORKEY | Communicates color key information between the renderer and another filter.
MPEG1VIDEOINFO | Contains additional MPEG-1 video system information.
MPEG2VIDEOINFO | Contains additional MPEG-2 video system information.
TIMECODE | Contains basic timecode frame count information.
TIMECODE_SAMPLE | Contains complete timecode information.
VIDEO_STREAM_CONFIG_CAPS | Contains information about possible connections.
VIDEOINFO | Contains information that specifies a video image and its color palette and bitmasks.
VIDEOINFOHEADER | Describes the bitmap and color information for a video image.
VIDEOINFOHEADER2 | Describes the bitmap and color information for a video image, including interlace, copy protection, and pixel aspect ratio information.


ALLOCATOR_PROPERTIES Structure

Structures

Describes an allocator's count, size, alignment, and prefix properties.

Syntax

typedef struct _AllocatorProperties {
    long cBuffers;
    long cbBuffer;
    long cbAlign;
    long cbPrefix;
} ALLOCATOR_PROPERTIES;

Members

cBuffers
Number of buffers created by the allocator.
cbBuffer
Size of each buffer in bytes, excluding any prefix.
cbAlign
Alignment of the buffer; buffer start will be aligned on a multiple of this value.
cbPrefix
Each buffer is preceded by a prefix of this many bytes.

Remarks

The IMediaSample::GetPointer method returns a pointer to the beginning of the buffer, not including the prefix bytes designated by cbPrefix.

The alignment is applied to the prefix data, if any. If a nonzero prefix is used, the beginning of the prefix is aligned according to cbAlign.


AM_DVD_RENDERSTATUS Structure

Structures

Contains codes indicating the status of DVD-Video playback. These codes are used in the IDvdGraphBuilder::RenderDvdVideoVolume method.

Syntax

typedef struct {
    HRESULT hrVPEStatus;
    BOOL    bVPEFailed;
    BOOL    bDVDVolInvalid;
    BOOL    bDVDVolUnknown;
    BOOL    bNoLine21In;
    BOOL    bNoLine21Out;
    int     iNumStreams;
    int     iNumStreamsFailed;
    DWORD   dwFailedStreamsFlag;
} AM_DVD_RENDERSTATUS;

Members

hrVPEStatus
Overlay/VPE error code. Zero indicates success; any other value is failure.
bDVDVolInvalid
TRUE if the specified DVD volume to be played does not exist; FALSE otherwise.
bDVDVolUnknown
TRUE if no DVD volume is specified or if it isn't found; FALSE otherwise.
bNoLine21In
TRUE if the video decoder doesn't produce line 21 (closed captioning) data; FALSE otherwise.
bNoLine21Out
TRUE if the video decoder can't be shown as closed captioning on video due to a problem with graph building; FALSE otherwise.
iNumStreams
Number of DVD streams to render.
iNumStreamsFailed
Number of streams that failed to render.
dwFailedStreamsFlag
Combination of AM_DVD_STREAM_FLAGS flags indicating which streams failed.

See Also

IDvdGraphBuilder::RenderDvdVideoVolume


AM_MEDIA_TYPE Structure

Structures

Describes the format of a media sample.

See Media Type Functions for more information on working with the AM_MEDIA_TYPE structure.

Syntax

typedef struct  _MediaType
{
    GUID      majortype;
    GUID      subtype;
    BOOL      bFixedSizeSamples;
    BOOL      bTemporalCompression;
    ULONG     lSampleSize;
    GUID      formattype;
    IUnknown  *pUnk;
    ULONG     cbFormat;
    /* [size_is] */ BYTE __RPC_FAR *pbFormat;
} AM_MEDIA_TYPE;

Members

majortype
Globally unique identifier (GUID) that specifies the major type of the media sample.
subtype
GUID that specifies the subtype of the media sample. For more information, see Media Types
bFixedSizeSamples
If TRUE, samples are of a fixed size. This field is informational only. For audio, it is generally set to TRUE. For video, it is usually TRUE for uncompressed video and FALSE for compressed video.
bTemporalCompression
If TRUE, samples are compressed using temporal (interframe) compression. A value of TRUE indicates that not all frames are key frames. This field is informational only.
lSampleSize
Size of the sample in bytes. For compressed data, the value can be zero.
formattype
GUID that specifies the format type. The pbFormat member points to the corresponding format structure. Format types include the following:
Format Type | Format Structure
FORMAT_None | No format type
FORMAT_MPEGVideo | MPEG1VIDEOINFO
FORMAT_MPEG2Video | MPEG2VIDEOINFO
FORMAT_VideoInfo | VIDEOINFOHEADER
FORMAT_VideoInfo2 | VIDEOINFOHEADER2
FORMAT_WaveFormatEx | WAVEFORMATEX
pUnk
Not used.
cbFormat
Size of the format block of the media type.
pbFormat
Pointer to the format structure. The structure type is specified by the formattype member. The format structure must be present, unless formattype is GUID_NULL or FORMAT_None.

Remarks

When filters connect, they typically negotiate a media type. The media type describes the format of the data that the filters will exchange. If the filters do not agree on a media type, they cannot connect. Microsoft® DirectShow® describes media types with the AM_MEDIA_TYPE structure.

The first part of the media type contains generic attributes of a data stream. For example, the bFixedSizeSamples member declares whether data will be passed in fixed-size buffers. The second part is a variable-length block of data that contains a format-specific header, called the format block. The pbFormat member points to this block. The layout of the format block depends on the type of data in the stream. For example, if the data stream contains video frames, the format block is a VIDEOINFOHEADER structure.

The stream type is specified by two GUIDs, called the major type and the subtype. The major type defines the general category, such as video, audio, or byte stream. The subtype defines a narrower category within the major type. For example, video subtypes include 8-bit, 16-bit, 24-bit, and 32-bit RGB.

In some cases, the subtype duplicates information that is specified in the format (such as the bit depth). However, sometimes it is useful to specify GUID_NULL for the format type. The subtype enables you to specify some format information without giving the complete format. For example, you can specify 24-bit RGB without giving a particular width or height for the video frame.


AM_SAMPLE2_PROPERTIES Structure

Structures

Describes the properties of a media sample. The IMediaSample2 interface uses this structure.

Syntax

typedef struct tagAM_SAMPLE2_PROPERTIES
{
    DWORD           cbData;
    DWORD           dwTypeSpecificFlags;
    DWORD           dwSampleFlags;
    LONG            lActual;
    REFERENCE_TIME  tStart;
    REFERENCE_TIME  tStop;
    DWORD           dwStreamId;
    AM_MEDIA_TYPE   *pMediaType;
    BYTE            *pbBuffer;
    LONG            cbBuffer;
} AM_SAMPLE2_PROPERTIES;

Members

cbData
Length of property data, in bytes. This structure member is for extensibility.
dwTypeSpecificFlags
Type-specific flags. Flags are defined separately for each media type. Default value is zero.
dwSampleFlags
Bitwise combination of flags the AM_SAMPLE_PROPERTY_FLAGS enumerated data type. Undefined bits are reserved and must be zero.
lActual
Length of the valid data in the buffer.
tStart
Start time, if valid. The dwSampleFlags member specifies whether this member is valid.
tStop
Stop time, if valid. The dwSampleFlags member specifies whether this member is valid.
dwStreamId
Stream identifier. If the value is AM_STREAM_MEDIA, the stream contains media data. If the value is AM_STREAM_CONTROL, the stream contains control information. Applications can define values of 0x80000000 or greater for their own use.
pMediaType
Pointer to an AM_MEDIA_TYPE structure that specifies the media type.
pbBuffer
Pointer to the buffer. This property is read-only.
cbBuffer
Size of the buffer, in bytes. This property is read-only.


AM_STREAM_INFO Structure

Structures

Contains start and stop information given to a pin.

Syntax

typedef struct {
    REFERENCE_TIME tStart;
    REFERENCE_TIME tStop;
    DWORD dwStartCookie;
    DWORD dwStopCookie;
    DWORD dwFlags;
} AM_STREAM_INFO;

Members

tStart
Time at which streaming will start.
tStop
Time at which streaming will stop.
dwStartCookie
Number that will be given to the application that ordered the start, when the event occurs.
dwStopCookie
Number that will be given to the application that ordered the stop, when the event occurs.
dwFlags
AM_STREAM_INFO_FLAGS enumeration type flag.

Remarks

Access this structure through the IAMStreamControl interface.


AMOVIESETUP_FILTER Structure

Structures

Contains information for registering a filter.

Syntax

typedef struct _AMOVIESETUP_FILTER
{
    const CLSID           *clsID;
    const WCHAR           *strName;
    DWORD                 dwMerit;
    UINT                  nPins;
    const AMOVIESETUP_PIN *lpPin;
} AMOVIESETUP_FILTER, * PAMOVIESETUP_FILTER, * FAR LPAMOVIESETUP_FILTER;

Members

clsID
Class identifier of the filter.
strName
Name of the filter.
dwMerit
Filter merit. Used by the IGraphBuilder interface when constructing a filter graph.
nPins
Number of pins on the filter.
lpPin
Pointer to an array of AMOVIESETUP_PIN structures, of size nPins.


AMOVIESETUP_MEDIATYPE Structure

See REGPINTYPES.


AMOVIESETUP_PIN Structure

See REGFILTERPINS.


AMVABeginFrameInfo Structure

Structures

Specifies information needed to begin processing the frame.

Note This structure is available in Microsoft® Windows® 98 Second Edition and Windows 2000.

Syntax

typedef struct _tag_AMVABeginFrameInfo{
    DWORD dwDestSurfaceIndex;
    LPVOID pInputData;
    DWORD dwSizeInputData;
    LPVOID pOutputData;
    DWORD dwSizeOutputData;
 } AMVABeginFrameInfo, *LPAMVABeginFrameInfo;

Members

dwDestSurfaceIndex
Destination buffer in which to decode this frame.
pInputData
Pointer to miscellaneous data.
dwSizeInputData
Size of miscellaneous data to begin processing frame.
pOutputData
Pointer to data which the video graphics array (VGA) is going to fill.
dwSizeOutputData
Size of data which the VGA is going to fill.

Remarks

Note that you can't store pointers in pInputData, because their addresses will not be valid in kernel mode, where the frame processing occurs.


AMVABUFFERINFO Structure

Structures

Describes buffer information.

Note This structure is available in Microsoft® Windows® 98 Second Edition and Windows 2000.

Syntax

typedef struct _tag_AMVABUFFERINFO{
    DWORD dwTypeIndex;
    DWORD dwBufferIndex;
    DWORD dwDataOffset;
    DWORD dwDataSize;
 } AMVABUFFERINFO, *LPAMVABUFFERINFO;

Members

dwTypeIndex
Type of buffer.
dwBufferIndex
Buffer index.
dwDataOffset
Offset of relevant data from the beginning of buffer.
dwDataSize
Size of relevant data.


AMVACompBufferInfo Structure

Structures

Describes the allocated surfaces and compressed buffer information.

Note This structure is available in Microsoft® Windows® 98 Second Edition and Windows 2000.

Syntax

typedef struct _tag_AMVACompBufferInfo{
    DWORD dwNumCompBuffers;
    DWORD dwWidthToCreate;
    DWORD dwHeightToCreate;
    DWORD dwBytesToAllocate;
    DDSCAPS2 ddCompCaps;
    DDPIXELFORMAT ddPixelFormat;
 } AMVACompBufferInfo, *LPAMVACompBufferInfo;

Members

dwNumCompBuffers
Number of buffers requested for compressed data.
dwWidthToCreate
Width of surface to create.
dwHeightToCreate
Height of surface to create.
dwBytesToAllocate
Total number of bytes used by each surface.
ddCompCaps
DDSCAPS2 structure defining the capabilities of the DirectDrawSurface object created to store compressed data.
ddPixelFormat
DDPIXELFORMAT structure, describing the pixel format used to create surfaces to store compressed data.


AMVAEndFrameInfo Structure

Structures

Specifies information to finish processing the frame.

Note This structure is available in Microsoft® Windows® 98 Second Edition and Windows 2000.

Syntax

typedef struct _tag_AMVAEndFrameInfo{
    DWORD dwSizeMiscData;
    LPVOID pMiscData;
 } AMVAEndFrameInfo, *LPAMVAEndFrameInfo;

Members

dwSizeMiscData
Size of other miscellaneous data to begin frame.
pMiscData
Pointer to miscellaneous data.

Remarks

Note that you are not allowed to store a pointer in pMiscData.


AMVAInternalMemInfo Structure

Structures

Specifies the amount of scratch memory the hardware abstraction layer (HAL) will allocate for its private use.

Note This structure is available in Microsoft® Windows® 98 Second Edition and Windows 2000.

Syntax

typedef struct _tag_AMVAInternalMemInfo{
    DWORD dwScratchMemAlloc;
 } AMVAInternalMemInfo, *LPAMVAInternalMemInfo;

Members

dwScratchMemAlloc
Amount of scratch memory the HAL will allocate for its private use.


AMVAUncompBufferInfo Structure

Structures

Describes the surfaces to be allocated.

Note This structure is available in Microsoft® Windows® 98 Second Edition and Windows 2000.

Syntax

typedef struct _tag_AMVAUncompBufferInfo{
    DWORD dwMinNumSurfaces;
    DWORD dwMaxNumSurfaces;
    DDPIXELFORMAT ddUncompPixelFormat;
 } AMVAUncompBufferInfo, *LPAMVAUncompBufferInfo;

Members

dwMinNumSurfaces
Minimum number of surfaces to be allocated.
dwMaxNumSurfaces
Maximum number of surfaces to be allocated.
ddUncompPixelFormat
DDPIXELFORMAT structure, describing the pixel format of surfaces to be allocated.


AMVAUncompDataInfo Structure

Structures

Specifies the pixel format and dimensional characteristics of the data input stream.

Note This structure is available in Microsoft® Windows® 98 Second Edition and Windows 2000.

Syntax

typedef struct _tag_AMVAUncompDataInfo{
    DWORD dwUncompWidth;
    DWORD dwUncompHeight;
    DDPIXELFORMAT ddUncompPixelFormat;
 } AMVAUncompDataInfo, *LPAMVAUncompDataInfo;

Members

dwUncompWidth
Width of uncompressed data.
dwUncompHeight
Height of uncompressed data.
ddUncompPixelFormat
DDPIXELFORMAT structure, describing the pixel format of uncompressed data.


AMVPDATAINFO Structure

Structures

Specifies the data-specific characteristics of the VP input stream.

Syntax

typedef struct _AMVPDATAINFO{
    DWORD dwSize;
    DWORD dwMicrosecondsPerField;
    AMVPDIMINFO amvpDimInfo;
    DWORD dwPictAspectRatioX;
    DWORD dwPictAspectRatioY;
    BOOL bEnableDoubleClock;
    BOOL bEnableVACT;
    BOOL bDataIsInterlaced;
    LONG lHalfLinesOdd;
    BOOL bFieldPolarityInverted;
    DWORD dwNumLinesInVREF;
    LONG lHalfLinesEven;
    DWORD dwReserved1;
} AMVPDATAINFO, *LPAMVPDATAINFO;

Members

dwSize
Size of the structure, in bytes.
dwMicrosecondsPerField
Time taken by each field.
amvpDimInfo
Dimensional information.
dwPictAspectRatioX
The X dimension of picture aspect ratio.
dwPictAspectRatioY
The Y dimension of picture aspect ratio.
bEnableDoubleClock
Video port should enable double clocking.
bEnableVACT
Video port should use an external VACT signal.
bDataIsInterlaced
Indicates that the signal is interlaced.
lHalfLinesOdd
Number of half lines in the odd field.
bFieldPolarityInverted
Video port should invert the field polarity.
dwNumLinesInVREF
Number of lines of data in VREF.
lHalfLinesEven
Number of half lines in the even field.
dwReserved1
Reserved for future use.


AMVPDIMINFO Structure

Structures

Specifies the dimensional characteristics of the VP input stream.

Syntax

typedef struct _AMVPDIMINFO{
    DWORD dwFieldWidth;
    DWORD dwFieldHeight;
    DWORD dwVBIWidth;
    DWORD dwVBIHeight;
    RECT rcValidRegion;
} AMVPDIMINFO, *LPAMVPDIMINFO;

Members

dwFieldWidth
Field width of the data.
dwFieldHeight
Field height of the data.
dwVBIWidth
Width of the VBI data.
dwVBIHeight
Height of the VBI data.
rcValidRegion
Valid rectangle, used for cropping.


AMVPSIZE Structure

Structures

Specifies the width and height for a VP image.

Syntax

typedef struct _AMVPSIZE{
DWORD dwWidth;
DWORD dwHeight;
} AMVPSIZE, *LPAMVPSIZE;

Members

dwWidth
Width, in pixels.
dwHeight
Height.

Remarks

The context could be anything such as scaling, cropping, and so on.


ANALOGVIDEOINFO Structure

Structures

Maintains information about the format of the analog video signal.

Syntax

typedef struct tagAnalogVideoInfo {
    RECT            rcSource;
    RECT            rcTarget;
    DWORD           dwActiveWidth;
    DWORD           dwActiveHeight;
    REFERENCE_TIME  AvgTimePerFrame;
} ANALOGVIDEOINFO;

Members

rcSource
Source video rectangle.
rcTarget
Destination target rectangle.
dwActiveWidth
Source video width.
dwActiveHeight
Source video height (483 for NTSC, 575 for PAL/SECAM).
AvgTimePerFrame
Average time per frame in 100-nanosecond units.

Remarks

Filters using this format usually pass the video signal using a hardware-based connection rather than using memory-based transports.

An example of a definition of an analog video media type connection would be a connection of NTSC video using "M" color encoding. This would use a major media type of MEDIATYPE_AnalogVideo, a subtype of MEDIASUBTYPE_AnalogVideo_NTSC_M, and a format type of FORMAT_AnalogVideo.


AUDIO_STREAM_CONFIG_CAPS Structure

Structures

Contains information about all possible audio formats supported.

Syntax

typedef struct _AUDIO_STREAM_CONFIG_CAPS {
        GUID guid;
        ULONG MinimumChannels;
        ULONG MaximumChannels;
        ULONG ChannelsGranularity;
        ULONG MinimumBitsPerSample;
        ULONG MaximumBitsPerSample;
        ULONG BitsPerSampleGranularity;
        ULONG MinimumSampleFrequency;
        ULONG MaximumSampleFrequency;
        ULONG SampleFrequencyGranularity;
    } AUDIO_STREAM_CONFIG_CAPS;

Members

guid
Will be set to MEDIATYPE_Audio to indicate an audio sample.
MinimumChannels
Minimum number of channels this pin supports.
MaximumChannels
Maximum number of channels this pin supports (for example, 2 for stereo).
ChannelsGranularity
Granularity of the channels. For example, you could specify channels 2 through 4 in steps of 2.
MinimumBitsPerSample
Minimum bits per sample.
MaximumBitsPerSample
Maximum bits per sample.
BitsPerSampleGranularity
Granularity of the bits. For example, you could specify 8 bits or 32 bits in steps of 8.
MinimumSampleFrequency
Minimum frequency allowed.
MaximumSampleFrequency
Maximum frequency allowed.
SampleFrequencyGranularity
Granularity of the frequency. For example, you could specify 11025 Hz to 44100 Hz in steps of 11025 Hz.

Remarks

This structure is returned by an audio capture or compression filter.

See Also

IAMStreamConfig::GetStreamCaps


COLORKEY Structure

Structures

Communicates color key information between the renderer and another filter.

Syntax

typedef struct tagCOLORKEY
    {
    DWORD           KeyType;
    DWORD           PaletteIndex;
    COLORREF        LowColorValue;
    COLORREF        HighColorValue;
    }    COLORKEY;

Members

KeyType
Key type. Can be CK_NOCOLORKEY, CK_INDEX, or CK_RGB. CK_INDEX and CK_RGB can be logically combined.
PaletteIndex
Palette index.
LowColorValue
Lowest RGB color value.
HighColorValue
Highest RGB color value.

Remarks

The video renderer supports a data transport accessed through the IOverlay interface. This will typically be used by hardware decoder filters that need the renderer to communicate where to put the data rather than requiring the renderer to draw the data. One mechanism for communicating where to put the images is by using a color key. This structure is used by a filter (typically a hardware decoder) to describe color key requirements to the video renderer.


DIBDATA Structure

Structures

Maintains information about each GDI DIB.

Syntax

typedef struct tagDIBDATA {
    LONG        PaletteVersion;
    DIBSECTION  DibSection;
    HBITMAP     hBitmap;
    HANDLE      hMapping;
    BYTE        *pBase;
} DIBDATA;

Members

PaletteVersion
Current palette version in use.
DibSection
Details of DIB section allocated.
hBitmap
Handle to bitmap for drawing.
hMapping
Handle to shared memory block.
pBase
Pointer to base memory address.

Remarks

When the allocator creates a sample, it allocates a DIBSECTION to the sample. When a window receives a sample, it can call the Microsoft Win32® BitBlt function to pass the sample from one device context to another device context. This is a mechanism for the image allocator, an image sample, and the draw class to pass bitmap information to each other.


DVD_ATR Structure

Structures

Describes various DVD attributes as found on the disc. To parse this information, refer to the DVD-Video specification.

Syntax

typedef struct tagDVD_ATR
{
    ULONG    ulCAT;
    BYTE    pbATRI[768];
} DVD_ATR;

Members

ulCAT
VMG_CAT if this is for a volume; or VTS_CAT if this is for a Video Title Set (VTS).
pbATRI
All stream attributes for menu and title from bytes 256 to 1023 of Video Manager Information (VMGI) or Video Title Set Information (VTSI).

Remarks

This structure is used with the deprecated IDVDInfo interface. Newer applications should use the IDVDInfo2 interface.


DVD_DECODER_CAPS Structure

Structures

Indicates the capabilities of a DVD decoder. Used in IDvdInfo2::GetDecoderCaps.

Syntax

typedef struct tagDVD_DECODER_CAPS
{
    DWORD   dwSize ;
    DWORD   dwAudioCaps ;
    double  dFwdMaxRateVideo ;
    double  dFwdMaxRateAudio ;
    double  dFwdMaxRateSP ;
    double  dBwdMaxRateVideo ;
    double  dBwdMaxRateAudio ;
    double  dBwdMaxRateSP ;
      DWORD   dwRes1 ;
      DWORD   dwRes2 ;
      DWORD   dwRes3 ;
      DWORD   dwRes4 ;
} DVD_DECODER_CAPS ;

Members

dwSize
Size of this structure.
dwAudioCaps
Bitwise OR indicating which audio formats are supported. Possible values are:
  • DVD_AUDIO_CAPS_AC3 = 0x00000001
  • DVD_AUDIO_CAPS_MPEG2 = 0x00000002
  • DVD_AUDIO_CAPS_LPCM = 0x00000004
  • DVD_AUDIO_CAPS_DTS = 0x00000008
  • DVD_AUDIO_CAPS_SDDS = 0x00000010
dFwdMaxRateVideo
Maximum video data rate in forward direction.
dFwdMaxRateAudio
Maximum audio data rate in forward direction.
dFwdMaxRateSP
Maximum subpicture data rate in forward direction.
dBwdMaxRateVideo
Maximum video data rate in reverse direction. (0 if decoder does not support the smooth reverse mechanism.)
dBwdMaxRateAudio
Maximum audio data rate in reverse direction. (0 if decoder does not support the smooth reverse mechanism.)
dBwdMaxRateSP
Maximum subpicture data rate in reverse direction. (0 if decoder does not support the smooth reverse mechanism.)
dwRes1
Reserved for future use.
dwRes2
Reserved for future use.
dwRes3
Reserved for future use.
dwRes4
Reserved for future use.


DVD_HMSF_TIMECODE Structure

Structures

Encapsulates the hours, minutes, seconds, and frames in a DVD timecode.

Syntax

typedef struct tagDVD_HMSF_TIMECODE
{
    BYTE    bHours;
    BYTE    bMinutes;
    BYTE    bSeconds;
    BYTE    bFrames;
} DVD_HMSF_TIMECODE;

Members

bHours
Hours.
bMinutes
Minutes.
bSeconds
Minutes.
bFrames
Frames.

Remarks

A DVD_HMSF_TIMECODE structure is for use with IDvdControl2 and IDvdInfo2. It is more convenient to use than the DVD_TIMECODE structure, which was used with the earlier interfaces IDvdControl and IDvdInfo. A DVD_HMSF_TIMECODE structure can be cast to/from a ULONG. This means that if you need to use the old BCD time format for backwards compatability, you can do so in place of a DVD_HMSF_TIMECODE structure.


DVD_KaraokeAttributes Structure

Structures

Contains information about a karaoke audio stream. The IDvdInfo2::GetKaraokeAttributes method fills in a DVD_KaraokeAttributes structure for a specified stream.

Syntax

typedef struct tagDVD_KaraokeAttributes
{
    BYTE            bVersion;
    BOOL            fMasterOfCeremoniesInGuideVocal1;
    BOOL            fDuet;
    DVD_KARAOKE_ASSIGNMENT  ChannelAssignment;
    WORD            wChannelContents[8];
} DVD_KaraokeAttributes;

Members

bVersion
The current karaoke version is 1.0.
fMasterOfCeremoniesInGuideVocal1
TRUE means that the "Guide Vocal 1" channel contains the "Master of Ceremonies" content.
fDuet
A BOOLEAN value indicating whether the song is intended to be sung as a duet.
ChannelAssignment
A bitwise OR of valid DVD_KARAOKE_ASSIGNMENT values indicating the speaker configuration into which all the channels will be mixed.
wChannelContents
An array of valid DVD_KARAOKE_CONTENTS values that identifies the content on each channel.


DVD_MenuAttributes Structure

Structures

Contains information about a DVD menu. The IDvdInfo2::GetTitleAttributes method fills in a DVD_MenuAttributes structure for a specified stream.

Syntax

typedef struct tagDVD_MenuAttributes
{

    BOOL                        fCompatibleRegion[8];
    DVD_VideoAttributes         VideoAttributes;

    BOOL                        fAudioPresent;
    DVD_AudioAttributes         AudioAttributes;

    BOOL                        fSubpicturePresent;
    DVD_SubpictureAttributes    SubpictureAttributes;
} DVD_MenuAttributes;

Members

fCompatibleRegion
An array of TRUE/FALSE values indicating with which DVD regions the disc's authored region is compatible. The eight array indexes (numbered 0-7) correspond to the eight DVD regions (numbered 1-8). This array is only filled in when the menu being queried is the Video Manager Menu (the main menu for the entire disc).
VideoAttributes
A DVD_VideoAttributes structure containing the video attributes of the menu. This applies to both a VMGM and VTSM.
fAudioPresent
A variable of type BOOL indicating whether the menu has an audio stream.
AudioAttributes
A DVD_AudioAttributes structure containing information about the menu's audio stream. This structure will only be filled in if fAudioPresent is true.
fSubpicturePresent
A variable of type BOOL indicating whether the menu has a subpicture stream.
SubpictureAttributes
A DVD_SubpictureAttributes structure containing information about the menu's subpicture stream. This structure will only be filled in if fSubpicturePresent is true.


DVD_MUA_Coeff Structure

Structures

Defines the mixing coefficients for one channel in a multichannel audio stream. The DVD_MultichannelAudioAttributes structure contains an array of eight DVD_MUA_Coeff structures, one for each channel in the stream.

Syntax

typedef struct tagDVD_MUA_Coeff
{
    double   log2_alpha;
    double   log2_beta;
} DVD_MUA_Coeff;

Members

log2_alpha
Variable of type double indicating the mixing coefficient for this channel to channel 0.
log2_beta
Variable of type double indicating the mixing coefficient for this channel to channel 1.

Remarks

The information contained in this structure reflects the mixing coefficients as authored on the digital video disc (DVD). An application cannot modify these values or otherwise use them unless it is also decoding the audio. In the typical DVD filter graph, the DVD Navigator filter does not send this information to the decoder.

The alpha coefficient is used to mix to audio channel 0 and the beta coefficient is used to mix to audio channel 1. In general, the following formula calculates the mixing coefficients.

Audio channel 0 = coeff[0].alpha * value[0] + coeff[1].alpha * value[1] + ...
Audio channel 1 = coeff[0].beta * value[0]  + coeff[1].beta * value[1] + ...

See Also

DVD_AudioAttributes, DVD_MUA_MixingInfo


DVD_MUA_MixingInfo Structure

Structures

Describes the surround sound mixing information for the channels in one audio stream in a specified title.

Syntax

typedef struct tagDVD_MUA_MixingInfo
{
    BOOL    fMixTo0;
    BOOL    fMixTo1;
    BOOL    fMix0InPhase;
    BOOL    fMix1InPhase;
    DWORD   dwSpeakerPosition;
} DVD_MUA_MixingInfo;

Members

fMixTo0
Variable of type BOOL; TRUE means the channel is mixed to channel 0.
fMixTo1
Variable of type BOOL; TRUE means the channel is mixed to channel 1.
fMix0InPhase
Variable of type BOOL; TRUE means the channel is mixed in phase to channel 0.
fMix1InPhase
Variable of type BOOL; TRUE means the channel is mixed in phase to channel 1.
dwSpeakerPosition
Variable of type DWORD indicating the speaker for which this channel is intended. See Remarks.

Remarks

Applications cannot use the information contained in this structure to change the mixing unless they have a way to communicate with a custom audio decoder that has been inserted manually into the filter graph. The default audio decoder handles Linear Pulse Code Modulated (LPCM) audio using the mixing information on the digital video disc (DVD), but applications have no way to instruct the decoder to modify the mixing values. This means that current DVD playback applications should have no need to access the multichannel-related data structures.

The DVD_MultichannelAudioAttributes structure contains information about one audio stream in a specified title. An array of up to eight DVD_MUA_MixingInfo structures will be populated in this structure, if the following conditions are true.

  • DVD_AudioAttributes.AppMode = DVD_AudioMode_Surround
  • DVD_AudioAttributes.AudioFormat = DVD_AudioFormat_LPCM
  • DVD_AudioAttributes.fHasMultichannelInfo = 1

Possible values for dwSpeakerPosition are defined in Ksmedia.h as follows:

KSAUDIO_SPEAKER_LEFT | 0x1
KSAUDIO_SPEAKER_RIGHT | 0x2
KSAUDIO_SPEAKER_CENTER | 0x4
KSAUDIO_SPEAKER_SURROUND_LEFT | 0x8
KSAUDIO_SPEAKER_SURROUND_RIGHT | 0x10
KSAUDIO_SPEAKER_SUBWOOFER | 0x20
KSAUDIO_SPEAKER_LEFT_OF_CENTER | 0x40
KSAUDIO_SPEAKER_RIGHT_OF_CENTER | 0x80
KSAUDIO_SPEAKER_SURROUND_MONO | 0x100
KSAUDIO_SPEAKER_SIDE_LEFT | 0x200
KSAUDIO_SPEAKER_SIDE_RIGHT | 0x400
KSAUDIO_SPEAKER_TOP | 0x800

See Also

DVD_AudioAttributes


DVD_MultichannelAudioAttributes Structure

Structures

Describes the multichannel attributes of one audio stream within a specified title.

Syntax

typedef struct tagDVD_MultichannelAudioAttributes
{
    DVD_MUA_MixingInfo  Info[8];
    DVD_MUA_Coeff       Coeff[8];
} DVD_MultichannelAudioAttributes;

Members

Info
Array of eight DVD_MUA_MixingInfo structures, which contain the mixing information for each channel in the audio stream.
Coeff
Array of eight DVD_MUA_Coeff structures, which contain the mixing coefficients for each channel in the audio stream.

Remarks

The DVD_TitleAttributes structure contains an array of up to eight DVD_MultichannelAudioAttributes structures. When DVD_TitleAttributes is filled by a call to the IDvdInfo2::GetTitleAttributes method, the array will be populated with one DVD_MultichannelAudioAttributes structure for each available audio stream in the title.


DVD_PLAYBACK_LOCATION Structure

Structures

Indicates DVD playback location.

Syntax

typedef struct tagDVD_PLAYBACK_LOCATION
{
ULONG   TitleNum;
    ULONG   ChapterNum;
    ULONG   TimeCode;
} DVD_PLAYBACK_LOCATION;

Members

TitleNum
Title number for the whole disc; Title Track Number (TTN) not Video Title Set_Title Track Number (VTS_TTN).
ChapterNum
Part-of-title number with title. 0xffffffff if not a simple linear movie.
TimeCode
Timecode. Use DVD_TIMECODE for current playback time. 0xffffffff if not a simple linear movie.

Remarks

TitleNum and ChapterNum or TitleNum and TimeCode are sufficient to save the playback location for simple linear movies.


DVD_PLAYBACK_LOCATION2 Structure

Structures

Indicates DVD playback location.

Syntax

typedef struct tagDVD_PLAYBACK_LOCATION2
{
    ULONG   TitleNum;
    ULONG   ChapterNum;
    DVD_HMSF_TIMECODE   TimeCode;
    ULONG   TimeCodeFlags;
} DVD_PLAYBACK_LOCATION2;

Members

TitleNum
Title number for the whole disc (not the track number of the Video Title Set).
ChapterNum
Part-of-title number with title. 0xffffffff if not a simple linear movie.
TimeCode
Timecode. Use DVD_HMSF_TIMECODE for current playback time. 0xffffffff if not a simple linear movie.
TimeCodeFlags
A union of DVD_TIMECODE_EVENT_FLAGS.

Remarks

TitleNum and ChapterNum or TitleNum and TimeCode are sufficient to save the playback location for simple linear movies.


DVD_SubpictureAttributes Structure

Structures

Contains information about the DVD subpicture. The IDvdInfo2::GetSubpictureAttributes method fills in a DVD_SubpictureAttributes structure for a specified stream.

Syntax

typedef struct tagDVD_SubpictureAttributes
{
    DVD_SUBPICTURE_TYPE     Type;
    DVD_SUBPICTURE_CODING   CodingMode;
    LCID                    Language;
    DVD_SUBPICTURE_LANG_EXT LanguageExtension;
} DVD_SubpictureAttributes;

Members

Type
Variable of type DVD_SUBPICTURE_TYPE that indicates whether the subpicture contains language-related content.
CodingMode
Variable of type DVD_SUBPICTURE_CODING that indicates how the subpicture graphics stream is encoded.
Language
Variable of type LCID that identifies the subpicture language if Type equals DVD_SPType_Language.
LanguageExtension
Variable of type DVD_SUBPICTURE_LANG_EXT that identifies the subpicture language extension if Type equals DVD_SPType_Language.


DVD_TIMECODE Structure

Structures

Contains DVD timecode in hours, minutes, seconds, and frames.

Syntax

typedef struct tagDVD_TIMECODE")
{
   ULONG Hours1   :4;
   ULONG Hours10  :4;

   ULONG Minutes1 :4;
   ULONG Minutes10:4;

   ULONG Seconds1 :4;
   ULONG Seconds10:4;

   ULONG Frames1  :4;
   ULONG Frames10 :2;

   ULONG FrameRateCode:2;
} DVD_TIMECODE;

Members

Hours1
Hours.
Hours10
Tens of hours.
Minutes1
Minutes.
Minutes10
Tens of minutes.
Seconds1
Seconds.
Seconds10
Tens of seconds.
Frames1
Frames.
Frames10
Tens of frames.
FrameRateCode
Frames per second dropped and not dropped as indicated by DVD_FRAMERATE.

Remarks

DVD timecode is binary coded decimal (BCD) encoded in the format 0xHhMmSsFf, where:

  • H is tens of hours
  • h is hours
  • M is tens of minutes
  • m is minutes
  • S is tens of seconds
  • s is seconds
  • F is tens of frames
  • f is frames

To use a BCD, first create the BCD.

ULONG timeCode = 0;	// create the BCD
//create a pointer to a DVD_TIMECODE structure at the address of the BCD
DVD_TIMECODE * dvdTimeCode = ( DVD_TIMECODE * ) &timeCode;

Then, dvdTimeCode can be used as a DVD_TIMECODE structure.

dvdTimeCode->Hours10 = 0;
dvdTimeCode->Hours1 = 2;

Finally, timeCode is passed to the IDvdControl::TimeSearch method.

TimeSearch ( timeCode );


DVD_TitleAttributes Structure

Structures

Contains information about a DVD title. The IDvdInfo2::GetTitleAttributes method fills in a DVD_TitleAttributes structure for a specified stream.

Syntax

typedef struct tagDVD_TitleMainAttributes
{

    DVD_TITLE_APPMODE                   AppMode;
    DVD_VideoAttributes                 VideoAttributes;
    ULONG                               ulNumberOfAudioStreams;
    DVD_AudioAttributes                 AudioAttributes[8];
    DVD_MultichannelAudioAttributes     MultichannelAudioAttributes[8];
    ULONG                               ulNumberOfSubpictureStreams;
    DVD_SubpictureAttributes            SubpictureAttributes[32];
} DVD_TitleAttributes;

Members

AppMode
A variable of type DVD_TITLE_APPMODE indicating whether the Navigator is in "karaoke" mode or some other mode.
VideoAttributes
A DVD_VideoAttributes structure containing information about the "main" video of the current menu or title.
ulNumberOfAudioStreams
A variable of type ULONG indicating the number of audio streams available in the title.
AudioAttributes
An array of DVD_AudioAttributes structures containing information about each available audio stream in the current title.
MultichannelAudioAttributes
An array of DVD_MultichannelAudioAttributes structures containing additional information about any available audio stream that is in a multichannel format. This structure will be filled in for the corresponding audio stream if the multichannel bit is set in that stream's DVD_AudioAttributes structure.
ulNumberOfSubpictureStreams
A variable of type ULONG indicating the number of subpicture streams available in the title.
SubpictureAttributes
An array of DVD_SubpictureAttributes structures that contain information about each subpicture stream in the title.DVD_SubpictureAttributes structures containing information about each available subpicture stream in the title.


DVD_VideoAttributes Structure

Structures

Describes the attributes of the video stream for the current title or menu.

Syntax

typedef struct tagDVD_VideoAttributes
{
    BOOL                     fPanscanPermitted;
    BOOL                     fLetterboxPermitted;
    ULONG                    ulAspectX;
    ULONG                    ulAspectY;
    ULONG                    ulFrameRate;
    ULONG                    ulFrameHeight;
    DVD_VIDEO_COMPRESSION    Compression;
    BOOL                     fLine21Field1InGOP;
    BOOL                     fLine21Field2InGOP;
    ULONG                    ulSourceResolutionX;
    ULONG                    ulSourceResolutionY;
    BOOL                     fIsSourceLetterboxed;
    BOOL                     fIsFilmMode;
} DVD_VideoAttributes;

Members

fPanscanPermitted
TRUE means the picture can be shown as pan-scan if the display aspect ratio is 4 x 3.
fLetterboxPermitted
TRUE means the picture can be shown as letterbox if the display aspect ratio is 4 x 3.
ulAspectX
The video stream's X aspect (4 or 16).
ulAspectY
The video stream's Y aspect (3 or 9).
ulFrameRate
The frame rate in hertz (Hz), either 50 or 60.
ulFrameHeight
The frame height in lines (525 for a frame rate of 60 Hz or 625 for 50 Hz).
Compression
Variable of type DVD_VIDEO_COMPRESSION indicating the MPEG compression type used on the disc.
fLine21Field1InGOP
TRUE means there is user data in line 21, field 1.
fLine21Field2InGOP
TRUE means there is user data in line 21, field 2.
ulSourceResolutionX
The x-axis source resolution (352, 704, or 720).
ulSourceResolutionY
The y-axis source resolution (240, 480, 288, or 576).
fIsSourceLetterboxed
TRUE means the source video is in letterbox format. Subpictures and menu buttons can only be displayed in the active video area.
fIsFilmMode
For 625/50 Hz systems, TRUE means "film mode" and FALSE means "camera mode."

Remarks

This structure is filled when an application calls the IDvdInfo2::GetCurrentVideoAttributes method.


FILTER_INFO Structure

Structures

Contains information about a filter.

Syntax

typedef struct _FilterInfo {
    WCHAR        achName[MAX_FILTER_NAME];
    IFilterGraph * pGraph;
} FILTER_INFO;

Members

achName
Null-terminated string containing the name of the filter.
pGraph
If the filter is member of a filter graph, contains a pointer to the filter graph's IFilterGraph interface. If the filter is not a member of a filter graph, this value of this member is NULL.

Remarks

If the pGraph member is not NULL, the application should release the IFilterGraph interface when it is finished using it.


MPEG1VIDEOINFO Structure

Structures

Describes an MPEG-1 video stream.

Syntax

typedef struct tagMPEG1VIDEOINFO {
    VIDEOINFOHEADER hdr;
    DWORD           dwStartTimeCode;
    DWORD           cbSequenceHeader;
    BYTE            bSequenceHeader[1];
} MPEG1VIDEOINFO;

Members

hdr
VIDEOINFOHEADER structure.
dwStartTimeCode
25-bit "group-of-pictures" time code at start of data.
cbSequenceHeader
Length of the bSequenceHeader member, in bytes.
bSequenceHeader
Sequence header including quantization matrices, if any.


MPEG2VIDEOINFO Structure

Structures

Describes an MPEG-2 video stream.

Syntax

typedef struct tagMPEG2VIDEOINFO {
    VIDEOINFOHEADER2    hdr;
    DWORD               dwStartTimeCode;
    DWORD               cbSequenceHeader;
    DWORD               dwProfile;
    DWORD               dwLevel;
    DWORD               dwFlags;
    DWORD               dwSequenceHeader[1];
} MPEG2VIDEOINFO;

Members

hdr
VIDEOINFOHEADER2 structure.
dwStartTimeCode
25-bit "group-of-pictures" time code at start of data (not used for DVD).
cbSequenceHeader
Length of the dwSequenceHeader member, in bytes. (Zero for DVD.)
dwProfile
MPEG2Profile enumerated type member.
dwLevel
MPEG2Level enumerated type member.
dwFlags
Flag indicating preferences. Set one or a combination of the following values.
AMMPEG2_DoPanScan | If set, the MPEG-2 video decoder should crop the output image based on pan-scan vectors in the picture display extension and change the picture aspect ratio accordingly.
AMMPEG2_DVDLine21Field1 | If set, the MPEG-2 decoder must be able to produce an output pin for DVD style closed-captioned data found in the Group Of Pictures (GOP) layer of field 1.
AMMPEG2_DVDLine21Field2 | If set, the MPEG-2 decoder must be able to produce an output pin for DVD style closed-captioned data found in the GOP layer of field 2.
AMMPEG2_SourceIsLetterboxed | If set, indicates that black bars have been encoded in the top and bottom of the video.
AMMPEG2_FilmCameraMode | If set, indicates "film mode" used for the 625/50 (line/field) content. If cleared, indicates that "camera mode" was used.
Set undefined flags to zero or connection will be rejected.
dwSequenceHeader
Sequence header including quantization matrices, if any.


PID_MAP Structure

Structures

Contains information that identifies the contents of an MPEG-2 transport stream packet ID. Used with the IEnumPIDMap::Next method.

Syntax

typedef struct {
    ULONG                   ulPID;
    MEDIA_SAMPLE_CONTENT    MediaSampleContent ;
} PID_MAP ;

Members

ulPID
Specifies the packet ID.
MediaSampleContent
Specifies the contents of the packet payload.


PIN_INFO Structure

Structures

Contains information about a pin. Used with the IPin::QueryPinInfo method.

Syntax

typedef struct  _PinInfo
{
    IBaseFilter *pFilter;
    PIN_DIRECTION dir;
    WCHAR achName[128];
} PIN_INFO;

Members

pFilter
Pointer to the IBaseFilter interface of the owning filter.
dir
Direction of the pin (input or output).
achName
Name of the pin.

Remarks

If the name of an output pin begins with a tilde (~), the filter graph manager ignores the pin when it builds a graph. During a call to IGraphBuilder::Connect, IGraphBuilder::Render, or IGraphBuilder::RenderFile, if the pin appears on an intermediate filter, the filter graph manager does not render the pin. (However, it renders the pin if you explicitly pass the pin to the Connect or Render method.)

Use a tilde if the pin delivers a secondary stream that should not be rendered by default, or if the pin requires special code to render correctly. For example, DVD filters should use it for pins that deliver subpicture or closed captioning data. Video capture filters should use it for capture pins (but not preview pins).


Quality Structure

Structures

Describes a quality message by indicating Flood or Famine in the renderer and specifying the percentage of frames to drop or add to optimize the renderer's performance.

Syntax

typedef struct{
    QualityMessageType  Type;
    long                Proportion;
    REFERENCE_TIME      Late;
    REFERENCE_TIME      TimeStamp;
} Quality;

Members

Type
Either Famine or Flood, indicating that a downstream filter needs more or less data.
Proportion
Value that specifies the rate at which Microsoft® DirectShow® should continue to send media samples. The base value is 1000, which indicates there should be no change. A percentage increase or decrease from 1000 indicates the percentage of frames to add or drop. If this value is 800, for example, DirectShow will drop 20 percent of the incoming frames to match the renderer's speed.
Late
If a famine exists downstream, this is the amount of time by which the stream is lagging.
TimeStamp
Value that specifies the time when DirectShow created this structure, which is usually the start time on a video sample.


REGFILTER Structure

Structures

Identifies a filter by name and class identifier (CLSID).

Syntax

typedef struct {
    CLSID Clsid;
    LPWSTR Name;
} REGFILTER;

Members

Clsid
CLSID of the filter.
Name
Name of the filter.

Remarks

The obsolete IEnumRegFilters interface uses this structure. However, new applications should use IFilterMapper2, which enumerates monikers.


REGFILTER2 Structure

Structures

Contains information for registering a filter.

Syntax

typedef struct
{
    DWORD dwVersion;
    DWORD dwMerit;
    union
    {
        struct
        {
            ULONG cPins;
            const REGFILTERPINS *rgPins;
        };
        struct
        {
            ULONG cPins2;
            const REGFILTERPINS2 *rgPins2;
        };
    };
} REGFILTER2;

Members

dwVersion
Filter registration format. If the value is 1, the union contains the first unnamed structure. If the value is 2, the union contains the second unnamed structure.
dwMerit
Filter merit. Filters with higher merit are enumerated first.
cPins
Number of pins. (Defined only if dwVersion is 1.)
rgPins
Pointer to an array of REGFILTERPINS structures, of size cPins. (Defined only if dwVersion is 1.)
cPins2
Number of pins. (Defined only if dwVersion is 2.)
rgPins2
Pointer to an array of REGFILTERPINS2 structures, of size cPins2. (Defined only if dwVersion is 2.)

Remarks

This structure is passed to the IFilterMapper2::RegisterFilter method.

If you need to register pin mediums or pin categories, set dwVersion to 2 and use the REGFILTERPINS2 structure.


REGFILTERPINS Structure

Structures

Contains pin information for registering a filter.

Syntax

typedef struct
{
    LPWSTR            strName;
    BOOL              bRendered;
    BOOL              bOutput;
    BOOL              bZero;
    BOOL              bMany;
    const CLSID       *clsConnectsToFilter;
    const WCHAR       *strConnectsToPin;
    UINT              nMediaTypes;
    const REGPINTYPES *lpMediaType;
} REGFILTERPINS;

typedef REGFILTERPINS AMOVIESETUP_PIN,
    * PAMOVIESETUP_PIN,
    * FAR LPAMOVIESETUP_PIN;

Members

strName
Name of the pin. (Obsolete.)
bRendered
If TRUE, the filter renders the input from this pin. (Applies only to input pins. For output pins, the value is always FALSE.)
bOutput
If TRUE, this pin is an output pin. Otherwise, the pin is an input pin.
bZero
If TRUE, the filter can have zero instances of this pin.
bMany
If TRUE, the filter can create more than one instance of this type of pin.
clsConnectsToFilter
Class identifier (CLSID) of the filter to which this pin connects. (Obsolete.)
strConnectsToPin
Name of the pin to which this pin connects. (Obsolete.)
nMediaTypes
Number of media types supported by this pin.
lpMediaType
Pointer to an array of REGPINTYPES structures, of size nMediaTypes.

Remarks

This structure is used in the IFilterMapper2 interface for filter registration. If you use this stucture, set the dwVersion member of the REGFILTER2 structure to 1. If you need to register a medium or pin category for the pin, use the REGFILTERPINS2 structure instead. In that case, set the REGFILTER2 structure's dwVersion member to 2.

The equivalent AMOVIESETUP_PIN type is used in class factory templates (CFactoryTemplate).

The strName, clsConnectsToFilter, and strConnectsToPin members are obsolete. Their values are not added to the registry.

For more information, see How to Register DirectShow Filters.


REGFILTERPINS2 Structure

Structures

Contains information for registering a filter through the IFilterMapper2 interface.

Syntax

typedef struct
{
    DWORD               dwFlags;
    UINT                cInstances;
    UINT                nMediaTypes;
    const REGPINTYPES   *lpMediaType;
    UINT                nMediums;
    const REGPINMEDIUM  *lpMedium;
    const CLSID         *clsPinCategory;
} REGFILTERPINS2;

Members

dwFlags
Bitwise combination of zero or more REG_PINFLAG flags.
cInstances
Number of instances of this pin.
nMediaTypes
Number of media types supported by this pin.
lpMediaType
Pointer to an array of REGPINTYPES structures, of size nMediaTypes.
nMediums
Number of mediums. Can be zero.
lpMedium
Pointer to an array of REGPINMEDIUM structures, of size nMediums.
clsPinCategory
Optional pin category, from the Pin Property Set.

Remarks

If you use this stucture, set the dwVersion member of the REGFILTER2 structure to 2.


REGPINMEDIUM Structure

Structures

Describes a pin medium for registration through the IFilterMapper2 interface.

Syntax

typedef struct
{
    CLSID clsMedium;
    DWORD dw1;
    DWORD dw2;
} REGPINMEDIUM;

Members

clsMedium
GUID that specifies the medium.
dw1
Variable of type DWORD that specifies the instance of this medium. This is necessary when two identical devices are present on the host system.
dw2
Not used.

Remarks

A medium identifies a hardware path of communication that exists within a single hardware device or between two devices. Register mediums if your filter is built on kernel streaming pins and needs to connect to other such filters.

This structure is equivalent to the KSPIN_MEDIUM structure, which is used by kernel streaming drivers. For more information, see the Microsoft® Windows® Driver Development Kit (DDK).


REGPINTYPES Structure

Structures

Contains media type information for registering a filter.

Syntax

typedef struct
{
    const CLSID *clsMajorType;
    const CLSID *clsMinorType;
} REGPINTYPES;

typedef REGPINTYPES AMOVIESETUP_MEDIATYPE,
    * PAMOVIESETUP_MEDIATYPE,
    * FAR LPAMOVIESETUP_MEDIATYPE;

Members

clsMajorType
Major type GUID of the media type.
clsMinorType
Subtype GUID of the media type. Can be MEDIASUBTYPE_NULL.

Remarks

This structure is used by the IFilterMapper2 interface to identify the media types that a pin supports. The equivalent AMOVIESETUP_MEDIATYPE type is used in class factory templates (CFactoryTemplate).

To register a range of subtypes within the same major type, use the value MEDIASUBTYPE_NULL.

For more information, see How to Register DirectShow Filters.


STREAM_ID_MAP Structure

Structures

Describes an elementary stream within an MPEG-2 program stream. Used with the IEnumStreamIdMap interface methods.

Syntax

typedef struct {
    ULONG   stream_id;
    DWORD   dwMediaSampleContent;
    ULONG   ulSubstreamFilterValue;
    int     iDataOffset;
} STREAM_ID_MAP ;

Members

stream_id
Specifies the ID of the PES stream.
dwMediaSampleContent
Specifies the media contents of the stream. May be one of the following values (#defined in axextend.idl):
    MPEG2_PROGRAM_STREAM_MAP                 0x00000000
    MPEG2_PROGRAM_ELEMENTARY_STREAM          0x00000001
    MPEG2_PROGRAM_DIRECTORY_PES_PACKET       0x00000002
    MPEG2_PROGRAM_PACK_HEADER                0x00000003
    MPEG2_PROGRAM_PES_STREAM                 0x00000004
    MPEG2_PROGRAM_SYSTEM_HEADER              0x00000005
ulSubstreamFilterValue
Specifies the substream within the elementary stream. If no substream filtering is required, use SUBSTREAM_FILTER_VAL_NONE (0x10000000).
iDataOffset
Specifies the offset in bytes for the substream. If no filtering is required, specify 0.


TIMECODE Structure

Structures

Contains basic timecode frame count information.

Syntax

typedef struct tagTIMECODE {
    WORD  wFrameRate;
    WORD  wFrameFract;
    DWORD  dwFrames;
}TIMECODE;

Members

wFrameRate
Number of frames per second. Specify with one of the following values.
ED_FORMAT_SMPTE_30 | 30 frames per second.
ED_FORMAT_SMPTE_30DROP | 30 frames per second drop frame (actual rate 29.97 fps).
ED_FORMAT_SMPTE_25 | 25 frames per second.
ED_FORMAT_SMPTE_24 | 24 frames per second.
wFrameFract
Fractional frame. Full scale is 0x1000.
dwFrames
Timecode value as a binary framecount.

Remarks

Fractional frame can be used to indicate temporal offset into frame when timecode was actually read from an external device; for example, wFrameFract=0x7ff means the timecode value was read from the device at the end of the first video field.

Note Because timecode commonly enters or leaves computer systems as ASCII values, conversion helper methods that convert the ASCII values to and from binary framecounts are supplied in the sample filter.


TIMECODE_SAMPLE Structure

Structures

Contains complete timecode information.

Syntax

typedef struct tagTIMECODE_SAMPLE {
    LONGLONG  qwTick;
    TIMECODE  timecode;
    DWORD  dwUser;
    DWORD  dwFlags;
} TIMECODE_SAMPLE;

Members

qwTick
Reference time, in 100-nanosecond units.
timecode
TIMECODE structure.
dwUser
Packed SMPTE userbits.
dwFlags
Timecode flag masks. Specify one or more of the following values.
AM_TIMECODE_FLAG_FCM | Frame code mode; 0 = nondrop; 1 = drop.
AM_TIMECODE_FLAG_CF | Color frame flag.
AM_TIMECODE_FLAG_FIELD | Field flag.
AM_TIMECODE_FLAG_DF | Drop frame flag (from flags in actual timecode on external media).
AM_TIMECODE_COLORFRAME | Specifies frame in color sequence.
AM_TIMECODE_COLORSEQUENCE | Duration in frames of complete sequence.
AM_TIMECODE_FILMSEQUENCE_TYPE | One of FILM_SEQUENCE_XXX defines.

Remarks

The upper 16 bits in dwFlags are reserved for future use—set to zero.


TRUECOLORINFO Structure

Structures

Contains color palette and bitmask information for a video image.

Syntax

typedef struct tag_TRUECOLORINFO {
    DWORD dwBitMasks[iMASK_COLORS];
    RGBQUAD bmiColors[iPALETTE_COLORS];
} TRUECOLORINFO;

Members

dwBitMasks[iMASK_COLORS]
Array of color masks (one per color element).
bmiColors[iPALETTE_COLORS]
Array of palette colors.

Remarks

This structure is not used for some RGB formats. For more information about which fields are valid under different circumstances, see the Platform SDK documentation for BITMAPINFO.

See Also

VIDEOINFO


VIDEO_STREAM_CONFIG_CAPS Structure

Structures

Contains information about possible connections.

Syntax

typedef struct  _VIDEO_STREAM_CONFIG_CAPS
    {
    GUID guid;
    ULONG VideoStandard;
    SIZE InputSize;
    SIZE MinCroppingSize;
    SIZE MaxCroppingSize;
    int CropGranularityX;
    int CropGranularityY;
    int CropAlignX;
    int CropAlignY;
    SIZE MinOutputSize;
    SIZE MaxOutputSize;
    int OutputGranularityX;
    int OutputGranularityY;
    int StretchTapsX;
    int StretchTapsY;
    int ShrinkTapsX;
    int ShrinkTapsY;
    LONGLONG MinFrameInterval;
    LONGLONG MaxFrameInterval;
    LONG MinBitsPerSecond;
    LONG MaxBitsPerSecond;
    }  VIDEO_STREAM_CONFIG_CAPS;

Members

guid
Will set MEDIATYPE_Video to indicate a video sample.
VideoStandard
The analog video standard supported. Set in the AnalogVideoStandard enumeration type (0 if not supported).
InputSize
Size of the incoming signal, expressed through the Win32 SIZE structure as the image rectangle's width and height in pixels. For a compressor, the size is taken from the width and height members of the Win32 BITMAPINFOHEADER structure in the input pin's AM_MEDIA_TYPE structure. For a capture filter, the size is the largest signal the filter can digitize with every pixel remaining unique.
MinCroppingSize
Smallest cropping rectangle allowed, as specified in the VIDEOINFOHEADER structure's rcSource member.
MaxCroppingSize
Largest cropping rectangle allowed, as specified in the VIDEOINFOHEADER structure's rcSource member.
CropGranularityX
Granularity of the cropping size. For example, you could specify that the only valid widths are an even multiple of four.
CropGranularityY
Granularity of the cropping size. For example, you could specify that the only valid heights are an even multiple of four.
CropAlignX
Alignment of the cropping rectangle inside InputSize. For example, you could specify that rectangles must start on a boundary that is a multiple of four.
CropAlignY
Alignment of the cropping rectangle inside InputSize. For example, you could specify that rectangles must start on a boundary that is a multiple of four.
MinOutputSize
Smallest bitmap this pin can produce.
MaxOutputSize
Largest bitmap this pin can produce.
OutputGranularityX
Granularity of output bitmap width.
OutputGranularityY
Granularity of output bitmap height.
StretchTapsX
Value indicating how well the filter can stretch the image's width. A value of 0 means the filter can't stretch; 1 means it uses pixel doubling; 2 means it uses interpolation (2 taps); 3 and higher indicate it implements better interpolation.
StretchTapsY
Value indicating how well the filter can stretch the image's height. A value of 0 means the filter can't stretch; 1 means it uses pixel doubling; 2 means it uses interpolation (2 taps); 3 and higher indicate it implements better interpolation.
ShrinkTapsX
Value indicating how well the filter can shrink the image's width. A value of 0 means the filter can't shrink; 1 means it just eliminates some rows of pixels; 2 means it uses interpolation (2 taps); 3 and higher indicate it implements better interpolation.
ShrinkTapsY
Value indicating how well the filter can shrink the image's height. A value of 0 means the filter can't shrink; 1 means it just eliminates some rows of pixels; 2 means it uses interpolation (2 taps); 3 and higher indicate it implements better interpolation.
MinFrameInterval
Minimum frame rate allowed. This applies to the capture filter only.
MaxFrameInterval
Maximum frame rate allowed. This applies to the capture filter only.
MinBitsPerSecond
Minimum data rate this pin can produce.
MaxBitsPerSecond
Maximum data rate this pin can produce.

Remarks

For example, assume the following values for some of the structure members.

  • MinCroppingSize = (160, 120)
  • MaxCroppingSize = (320, 240)
  • CropGranularityX = 4
  • CropGranularityY = 8

These values indicate that valid cropping sizes begin at MinCroppingSize and increase in steps in the x-direction by CropGranularityX and in the y-direction by CropGranularityY. In this case the x-value can be anywhere from 160 to 320 pixels in steps of 4 and the y-value can be anywhere from 120 to 240 pixels in steps of 8.

In this scenario a few of the valid sizes are:

  • 160 × 120, 164 × 120, 168 × 120, 172 × 120, and so on
  • 160 × 128, 164 × 128, 168 × 128, 172 × 128, and so on
  • 160 × 136, 164 × 136, 168 × 136, 172 × 136, and so on

CropAlignX and CropAlignY indicate where the cropping rectangle can be inside the input size rectangle. Given a 160 × 120 sized cropping rectangle and the following:

  • CropAlignX = 2
  • CropAlignY = 4

Some of the valid values for the VIDEOINFOHEADER structure's rcSource member are:

  • (0, 0, 160, 120)
  • (2, 0, 162, 120)
  • (2, 4, 162, 124)
  • (2, 8, 162, 128)

For a 320 × 240 cropping rectangle and the same cropping alignment values, (2, 4, 322, 244) is one example of the many legal rectangles.

The structure members discussed in this section work together to specify what values of rcSource are valid for the VIDEOINFOHEADER structure that describes the output pin's media type. Of the remaining structure members, MinOutputSize, MaxOutputSize, OutputGranularityX, and OutputGranularityY describe the biWidth and biHeight members of the BITMAPINFOHEADER structure contained in the output pin's media type VIDEOINFOHEADER structure.


VIDEOINFO Structure

Structures

Describes the bitmap and color information for a video image.

Syntax

typedef struct tagVIDEOINFO {
    RECT              rcSource,
    RECT              rcTarget,
    DWORD             dwBitRate,
    DWORD             dwBitErrorRate,
    REFERENCE_TIME    AvgTimePerFrame;
    BITMAPINFOHEADER  bmiHeader;
    union {
        RGBQUAD         bmiColors[iPALETTE_COLORS];
        DWORD           dwBitMasks[iMASK_COLORS];
        TRUECOLORINFO   TrueColorInfo;
    };
} VIDEOINFO;

Members

rcSource
Portion of the input video to use.
rcTarget
Where the video should be displayed.
dwBitRate
Approximate bit data rate.
dwBitErrorRate
Bit error rate for this stream.
AvgTimePerFrame
Average time per frame, in 100-nanosecond units.
bmiHeader
Win32 BITMAPINFOHEADER structure that contains color and dimension information for a device-independent bitmap.
bmiColors
Array of Win32 RGBQUAD structures that specifies the video's color palette. Each structure represents a single color, which is a combination of red, green, and blue intensities.
dwBitMasks
Array of DWORD values that specify true color bitmasks.
TrueColorInfo
TRUECOLORINFO structure that contains both a color palette and an array of color bitmasks.

Remarks

Never use this structure unless you are sure that you will use it only to store standard RGB formats. If you store anything other than standard RGB, the variable size of the bmiHeader structure will almost certainly cause problems, and you should use the VIDEOINFOHEADER structure instead. If you find it absolutely necessary to use the VIDEOINFO structure, do not access the TrueColorInfo, dwBitMasks, or bmiColors members directly. Instead, use the TRUECOLORINFO, COLORS, and BITMASKS macros to return the pointers to the color information. Which of these members is valid depends on the contents of the BITMAPINFOHEADER structure.

The first five data members are equivalent to a VIDEOINFOHEADER structure. They are expanded in full simply to reduce the amount of dereferencing needed when dealing with a pointer to a VIDEOINFO structure.

For information about using the rcSource and rcTarget members, see Source and Target Rectangles in Video Renderers.


VIDEOINFOHEADER Structure

Structures

Describes the bitmap and color information for a video image.

Syntax

typedef struct tagVIDEOINFOHEADER {
    RECT                rcSource,
    RECT                rcTarget;
    DWORD               dwBitRate;
    DWORD               dwBitErrorRate;
    REFERENCE_TIME      AvgTimePerFrame;
    BITMAPINFOHEADER    bmiHeader;
} VIDEOINFOHEADER;

Members

rcSource
RECT structure that specifies the source video window. This structure can be a clipping rectangle, to select a portion of the source video stream.
rcTarget
RECT structure that specifies the destination video window.
dwBitRate
Approximate data rate of the video stream, in bits per second.
dwBitErrorRate
Data error rate, in bit errors per second.
AvgTimePerFrame
Average display time of the video frames, in 100-nanosecond units.
bmiHeader
Win32 BITMAPINFOHEADER structure that contains color and dimension information for the video image bitmap.

Remarks

For information about using the rcSource and rcTarget members, see Source and Target Rectangles in Video Renderers.


VIDEOINFOHEADER2 Structure

Structures

Describes the bitmap and color information for a video image, including interlace, copy protection, and pixel aspect ratio information.

Syntax

typedef struct tagVIDEOINFOHEADER2 {
    RECT                rcSource;
    RECT                rcTarget;
    DWORD               dwBitRate;
    DWORD               dwBitErrorRate;
    REFERENCE_TIME      AvgTimePerFrame;
    DWORD               dwInterlaceFlags;
    DWORD               dwCopyProtectFlags;
    DWORD               dwPictAspectRatioX;
    DWORD               dwPictAspectRatioY;
    DWORD               dwReserved1;
    DWORD               dwReserved2;
    BITMAPINFOHEADER    bmiHeader;
} VIDEOINFOHEADER2;

Members

rcSource
RECT structure that specifies what part of the source stream should be used to fill the destination buffer. Renderers can use this field to ask the decoders to stretch or clip. For more information, see Source and Target Rectangles in Video Renderers.
rcTarget
RECT structure that specifies that specifies what part of the destination buffer should be used. For more information, see Source and Target Rectangles in Video Renderers.
dwBitRate
Approximate data rate of the video stream, in bits per second.
dwBitErrorRate
Data error rate of the video stream, in bits per second.
AvgTimePerFrame
The video frame's average display time, in 100-nanosecond units.
dwInterlaceFlags
Bit-wise combination of zero or more of the following flags. See the table at the bottom of this page for more information about these flags.
AMINTERLACE_IsInterlaced | The stream is interlaced. If this flag is absent, the other bits are irrelevant.
AMINTERLACE_1FieldPerSample | One field per media sample. If this flag is absent, there are two fields per media sample.
AMINTERLACE_Field1First | Field 1 is first. If this flag is absent, Field 2 is first. (Top field in PAL is field 1, top field in NTSC is field 2.)
AMINTERLACE_FieldPatField1Only | Stream never contains a Field 2.
AMINTERLACE_FieldPatField2Only | Stream never contains a Field 1.
AMINTERLACE_FieldPatBothRegular | One Field 2 for every Field 1.
AMINTERLACE_FieldPatBothIrregular | Random pattern of Field 1 and Field 2.
AMINTERLACE_DisplayModeBobOnly | Bob display mode only.
AMINTERLACE_DisplayModeWeaveOnly | Weave display mode only.
AMINTERLACE_DisplayModeBobOrWeave | Either bob or weave mode.
Set undefined flags to zero, or the connection will be rejected.
dwCopyProtectFlags
Flag set with the AMCOPYPROTECT_RestrictDuplication value to indicate duplication of stream should be restricted. If undefined, specify zero or connection will be rejected.
dwPictAspectRatioX
The X dimension of picture aspect ratio. For example, 16 for a 16-inch × 9-inch display.
dwPictAspectRatioY
The Y dimension of picture aspect ratio. For example, 9 for a 16-inch × 9-inch display.
dwReserved1
Reserved. Must be zero.
dwReserved2
Reserved for future use. Must be zero.
bmiHeader
Microsoft® Win32® BITMAPINFOHEADER structure that contains color and dimension information for the video image bitmap.

Remarks

Use the bit mask AMINTERLACE_FieldPatternMask to check the field pattern flags in dwInterlaceFlags:

switch (dwInterlaceFlags & AMINTERLACE_FieldPatternMask)
{
    case AMINTERLACE_FieldPatField1Only:
        // Stream never contains a Field 2.

    case AMINTERLACE_FieldPatField2Only:
        // Stream never contains a Field 1.

    case AMINTERLACE_FieldPatBothRegular:
        // One Field 2 for every Field 1.

    case AMINTERLACE_FieldPatBothIrregular:
        // Random pattern of Field 1 and Field 2.
}

Use the bit mask AMINTERLACE_DisplayModeMask to check the display mode flags in dwInterlaceFlags:

switch (dwInterlaceFlags & AMINTERLACE_DisplayModeMask)
{
    case AMINTERLACE_DisplayModeBobOnly:
        // Bob display mode only.

    case AMINTERLACE_DisplayModeWeaveOnly:
        // Weave display mode only.

    case AMINTERLACE_DisplayModeBobOrWeave:
        // Either bob or weave mode.
}

The following table describes the valid combinations of interlace flags and sample properties, for displaying interlaced fields/frames on the Overlay Mixer filter. Sample properties are specified in the dwTypeSpecificFlags member of each sample's AM_SAMPLE2_PROPERTIES structure.

Display Mode | Interlace Flags | Media Sample Properties
Frame | 0 | 0
Non-Interleaved Bob AMINTERLACE_IsInterlaced |
AMINTERLACE_1FieldPerSample |
AMINTERLACE_DisplayModeBobOnly 		AM_VIDEO_FLAG_FIELD1 or AM_VIDEO_FLAG_FIELD2
Weave Only AMINTERLACE_IsInterlaced |
AMINTERLACE_FieldPatBothRegular |
AMINTERLACE_DisplayModeWeaveOnly 		AM_VIDEO_FLAG_WEAVE
Interleaved Bob Only Field 1 First AMINTERLACE_IsInterlaced |
AMINTERLACE_DisplayModeBobOnly 		AM_VIDEO_FLAG_FIELD1_FIRST
Field 2 First AMINTERLACE_IsInterlaced |
AMINTERLACE_DisplayModeBobOnly 		0
Bob or Weave
(Interchangeable) 		Bob, Field 1 First AMINTERLACE_IsInterlaced |
AMINTERLACE_DisplayModeBobOrWeave 		AM_VIDEO_FLAG_FIELD1_FIRST
Bob, Field 2 First AMINTERLACE_IsInterlaced |
AMINTERLACE_DisplayModeBobOrWeave 		0
Weave AMINTERLACE_IsInterlaced |
AMINTERLACE_DisplayModeBobOrWeave 		AM_VIDEO_FLAG_WEAVE


Enumerated Types

This section describes the Microsoft® DirectShow® enumerated types. Closed captioning, DVD, and VPE enumerated types are grouped by functionality below the primary list.

Enumerated type | Description
AM_ASPECT_RATIO_MODE | Specifies the aspect ratio of a video image in a display window.
AM_FILTER_MISC_FLAGS | Contains the source or renderer filter flags.
AM_GRAPH_CONFIG_RECONNECT_FLAGS | Specifies how to reconnect filters when dynamically rebuilding the filter graph.
AM_INTF_SEARCH_FLAGS | Specifies the types of object to search, when attempting to find an interface on the filter graph.
AM_OVERLAY_NOTIFY_FLAGS | Contains information on what the overlay has changed or what the overlay is about to change.
AM_PIN_CONNECTION_BLOCK_FLAGS | Defines flags that specify how to block data flow from an output pin.
AM_PUSHSOURCE_FLAGS | Contains flags specifying whether to increment or decrement the number of resources currently being reserved.
AM_RESCTL_RESERVEFLAGS | Contains flags specifying whether to increment or decrement the number of resources currently being reserved.
AM_SAMPLE_PROPERTY_FLAGS | Specifies values for the dwSampleFlags and dwStreamId members of the AM_SAMPLE2_PROPERTIES structure. These values describe the properties of media samples.
AM_SEEKING_SEEKING_CAPABILITIES | Specifies the seeking capabilities of a media stream.
AM_STREAM_INFO_FLAGS | Indicates whether various components of the AM_STREAM_INFO structure have been set.
AMOVERLAYFX | Specifies effects on a Microsoft® DirectDraw® hardware overlay surface.
AMTunerModeType | Specifies the frequency of a TV tuner (cable or antenna).
AnalogVideoStandard | Specifies the format of the baseband analog video signal.
CameraControlFlags | Specifies whether the camera is automatic or manual.
CameraControlProperty | Specifies what part of the camera DirectShow is controlling.
CL_ELEM_FLAGS | Specifies cutlist element flags.
CL_ELEM_STATUS | Specifies cutlist status flags.
CompressionCaps | Indicates video compression capabilities.
DECIMATION_USAGE | Describes the decimation strategy used by the overlay mixer filter.
DVDECODERRESOLUTION | Indicates the digital video (DV) decoding resolution.
DVENCODERFORMAT | Indicates the DV format.
DVENCODERRESOLUTION | Indicates the DV encoding resolution.
DVENCODERVIDEOFORMAT | Indicates the video standard (NTSC or PAL) for DV encoding.
FILTER_STATE | Specifies a filter's state.
InterleavingMode | Specifies how video frames and audio samples will be written to disk.
MEDIA_SAMPLE_CONTENT | Describes the contents of an elementary stream within an MPEG-2 transport stream.
MPEG2Level | Indicates the MPEG-2 video level as specified in the MPEG-2 video standard. (ISO13818-2)
MPEG2Profile | Indicates the MPEG-2 video profile as specified in the MPEG-2 video standard. (ISO13818-2)
PhysicalConnectorType | Specifies the physical type of pin (audio or video).
PIN_DIRECTION | Indicates a pin's direction.
QualityMessageType | Describes a quality message type.
REG_PINFLAG | Indicates flags for the dwFlags member in the REGFILTERPINS2 structure.
REM_FILTER_FLAGS | Specifies how to remove a filter from the filter graph.
SNDDEV_ERR | Specifies how the audio device was being accessed when the failure occurred.
StreamControlState | Specifies the state of the stream.
TunerInputType | Specifies the frequency of a TV tuner (cable or antenna).
TVAudioMode | Specifies the mode of a TV audio control.
VfwCaptureDialogs | Specifies a dialog box that might exist in a Microsoft Video for Windows® capture driver.
VfwCompressDialogs | Specifies a dialog box that might exist in a Video for Windows compression (codec) driver.
VideoControlFlags | Specifies video mode of operation (horizontal or vertical flip, external trigger enable, and trigger simulate) for a video device.
VideoProcAmpFlags | Specifies how to set video properties.
VideoProcAmpProperty | Specifies video properties.

The following enumerated types are specific to closed captioning.

Closed captioning enumerated type | Description
AM_LINE21_CCLEVEL | Indicates the closed captioning capability level.
AM_LINE21_CCSERVICE | Indicates the closed captioning decoder service.
AM_LINE21_CCSTATE | Indicates the closed captioning state (on or off).
AM_LINE21_DRAWBGMODE | Indicates the closed-captioned text background mode.

The following enumerated types are specific to DVD.

DVD enumerated type | Description
AM_DVD_GRAPH_FLAGS | Specifies the type of decoder to use in a DVD filter graph.
AM_DVD_STREAM_FLAGS | Describes a DVD stream type (video, audio, or subpicture).
DVD_AUDIO_APPMODE | Indicates the current audio mode.
DVD_AUDIO_FORMAT | Indicates the audio format of a digital video disc (DVD).
DVD_AUDIO_LANG_EXT | Defines flags that indicate whether an audio stream contains audio language extensions.
DVD_CMD_FLAGS | Defines flags that control how the DVD Navigator filter handles command synchronization.
DVD_DISC_SIDE | Indicates the sides of a DVD disc.
DVD_DOMAIN | Specifies DVD domains.
DVD_ERROR | Specifies DVD error conditions.
DVD_FRAMERATE | Indicates whether the DVD is authored to play at 25 or 30 frames per second.
DVD_KARAOKE_ASSIGNMENT | Defines flags that indicate which speaker an audio channel is assigned to.
DVD_KARAOKE_CONTENTS | Specifies flags that, when used in a bitwise OR operation, describe the contents of each channel of an audio stream in a karaoke title.
DVD_KARAOKE_DOWNMIX | Defines flags used by the IDvdControl2::SelectKaraokeAudioPresentationMode method to control which speakers, if any, each auxiliary channel is downmixed to.
DVD_MENU_ID | Specifies DVD Video Title Set (VTS) menu identifiers.
DVD_OPTION_FLAG | Defines flags that control aspects of the DVD Navigator filter's behavior related to playback of digital video disc (DVD) content.
DVD_PARENTAL_LEVEL | Identifies flags for the generic parental levels defined in the DVD specification.
DVD_PREFERRED_DISPLAY_MODE | Indicates the user's preferred window aspect ratio and conversion method.
DVD_RELATIVE_BUTTON | Identifies the four directional buttons used for digital video disc (DVD) menu navigation and other operations.
DVD_SUBPICTURE_CODING | Indicates what kind of content the subpicture stream contains.
DVD_SUBPICTURE_LANG_EXT | Defines the possible language extensions in a specified subpicture stream.
DVD_SUBPICTURE_TYPE | Defines flags used to determine what kind of content the subpicture stream contains.
DVD_TextCharSet | Defines which ISO character set a specified string is encoded with.
DVD_TextStringType | Defines a subset of the DVD text string types.
DVD_TIMECODE_FLAGS | Indicates the frame rate at which a digital video disc (DVD) has been authored to play.
DVD_TITLE_APPMODE | Indicates whether a DVD title is a karaoke title.
DVD_VALID_UOP_FLAG | Indicates which user operation (UOP) commands are currently allowed by the digital video disc (DVD).
DVD_VIDEO_COMPRESSION | Defines the possible digital video disc (DVD) video compression types.
DVD_WARNING | Specifies DVD warning conditions.

The following enumerated types are specific to VPE.

VPE enumerated type | Description
AMVP_MODE | Specifies the various modes for video ports (VP).
AMVP_SELECT_FORMAT_BY | Specifies the criteria that the VP mixer should use to select the video format.


AM_ASPECT_RATIO_MODE Enumeration

Enumerated Types

Specifies the aspect ratio of a video image in a display window.

Syntax

typedef enum _AM_ASPECT_RATIO_MODE
{
    AM_ARMODE_STRETCHED,
    AM_ARMODE_LETTER_BOX,
    AM_ARMODE_CROP,
    AM_ARMODE_STRETCHED_AS_PRIMARY
} AM_ASPECT_RATIO_MODE;

Elements

AM_ARMODE_STRETCHED
No aspect ratio correction.
AM_ARMODE_LETTER_BOX
Put the video in letterbox format. Paint background color in the excess region so the video is not distorted.
AM_ARMODE_CROP
Crop the video to the correct aspect ratio.
AM_ARMODE_STRETCHED_AS_PRIMARY
Use whatever mode is currently set for the primary stream. This value is valid only for secondary streams.

Remarks

The AM_ARMODE_STRETCHED member causes a video stream to occupy the entire region of the display window when the window is resized, possibly stretching the video. The AM_ARMODE_LETTER_BOX member eliminates video stretching and distortions by keeping the aspect ratio consistent and painting the excess areas of the window a background color. The AM_ARMODE_CROP member also prevents stretching, by cropping the image if necessary.

See Also

IMixerPinConfig::GetAspectRatioMode, IMixerPinConfig::SetAspectRatioMode


AM_DVD_GRAPH_FLAGS Enumeration

Enumerated Types

Specifies the type of decoder to use in a DVD filter graph.

Syntax

enum {
    AM_DVD_HWDEC_PREFER,
    AM_DVD_HWDEC_ONLY,
    AM_DVD_SWDEC_PREFER,
    AM_DVD_SWDEC_ONLY,
    AM_DVD_NOVPE
} AM_DVD_GRAPH_FLAGS;

Elements

AM_DVD_HWDEC_PREFER
Maximum hardware decoding. Default.
AM_DVD_HWDEC_ONLY
Hardware decoding only.
AM_DVD_SWDEC_PREFER
Maximum software decoding.
AM_DVD_SWDEC_ONLY
Software decoding only.
AM_DVD_NOVPE
Do not show video on computer monitor. Use of this flag should be limited only to the combination of a hardware DVD-Video decoder and a display device with a port that can connect to a TV. A set-top box type of device that can play back DVD-Video could play DVD titles to be viewed on a TV set rather than a computer monitor.

Remarks

Do not combine any of the hardware flags (AM_DVD_HWDEC_*) with any of the software flags (AM_DVD_SWDEC_*). However, you can combine AM_DVD_NOVPE with any of the hardware flags.

See Also

IDvdGraphBuilder::RenderDvdVideoVolume


AM_DVD_STREAM_FLAGS Enumeration

Enumerated Types

Describes a DVD stream type (video, audio, or subpicture).

Syntax

enum {
    AM_DVD_STREAM_VIDEO,
    AM_DVD_STREAM_AUDIO,
    AM_DVD_STREAM_SUBPIC
} AM_DVD_STREAM_FLAGS;

Elements

AM_DVD_STREAM_VIDEO
DVD video stream.
AM_DVD_STREAM_AUDIO
DVD audio stream.
AM_DVD_STREAM_SUBPIC
DVD subpicture stream.

See Also

AM_DVD_RENDERSTATUS


AM_FILTER_MISC_FLAGS Enumeration

Enumerated Types

Contains the source or renderer filter flags.

Syntax

typedef enum _AM_FILTER_MISC_FLAGS {
    AM_FILTER_MISC_FLAGS_IS_RENDERER = 0x00000001,
    AM_FILTER_MISC_FLAGS_IS_SOURCE   = 0x00000002
};

Elements

AM_FILTER_MISC_FLAGS_IS_RENDERER
Filter is the renderer.
AM_FILTER_MISC_FLAGS_IS_SOURCE
Filter is the source.


AM_GRAPH_CONFIG_RECONNECT_FLAGS Enumeration

Enumerated Types

Specifies how to reconnect filters when dynamically rebuilding the filter graph.

Syntax

typedef enum _AM_GRAPH_CONFIG_RECONNECT_FLAGS {
    AM_GRAPH_CONFIG_RECONNECT_DIRECTCONNECT = 0x00000001,
    AM_GRAPH_CONFIG_RECONNECT_CACHE_REMOVED_FILTERS = 0x00000002,
    AM_GRAPH_CONFIG_RECONNECT_USE_ONLY_CACHED_FILTERS = 0x00000004
} AM_GRAPH_CONFIG_RECONNECT_FLAGS;

Elements

AM_GRAPH_CONFIG_RECONNECT_DIRECTCONNECT
Do not insert additional filters into the graph while reconnecting, aside from any filter explicitly requested.
AM_GRAPH_CONFIG_RECONNECT_CACHE_REMOVED_FILTERS
Place filters removed from the graph into the filter cache.
AM_GRAPH_CONFIG_RECONNECT_USE_ONLY_CACHED_FILTERS
When inserting additional filters into the graph, use only filters currently in the filter cache.

See Also

IGraphConfig::Reconnect, IPinFlowControl::Block


AM_INTF_SEARCH_FLAGS Enumeration

Enumerated Types

Specifies the types of object to search, when attempting to find an interface on the filter graph.

Syntax

enum _AM_INTF_SEARCH_FLAGS {
    AM_INTF_SEARCH_INPUT_PIN  = 0x00000001,
    AM_INTF_SEARCH_OUTPUT_PIN = 0x00000002,
    AM_INTF_SEARCH_FILTER     = 0x00000004
};

Elements

AM_INTF_SEARCH_INPUT_PIN
Search input pins.
AM_INTF_SEARCH_OUTPUT_PIN
Search output pins.
AM_INTF_SEARCH_FILTER
Search filters.

Remarks

If no flags are set (the default case), it is equivalent to the bitwise OR of all the flags. All filters and pins are searched.

See Also

IAMGraphStreams::FindUpstreamInterface


AM_LINE21_CCLEVEL Enumeration

Enumerated Types

Indicates the closed captioning capability level.

Syntax

 typedef enum _AM_LINE21_CCLEVEL {
    AM_L21_CCLEVEL_TC2
} AM_LINE21_CCLEVEL, *PAM_LINE21_CCLEVEL ;

Elements

AM_L21_CCLEVEL_TC2
Capability level 2.

See Also

IAMLine21Decoder::GetDecoderLevel


AM_LINE21_CCSERVICE Enumeration

Enumerated Types

Indicates the closed captioning decoder service.

Syntax

 typedef enum _AM_LINE21_CCSERVICE {
    AM_L21_CCSERVICE_None,
    AM_L21_CCSERVICE_Caption1,
    AM_L21_CCSERVICE_Caption2,
    AM_L21_CCSERVICE_Text1,
    AM_L21_CCSERVICE_Text2,
    AM_L21_CCSERVICE_XDS,
} AM_LINE21_CCSERVICE, *PAM_LINE21_CCSERVICE ;

Elements

AM_L21_CCSERVICE_None
No current service.
AM_L21_CCSERVICE_Caption1
True captioning, first field. Default service.
AM_L21_CCSERVICE_Caption2
Captioning for secondary language, second field. Generally not used.
AM_L21_CCSERVICE_Text1
First text field. Not currently implemented; provided for future compatibility.
AM_L21_CCSERVICE_Text2
Second text field. Not currently implemented; provided for future compatibility.
AM_L21_CCSERVICE_XDS
Extended Data Services (XDS or EDS). Not currently implemented; provided for future compatibility.

See Also

IAMLine21Decoder::GetCurrentService, IAMLine21Decoder::SetCurrentService


AM_LINE21_CCSTATE Enumeration

Enumerated Types

Indicates the closed captioning state (on or off).

Syntax

 typedef enum _AM_LINE21_CCSTATE {
    AM_L21_CCSTATE_Off,
    AM_L21_CCSTATE_On
} AM_LINE21_CCSTATE, *PAM_LINE21_CCSTATE ;

Elements

AM_L21_CCSTATE_Off
Closed captioning off.
AM_L21_CCSTATE_On
Closed captioning on.

See Also

IAMLine21Decoder::GetServiceState, IAMLine21Decoder::SetServiceState


AM_LINE21_DRAWBGMODE Enumeration

Enumerated Types

Indicates the closed captioning text background mode.

Syntax

 typedef enum _AM_LINE21_DRAWBGMODE {
    AM_L21_DRAWBGMODE_Opaque,
    AM_L21_DRAWBGMODE_Transparent
} AM_LINE21_DRAWBGMODE, *PAM_LINE21_DRAWBGMODE ;

Elements

AM_L21_DRAWBGMODE_Opaque
Opaque background.
AM_L21_DRAWBGMODE_Transparent
Transparent background.

See Also

IAMLine21Decoder::GetDrawBackgroundMode, IAMLine21Decoder::SetDrawBackgroundMode


AM_OVERLAY_NOTIFY_FLAGS Enumeration

Enumerated Types

Contains information on what the overlay has changed or what the overlay is about to change.

Syntax

typedef enum _AM_OVERLAY_NOTIFY_FLAGS {
    AM_OVERLAY_NOTIFY_FLAGS_VISIBLE_CHANGE = 0x00000001,
    AM_OVERLAY_NOTIFY_FLAGS_SOURCE_CHANGE   = 0x00000002,
    AM_OVERLAY_NOTIFY_FLAGS_DEST_CHANGE   = 0x00000004
};

Elements

AM_OVERLAY_NOTIFY_VISIBLE_CHANGE
Notifies the overlay that the rectangle will be changed from visible to invisible or invisible to visible.
AM_OVERLAY_NOTIFY_SOURCE_CHANGE
Source rectangle changed or changing.
AM_OVERLAY_NOTIFY_DEST_CHANGE
Destination rectangle changed or changing.

Remarks

The IDDrawExclModeVideoCallback::OnUpdateOverlay method uses these flags to indicate how the overlay has changed, so that applications can take the necessary steps.

See Also

IDDrawExclModeVideoCallback::OnUpdateOverlay


AM_PIN_CONNECTION_BLOCK_FLAGS Enumeration

Enumerated Types

Defines flags that specify how to block data flow from an output pin.

Syntax

enum _AM_PIN_CONNECTION_BLOCK_FLAGS {
    AM_PIN_FLOW_CONTROL_BLOCK = 0x00000001,
    AM_PIN_PUSH_THROUGH_DATA = 0x00000002
};

Elements

AM_PIN_FLOW_CONTROL_BLOCK
Block the data flow.
AM_PIN_PUSH_THROUGH_DATA
Push the data through the filter graph.

See Also

IPinFlowControl::Block


AM_PUSHSOURCE_FLAGS Enumeration

Enumerated Types

Indicates the behavior of a live source filter.

Syntax

enum _AM_PUSHSOURCE_FLAGS {
    AM_PUSHSOURCECAPS_INTERNAL_RM        = 0x00000001,
    AM_PUSHSOURCECAPS_NOT_LIVE           = 0x00000002,
    AM_PUSHSOURCECAPS_PRIVATE_CLOCK      = 0x00000004,
    AM_PUSHSOURCEREQS_USE_STREAM_CLOCK   = 0x00010000
};

Elements

AM_PUSHSOURCECAPS_INTERNAL_RM
The filter uses its own rate-matching mechanism; the renderer should therefore not attempt to match rates with this filter.
AM_PUSHSOURCECAPS_NOT_LIVE
The filter is not live. Do not treat it as a live source, even though it exposes the IAMPushSource interface.
AM_PUSHSOURCECAPS_PRIVATE_CLOCK
Reserved; do not use.
AM_PUSHSOURCEREQS_USE_STREAM_CLOCK
Reserved; do not use.

Remarks

If no flags are set (the default case), the source filter is assumed to be live and not to perform any rate matching on its own.


AM_SAMPLE_PROPERTY_FLAGS Enumeration

Enumerated Types

Specifies values for the dwSampleFlags and dwStreamId members of the AM_SAMPLE2_PROPERTIES structure. These values describe the properties of media samples.

Syntax

enum tagAM_SAMPLE_PROPERTY_FLAGS
     { AM_SAMPLE_SPLICEPOINT        = 0x01,
       AM_SAMPLE_PREROLL            = 0x02,
       AM_SAMPLE_DATADISCONTINUITY  = 0x04,
       AM_SAMPLE_TYPECHANGED        = 0x08,
       AM_SAMPLE_TIMEVALID          = 0x10,
       AM_SAMPLE_TIMEDISCONTINUITY  = 0x40,
       AM_SAMPLE_FLUSH_ON_PAUSE     = 0x80,
       AM_SAMPLE_STOPVALID          = 0x100,
       AM_SAMPLE_ENDOFSTREAM        = 0x200,
       AM_STREAM_MEDIA              = 0,
       AM_STREAM_CONTROL            = 1
     };

Elements

AM_SAMPLE_SPLICEPOINT
Sample is a splice point (it can be decoded without reference to previous data).
AM_SAMPLE_PREROLL
Sample is a preroll sample.
AM_SAMPLE_DATADISCONTINUITY
Initial data in this sample is a splice point. The data in the previous sample was not intended to be followed by data in this sample. For more information, see Remarks.
AM_SAMPLE_TYPECHANGED
Sample type changed.
AM_SAMPLE_TIMEVALID
Time is valid.
AM_SAMPLE_TIMEDISCONTINUITY
A time gap in the data starts after this sample. The pbBuffer member of the AM_SAMPLE2_PROPERTIES structure can be NULL in this case.
AM_SAMPLE_FLUSH_ON_PAUSE
For live data only; indicates discard in the paused state.
AM_SAMPLE_STOPVALID
Stop time is valid.
AM_SAMPLE_ENDOFSTREAM
End of stream occurs after this sample. This is reserved for kernel streaming and Microsoft® DirectShow® currently doesn't use it.
AM_STREAM_MEDIA
Normal data stream identifier.
AM_STREAM_CONTROL
Control stream identifier. A value greater than 0x7FFFFFFF indicates an application-defined stream.

Remarks

The AM_SAMPLE_DATADISCONTINUITY flag indicates that the data in the current media sample is not considered contiguous with the data in previous samples. A filter receiving a sample with the AM_SAMPLE_DATADISCONTINUITY flag set should not discard unprocessed data in its buffers. A filter waiting for incoming data before it can process buffered data should process the buffered data immediately; so, buffered data might be discarded if it is incomplete.

For example, a video decompressor filter might receive a media sample with the AM_SAMPLE_DATADISCONTINUITY flag set when it has two complete compressed video frames and one incomplete compressed video frame in its buffers. In this case, the filter decompresses the two complete frames and discards the incomplete third frame before beginning to process data from the current media sample.

The AM_SAMPLE_DATADISCONTINUITY flag is set on the first sample received following a flush or a stop. In addition, you should use the AM_SAMPLE_DATADISCONTINUITY flag when content is switched in the source, when a channel change occurs (when there might also be a format change), or when there is missing data because of stream interruptions.

The AM_SAMPLE_DATADISCONTINUITY flag is equivalent to the IMediaSample::IsDiscontinuity method returning S_OK.


AM_SEEKING_SEEKING_CAPABILITIES Enumeration

Enumerated Types

Specifies the seeking capabilities of a media stream.

Syntax

typedef
enum AM_SEEKING_SeekingCapabilities {
    AM_SEEKING_CanSeekAbsolute        = 0x1,
    AM_SEEKING_CanSeekForwards        = 0x2,
    AM_SEEKING_CanSeekBackwards       = 0x4,
    AM_SEEKING_CanGetCurrentPos       = 0x8,
    AM_SEEKING_CanGetStopPos          = 0x10,
    AM_SEEKING_CanGetDuration         = 0x20,
    AM_SEEKING_CanPlayBackwards       = 0x40,
    AM_SEEKING_CanDoSegments          = 0x80,
    AM_SEEKING_Source                 = 0x100
}   AM_SEEKING_SEEKING_CAPABILITIES;

Elements

AM_SEEKING_CanSeekAbsolute
The stream can seek to an absolute position.
AM_SEEKING_CanSeekForwards
The stream can seek forward.
AM_SEEKING_CanSeekBackwards
The stream can seek backward.
AM_SEEKING_CanGetCurrentPos
The stream can report its current position.
AM_SEEKING_CanGetStopPos
The stream can report its stop position.
AM_SEEKING_CanGetDuration
The stream can report its duration.
AM_SEEKING_CanPlayBackwards
The stream can play backward.
AM_SEEKING_CanDoSegments
The stream can do seamless looping (see IMediaSeeking::SetPositions).
AM_SEEKING_Source
Reserved.

See Also

IMediaSeeking::GetCapabilities, IMediaSeeking::CheckCapabilities


AM_STREAM_INFO_FLAGS Enumeration

Enumerated Types

Indicates whether various components of the AM_STREAM_INFO structure have been set.

Syntax

typedef enum {
    AM_STREAM_INFO_START_DEFINED = 0x00000001,
    AM_STREAM_INFO_STOP_DEFINED  = 0x00000002,
    AM_STREAM_INFO_DISCARDING    = 0x00000004,
    AM_STREAM_INFO_STOP_SEND_EXTRA = 0x00000010
} AM_STREAM_INFO_FLAGS;

Elements

AM_STREAM_INFO_START_DEFINED
Indicates a valid stream start time has been set.
AM_STREAM_INFO_STOP_DEFINED
Indicates a valid stream stop time has been set.
AM_STREAM_INFO_DISCARDING
Indicates that stream discarding is currently active.
AM_STREAM_INFO_STOP_SEND_EXTRA
Indicates that the pin will send an extra stream sample upon completion.


AMOVERLAYFX Enumeration

Enumerated Types

Specifies effects on a Microsoft® DirectDraw® hardware overlay surface.

Syntax

enum AMOVERLAYFX {
    AMOVERFX_NOFX =             0x00000000,
    AMOVERFX_MIRRORLEFTRIGHT =  0x00000002,
    AMOVERFX_MIRRORUPDOWN =     0x00000004,
    AMOVERFX_DEINTERLACE =      0x00000008
};

Elements

AMOVERFX_NOFX
Normal video (no effects).
AMOVERFX_MIRRORLEFTRIGHT
Mirror the overlay across the vertical axis.
AMOVERFX_MIRRORUPDOWN
Mirror the overlay across the horizontal axis.
AMOVERFX_DEINTERLACE
When used in IAMOverlayFX::QueryOverlayFXCaps, this flag specifies whether the hardware can support the DirectDraw 7 DDOVERFX_DEINTERLACE hint. When used with GetOverlayFX or SetOverlayFX, this flag indicates that the overlay should be deinterlaced if possible.

See Also

IAMOverlayFX Interface


AMRESCTL_RESERVEFLAGS Enumeration

Enumerated Types

Specifies whether to increment or decrement the number of resources currently being reserved.

Syntax

enum _AMRESCTL_RESERVEFLAGS{
    AMRESCTL_RESERVEFLAGS_RESERVE     = 0x00,
    AMRESCTL_RESERVEFLAGS_UNRESERVE   = 0x01
};

Elements

AMRESCTL_RESERVEFLAGS_RESERVE
Increment the reserved resource count.
AMRESCTL_RESERVEFLAGS_UNRESERVE
Decrement the reserved resource count.


AMTunerModeType Enumeration

Enumerated Types

Specifies the frequency of a TV tuner (cable or antenna).

Syntax

typedef enum tagAMTunerModeType
    {
        AMTUNER_MODE_DEFAULT = 0x0000,
        AMTUNER_MODE_TV = 0x0001,
        AMTUNER_MODE_FM_RADIO = 0x0002,
        AMTUNER_MODE_AM_RADIO = 0x0004,
        AMTUNER_MODE_DSS = 0x0008
    } AMTunerModeType;

Elements

AMTUNER_MODE_DEFAULT
Indicates default tuner mode.
AMTUNER_MODE_TV
Indicates TV tuner mode.
AMTUNER_MODE_FM_RADIO
Indicates FM radio tuner mode.
AMTUNER_MODE_AM_RADIO
Indicates AM radio tuner mode.
AMTUNER_MODE_DSS
Indicates Digital Satellite Service (DSS) tuner mode.


AMVP_MODE Enumeration

Enumerated Types

Specifies the various modes for video ports.

Syntax

typedef enum _AMVP_MODE{
AMVP_MODE_WEAVE,
AMVP_MODE_BOBINTERLEAVED,
AMVP_MODE_BOBNONINTERLEAVED,
AMVP_MODE_SKIPEVEN,
AMVP_MODE_SKIPODD
} AMVP_MODE;

Elements

AMVP_MODE_WEAVE
weave.
AMVP_MODE_BOBINTERLEAVED
Interleaved bob. Bob mode in which resources are allocated to switch to weave mode, for example, on the next frame.
MODE_BOBNONINTERLEAVED
Noninterleaved bob. Bob mode in which resources are not allocated to switch to weave mode.
AMVP_MODE_SKIPEVEN
Skip even fields.
AMVP_MODE_SKIPODD
Skip odd fields.


AMVP_SELECT_FORMAT_BY Enumeration

Enumerated Types

Specifies the criteria that the Overlay Mixer should use to select the video format.

Syntax

typedef enum _AMVP_SELECT_FORMAT_BY{
AMVP_DO_NOT_CARE,
AMVP_BEST_BANDWIDTH,
AMVP_INPUT_SAME_AS_OUTPUT
} AMVP_SELECT_FORMAT_BY;

Elements

AMVP_DO_NOT_CARE
Format doesn't matter.
AMVP_BEST_BANDWIDTH
Use the largest bandwidth.
AMVP_INPUT_SAME_AS_OUTPUT
Use the same input format as output format.


AnalogVideoStandard Enumeration

Enumerated Types

Specifies the format of the baseband analog video signal.

Syntax

 typedef enum
    {
        AnalogVideo_None       = 0x00000000
        AnalogVideo_NTSC_M     = 0x00000001,
        AnalogVideo_NTSC_M_J   = 0x00000002,
        AnalogVideo_NTSC_433   = 0x00000004,
        AnalogVideo_PAL_B      = 0x00000010,
        AnalogVideo_PAL_D      = 0x00000020,
        AnalogVideo_PAL_H      = 0x00000080,
        AnalogVideo_PAL_I      = 0x00000100,
        AnalogVideo_PAL_M      = 0x00000200,
        AnalogVideo_PAL_N      = 0x00000400,
        AnalogVideo_PAL_60     = 0x00000800,
        AnalogVideo_SECAM_B    = 0x00001000,
        AnalogVideo_SECAM_D    = 0x00002000,
        AnalogVideo_SECAM_G    = 0x00004000,
        AnalogVideo_SECAM_H    = 0x00008000,
        AnalogVideo_SECAM_K    = 0x00010000,
        AnalogVideo_SECAM_K1   = 0x00020000,
        AnalogVideo_SECAM_L    = 0x00040000,
        AnalogVideo_SECAM_L1   = 0x00080000,
        AnalogVideo_PAL_N_COMBO = 0x00100000
    } AnalogVideoStandard;

Elements

AnalogVideo_None
Digital sensor
AnalogVideo_NTSC_M
75 IRE Setup
AnalogVideo_NTSC_M_J
Japan, 0 IRE Setup
AnalogVideo_PAL_B
PAL_B
AnalogVideo_PAL_D
PAL_D
AnalogVideo_PAL_H
PAL_H
AnalogVideo_PAL_I
PAL_I
AnalogVideo_PAL_M
PAL_M
AnalogVideo_PAL_N
PAL_N
AnalogVideo_SECAM_B
SECAM_B
AnalogVideo_SECAM_D
SECAM_D
AnalogVideo_SECAM_G
SECAM_G
AnalogVideo_SECAM_H
SECAM_H
AnalogVideo_SECAM_K
SECAM_K
AnalogVideo_SECAM_K1
SECAM_K1
AnalogVideo_SECAM_L
SECAM_L
Signifies Argentina's PAL N Combo color standard.
SECAM_K1


CameraControlFlags Enumeration

Enumerated Types

Specifies whether the camera is automatic or manual.

Syntax

typedef enum{
    CameraControl_Flags_Auto    = 0x0001,
    CameraControl_Flags_Manual = 0x0002
} CameraControlFlags;

Elements

CameraControl_Flags_Auto
Sets the camera's automatic flag.
CameraControl_Flags_Manual
Sets the camera's manual flag.


CameraControlProperty Enumeration

Enumerated Types

Specifies what part of the camera Microsoft® DirectShow® is controlling.

Syntax

typedef enum
{
    CameraControl_Pan = 1,
    CameraControl_Tilt,
    CameraControl_Roll,
    CameraControl_Zoom,
    CameraControl_Exposure,
    CameraControl_Iris,
    CameraControl_Focus
} CameraControlProperty;

Elements

CameraControl_Pan
Used to set and retrieve the camera's pan settings.
CameraControl_Tilt
Control the camera's tilt.
CameraControl_Roll
Control the camera's roll.
CameraControl_Zoom
Control the camera's zoom.
CameraControl_Exposure
Control the camera's exposure.
CameraControl_Iris
Control the camera's iris.
CameraControl_Focus
Control the camera's focus.


CL_ELEM_FLAGS Enumeration

Enumerated Types

Indicates cutlist element flags.

Syntax

enum CL_ELEM_FLAGS{
    CL_ELEM_FIRST,
    CL_ELEM_LAST,
    CL_ELEM_NULL,
    CL_ELEM_ALL,
    CL_ELEM_NONE};

Elements

CL_ELEM_FIRST
First element.
CL_ELEM_LAST
Last element.
CL_ELEM_NULL
Null element.
CL_ELEM_ALL
All elements.
CL_ELEM_NONE
No elements.


CL_ELEM_STATUS Enumeration

Enumerated Types

Indicates cutlist status flags.

Syntax

enum CL_ELEM_STATUS{
    CL_NOT_PLAYED,
    CL_PLAYING,
    CL_FINISHED,
    CL_STATE_INVALID,
    CL_STATE_MASK,
    CL_WAIT_FOR_STATE};

Elements

CL_NOT_PLAYED
Element has not played.
CL_PLAYING
Element is playing.
CL_FINISHED
Element finished playing.
CL_STATE_INVALID
Invalid state.
CL_STATE_MASK
Mask for invalid states (equals CL_STATE_INVALID).
CL_WAIT_FOR_STATE
Wait flag. For input parameter only.


CompressionCaps Enumeration

Enumerated Types

Indicates video compression capabilities.

Syntax

typedef enum {
    CompressionCaps_CanQuality = 0x00000001,
    CompressionCaps_CanCrunch = 0x00000002,
    CompressionCaps_CanKeyFrame = 0x00000004,
    CompressionCaps_CanBFrame = 0x00000008,
    CompressionCaps_CanWindow = 0x0000000A
} CompressionCaps;

Elements

CompressionCaps_CanQuality
Video compressor supports the IAMVideoCompression::put_Quality and IAMVideoCompression::get_Quality methods.
CompressionCaps_CanCrunch
Video compressor can compress video to a specified data rate. If the compressor has this capability then the output pins media type will contain the data rate in the VIDEOINFOHEADER structure's dwBitRate member. The only way to set the data rate is to set dwBitRate.
CompressionCaps_CanKeyFrame
Video compressor supports the IAMVideoCompression::put_KeyFrameRate and IAMVideoCompression::get_KeyFrameRate methods.
CompressionCaps_CanBFrame
Video compressor supports the IAMVideoCompression::put_PFramesPerKeyFrame and IAMVideoCompression::get_PFramesPerKeyFrame methods.
CompressionCaps_CanWindow
Video compressor supports the IAMVideoCompression::put_WindowSize and IAMVideoCompression::get_WindowSize methods.

See Also

IAMVideoCompression


DECIMATION_USAGE Enumeration

Enumerated Types

Describes the strategy that the Overlay Mixer filter uses to scale the video image down to a smaller size.

Syntax

typedef enum {
    DECIMATION_LEGACY,
    DECIMATION_USE_DECODER_ONLY,
    DECIMATION_USE_VIDEOPORT_ONLY,
    DECIMATION_USE_OVERLAY_ONLY,
    DECIMATION_DEFAULT
} DECIMATION_USAGE;

Elements

DECIMATION_LEGACY
Decimate the video by taking the following steps, in the order listed, until one of them succeeds.
  1. Try to use the overlay scaler on the VGA chip.
  2. If the Overlay Mixer is connected through a video port, try to use the scaler on the video port.
  3. Crop the video image.
DECIMATION_USE_DECODER_ONLY
Decimate using the scaler on the video decoder. If that fails, crop the video image.
DECIMATION_USE_VIDEOPORT_ONLY
Decimate using the scaler on the video port. If that fails, crop the video image.
DECIMATION_USE_OVERLAY_ONLY
Decimate using the overlay scaler on the VGA chip. If that fails, crop the video image.
DECIMATION_DEFAULT
Decimate the video by taking the following steps, in the order listed, until one of them succeeds.
  1. Try to use the scaler on the video decoder.
  2. Try to use the overlay scaler on the VGA chip.
  3. If the Overlay Mixer is connected through a video port, try to use the scaler on the video port.
  4. Crop the video image.
This mode is the default decimation strategy.

See Also

IAMVideoDecimationProperties


DVD_AUDIO_APPMODE Enumeration

Enumerated Types

Indicates the current audio mode as retrieved in a call to IDvdInfo2::GetAudioAttributes.

Syntax

typedef enum tagDVD_AUDIO_APPMODE
{
    DVD_AudioMode_None     = 0,
    DVD_AudioMode_Karaoke  = 1,
    DVD_AudioMode_Surround = 2,
    DVD_AudioMode_Other    = 3,
} DVD_AUDIO_APPMODE;

Elements

DVD_AudioMode_None
No special audio mode. The DVD Navigator will send the audio to the decoder with no special processing.
DVD_AudioMode_Karaoke
The current audio mode is karaoke content.
DVD_AudioMode_Surround
The current audio mode is surround sound.
DVD_AudioMode_Other
Unrecognized audio mode.


DVD_AUDIO_FORMAT Enumeration

Enumerated Types

Indicates the audio format of a digital video disc (DVD).

Syntax

typedef enum tagDVD_AUDIO_FORMAT
{
    DVD_AudioFormat_AC3       = 0,
    DVD_AudioFormat_MPEG1     = 1,
    DVD_AudioFormat_MPEG1_DRC = 2,
    DVD_AudioFormat_MPEG2     = 3,
    DVD_AudioFormat_MPEG2_DRC = 4,
    DVD_AudioFormat_LPCM      = 5,
    DVD_AudioFormat_DTS       = 6,
    DVD_AudioFormat_SDDS      = 7,
    DVD_AudioFormat_Other     = 8
} DVD_AUDIO_FORMAT;

Elements

DVD_AudioFormat_AC3
Audio format is Dolby AC-3.
DVD_AudioFormat_MPEG1
Audio format is MPEG-1.
DVD_AudioFormat_MPEG1_DRC
Audio format is MPEG-1 with dynamic range control.
DVD_AudioFormat_MPEG2
Audio format is MPEG-2.
DVD_AudioFormat_MPEG2_DRC
Audio format is MPEG-2 with dynamic range control.
DVD_AudioFormat_LPCM
Audio format is Linear Pulse Code Modulated (LPCM).
DVD_AudioFormat_DTS
Audio format is Digital Theater Systems (DTS).
DVD_AudioFormat_SDDS
Audio format is Sony Dynamic Digital Sound (SDDS).
DVD_AudioFormat_Other
Audio format is unrecognized.

Remarks

This enumeration is a member of the DVD_AudioAttributes structure.


DVD_AUDIO_LANG_EXT Enumeration

Enumerated Types

Defines flags that indicate whether an audio stream contains audio language extensions.

Syntax

typedef enum tagDVD_AUDIO_LANG_EXT
{
    DVD_AUD_EXT_NotSpecified        = 0,
    DVD_AUD_EXT_Captions            = 1,
    DVD_AUD_EXT_VisuallyImpaired    = 2,
    DVD_AUD_EXT_DirectorComments1   = 3,
    DVD_AUD_EXT_DirectorComments2   = 4
} DVD_AUDIO_LANG_EXT;

Elements

DVD_AUD_EXT_NotSpecified
The digital video disc (DVD) doesn't specify an audio language extension for this audio stream.
DVD_AUD_EXT_Captions
The audio stream contains captions.
DVD_AUD_EXT_VisuallyImpaired
The audio stream contains content for people with low vision.
DVD_AUD_EXT_DirectorComments1
The audio stream contains "director comments 1."
DVD_AUD_EXT_DirectorComments2
The audio stream contains "director comments 2."

Remarks

This enumeration is used (as a member of the DVD_AudioAttributes structure) in the IDvdInfo2::GetAudioAttributes, and IDvdInfo2::GetDefaultAudioLanguage methods.


DVD_CMD_FLAGS Enumeration

Enumerated Types

Defines flags that control how the DVD Navigator filter handles command synchronization.

Syntax

typedef enum {
    DVD_CMD_FLAG_None          = 0x00000000,
    DVD_CMD_FLAG_Flush         = 0x00000001,
    DVD_CMD_FLAG_SendEvents    = 0x00000002,
    DVD_CMD_FLAG_Block         = 0x00000004,
} DVD_CMD_FLAGS;

Elements

DVD_CMD_FLAG_None
Tells the DVD Navigator not to flush the buffers when new commands are issued, not to send any events, and not to block the thread of execution on any method call.
DVD_CMD_FLAG_Flush
Tells the DVD Navigator, when it receives a new command such as PlayTitle or PlayForwards, to discard the approximately two seconds of video currently in the buffer and create an instance of the new command immediately.
DVD_CMD_FLAG_SendEvents
Tells the DVD Navigator to send events to the application when asynchronous operations are complete. The event parameters will contain the return value of the operation.
DVD_CMD_FLAG_Block
Tells the DVD Navigator to block on asynchronous operations until the operation completes or is canceled.


DVD_DISC_SIDE Enumeration

Enumerated Types

Indicates the sides of a DVD disc.

Syntax

typedef enum tagDVD_DISC_SIDE {
    DVD_SIDE_A,
    DVD_SIDE_B
} DVD_DISC_SIDE;

Elements

DVD_SIDE_A
Side A.
DVD_SIDE_B
Side B.

Elements

This enumeration is used in the IDVDInfo2::GetDVDVolumeInfo method.


DVD_DOMAIN Enumeration

Enumerated Types

Defines the DVD domains.

Syntax

typedef enum tagDVD_DOMAIN {
    DVD_DOMAIN_FirstPlay,
    DVD_DOMAIN_VideoManagerMenu,
    DVD_DOMAIN_VideoTitleSetMenu,
    DVD_DOMAIN_Title,
    DVD_DOMAIN_Stop
} DVD_DOMAIN;

Elements

DVD_DOMAIN_FirstPlay
Performing default initialization of a DVD disc.
DVD_DOMAIN_VideoManagerMenu
Displaying menus for whole disc.
DVD_DOMAIN_VideoTitleSetMenu
Displaying menus for current title set.
DVD_DOMAIN_Title
Displaying the current title.
DVD_DOMAIN_Stop
The DVD Navigator is in the DVD Stop domain.

Remarks

This enumeration is used in the IDVDInfo2::GetCurrentDomain method.

A domain is a logical space on a DVD disc. When the DVD Navigator is displaying the disc's main menu, it is said to be in the Video Manager domain. When it is displaying a menu specific to a title, it is in the Video Title Set domain. When it is playing video, it is the Title domain. When the user issues a Stop command, the Navigator goes into the Stop domain.


DVD_ERROR Enumeration

Enumerated Types

Specifies DVD error conditions.

Syntax

typedef enum _tagDVD_ERROR {
    DVD_ERROR_Unexpected                          = 1,
    DVD_ERROR_CopyProtectFail                     = 2,
    DVD_ERROR_InvalidDVD1_0Disc                   = 3,
    DVD_ERROR_InvalidDiscRegion                   = 4,
    DVD_ERROR_LowParentalLevel                    = 5,
    DVD_ERROR_MacrovisionFail                     = 6,
    DVD_ERROR_IncompatibleSystemAndDecoderRegions = 7,
    DVD_ERROR_IncompatibleDiscAndDecoderRegions   = 8
} DVD_ERROR;

Elements

DVD_ERROR_Unexpected
Something unexpected happened; perhaps content is authored incorrectly. Playback is stopped.
DVD_ERROR_CopyProtectFail
Key exchange for DVD copy protection failed. Playback is stopped.
DVD_ERROR_InvalidDVD1_0Disc
DVD-Video disc is authored incorrectly for specification version 1.x. Playback is stopped.
DVD_ERROR_InvalidDiscRegion
DVD-Video disc cannot be played because the disc is not authored to play in the system region. You can try fixing the region mismatch by changing the system region with Dvdrgn.exe.
DVD_ERROR_LowParentalLevel
Player parental level is lower than the lowest parental level available in the DVD content. Playback is stopped.
DVD_ERROR_MacrovisionFail
Macrovision® distribution failed. Playback stopped.
DVD_ERROR_IncompatibleSystemAndDecoderRegions
No discs can be played because the system region does not match the decoder region.
DVD_ERROR_IncompatibleDiscAndDecoderRegions
The disc cannot be played because the disc is not authored to be played in the decoder's region.

Remarks

See Also

EC_DVD_ERROR, DVD Region Change Support in Windows


DVD_FRAMERATE Enumeration

Enumerated Types

Indicates whether the DVD is authored to play at 25 or 30 frames per second.

Syntax

typedef enum tagDVD_FRAMERATE
{
    DVD_FPS_25 = 1,
    DVD_FPS_30NonDrop = 3
} DVD_FRAMERATE;

Elements

DVD_FPS_25
Twenty-five frames per second.
DVD_FPS_30NonDrop
Exactly 30 frames per second.

Remarks

You must know the frame rate to interpret the frame count as time.


DVD_KARAOKE_ASSIGNMENT Enumeration

Enumerated Types

Defines flags that indicate which speaker an audio channel is assigned to. This enumeration is a member of the DVD_KaraokeAttributes structure.

Syntax

typedef enum tagDVD_KARAOKE_ASSIGNMENT
{
    DVD_Assignment_reserved0   = 0,
    DVD_Assignment_reserved1   = 1,
    DVD_Assignment_LR    = 2,
    DVD_Assignment_LRM   = 3,
    DVD_Assignment_LR1   = 4,
    DVD_Assignment_LRM1  = 5,
    DVD_Assignment_LR12  = 6,
    DVD_Assignment_LRM12 = 7
} DVD_KARAOKE_ASSIGNMENT;

Elements

DVD_Assignment_reserved0
Currently not used.
DVD_Assignment_reserved1
Currently not used.
DVD_Assignment_LR
The channel is assigned to the left and right speakers.
DVD_Assignment_LRM
The channel is assigned to the left, right, and middle speakers.
DVD_Assignment_LR1
The channel is assigned to the left, right, and audio1 speakers.
DVD_Assignment_LRM1
The channel is assigned to the left, right, middle, and audio1 speakers.
DVD_Assignment_LR12
The channel is assigned to the left, right, and audio2 speakers.
DVD_Assignment_LRM12
The channel is assigned to the left, right, middle, and audio2 speakers.


DVD_KARAOKE_CONTENTS Enumeration

Enumerated Types

Specifies flags that, when used in a bitwise OR operation, describe the contents of each channel of an audio stream in a karaoke title.

Syntax

typedef enum tagDVD_KARAOKE_CONTENTS
{
    DVD_Karaoke_GuideVocal1  = 0x0001,
    DVD_Karaoke_GuideVocal2  = 0x0002,
    DVD_Karaoke_GuideMelody1 = 0x0004,
    DVD_Karaoke_GuideMelody2 = 0x0008,
    DVD_Karaoke_GuideMelodyA = 0x0010,
    DVD_Karaoke_GuideMelodyB = 0x0020,
    DVD_Karaoke_SoundEffectA = 0x0040,
    DVD_Karaoke_SoundEffectB = 0x0080
} DVD_KARAOKE_CONTENTS;

Elements

DVD_Karaoke_GuideVocal1
The channel contains guide vocal 1.
DVD_Karaoke_GuideVocal2
The channel contains guide vocal 2.
DVD_Karaoke_GuideMelody1
The channel contains guide melody 1.
DVD_Karaoke_GuideMelody2
The channel contains guide melody 2.
DVD_Karaoke_GuideMelodyA
The channel contains guide melody A.
DVD_Karaoke_GuideMelodyB
The channel contains guide melody B.
DVD_Karaoke_SoundEffectA
The channel contains sound effect A.
DVD_Karaoke_SoundEffectB
The channel contains sound effect B.

Remarks

This enumeration is used in the DVD_KaraokeAttributes structure.


DVD_KARAOKE_DOWNMIX Enumeration

Enumerated Types

Defines flags used by the IDvdControl2::SelectKaraokeAudioPresentationMode method to control which speakers, if any, each auxiliary channel is downmixed to.

Syntax

typedef enum tagDVD_KARAOKE_DOWNMIX
{
    DVD_Mix_0to0 = 0x0001,
    DVD_Mix_1to0 = 0x0002,
    DVD_Mix_2to0 = 0x0004,
    DVD_Mix_3to0 = 0x0008,
    DVD_Mix_4to0 = 0x0010,
    DVD_Mix_Lto0 = 0x0020,
    DVD_Mix_Rto0 = 0x0040,

    DVD_Mix_0to1 = 0x0100,
    DVD_Mix_1to1 = 0x0200,
    DVD_Mix_2to1 = 0x0400,
    DVD_Mix_3to1 = 0x0800,
    DVD_Mix_4to1 = 0x1000,
    DVD_Mix_Lto1 = 0x2000,
    DVD_Mix_Rto1 = 0x4000,
} DVD_KARAOKE_DOWNMIX;

Elements

DVD_Mix_0to0
Unused. Reserved for future use.
DVD_Mix_1to0
Unused. Reserved for future use.
DVD_Mix_2to0
Downmix channel 2 to the left speaker.
DVD_Mix_3to0
Downmix channel 3 to the left speaker.
DVD_Mix_4to0
Downmix channel 4 to the left speaker.
DVD_Mix_Lto0
Unused. Reserved for future use.
DVD_Mix_Rto0
Unused. Reserved for future use.
DVD_Mix_0to1
Unused. Reserved for future use.
DVD_Mix_1to1
Unused. Reserved for future use.
DVD_Mix_2to1
Downmix channel 2 to the right speaker.
DVD_Mix_3to1
Downmix channel 3 to the right speaker.
DVD_Mix_4to1
Downmix channel 4 to the right speaker.
DVD_Mix_Lto1
Unused. Reserved for future use.
DVD_Mix_Rto1
Unused. Reserved for future use.

Remarks

Audio channels are zero-based, so channels 2 through 4 are the three auxiliary karaoke channels. Use bitwise OR operations to set the appropriate bit to send a channel to the left speaker (0), right speaker (1), both speakers, or to no speakers by turning both bits off. These bits are all off by default whenever the DVD Navigator filter enters karaoke mode.


DVD_MENU_ID Enumeration

Enumerated Types

Specifies the DVD menu in a call to IDVDControl2::ShowMenu.

Syntax

typedef enum tagDVD_MENU_ID {
    DVD_MENU_Title      = 2,
    DVD_MENU_Root       = 3,
    DVD_MENU_Subpicture = 4,
    DVD_MENU_Audio      = 5,
    DVD_MENU_Angle      = 6,
    DVD_MENU_Chapter    = 7
} DVD_MENU_ID;

Elements

DVD_MENU_Title
Specifies the top menu in a DVD-Video volume. This menu is also known as the Title Menu or Video Manager Menu and it provides access to all VTS (Video Title Set) menus on the disc.
DVD_MENU_Root
Specifies the root menu for a VTS.
DVD_MENU_Subpicture
Specifies the subpicture submenu in a VTS menu.
DVD_MENU_Audio
Specifies the audio submenu in a VTS menu.
DVD_MENU_Angle
Specifies the angle submenu in a VTS menu.
DVD_MENU_Chapter
Choose a chapter submenu in a VTS menu.

Remarks

The root menu always provides a means of getting to the subpicture, audio, angle and chapter menus if they exist.


DVD_OPTION_FLAG Enumeration

Enumerated Types

Defines flags that control aspects of the DVD Navigator filter's behavior related to playback of digital video disc (DVD) content.

Syntax

typedef enum {
    DVD_ResetOnStop               = 1,
    DVD_NotifyParentalLevelChange = 2,
    DVD_HMSF_TimeCodeEvents       = 3
} DVD_OPTION_FLAG;

Elements

DVD_ResetOnStop
When this flag is set, the DVD Navigator will resume play at the beginning of the disc if the filter graph stops and then restarts. This flag is on by default.
DVD_NotifyParentalLevelChange
Tells the DVD Navigator to inform the application when it encounters a temporary parental management level command on the disc. If this flag is not set, the DVD Navigator will automatically reject such commands and branch accordingly. This flag is off by default.
DVD_HMSF_TimeCodeEvents
Tells the DVD Navigator to send all timecode information in the new DVD_HMSF_Timecode format instead of the old binary coded decimal (BCD) format, which is defined in the DVD_TIMECODE structure. This flag is off by default.


DVD_PARENTAL_LEVEL Enumeration

Enumerated Types

Identifies flags for the generic parental levels defined in the DVD specification.

Syntax

typedef enum tagDVD_PARENTAL_LEVEL
{
    DVD_PARENTAL_LEVEL_8 = 0x8000,
    DVD_PARENTAL_LEVEL_7 = 0x4000,
    DVD_PARENTAL_LEVEL_6 = 0x2000,
    DVD_PARENTAL_LEVEL_5 = 0x1000,
    DVD_PARENTAL_LEVEL_4 = 0x0800,
    DVD_PARENTAL_LEVEL_3 = 0x0400,
    DVD_PARENTAL_LEVEL_2 = 0x0200,
    DVD_PARENTAL_LEVEL_1 = 0x0100
} DVD_PARENTAL_LEVEL;

Remarks

DVD_PARENTAL_LEVEL_8 is the most restrictive level and DVD_PARENTAL_LEVEL_1 is the least restrictive. The way in which the levels are interpreted or used varies from country to country. In the United States and Canada, the levels correspond to the Motion Picture Association of America (MPAA) rating levels as shown in the following table.
Parental level | Meaning
1 | The rating is G, General.
3 | The rating is PG, Parental Guidance Suggested.
4 | The rating is PG-13, Parental Guidance Suggested, not recommended for those under 13.
6 | The rating is R, Restricted.
7 | The rating is NC-17.

This enumeration is used in the IDVDInfo2::GetTitleParentalLevels method.


DVD_PREFERRED_DISPLAY_MODE Enumeration

Enumerated Types

Indicates the user's preferred window aspect ratio and conversion method.

Syntax

typedef enum tagDVD_PREFERRED_DISPLAY_MODE
{
    DISPLAY_CONTENT_DEFAULT = 0,
    DISPLAY_16x9 = 1,
    DISPLAY_4x3_PANSCAN_PREFERRED = 2,
    DISPLAY_4x3_LETTERBOX_PREFERRED = 3
} DVD_PREFERRED_DISPLAY_MODE;

Elements

DISPLAY_CONTENT_DEFAULT
Use the default window size and content type.
DISPLAY_16x9
Use a 16 × 9 window.
DISPLAY_4x3_PANSCAN_PREFERRED
Use a 4 × 3 window and convert to pan-scan, if possible.
DISPLAY_4x3_LETTERBOX_PREFERRED
Use a 4 × 3 window and convert to letterbox, if possible.

Remarks

DVD_PREFERRED_DISPLAY_MODE indicates the user's preferred window aspect ratio and preferred method of conversion of 16 × 9 content to a 4 × 3 window aspect ratio. Pan-scan and letterboxing are the two conversion methods. Displaying a video at the largest possible size inside the display window without any cropping or stretching is called displaying in letterbox format. Pan-scan is specifically cropping a 16 × 9 video for display in a 4 × 3 window using parameters defined by the video author.

This enumerated type indicates a preference of conversion mechanisms because some content can only be displayed using one of these methods. Content that is 4 × 3 is always converted to a 16 × 9 window by using sideboxing, where black bars are added to the right and left sides of the display instead of the top and bottom of the display as in the 16 × 9 to 4 × 3 conversion using letterboxing.

The following table shows the conversion method used between the actual content type listed in the first column, and the user display preference setting, indicated by one of the other columns.
Actual content type | 16 × 9 | 4 × 3 pan-scan | 4 × 3 letterbox
4 × 3 | Sideboxing | None | None
16 × 9 letterbox only | None | Letterbox | Letterbox
16 × 9 pan-scan only | None | Pan-scan | Pan-scan
16 × 9 pan-scan or letterbox | None | Pan-scan | Letterbox

The native window size used is always the user's preferred size.


DVD_RELATIVE_BUTTON Enumeration

Enumerated Types

Identifies the four directional buttons used for digital video disc (DVD) menu navigation and other operations.

Syntax

typedef enum tagDVD_RELATIVE_BUTTON {
    DVD_RELATIVE_BUTTON_Upper = 1,
    DVD_RELATIVE_BUTTON_Lower = 2,
    DVD_RELATIVE_BUTTON_Left =  3,
    DVD_RELATIVE_BUTTON_Right = 4
    } DVD_RELATIVE_BUTTON;

Elements

DVD_RELATIVE_BUTTON_Upper
Upper button.
DVD_RELATIVE_BUTTON_Lower
Lower button.
DVD_RELATIVE_BUTTON_Left
Left button.
DVD_RELATIVE_BUTTON_Right
Right button.


DVD_SUBPICTURE_LANG_EXT Enumeration

Enumerated Types

Defines the possible language extensions in a specified subpicture stream.

Syntax

typedef enum tagDVD_SUBPICTURE_LANG_EXT
{
    DVD_SP_EXT_NotSpecified     =0,
    DVD_SP_EXT_Caption_Normal   =1,
    DVD_SP_EXT_Caption_Big      =2,
    DVD_SP_EXT_Caption_Children =3,
    DVD_SP_EXT_CC_Normal        =5,
    DVD_SP_EXT_CC_Big           =6,
    DVD_SP_EXT_CC_Children      =7,
    DVD_SP_EXT_Forced           =9,
    DVD_SP_EXT_DirectorComments_Normal      =13,
    DVD_SP_EXT_DirectorComments_Big         =14,
    DVD_SP_EXT_DirectorComments_Children    =15,
} DVD_SUBPICTURE_LANG_EXT;

Elements

DVD_SP_EXT_NotSpecified
Indicates that no language extensions are present.
DVD_SP_EXT_Caption_Normal
Indicates that the specified stream contains normal captions.
DVD_SP_EXT_Caption_Big
Indicates that the specified stream contains big captions.
DVD_SP_EXT_Caption_Children
Indicates that the specified stream contains captions for children.
DVD_SP_EXT_CC_Normal
Indicates that the specified stream contains normal closed captions.
DVD_SP_EXT_CC_Big
Indicates that the specified stream contains big closed captions.
DVD_SP_EXT_CC_Children
Indicates that the specified stream contains closed captions for children.
DVD_SP_EXT_Forced
Indicates that the subpicture stream is forcedly activated, meaning that the application will not be able to turn it off.
DVD_SP_EXT_DirectorComments_Normal
Indicates that the specified stream contains normal-sized director's comments.
DVD_SP_EXT_DirectorComments_Big
Indicates that the specified stream contains large-sized director's comments.
DVD_SP_EXT_DirectorComments_Children
Indicates that the specified stream contains director's comments for children.


DVD_SUBPICTURE_TYPE Enumeration

Enumerated Types

Defines flags used to determine what kind of content the subpicture stream contains.

Syntax

typedef enum tagDVD_SUBPICTURE_TYPE
{
    DVD_SPType_NotSpecified = 0,
    DVD_SPType_Language     = 1,
    DVD_SPType_Other        = 2,
} DVD_SUBPICTURE_TYPE;

Elements

DVD_SPType_NotSpecified
The digital video disc (DVD) does not specify the subpicture type.
DVD_SPType_Language
The subpicture contains language-related content such as movie subtitles or other text.
DVD_SPType_Other
The subpicture contains nonlanguage-related content such as a bouncing ball in karaoke titles.


DVD_SUBPICTURE_CODING Enumeration

Enumerated Types

Indicates what kind of content the subpicture stream contains.

Syntax

typedef enum tagDVD_SUBPICTURE_CODING
{
    DVD_SPCoding_RunLength    = 0,
    DVD_SPCoding_Extended     = 1,
    DVD_SPCoding_Other        = 2,
} DVD_SUBPICTURE_CODING;

Elements

DVD_SPCoding_RunLength
Indicates that the subpicture uses run length encoding.
DVD_SPCoding_Extended
Indicates that subpicture uses extended encoding.
DVD_SPCoding_Other
Indicates that the subpicture uses some other encoding scheme.

Remarks

Most subpicture streams contain language-related content such as movie subtitles, but subpictures can also be used for the bouncing ball in karaoke or other non-language-related purposes.


DVD_TextCharSet Enumeration

Enumerated Types

Defines which character set a specified string is encoded with.

Syntax

enum DVD_TextCharSet {
    DVD_CharSet_Unicode                       = 0,
    DVD_CharSet_ISO646                        = 1,
    DVD_CharSet_JIS_Roman_Kanji               = 2,
    DVD_CharSet_ISO8859_1                     = 3,
    DVD_CharSet_ShiftJIS_Kanji_Roman_Katakana = 4
};

Elements

DVD_CharSet_Unicode
Unicode™ character set.
DVD_CharSet_ISO646
ISO 646 character set.
DVD_CharSet_JIS_Roman_Kanji
JIS Roman Kanji character set.
DVD_CharSet_ISO8859_1
ISO 8859-1 character set.
DVD_CharSet_ShiftJIS_Kanji_Roman_Katakana
JIS Kanji-Roman-Katakana character set.


DVD_TextStringType Enumeration

Enumerated Types

Defines a subset of the DVD text string types.

Syntax

enum DVD_TextStringType {
    // Disc structure identifiers (0x00..0x0f)
    // These are empty strings whose string type
    // is used to organize the content strings.
    DVD_Struct_Volume               = 0x01,
    DVD_Struct_Title                = 0x02,
    DVD_Struct_ParentalID           = 0x03,
    DVD_Struct_PartOfTitle          = 0x04,
    DVD_Struct_Cell                 = 0x05,
    // Stream (0x10..0x1f)
    DVD_Stream_Audio                = 0x10,
    DVD_Stream_Subpicture           = 0x11,
    DVD_Stream_Angle                = 0x12,
    // Channel in stream (0x20..0x2f)
    DVD_Channel_Audio               = 0x20,

    // Application information
    // General (0x30..0x37)
    // This is used to identify the name
    // for the current node, that is, volume title,
    // movie title, song title, and so on.
    DVD_General_Name                = 0x30,
    DVD_General_Comments            = 0x31,

    // Title (0x38..0x3f)
    DVD_Title_Series                = 0x38,
    DVD_Title_Movie                 = 0x39,
    DVD_Title_Video                 = 0x3a,
    DVD_Title_Album                 = 0x3b,
    DVD_Title_Song                  = 0x3c,
    DVD_Title_Other                 = 0x3f,

    // Title (sub) (0x40..0x47)
    DVD_Title_Sub_Series            = 0x40,
    DVD_Title_Sub_Movie             = 0x41,
    DVD_Title_Sub_Video             = 0x42,
    DVD_Title_Sub_Album             = 0x43,
    DVD_Title_Sub_Song              = 0x44,
    DVD_Title_Sub_Other             = 0x47,

    // Title (original) (0x48..0x4f)
    DVD_Title_Orig_Series           = 0x48,
    DVD_Title_Orig_Movie            = 0x49,
    DVD_Title_Orig_Video            = 0x4a,
    DVD_Title_Orig_Album            = 0x4b,
    DVD_Title_Orig_Song             = 0x4c,
    DVD_Title_Orig_Other            = 0x4f,

    // Other info (0x50..0x57)
    DVD_Other_Scene                 = 0x50,
    DVD_Other_Cut                   = 0x51,
    DVD_Other_Take                  = 0x52,

    //These less-used categories are defined in
    //the DVD specification but not in the
    //DVD_TextStringType enumeration.
    // Language     0x58..0x5b
    // Work         0x5c..0x6b
    // Character    0x6c..0x8f
    // Data         0x90..0x93
    // Karaoke      0x94..0x9b
    // Category     0x9c..0x9f
    // Lyrics       0xa0..0xa3
    // Document     0xa4..0xa7
    // Others       0xa8..0xab
    // Reserved     0xac..0xaf
    // Admin        0xb0..0xb7
    // more admin   0xb8..0xc0
    // Reserved     0xd0..0xdf
    // vendor       0xe0..0xef
    // extension    0xf0..0xf7
    // reserved     0xf8..0xff
};

Elements

DVD_Struct_Volume
Indicates the top-level of the logical hierarchy. Refers to the entire contents of a one-sided disc or one side of a two-sided disc.
DVD_Struct_Title
Indicates that all content strings, until the next DVD_Struct_Title, belong to one title.
DVD_Struct_ParentalID
Indicates the parental ID of the following strings.
DVD_Struct_PartOfTitle
Indicates that all content strings, until the next DVD_Struct_PartOfTitle, belong to one chapter.
DVD_Struct_Cell
Indicates that all content strings, until the next DVD_Struct_Cell, belong to one cell, which can be a scene from a chapter.
DVD_Stream_Audio
Indicates that the following content strings refer to the audio stream.
DVD_Stream_Subpicture
Indicates that the following content strings refer to the subpicture stream.
DVD_Stream_Angle
Indicates that the following content strings refer to the angle.
DVD_Channel_Audio
Indicates that the following content strings refer to the audio channel.
DVD_General_Name
Indicates the most important content string. Strings of this type contain the name of the volume, title, chapter, and so on, and can follow any structure identifiers.
DVD_General_Comments
Identifies a content string with additional information about the title, chapter, and so on, described by the DVD_General_Name string. The exact nature or structure of these comments is not defined.
DVD_Title_Series
Identifies a content string containing the name of a series to which the title belongs.
DVD_Title_Movie
Identifies a content string with the main movie title.
DVD_Title_Video
Identifies a content string containing the name of the video title.
DVD_Title_Album
Identifies a content string containing the name of the album title.
DVD_Title_Song
Identifies a content string containing the name of the song title.
DVD_Title_Other
Identifies a content string containing the name of the title of some other genre.
DVD_Title_Sub_Series
Identifies a content string with the name of the series localized to a particular country.
DVD_Title_Sub_Movie
Identifies a content string with the movie title localized to a particular country.
DVD_Title_Sub_Video
Identifies a content string with the video title localized to a particular country.
DVD_Title_Sub_Album
Identifies a content string with the album title localized to a particular country.
DVD_Title_Sub_Song
Identifies a content string with the song title localized to a particular country.
DVD_Title_Sub_Other
Identifies a content string with the title of some other genre localized to a particular country.
DVD_Title_Orig_Series
Identifies a content string with the original name of the series.
DVD_Title_Orig_Movie
Identifies a content string with the original name of the movie.
DVD_Title_Orig_Video
Identifies a content string with the original name of the video.
DVD_Title_Orig_Album
Identifies a content string with the original name of the album.
DVD_Title_Orig_Song
Identifies a content string with the original name of the song.
DVD_Title_Orig_Other
Identifies a content string with the original name of the content.
DVD_Other_Scene
Identifies a content string pertaining to a particular scene in a movie or video.
DVD_Other_Cut
Identifies a content string pertaining to a particular cut in a movie or video.
DVD_Other_Take
Identifies a content string pertaining to a particular take in a movie or video.

Remarks

A DVD_TextStringType is returned in the IDvdInfo2::GetDVDTextStringAsUnicode and IDvdInfo2::GetDVDTextStringAsNative methods to identify how the disc authors have categorized the specified text string. See Working with DVD Text Strings for general information on text strings.

One important text string type not defined in this enumeration is 0xF0, the extension sorting text string type. You can use this type of string in many ways to enable players to sort the string data. It can be a unique number or a repetition of a previous string with the word order changed. For example, a string type of 0x30 that has the name "The Greatest Country Hits" might be followed by a string of type 0xF0 that says "Greatest Country Hits, The." As with content strings, the use of the sorting string is not strictly defined.


DVD_TIMECODE_FLAGS Enumeration

Enumerated Types

Indicates the frame rate at which a digital video disc (DVD) has been authored to play.

Syntax

typedef enum tagDVD_TIMECODE_FLAGS {
    DVD_TC_FLAG_25fps         = 0x00000001,
    DVD_TC_FLAG_30fps         = 0x00000002,
    DVD_TC_FLAG_DropFrame     = 0x00000004,
    DVD_TC_FLAG_Interpolated  = 0x00000008,
} DVD_TIMECODE_FLAGS;

Elements

DVD_TC_FLAG_25fps
Disc is authored to play at 25 frames per second.
DVD_TC_FLAG_30fps
Disc is authored to play at 30 frames per second.
DVD_TC_FLAG_DropFrame
Disc is authored to play at 29.97 frames per second.
DVD_TC_FLAG_Interpolated
Value representing the DVD Navigator filter's best estimate of the disc's frame rate.


DVD_TITLE_APPMODE Enumeration

Enumerated Types

Indicates whether a digital video disc (DVD) title is a karaoke title. This enumeration is a member of the DVD_TitleAttributes structure, which is filled when an application calls the IDvdInfo2::GetTitleAttributes method.

Syntax

typedef enum tagDVD_TITLE_APPMODE
{
    DVD_AppMode_Not_Specified = 0,
    DVD_AppMode_Karaoke  = 1,
    DVD_AppMode_Other    = 3,
} DVD_TITLE_APPMODE;

Elements

DVD_AppMode_Not_Specified
The disc does not provide any application mode information about this title.
DVD_AppMode_Karaoke
Title contains karaoke content.
DVD_AppMode_Other
Title contains a type of content that the DVD Navigator filter does not recognize, so the application should treat the title as a regular DVD-Video title.

Remarks

When the DVD Navigator encounters a karaoke title on a disc, it goes into "karaoke mode" and informs the audio decoder. The decoder must respond by initially muting the three auxiliary channels. Applications can then selectively control the volume and mixing configuration of these channels using the karaoke-related methods in IDvdControl2. For more information, see Playing Karaoke Audio Streams.


DVD_VIDEO_COMPRESSION Enumeration

Enumerated Types

Defines the possible digital video disc (DVD) video compression types.

Syntax

typedef enum tagDVD_VIDEO_COMPRESSION
{
    DVD_VideoCompression_Other  = 0,
    DVD_VideoCompression_MPEG1  = 1,
    DVD_VideoCompression_MPEG2  = 2,
} DVD_VIDEO_COMPRESSION;

Elements

DVD_VideoCompression_Other
Unrecognized compression type.
DVD_VideoCompression_MPEG1
MPEG-1 compression type.
DVD_VideoCompression_MPEG2
MPEG-2 compression type.

Remarks

This enumeration is a member of the DVD_VideoAttributes structure, which is filled by a call to the IDvdInfo2::GetCurrentVideoAttributes method.


DVD_WARNING Enumeration

Enumerated Types

Specifies DVD warning conditions.

Syntax

typedef enum _tagDVD_WARNING {
    DVD_WARNING_InvalidDVD1_0Disc=1,
    DVD_WARNING_FormatNotSupported=2,
    DVD_WARNING_IllegalNavCommand=3
} DVD_WARNING;

Elements

DVD_WARNING_InvalidDVD1_0Disc
DVD-Video disc is authored incorrectly. Playback can continue, but unexpected behavior might occur.
DVD_WARNING_FormatNotSupported
A decoder would not support the current format. Playback of a stream might not function.
DVD_WARNING_IllegalNavCommand
The internal DVD navigation command processor attempted to process an illegal command.

See Also

EC_DVD_WARNING


DVDECODERRESOLUTION Enumeration

Enumerated Types

Indicates the digital video (DV) decoding resolution.

Syntax

enum _DVDECODERRESOLUTION {
    DVDECODERRESOLUTION_720x480     = 1000,
    DVDECODERRESOLUTION_360x240     = 1001,
    DVDECODERRESOLUTION_180x120     = 1002,
    DVDECODERRESOLUTION_88x60       = 1003
};

enum _DVRESOLUTION {
    DVRESOLUTION_FULL    = 1000,
    DVRESOLUTION_HALF    = 1001,
    DVRESOLUTION_QUARTER = 1002,
    DVRESOLUTION_DC      = 1003
};

Elements

DVRESOLUTION_FULL
Decode at full size.
DVRESOLUTION_HALF
Decode at half size.
DVRESOLUTION_QUARTER
Decode at quarter size.
DVRESOLUTION_DC
Decode at one-eighth size.

Remarks

The DVDECODERRESOLUTION and DVRESOLUTION enumerations are equivalent; DVDECODERRESOLUTION is included for compatibility with existing applications.

The decoding resolution depends on whether the current format is NTSC or PAL:

Enumeration | NTSC | PAL
DVRESOLUTION_FULL | 720 x 480 | 720 x 576
DVRESOLUTION_HALF | 360 x 240 | 360 x 288
DVRESOLUTION_QUARTER | 180 x 120 | 180 x 144
DVRESOLUTION_DC | 88 x 60 | 88 x 72

See Also

IIPDVDec


DVENCODERFORMAT Enumeration

Enumerated Types

Indicates the digital video (DV) format.

Syntax

enum _DVENCODERFORMAT {
    DVENCODERFORMAT_DVSD        =   2007,
    DVENCODERFORMAT_DVHD        =   2008,
    DVENCODERFORMAT_DVSL        =   2009
};

Elements

DVENCODERFORMAT_DVSD
Use the 'dvsd' stream handler.
DVENCODERFORMAT_DVHD
Use the 'dvhd' stream handler.
DVENCODERFORMAT_DVSL
Use the 'dvsl' stream handler.

Remarks

This enumeration specifies the fccType member of the AVI stream header. For more information, see DV Data in the AVI File Format.

See Also

IDVEnc


DVENCODERRESOLUTION Enumeration

Enumerated Types

Indicates the digital video (DV) encoding resolution.

Syntax

enum _DVENCODERRESOLUTION {
    DVENCODERRESOLUTION_720x480     =   2012,
    DVENCODERRESOLUTION_360x240     =   2013,
    DVENCODERRESOLUTION_180x120     =   2014,
    DVENCODERRESOLUTION_88x60       =   2015
};

Elements

The meaning of the enumeration elements depends on whether the current format is NTSC or PAL:

Element | NTSC | PAL
DVENCODERRESOLUTION_720x480 | 720 x 480 | 720 x 576
DVENCODERRESOLUTION_360x240 | 360 x 240 | 360 x 288
DVENCODERRESOLUTION_180x120 | 180 x 120 | 180 x 144
DVENCODERRESOLUTION_88x60 | 88 x 66 | 88 x 72

See Also

IDVEnc


DVENCODERVIDEOFORMAT Enumeration

Enumerated Types

Indicates the video standard (NTSC or PAL) for digital video (DV) encoding.

Syntax

enum _DVENCODERVIDEOFORMAT {
    DVENCODERVIDEOFORMAT_NTSC       =   2000,
    DVENCODERVIDEOFORMAT_PAL        =   2001
};

Elements

DVENCODERVIDEOFORMAT_NTSC
NTSC
DVENCODERVIDEOFORMAT_PAL
PAL

See Also

IDVEnc


FILTER_STATE Enumeration

Enumerated Types

Specifies a filter's state or the state of the filter graph (when returned from the IMediaControl::GetState method).

Syntax

typedef enum _FilterState
{
    State_Stopped   = 0,
    State_Paused    = State_Stopped + 1,
    State_Running   = State_Paused + 1
} FILTER_STATE;

Elements

State_Stopped
Stopped. The filter is not processing data.
State_Paused
Paused. The filter is processing data, but not rendering it.
State_Running
Running. The filter is processing and rendering data.

Remarks

See Data Flow in the Filter Graph for more information on the various filter states.


InterleavingMode Enumeration

Enumerated Types

Specifies how video frames and audio samples will be written to disk.

Syntax

  typedef enum
    {
        INTERLEAVE_NONE,
        INTERLEAVE_CAPTURE,
        INTERLEAVE_FULL
    } InterleavingMode;

Elements

INTERLEAVE_NONE
Write out frames in the order they arrive (noninterleaved). Files must be turned into playback at a later time.
INTERLEAVE_CAPTURE
Approximate interleaving with less overhead than INTERLEAVE_FULL. Geared to video capture.
INTERLEAVE_FULL
Full, precise interleaving of audio samples and video frames. Geared to authoring and playback.


MEDIA_SAMPLE_CONTENT Enumeration

Enumerated Types

Describes the contents of an elementary stream within an MPEG-2 transport stream. This enumeration is used in the IMPEG2PIDMap interface, which is implemented on the output pins of the MPEG-2 Demultiplexer filter.

Syntax

typedef enum {
    MEDIA_TRANSPORT_PACKET,
    MEDIA_ELEMENTARY_STREAM,
    MEDIA_MPEG2_PSI,
    MEDIA_TRANSPORT_PAYLOAD
} MEDIA_SAMPLE_CONTENT ;

Members

MEDIA_TRANSPORT_PACKET
Specifies a complete transport stream packet to be passed through without processing.
MEDIA_ELEMENTARY_STREAM
Specifies an audio or video PES payload.
MEDIA_MPEG2_PSI
Specifies a PAT, PMT, CAT, or Private data stream. These are complete PSI sections which do not need to be reassembled.
MEDIA_TRANSPORT_PAYLOAD
Specifies gathered TS packet payloads, such as PES packets.


MPEG2Level Enumeration

Enumerated Types

Indicates the MPEG-2 video level as specified in the MPEG-2 video standard. (ISO13818-2)

Syntax

enum MPEG2Level {
    MPEG2Level_Low = 1,
    MPEG2Level_Main,
    MPEG2Level_High1440,
    MPEG2Level_High
};

Elements

MPEG2Level_Low
Low level.
MPEG2Level_Main
Main level.
MPEG2Level_High1440
High level.
MPEG2Level_High
Highest level.

Remarks

DVD MPEG-2 video decoders should support MPEG2Level_Low or MPEG2Level_Main.


MPEG2Profile Enumeration

Enumerated Types

Indicates the MPEG-2 video profile as specified in the MPEG-2 video standard. (ISO13818-2)

Syntax

enum MPEG2Profile {
    MPEG2Profile_Simple = 1,
    MPEG2Profile_Main,
    MPEG2Profile_SNRScalable,
    MPEG2Profile_SpatiallyScalable,
    MPEG2Profile_High
};

Elements

MPEG2Profile_Simple
Simple.
MPEG2Profile_Main
Main.
MPEG2Profile_SNRScalable
Signal to Noise Ratio (SNR) scalable.
MPEG2Profile_SpatiallyScalable
Spatially scalable.
MPEG2Profile_High
High.

Remarks

DVD video decoders should support MPEG2Profile_Simple or MPEG2Profile_Main.


PhysicalConnectorType Enumeration

Enumerated Types

Specifies the physical type of pin (audio or video).

Syntax

  typedef enum
    {
    PhysConn_Video_Tuner = 1,
    PhysConn_Video_Composite,
    PhysConn_Video_SVideo,
    PhysConn_Video_RGB,
    PhysConn_Video_YRYBY,
    PhysConn_Video_SerialDigital,
    PhysConn_Video_ParallelDigital,
    PhysConn_Video_SCSI,
    PhysConn_Video_AUX,
    PhysConn_Video_1394,
    PhysConn_Video_USB,
    PhysConn_Video_VideoDecoder,
    PhysConn_Video_VideoEncoder,
    PhysConn_Video_SCART,

    PhysConn_Audio_Tuner = 4096,
    PhysConn_Audio_Line,
    PhysConn_Audio_Mic,
    PhysConn_Audio_AESDigital,
    PhysConn_Audio_SPDIFDigital,
    PhysConn_Audio_SCSI,
    PhysConn_Audio_AUX,
    PhysConn_Audio_1394,
    PhysConn_Audio_USB,
    PhysConn_Audio_AudioDecoder,
    } PhysicalConnectorType;

Elements

PhysConn_Video_Tuner
Specifies a tuner pin for video.
PhysConn_Video_Composite
Specifies a composite pin for video.
PhysConn_Video_SVideo
Specifies an S-Video (Y/C video) pin.
PhysConn_Video_RGB
Specifies an RGB pin for video.
PhysConn_Video_YRYBY
Specifies a YRYBY (Y, R–Y, B–Y) pin for video.
PhysConn_Video_SerialDigital
Specifies a serial digital pin for video.
PhysConn_Video_ParallelDigital
Specifies a parallel digital pin for video.
PhysConn_Video_SCSI
Specifies a SCSI (Small Computer System Interface) pin for video.
PhysConn_Video_AUX
Specifies an AUX (auxiliary) pin for video.
PhysConn_Video_1394
Specifies an IEEE 1394 pin for video.
PhysConn_Video_USB
Specifies a USB (Universal Serial Bus) pin for video.
PhysConn_Video_VideoDecoder
Specifies a video decoder pin.
PhysConn_Video_VideoEncoder
Specifies a video encoder pin.
PhysConn_Video_SCART
Specifies a SCART (Peritel) pin for video.
PhysConn_Audio_Tuner
Specifies a tuner pin for audio.
PhysConn_Audio_Line
Specifies a line pin for audio.
PhysConn_Audio_Mic
Specifies a microphone pin.
PhysConn_Audio_AESDigital
Specifies an AES/EBU (Audio Engineering Society/European Broadcast Union) digital pin for audio.
PhysConn_Audio_SPDIFDigital
Specifies an S/PDIF (Sony/Philips Digital Interface Format) digital pin for audio.
PhysConn_Audio_SCSI
Specifies a SCSI pin for audio.
PhysConn_Audio_AUX
Specifies an AUX pin for audio.
PhysConn_Audio_1394
Specifies an IEEE 1394 pin for audio.
PhysConn_Audio_USB
Specifies a USB pin for audio.
PhysConn_Audio_AudioDecoder
Specifies an audio decoder pin.


PIN_DIRECTION Enumeration

Enumerated Types

Indicates a pin's direction.

Syntax

typedef enum _PinDirection {
    PINDIR_INPUT,
    PINDIR_OUTPUT
} PIN_DIRECTION;

Elements

PINDIR_INPUT
Input pin.
PINDIR_OUTPUT
Output pin.


QualityMessageType Enumeration

Enumerated Types

Describes a quality message type.

Syntax

typedef enum {
    Famine,
    Flood
} QualityMessageType;

Elements

Famine
Downstream filter needs more data.
Flood
Downstream filter needs less data.


REG_PINFLAG Enumeration

Enumerated Types

Defines flags for the dwFlags member in the REGFILTERPINS2 structure.

Syntax

enum
{
    REG_PINFLAG_B_ZERO = 0x1,
    REG_PINFLAG_B_RENDERER = 0x2,
    REG_PINFLAG_B_MANY = 0x4,
    REG_PINFLAG_B_OUTPUT = 0x8
} REG_PINFLAG;

Elements

REG_PINFLAG_B_ZERO
The filter can have zero instances of this pin.
REG_PINFLAG_B_RENDERER
The filter renders the input from this pin. (Applies only to input pins. Output pins must not set this flag.)
REG_PINFLAG_B_MANY
The filter can create more than one instance of this pin.
REG_PINFLAG_B_OUTPUT
This pin is an output pin.


REM_FILTER_FLAGS Enumeration

Enumerated Types

Specifies how to remove a filter from the filter graph.

Syntax

enum _REM_FILTER_FLAGS {
    REMFILTERF_LEAVECONNECTED = 0x00000001
};

Elements

REMFILTERF_LEAVECONNECTED
Leave the filter connected. By default, filters are disconnected when removed from the graph.

See Also

IGraphConfig::RemoveFilterEx


SNDDEV_ERR Enumeration

Enumerated Types

Specifies how the audio device was being accessed when the failure occurred.

Syntax

typedef enum _tagSND_DEVICE_ERROR {
    SNDDEV_ERROR_Open             = 1,
    SNDDEV_ERROR_Close            = 2,
    SNDDEV_ERROR_GetCaps          = 3,
    SNDDEV_ERROR_PrepareHeader    = 4,
    SNDDEV_ERROR_UnprepareHeader  = 5,
    SNDDEV_ERROR_Reset            = 6,
    SNDDEV_ERROR_Restart          = 7,
    SNDDEV_ERROR_GetPosition      = 8,
    SNDDEV_ERROR_Write            = 9,
    SNDDEV_ERROR_Pause            = 10,
    SNDDEV_ERROR_Stop             = 11,
    SNDDEV_ERROR_Start            = 12,
    SNDDEV_ERROR_AddBuffer        = 13,
    SNDDEV_ERROR_Query            = 14,
} SNDDEV_ERR;

Elements

SNDDEV_ERROR_Open
The audio device attempted to open.
SNDDEV_ERROR_Close
The audio device attempted to close.
SNDDEV_ERROR_GetCaps
The capabilities of the underlying hardware were being retrieved.
SNDDEV_ERROR_PrepareHeader
The header for the audio device was being prepared.
SNDDEV_ERROR_UnprepareHeader
The header for the audio device was being unprepared.
SNDDEV_ERROR_Reset
The audio device attempted to reset.
SNDDEV_ERROR_Restart
The audio device attempted to restart.
SNDDEV_ERROR_GetPosition
The current and stop position settings were being retrieved.
SNDDEV_ERROR_Write
The audio device was being written to.
SNDDEV_ERROR_Pause
The audio device attempted to pause.
SNDDEV_ERROR_Stop
The audio device attempted to stop.
SNDDEV_ERROR_Start
The audio device attempted to start.
SNDDEV_ERROR_AddBuffer
A buffer was being added to the audio device.
SNDDEV_ERROR_Query
The audio device was being queried.


StreamControlState Enumeration

Enumerated Types

Specifies the state of the stream.

Syntax

enum StreamControlState {
      STREAM_FLOWING,
      STREAM_DISCARDING
    };

Elements

STREAM_FLOWING
Indicates the stream is currently transmitting data.
STREAM_DISCARDING
Discards the samples as they are received.


TunerInputType Enumeration

Enumerated Types

Specifies the frequency of a TV tuner (cable or antenna).

Syntax

typedef enum
    {
        TunerInputCable,
        TunerInputAntenna
    } TunerInputType;

Elements

TunerInputCable
Indicates cable frequency.
TunerInputAntenna
Indicates broadcast antenna frequency.


TVAudioMode Enumeration

Enumerated Types

Specifies the mode of a TV audio control.

Syntax

typedef enum tagTVAudioMode
    {
        AMTVAUDIO_MODE_MONO	    = 0x0001,
        AMTVAUDIO_MODE_STEREO       = 0x0002,
        AMTVAUDIO_MODE_LANG_A       = 0x0010,
        AMTVAUDIO_MODE_LANG_B       = 0x0020,
        AMTVAUDIO_MODE_LANG_C       = 0x0040,
    } TVAudioMode;

Elements

AMTVAUDIO_MODE_MONO
Specifies the audio is in mono.
AMTVAUDIO_MODE_STEREO
Specifies the audio is in stereo.
AMTVAUDIO_MODE_LANG_A
Specifies the audio is an additional language. See Remarks.
AMTVAUDIO_MODE_LANG_B
Specifies the audio is an additional language. See Remarks.
AMTVAUDIO_MODE_LANG_C
Specifies the audio is an additional language. See Remarks.

Remarks

When using bilingual TV Audio in a specific country, such as Japan, the elements are defined as follows.

Elements | Description
AMTVAUDIO_MODE_LANG_A | Main multilingual audio program.
AMTVAUDIO_MODE_LANG_B | Secondary multilingual audio program.
AMTVAUDIO_MODE_LANG_C | Either a third language, or the main multilingual audio program plus the secondary multilingual audio program. For example, use this element to get English from one speaker and Japanese from the other speaker.


VALID_UOP_FLAG Enumeration

Enumerated Types

Indicates which user operation (UOP) commands are currently allowed by the digital video disc (DVD). This enumeration is used with the IDvdInfo2::GetCurrentUOPS method.

Syntax

typedef enum {

    UOP_FLAG_Play_Title_Or_AtTime           = 0x00000001,
    UOP_FLAG_Play_Chapter                   = 0x00000002,
    UOP_FLAG_Play_Title                     = 0x00000004,
    UOP_FLAG_Stop                           = 0x00000008,
    UOP_FLAG_ReturnFromSubMenu              = 0x00000010,
    UOP_FLAG_Play_Chapter_Or_AtTime         = 0x00000020,
    UOP_FLAG_PlayPrev_Or_Replay_Chapter     = 0x00000040,
    UOP_FLAG_PlayNext_Chapter               = 0x00000080,
    UOP_FLAG_Play_Forwards                  = 0x00000100,
    UOP_FLAG_Play_Backwards                 = 0x00000200,
    UOP_FLAG_ShowMenu_Title                 = 0x00000400,
    UOP_FLAG_ShowMenu_Root                  = 0x00000800,
    UOP_FLAG_ShowMenu_SubPic                = 0x00001000,
    UOP_FLAG_ShowMenu_Audio                 = 0x00002000,
    UOP_FLAG_ShowMenu_Angle                 = 0x00004000,
    UOP_FLAG_ShowMenu_Chapter               = 0x00008000,
    UOP_FLAG_Resume                         = 0x00010000,
    UOP_FLAG_Select_Or_Activate_Button      = 0x00020000,
    UOP_FLAG_Still_Off                      = 0x00040000,
    UOP_FLAG_Pause_On                       = 0x00080000,
    UOP_FLAG_Select_Audio_Stream            = 0x00100000,
    UOP_FLAG_Select_SubPic_Stream           = 0x00200000,
    UOP_FLAG_Select_Angle                   = 0x00400000,
    UOP_FLAG_Select_Karaoke_Audio_Presentation_Mode = 0x00800000,
    UOP_FLAG_Select_Video_Mode_Preference   = 0x01000000
} VALID_UOP_FLAG ;

Elements

UOP_FLAG_Play_Title_Or_AtTime
Annex J command name: Title_Or_Time_Play
UOP_FLAG_Play_Chapter
Annex J command name: Chapter_Search_Or_Play
UOP_FLAG_Play_Title
Annex J command name: Title_Play
UOP_FLAG_Stop
Annex J command name: Stop
UOP_FLAG_ReturnFromSubMenu
Annex J command name: GoUp
UOP_FLAG_ReturnFromSubMenu
Annex J command name: Time_Or_Chapter_Search
UOP_FLAG_PlayPrev_Or_Replay_Chapter
Annex J command name: Prev_Or_Top_PG_Search
UOP_FLAG_PlayNext_Chapter
Annex J command name: Next_PG_Search
UOP_FLAG_Play_Forwards
Annex J command name: Forward_Scan
UOP_FLAG_Play_Backwards
Annex J command name: Backward_Scan
UOP_FLAG_ShowMenu_Title
Annex J command name: Title_Menu_Call
UOP_FLAG_ShowMenu_Root
Annex J command name: Root_Menu_Call
UOP_FLAG_ShowMenu_SubPic
Annex J command name: SubPic_Menu_Call
UOP_FLAG_ShowMenu_Audio
Annex J command name: Audio_Menu_Call
UOP_FLAG_ShowMenu_Angle
Annex J command name: Angle_Menu_Call
UOP_FLAG_ShowMenu_Chapter
Annex J command name: Chapter_Menu_Call
UOP_FLAG_Resume
Annex J command name: Resume
UOP_FLAG_Select_Or_Activate_Button
Annex J command name: Button_Select_Or_Activate
UOP_FLAG_Still_Off
Annex J command name: Still_Off
UOP_FLAG_Pause_On
Annex J command name: Pause_On
UOP_FLAG_Select_Audio_Stream
Annex J command name: Audio_Stream_Change
UOP_FLAG_Select_SubPic_Stream
Annex J command name: SubPic_Stream_Change
UOP_FLAG_Select_Angle
Annex J command name: Angle_Change
UOP_FLAG_Select_Karaoke_Audio_Presentation_Mode
Annex J command name: Karaoke_Audio_Pres_Mode_Change
UOP_FLAG_Select_Video_Mode_Preference
Annex J command name: Video_Pres_Mode_Change


VfwCaptureDialogs Enumeration

Enumerated Types

Specifies a dialog box that might exist in a Video for Windows capture driver.

Syntax

 typedef enum {
    VfwCaptureDialog_Source = 1,
    VfwCaptureDialog_Format = 2,
    VfwCaptureDialog_Display = 4
} VfwCaptureDialogs;

Elements

VfwCaptureDialog_Source
Video source dialog box.
VfwCaptureDialog_Format
Video format dialog box.
VfwCaptureDialog_Display
Video display dialog box.

Remarks

The IAMVfwCaptureDialogs interface uses this enumerated data type.


VfwCompressDialogs Enumeration

Enumerated Types

Specifies a dialog box that might exist in a Video for Windows compression (codec) driver.

Syntax

typedef enum {
    VfwCompressDialog_Config = 1,
    VfwCompressDialog_About = 2,
    VfwCompressDialog_QueryConfig = 4,
    VfwCompressDialog_QueryAbout = 8
} VfwCompressDialogs;

Elements

VfwCompressDialog_Config
Configure dialog box.
VfwCompressDialog_About
About dialog box.
VfwCompressDialog_QueryConfig
Specifies whether the Configure dialog box is available.
VfwCompressDialog_QueryAbout
Specifies whether the About dialog box is available.

Remarks

The IAMVfwCompressDialogs interface uses this enumerated data type.


VideoControlFlags Enumeration

Enumerated Types

Specifies the video mode of operation for a video device.

Syntax

typedef enum tagVideoControlFlags
{
    VideoControlFlag_FlipHorizontal        = 0x0001,
    VideoControlFlag_FlipVertical          = 0x0002,
    VideoControlFlag_ExternalTriggerEnable = 0x0004,
    VideoControlFlag_Trigger               = 0x0008
} VideoControlFlags;

Elements

VideoControlFlag_FlipHorizontal
Specifies that the picture is flipped horizontally.
VideoControlFlag_FlipVertical
Specifies that the picture is flipped vertically.
VideoControlFlag_ExternalTriggerEnable
Sets up a stream to capture a trigger from an external source, for example, a push button on a camera. Buffers can be queued to the driver but will not be passed up from the WDM capture driver (for compression, display, or writing to a file) until the external event happens. See Remarks.
VideoControlFlag_Trigger
In software, simulates an external trigger when the stream has the VideoControlFlag_ExternalTriggerEnable flag set.

Remarks

The IAMVideoControl interface uses this enumerated data type.

Multiple capture buffers are queued to a capture driver and are filled at a fixed rate once the stream is put into the "run" state. If the VideoControlFlag_ExternalTriggerEnable flag is set, a filled buffer is not passed up from the WDM capture driver for compression, display, or writing to a file until the external event happens.


VideoProcAmpFlags Enumeration

Enumerated Types

Specifies how to set video properties.

Syntax

typedef enum tagVideoProcAmpFlags
    {
        VideoProcAmp_Flags_Manual = 0x0000,
        VideoProcAmp_Flags_Auto   = 0x0001,
    } VideoProcAmpFlags;

Elements

VideoProcAmp_Flags_Manual
Set properties manually.
VideoProcAmp_Flags_Auto
Use auto setting.

Remarks

The IAMVideoProcAmp interface uses this enumerated data type.


VideoProcAmpProperty Enumeration

Enumerated Types

Specifies video properties.

Syntax

typedef enum tagVideoProcAmpProperty
{
    VideoProcAmp_Brightness,
    VideoProcAmp_Contrast,
    VideoProcAmp_Hue,
    VideoProcAmp_Saturation,
    VideoProcAmp_Sharpness,
    VideoProcAmp_Gamma,
    VideoProcAmp_ColorEnable,
    VideoProcAmp_WhiteBalance,
    VideoProcAmp_BacklightCompensation,
    VideoProcAmp_Gain
} VideoProcAmpProperty;

Elements

VideoProcAmp_Brightness
Brightness.
VideoProcAmp_Contrast
Contrast.
VideoProcAmp_Hue
Hue.
VideoProcAmp_Saturation
Saturation.
VideoProcAmp_Sharpness
Sharpness.
VideoProcAmp_Gamma
Gamma.
VideoProcAmp_ColorEnable
Color.
VideoProcAmp_WhiteBalance
White balance.
VideoProcAmp_BacklightCompensation
Backlight compensation.
VideoProcAmp_Gain
Gain adjustment.

See Also

IAMVideoProcAmp


Constants

Microsoft DirectX 8.0

Constants and GUIDs

This section describes constants and globally unique identifiers (GUIDs) that are defined in Microsoft® DirectShow®.

  • DVD Event Notification Codes
  • Error and Success Codes
  • Event Notification Codes
  • Filter Categories
  • Media Types
  • Merit
  • Time Format GUIDs

See Also

  • Filter class identifiers (CLSIDs): See Filters.
  • Other component CLSIDs: See DirectShow Components.
  • Interface identifiers (IIDs): All DirectShow IIDs have the form IID_InterfaceName. For example, the IID for the IGraphBuilder interface is IID_IGraphBuilder.


DVD Event Notification Codes

Note This introductory material applies only to C++ developers.

Microsoft® DirectShow® supports system-defined events, which filters in the filter graph pass to the filter graph manager. Filters pass these events to the filter graph manager by using the IMediaEventSink::Notify method, and the application retrieves them with the IMediaEvent::GetEvent method.

When you retrieve an event by calling GetEvent, the event can contain interface pointers or pointers to allocated memory. Code that uses GetEvent should, therefore, call IMediaEvent::FreeEventParams to free any resources associated with the event's parameters after it handles the event.

The DVD event notification codes are listed in Dvdevcod.h. See Event Notification Codes for non-DVD event notification codes. The following list shows the available DVD event notification codes in alphabetical order.

DVD event notification code | Description
EC_DVD_ANGLE_CHANGE | Signals that either the number of available angles changed or that the current angle number changed.
EC_DVD_ ANGLES_AVAILABLE | Indicates whether an angle block is being played and angle changes can be performed.
EC_DVD_AUDIO_STREAM_CHANGE | Signals that the current audio stream number changed for the main title.
EC_DVD_BUTTON_AUTO_ACTIVATED | Signals that a menu button has been automatically activated per instructions on the disc.
EC_DVD_BUTTON_CHANGE | Signals that either the number of available buttons changed or that the currently selected button number changed.
EC_DVD_CHAPTER_AUTOSTOP | Indicates that playback stopped as the result of a call to the IDvdControl2::PlayChaptersAutoStop method.
EC_DVD_CHAPTER_START | Signals that the DVD Navigator started playback of a new chapter in the current title.
EC_DVD_CMD_START | Signals that a particular command has begun.
EC_DVD_CMD_END | Signals that a particular command has completed.
EC_DVD_CURRENT_HMSF_TIME | Signals the current time in DVD_HMSF_TIMECODE format at the beginning of every VOBU, which occurs every .4 to 1.0 sec.
EC_DVD_CURRENT_TIME | Signals the beginning of every video object unit (VOBU), a video segment which is 0.4 to 1.0 seconds in length.
EC_DVD_DISC_EJECTED | Signals that a disc has been ejected from the drive.
EC_DVD_DISC_INSERTED | Signals that a disc has been inserted into the drive.
EC_DVD_DOMAIN_CHANGE | Indicates the DVD Navigator's new domain.
EC_DVD_ERROR | Signals a DVD error condition.
EC_DVD_KARAOKE_MODE | Indicates that the Navigator has either begun playing or finished playing karaoke data.
EC_DVD_NO_FP_PGC | Indicates that the DVD disc does not have a FP_PGC (First Play Program Chain).
EC_DVD_PARENTAL_LEVEL_CHANGE | Signals that the parental level of the authored content is about to change.
EC_DVD_PLAYBACK_RATE_CHANGE | Indicates that a playback rate change has been initiated and the new rate is in the parameter.
EC_DVD_PLAYBACK_STOPPED | Indicates that playback has been stopped. The DVD Navigator has completed playback of the title and did not find any other branching instruction for subsequent playback.
EC_DVD_PLAYPERIOD_AUTOSTOP | Indicates that the Navigator has finished playing the segment specified in a call to PlayPeriodInTitleAutoStop.
EC_DVD_STILL_OFF | Signals the end of any still.
EC_DVD_STILL_ON | Signals the beginning of any still.
EC_DVD_SUBPICTURE_STREAM_CHANGE | Signals that the current subpicture stream number changed for the main title.
EC_DVD_TITLE_CHANGE | Indicates when the current title number changes.
EC_DVD_VALID_UOPS_CHANGE | Signals that the available set of IDVDControl2 interface methods has changed.
EC_DVD_WARNING | Signals a DVD warning condition.

EC_DVD_ANGLE_CHANGE

DVD Event Notification Codes

Signals that either the number of available angles changed or that the current angle number changed.

Parameters

lParam1
DWORD value indicating the number of available angles. When the number of available angles is 1, the current video is not multiangle.
lParam2
DWORD value indicating the current angle number.

Remarks

Angle numbers range from 1 to 9.

The current angle number can change automatically with a navigation command authored on the disc as well as through application control by using the IDVDControl2 interface.

This event is raised in all domains.

EC_DVD_ANGLES_AVAILABLE

DVD Event Notification Codes

Indicates whether an angle block is being played and angle changes can be performed.

Parameters

lParam1
Boolean (BOOL) value that indicates if an angle block is being played back. Zero (0) indicates that playback is not in an angle block and angles are not available, One (1) indicates that an angle block is being played back and angle changes can be performed.
lParam2
Zero.

Remarks

Angle changes are not restricted to angle blocks and the manifestation of the angle change can be seen only in an angle block.

EC_DVD_AUDIO_STREAM_CHANGE

DVD Event Notification Codes

Signals that the current audio stream number changed for the main title.

Parameters

lParam1
DWORD value indicating the new user audio stream number. Audio stream numbers range from 0 to 7. Stream 0xFFFFFFFF indicates that no stream is selected.
lParam2
Zero.

Remarks

The current audio stream can change automatically with a navigation command authored on the disc as well as through application control by using the IDVDControl2 interface.

This event is raised in all domains.

EC_DVD_BUTTON_AUTO_ACTIVATED

DVD Event Notification Codes

Signals that a menu button has been automatically activated per instructions on the disc. This occurs when a menu times out and the disc has specified a button to be automatically activated.

Parameters

lParam1
DWORD value indicating the button that was activated.
lParam2
Zero.

This event is raised in all domains.

EC_DVD_BUTTON_CHANGE

DVD Event Notification Codes

Signals that either the number of available buttons changed or that the currently selected button number changed.

Parameters

lParam1
DWORD value indicating the number of available buttons.
lParam2
DWORD value indicating the currently selected button number. Selected button number zero implies that no button is selected.

Remarks

Button numbers range from 1 to 36.

The currently selected button can change automatically with a navigation command authored on the disc as well as through application control by using IDVDControl2 interface.

This event can signal any of the available button numbers. These numbers do not always correspond to button numbers used for IDvdControl::SelectAndActivateButton because that method can activate only a subset of buttons.

This event is raised in all domains.

EC_DVD_CHAPTER_AUTOSTOP

DVD Event Notification Codes

Indicates that playback stopped as the result of a call to the IDvdControl::PlayChaptersAutoStop method.

Parameters

lParam1
Zero.
lParam2
Zero.

Remarks

This event is raised in the title domain.

EC_DVD_CHAPTER_START

DVD Event Notification Codes

Signals that the DVD player started playback of a new program in the DVD_DOMAIN_Title domain.

Parameters

lParam1
DWORD value indicating the new chapter (program) number.
lParam2
Zero.

Remarks

Only simple linear movies signal this event.

This event is raised in the title domain.

EC_DVD_CMD_START

DVD Event Notification Codes

Signals that a particular command has begun.

Parameters

lParam1
The Command ID and the HRESULT return value.
lParam2
Zero.

Remarks

This event is only fired if your application has expressed interest in it by setting the DVD_CMD_FLAG_SendEvents flag in any of the IDVDControl2::Play... methods. See Synchronizing DVD Commands for more details.

This event is raised in the title domain.

EC_DVD_CMD_END

DVD Event Notification Codes

Signals that a particular command has completed.

Parameters

lParam1
The Command ID and the completion result.
lParam2
Zero.

Remarks

This event is only fired if your application has expressed interest in it by setting the DVD_CMD_FLAG_SendEvents flag in any of the IDVDControl2::Play... methods. See Synchronizing DVD Commands for more details.

This event is raised in the title domain.

EC_DVD_CURRENT_HMSF_TIME

DVD Event Notification Codes

Signals the current time, in DVD_HMSF_TIMECODE format, relative to the start of the title. This event is triggered at the beginning of every VOBU, which occurs every 0.4 to 1.0 seconds.

Parameters

lParam1
A ULONG value that contains the DVD_HMSF_TIMECODE structure. Assign lParam1 to a ULONG variable and then cast that variable to a DVD_HMSF_TIMECODE to access its values.
lParam2
A ULONG value containing a union of DVD_TIMECODE_FLAGS.

Remarks

The DVD_HMSF_TIMECODE format is intended to replace the old BCD format that is returned in EC_DVD_CURRENT_TIME events. The HMSF timecodes are easier to work with. To have the Navigator send EC_DVD_CURRENT_HMSF_TIME events instead of EC_DVD_CURRENT_TIME events, an application must call IDVDControl2::SetOption(DVD_HMSF_TimeCodeEvents, TRUE). When this flag is set, the Navigator will also expect all time parameters in the IDVDControl2 and IDVDInfo2 methods to be passed as DVD_HMSF_TIMECODEs.

This event is raised in the title domains.

EC_DVD_CURRENT_TIME

DVD Event Notification Codes

Signals the beginning of every video object unit (VOBU), a video segment which is 0.4 to 1.0 seconds in length.

Parameters

lParam1
DWORD value indicating the current playback timecode in a binary coded decimal (BCD) hours, minutes, seconds, frames (HH:MM:SS:FF) format. Member of the DVD_TIMECODE structure.
lParam2
Boolean (BOOL) value indicating the timecode. Zero (0) indicates 25 frames per second while 1 indicates 30 frames per second (nondropped). A value of 2 indicates the playback time cannot be determined.

Remarks

Only simple linear movies signal this event.

This event is raised in the title domain.

EC_DVD_DISC_EJECTED

DVD Event Notification Codes

Signals that a disc was ejected.

Parameters

lParam1
Zero.
lParam2
Zero.

Remarks

Playback automatically stops when a disc is ejected. The application does not have to take any special action in response to this event.

This event is raised in all domains.

EC_DVD_DISC_INSERTED

DVD Event Notification Codes

Signals that a disc was inserted into the drive.

Parameters

lParam1
Zero.
lParam2
Zero.

Remarks

Playback automatically begins when a disc is ejected. The application does not have to take any special action in response to this event.

This event is raised in all domains.

EC_DVD_DOMAIN_CHANGE

DVD Event Notification Codes

Indicates the DVD player's new domain.

Parameters

lParam1
DWORD value indicating the new domain. Member of the DVD_DOMAIN enumerated data type.
lParam2
Zero unless lParam1 == DVD_ERROR_LowParentalLevel. In that case lParam2 will be set to the minimum parental level required to play the title, or to DWORD_PTR(-1) if parental controls must be disabled in order to play the title.

Remarks

The DVD player signals this event whenever it changes domains.

This event is raised in all DVD domains.

EC_DVD_ERROR

DVD Event Notification Codes

Signals a DVD error condition.

Parameters

lParam1
DWORD value indicating the error condition. Member of the DVD_ERROR enumerated data type.
lParam2
DWORD value whose HIWORD contains the decoder region as a reversed set of bits and whose LOWORD contains the drive/system region as a reversed set of bits. See Remarks.

Remarks

This event is raised in all domains.

If lParam1 = DVD_ERROR_IncompatibleSystemAndDecoderRegion, it indicates that (1) the decoder has a region specified and (2) the drive and decoder region do not match.

If lParam1 = DVD_ERROR_IncompatibleDiscAndDecoderRegion, it indicates that (1) the decoder has a region specified and (2) the disc and decoder region do not match.

The disc region is encoded exactly as it is on the disc: as a reversed set of bits in the LOWORD of lParam2. If a disc is allowed in a region, that bit will be OFF. For example, for a Region 2 disc the returned value will be 253 (1111 1101) which has the second least significant bit turned off. A multi-region disc will have more than one such bit turned off.

The decoder region in the HIWORD of lParam2 is encoded in the same way.

If

EC_DVD_KARAOKE_MODE

DVD Event Notification Codes

Indicates that the Navigator has either begun playing or finished playing karaoke data.

Parameters

lParam1
BOOL value. TRUE means that a karaoke track is being played and FALSE means that no karaoke data is being played.
lParam2
Reserved.

Remarks

The DVD player signals this event whenever it changes domains.

This event is raised in all DVD domains.

EC_DVD_NO_FP_PGC

DVD Event Notification Codes

Signals that the DVD disc does not have a FP_PGC (First Play Program Chain) and that the DVD Navigator will not automatically load any PGC and start playback.

Remarks

This event is raised from the First Play domain.

EC_DVD_PARENTAL_LEVEL_CHANGE

DVD Event Notification Codes

Signals that the parental level of the authored content is about to change.

Parameters

lParam1
LONG value representing the new parental level set in the player.
lParam2
Zero.

Remarks

The DVD Navigator source filter does not currently support "on the fly" parental level changes in response to SetTmpPML commands on a DVD disc.

EC_DVD_PLAYBACK_RATE_CHANGE

DVD Event Notification Codes

Signals that a rate change in the playback has been initiated; the parameter lParam1 indicates the new playback rate being used.

Parameters

lParam1
LONG indicating the new playback rate. lParam1 < 0 indicates reverse playback mode. lParam1 > 0 indicates forward playback mode. The value of lParam1 is the actual playback rate multiplied by 10,000, that is, lParam1 = playback_rate * 10000.
lParam2
Zero.

Remarks

This event is raised in the title domain.

EC_DVD_PLAYBACK_STOPPED

DVD Event Notification Codes

Indicates that playback has been stopped. The DVD Navigator has completed playback of the title or chapter and did not find any other branching instruction for subsequent playback.

Parameters

lParam1
Zero.
lParam2
Zero.

Remarks

This event is raised in the title domain, but it is not raised on user initiated Stop.

EC_DVD_STILL_OFF

DVD Event Notification Codes

Signals the end of any still (PGC, Cell, or VOBU).

Parameters

lParam1
Zero.
lParam2
Zero.

Remarks

This event indicates that any currently active still has been released.

This event is raised in all domains.

EC_DVD_PLAYPERIOD_AUTOSTOP

DVD Event Notification Codes

Indicates that the Navigator has finished playing the segment specified in a call to PlayPeriodInTitleAutoStop.

Parameters

lParam1
Zero.
lParam2
Zero.

Remarks

This event is raised in in the Title domain.

This event is also sent when playback is cancelled before the Navigator finishes playing the specified segment.

EC_DVD_STILL_ON

DVD Event Notification Codes

Signals the beginning of any still (PGC, Cell, or VOBU).

Parameters

lParam1
Boolean (BOOL) value indicating whether buttons are available. Zero (0) indicates buttons are available so the IDVDControl2::StillOff method won't work. One (1) indicates no buttons are available, so IDVDControl2::StillOff will work.
lParam2
DWORD value indicating the number of seconds the still will last. 0xFFFFFFFF indicates an infinite still, meaning wait until the user presses a button or until the application calls IDVDControl2::StillOff.

Remarks

All combinations of buttons and still are possible (buttons on with still on, buttons on with still off, button off with still on, button off with still off).

This event is raised in all domains.

EC_DVD_SUBPICTURE_STREAM_CHANGE

DVD Event Notification Codes

Signals that the current subpicture stream number changed for the main title.

Parameters

lParam1
DWORD value indicating the new user subpicture stream number. Subpicture stream numbers range from 0 to 31. Stream 0xFFFFFFFF indicates that no stream is selected.
lParam2
Zero.

Remarks

The subpicture can change automatically with a navigation command authored on disc as well as through application control using IDVDControl2.

This event is raised in all domains.

EC_DVD_TITLE_CHANGE

DVD Event Notification Codes

Indicates when the current title number changes.

Parameters

lParam1
DWORD value indicating the new title number.
lParam2
Zero.

Remarks

Title numbers range from 1 to 99. This number indicates the TTN, which is the title number with respect to the whole disc, not the VTS_TTN which is the title number with respect to just a current VTS.

This event is raised in the title domain.

EC_DVD_VALID_UOPS_CHANGE

DVD Event Notification Codes

Signals that the available set of IDVDControl2 interface methods has changed.

Parameters

lParam1
DWORD value representing a ULONG whose bits indicate which IDVDControl2 commands the DVD disc explicitly disabled.
lParam2
Zero.

Remarks

This event indicates only which operations are explicitly disabled by the content on the DVD disc, and does not guarantee that it is valid to call methods that are not disabled. For example, if no buttons are present, the IDvdControl::ActivateButton method won't work, even though the method is not explicitly disabled.

This event is raised in all domains.

EC_DVD_WARNING

DVD Event Notification Codes

Signals a DVD warning condition.

Parameters

lParam1
DWORD value indicating the warning condition. Member of the DVD_WARNING enumerated data type.
lParam2
Zero.

Remarks

This event is raised in all domains.


Error and Success Codes

Microsoft® DirectShow® returns error and success notifications (return codes) to applications in the form of HRESULT values. A return code's LOWORD portion is the return code itself, in hexadecimal format. After you obtain the return code, a call to the AMGetErrorText function returns the code's text description. The COM Win32 HRESULT documentation contains more information, including how to use the FAILED and SUCCEEDED macros to test return values.

This article contains the following sections:

  • Typical COM HRESULT Values
  • HRESULT Values Specific to DirectShow
  • HRESULT Values Specific to DirectShow Editing Services

Typical COM HRESULT Values

The following list presents some of the typical COM error and success codes that DirectShow returns.
Value | Meaning
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
E_UNEXPECTED | Unexpected error.
NOERROR | No error. Numerically equivalent to S_OK.
S_FALSE | Success. Condition was FALSE.
S_OK | Success. Numerically equivalent to NOERROR.
S_TRUE | Success. Condition was TRUE.

HRESULT Values Specific to DirectShow

The following table contains DirectShow-specific error and success codes in numerical order. Return codes beginning with VFW_S_ indicate success overall. An operation might partially succeed and still have a successful return value. For example, VFW_S_SOME_DATA_IGNORED indicates that a file was rendered by ignoring some of its property settings. Return codes beginning with VFW_E_ indicate an error, while those beginning with CTL_ (Control Error Codes) pertain specifically to the Microsoft® Windows Media™ Player control. This table does not contain all possible return values; the return codes shown apply specifically to DirectShow. DirectShow-specific return codes also appear in the Vfwmsgs.h header file. If you encounter an error not listed here, the error code might appear in another source, such as a list of COM or Microsoft® Windows® 9x errors. For example, Microsoft® Visual C++® users can find COM or Windows 9x errors in the Winerror.h include file.

C/C++ programmers receive error codes in complete (32-bit) hexadecimal format. Microsoft® Visual Basic® programmers, on the other hand, will see only the decimal equivalent of the error code's first 16-bit portion. This value appears in an error notification dialog box or in the Err object as a run-time error. If the error is not in the following list, you must convert the decimal number to its hexadecimal equivalent, and then look for the error as described previously. Note that the error's hexadecimal version will be a maximum of four digits long; to find the error, match the last four digits of the hexadecimal code in the error code list to the converted run-time error.
Return code | Description | Hexadecimal value | Decimal value (LOWORD)
CTL_E_ILLEGALFUNCTIONCALL | The syntax in the function call was incorrect. | 0x800A0005 | 5
CTL_E_OVERFLOW | The result is too large to be represented in function's return type. | 0x800A0006 | 6
CTL_E_OUTOFMEMORY | There is insufficient memory to perform the requested operation. | 0x800A0007 | 7
CTL_E_DIVISIONBYZERO | The function attempted to divide by zero. | 0x800A000B | 11
CTL_E_OUTOFSTRINGSPACE | There is insufficient string space to perform the requested operation. Certain operations (copying, for example) involve temporary strings that use up string space. | 0x800A000E | 14
CTL_E_OUTOFSTACKSPACE | There is insufficient string space to perform the requested operation. Each thread has its own stack while other resources, such as heap memory, are shared by all threads in the process. You must specify how much memory to allocate for a separate stack for each additional thread your program needs. The operating system will allocate additional stack space for the thread, if necessary, but you must specify a default value. If the operating system cannot allocate the necessary space, you receive this error. | 0x800A001C | 28
CTL_E_BADFILENAMEORNUMBER | The function attempted to access a file with a bad file name or number. | 0x800A0034 | 52
CTL_E_FILENOTFOUND | The function attempted to access a file that could not be found. | 0x800A0035 | 53
CTL_E_BADFILEMODE | The function attempted to perform an operation on a file that has an incompatible file mode. File modes are Append, Binary, Input, Output, or Random. | 0x800A0036 | 54
CTL_E_FILEALREADYOPEN | The function attempted to open a file that was already open. | 0x800A0037 | 55
CTL_E_DEVICEIOERROR | There was a device I/O error during the function execution. | 0x800A0039 | 57
CTL_E_FILEALREADYEXISTS | The function attempted to create a file that already exists. | 0x800A003A | 58
CTL_E_BADRECORDLENGTH | The function attempted to access a file record that is incorrect. For example, it is assumed that a file opened for random access is composed of a set of identical-length records. | 0x800A003B | 59
CTL_E_DISKFULL | The function attempted to write to the disk, but the disk is full. | 0x800A003D | 61
CTL_E_BADRECORDNUMBER | The function attempted to access a file record that is incorrect. The record number is the position of the position in a recordset (a set of records in a data source). | 0x800A003F | 63
CTL_E_BADFILENAME | The function attempted to access a file name that is incorrect. | 0x800A0040 | 64
CTL_E_TOOMANYFILES | The function attempted to open a file when too many files were already open. | 0x800A0043 | 67
CTL_E_DEVICEUNAVAILABLE | The function attempted to access a device that was not available. | 0x800A0044 | 68
CTL_E_PERMISSIONDENIED | The function attempted to access a file without the proper permission setting. | 0x800A0046 | 70
CTL_E_DISKNOTREADY | The function attempted to access a file when the disk was not ready. | 0x800A0047 | 71
CTL_E_PATHFILEACCESSERROR | The function attempted to access a file or path that was incorrect or had the wrong permissions. | 0x800A004B | 75
CTL_E_PATHNOTFOUND | The function attempted to access a file with an incorrect path. | 0x800A004C | 76
CTL_E_INVALIDPATTERNSTRING | The function was called with an invalid string. | 0x800A005D | 93
CTL_E_INVALIDUSEOFNULL | The function was called with an invalid NULL. | 0x800A005E | 94
VFW_S_NO_MORE_ITEMS | There are no more items in the list. | 0x00040103 | 259
CTL_E_INVALIDFILEFORMAT | The function attempted to perform an operation on a file that has an incompatible file format. | 0x800A0141 | 321
CTL_E_INVALIDPROPERTYVALUE | The function was called with an invalid property value. | 0x800A017C | 380
CTL_E_INVALIDPROPERTYARRAYINDEX | The function was called with an invalid property array index. | 0x800A017D | 381
CTL_E_SETNOTSUPPORTEDATRUNTIME | The function attempted to set a property that cannot be set at run time. | 0x800A017E | 382
CTL_E_SETNOTSUPPORTED | The function attempted to set a property that cannot be set. | 0x800A017F | 383
CTL_E_NEEDPROPERTYARRAYINDEX | The function attempted to access a property that needs an array index without the array index. | 0x800A0181 | 385
CTL_E_SETNOTPERMITTED | The function attempted to set a property without the proper permissions to set the property. | 0x800A0183 | 387
CTL_E_GETNOTSUPPORTEDATRUNTIME | The function attempted to get a property that cannot be retrieved at run time. | 0x800A0189 | 393
CTL_E_GETNOTSUPPORTED | The function attempted to get a property that cannot be retrieved. | 0x800A018A | 394
CTL_E_PROPERTYNOTFOUND | The function attempted to get a property that could not be found. | 0x800A01A6 | 422
CTL_E_INVALIDCLIPBOARDFORMAT | The function attempted an operation with an invalid Clipboard format. | 0x800A01CC | 460
CTL_E_INVALIDPICTURE | The function attempted an operation with an invalid picture. | 0x800A01E1 | 481
CTL_E_PRINTERERROR | The function attempted to print, and there was a printer error. | 0x800A01E2 | 482
VFW_E_INVALIDMEDIATYPE | The specified media type is invalid. | 0x80040200 | 512
VFW_E_INVALIDSUBTYPE | The specified media subtype is invalid. | 0x80040201 | 513
VFW_E_NEED_OWNER | This object can only be created as an aggregated object. | 0x80040202 | 514
VFW_E_ENUM_OUT_OF_SYNC | The state of the enumerated object has changed and is now inconsistent with the state of the enumerator. Discard any data obtained from previous calls to the enumerator and then update the enumerator by calling the enumerator's Reset method. | 0x80040203 | 515
VFW_E_ALREADY_CONNECTED | At least one of the pins involved in the operation is already connected. | 0x80040204 | 516
VFW_E_FILTER_ACTIVE | This operation cannot be performed because the filter is active. | 0x80040205 | 517
VFW_E_NO_TYPES | One of the specified pins supports no media types. | 0x80040206 | 518
VFW_E_NO_ACCEPTABLE_TYPES | There is no common media type between these pins. | 0x80040207 | 519
VFW_E_INVALID_DIRECTION | Two pins of the same direction cannot be connected. | 0x80040208 | 520
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected. | 0x80040209 | 521
VFW_E_NO_ALLOCATOR | No sample buffer allocator is available. | 0x8004020A | 522
VFW_E_RUNTIME_ERROR | A run-time error occurred. | 0x8004020B | 523
VFW_E_BUFFER_NOTSET | No buffer space has been set. | 0x8004020C | 524
VFW_E_BUFFER_OVERFLOW | The buffer is not big enough. | 0x8004020D | 525
VFW_E_BADALIGN | An invalid alignment was specified. | 0x8004020E | 526
VFW_E_ALREADY_COMMITTED | Cannot change allocated memory while the filter is active. | 0x8004020F | 527
VFW_E_BUFFERS_OUTSTANDING | One or more buffers are still active. | 0x80040210 | 528
VFW_E_NOT_COMMITTED | Cannot allocate a sample when the allocator is not active. | 0x80040211 | 529
VFW_E_SIZENOTSET | Cannot allocate memory because no size has been set. | 0x80040212 | 530
VFW_E_NO_CLOCK | Cannot lock for synchronization because no clock has been defined. | 0x80040213 | 531
VFW_E_NO_SINK | Quality messages could not be sent because no quality sink has been defined. | 0x80040214 | 532
VFW_E_NO_INTERFACE | A required interface has not been implemented. | 0x80040215 | 533
VFW_E_NOT_FOUND | An object or name was not found. | 0x80040216 | 534
VFW_E_CANNOT_CONNECT | No combination of intermediate filters could be found to make the connection. | 0x80040217 | 535
VFW_E_CANNOT_RENDER | No combination of filters could be found to render the stream. | 0x80040218 | 536
VFW_E_CHANGING_FORMAT | Could not change formats dynamically. | 0x80040219 | 537
VFW_E_NO_COLOR_KEY_SET | No color key has been set. | 0x8004021A | 538
VFW_E_NOT_OVERLAY_CONNECTION | Current pin connection is not using the IOverlay transport. | 0x8004021B | 539
VFW_E_NOT_SAMPLE_CONNECTION | Current pin connection is not using the IMemInputPin transport. | 0x8004021C | 540
VFW_E_PALETTE_SET | Setting a color key would conflict with the palette already set. | 0x8004021D | 541
VFW_E_COLOR_KEY_SET | Setting a palette would conflict with the color key already set. | 0x8004021E | 542
VFW_E_NO_COLOR_KEY_FOUND | No matching color key is available. | 0x8004021F | 543
VFW_E_NO_PALETTE_AVAILABLE | No palette is available. | 0x80040220 | 544
VFW_E_NO_DISPLAY_PALETTE | Display does not use a palette. | 0x80040221 | 545
VFW_E_TOO_MANY_COLORS | Too many colors for the current display settings. | 0x80040222 | 546
VFW_E_STATE_CHANGED | The state changed while waiting to process the sample. | 0x80040223 | 547
VFW_E_NOT_STOPPED | The operation could not be performed because the filter is not stopped. | 0x80040224 | 548
VFW_E_NOT_PAUSED | The operation could not be performed because the filter is not paused. | 0x80040225 | 549
VFW_E_NOT_RUNNING | The operation could not be performed because the filter is not running. | 0x80040226 | 550
VFW_E_WRONG_STATE | The operation could not be performed because the filter is in the wrong state. | 0x80040227 | 551
VFW_E_START_TIME_AFTER_END | The sample start time is after the sample end time. | 0x80040228 | 552
VFW_E_INVALID_RECT | The supplied rectangle is invalid. | 0x80040229 | 553
VFW_E_TYPE_NOT_ACCEPTED | This pin cannot use the supplied media type. | 0x8004022A | 554
VFW_E_SAMPLE_REJECTED | This sample cannot be rendered. | 0x8004022B | 555
VFW_E_SAMPLE_REJECTED_EOS | This sample cannot be rendered because the end of the stream has been reached. | 0x8004022C | 556
VFW_E_DUPLICATE_NAME | An attempt to add a filter with a duplicate name failed. | 0x8004022D | 557
VFW_S_DUPLICATE_NAME | An attempt to add a filter with a duplicate name succeeded with a modified name. | 0x0004022D | 557
VFW_E_TIMEOUT | A time-out has expired. | 0x8004022E | 558
VFW_E_INVALID_FILE_FORMAT | The file format is invalid. | 0x8004022F | 559
VFW_E_ENUM_OUT_OF_RANGE | The list has already been exhausted. | 0x80040230 | 560
VFW_E_CIRCULAR_GRAPH | The filter graph is circular. | 0x80040231 | 561
VFW_E_NOT_ALLOWED_TO_SAVE | Updates are not allowed in this state. | 0x80040232 | 562
VFW_E_TIME_ALREADY_PASSED | An attempt was made to queue a command for a time in the past. | 0x80040233 | 563
VFW_E_ALREADY_CANCELLED | The queued command was already canceled. | 0x80040234 | 564
VFW_E_CORRUPT_GRAPH_FILE | Cannot render the file because it is corrupt. | 0x80040235 | 565
VFW_E_ADVISE_ALREADY_SET | An IOverlay advise link already exists. | 0x80040236 | 566
VFW_S_STATE_INTERMEDIATE | The state transition is not complete. | 0x00040237 | 567
VFW_E_NO_MODEX_AVAILABLE | No full-screen modes are available. | 0x80040238 | 568
VFW_E_NO_ADVISE_SET | This advise cannot be canceled because it was not successfully set. | 0x80040239 | 569
VFW_E_NO_FULLSCREEN | Full-screen mode is not available. | 0x8004023A | 570
VFW_E_IN_FULLSCREEN_MODE | Cannot call IVideoWindow methods while in full-screen mode. | 0x8004023B | 571
VFW_E_UNKNOWN_FILE_TYPE | The media type of this file is not recognized. | 0x80040240 | 576
VFW_E_CANNOT_LOAD_SOURCE_FILTER | The source filter for this file could not be loaded. | 0x80040241 | 577
VFW_S_PARTIAL_RENDER | Some of the streams in this movie are in an unsupported format. | 0x00040242 | 578
VFW_E_FILE_TOO_SHORT | A file appeared to be incomplete. | 0x80040243 | 579
VFW_E_INVALID_FILE_VERSION | The file's version number is invalid. | 0x80040244 | 580
VFW_S_SOME_DATA_IGNORED | The file contained some property settings that were not used. | 0x00040245 | 581
VFW_S_CONNECTIONS_DEFERRED | Some connections failed and were deferred. | 0x00040246 | 582
VFW_E_INVALID_CLSID | This file is corrupt: it contains an invalid class identifier. | 0x80040247 | 583
VFW_E_INVALID_MEDIA_TYPE | This file is corrupt: it contains an invalid media type. | 0x80040248 | 584
VFW_E_SAMPLE_TIME_NOT_SET | No time stamp has been set for this sample. | 0x80040249 | 585
VFW_S_RESOURCE_NOT_NEEDED | The resource specified is no longer needed. | 0x00040250 | 592
VFW_E_MEDIA_TIME_NOT_SET | No media time stamp was set for this sample. | 0x80040251 | 593
VFW_E_NO_TIME_FORMAT_SET | No media time format was selected. | 0x80040252 | 594
VFW_E_MONO_AUDIO_HW | Cannot change balance because audio device is monoaural only. | 0x80040253 | 595
VFW_S_MEDIA_TYPE_IGNORED | Could not connect with the media type in the persistent graph. | 0x00040254 | 596
VFW_E_NO_DECOMPRESSOR | Cannot play back the video stream: could not find a suitable decompressor. | 0x80040255 | 597
VFW_E_NO_AUDIO_HARDWARE | Cannot play back the audio stream: no audio hardware is available, or the hardware is not supported. | 0x80040256 | 598
VFW_S_VIDEO_NOT_RENDERED | Cannot play back the video stream: could not find a suitable renderer. | 0x00040257 | 599
VFW_S_AUDIO_NOT_RENDERED | Cannot play back the audio stream: could not find a suitable renderer. | 0x00040258 | 600
VFW_E_RPZA | Cannot play back the video stream: format 'RPZA' is not supported. | 0x80040259 | 601
VFW_S_RPZA | Cannot play back the video stream: format 'RPZA' is not supported. | 0x0004025A | 602
VFW_E_PROCESSOR_NOT_SUITABLE | DirectShow cannot play MPEG movies on this processor. | 0x8004025B | 603
VFW_E_UNSUPPORTED_AUDIO | Cannot play back the audio stream: the audio format is not supported. | 0x8004025C | 604
VFW_E_UNSUPPORTED_VIDEO | Cannot play back the video stream: the video format is not supported. | 0x8004025D | 605
VFW_E_MPEG_NOT_CONSTRAINED | DirectShow cannot play this video stream because it falls outside the constrained standard. | 0x8004025E | 606
VFW_E_NOT_IN_GRAPH | Cannot perform the requested function on an object that is not in the filter graph. | 0x8004025F | 607
VFW_S_ESTIMATED | The value returned had to be estimated. Its accuracy can't be guaranteed. | 0x00040260 | 608
VFW_E_NO_TIME_FORMAT | Cannot access the time format on an object. | 0x80040261 | 609
VFW_E_READ_ONLY | Could not make the connection because the stream is read-only and the filter alters the data. | 0x80040262 | 610
VFW_S_RESERVED | This success code is reserved for internal purposes within DirectShow. | 0x00040263 | 611
VFW_E_BUFFER_UNDERFLOW | The buffer is not full enough. | 0x80040264 | 612
VFW_E_UNSUPPORTED_STREAM | Cannot play back the file: the format is not supported. | 0x80040265 | 613
VFW_E_NO_TRANSPORT | Pins cannot connect because they don't support the same transport. | 0x80040266 | 614
VFW_S_STREAM_OFF | The stream was turned off. | 0x00040267 | 615
VFW_S_CANT_CUE | The filter is active, but cannot deliver data. See IMediaFilter::GetState. | 0x00040268 | 616
VFW_E_BAD_VIDEOCD | The Video CD can't be read correctly by the device or the data is corrupt. | 0x80040269 | 617
VFW_S_NO_STOP_TIME | The sample had a start time but not a stop time. In this case, the stop time that is returned is set to the start time plus one. | 0x80040270 | 624
VFW_E_OUT_OF_VIDEO_MEMORY | There is not enough video memory at this display resolution and number of colors. Reducing resolution might help. | 0x80040271 | 625
VFW_E_VP_NEGOTIATION_FAILED | The video port connection negotiation process has failed. | 0x80040272 | 626
VFW_E_DDRAW_CAPS_NOT_SUITABLE | Either Microsoft® DirectDraw® has not been installed or the video card capabilities are not suitable. Make sure the display is not in 16-color mode. | 0x80040273 | 627
VFW_E_NO_VP_HARDWARE | No video port hardware is available, or the hardware is not responding. | 0x80040274 | 628
VFW_E_NO_CAPTURE_HARDWARE | No capture hardware is available, or the hardware is not responding. | 0x80040275 | 629
VFW_E_DVD_OPERATION_INHIBITED | This user operation is inhibited by DVD content at this time. | 0x80040276 | 630
VFW_E_DVD_INVALIDDOMAIN | This operation is not permitted in the current domain. | 0x80040277 | 631
VFW_E_DVD_NO_BUTTON | Requested button is not available. | 0x80040278 | 632
VFW_E_DVD_GRAPHNOTREADY | DVD-Video playback graph has not been built yet. | 0x80040279 | 633
VFW_E_DVD_RENDERFAIL | DVD-Video playback graph building failed. | 0x8004027A | 634
VFW_E_DVD_DECNOTENOUGH | DVD-Video playback graph could not be built due to insufficient decoders. | 0x8004027B | 635
VFW_E_DVD_NOT_IN_KARAOKE_MODE | The DVD Navigator is not in karaoke mode. | 0x8004028B | 651
VFW_E_FRAME_STEP_UNSUPPORTED | Frame stepping is not supported. | 0x8004028E | 654
VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD | Pin is already blocked on the calling thread. | 0x80040293 | 659
VFW_E_PIN_ALREADY_BLOCKED | Pin is already blocked on another thread. | 0x80040294 | 660
VFW_E_CERTIFICATION_FAILURE | Use of this filter is restricted by a software key. The application must unlock the filter. | 0x80040295 | 661
CTL_E_CANTSAVEFILETOTEMP | The file cannot be saved to the TEMP directory. | 0x800A02DF | 735
CTL_E_SEARCHTEXTNOTFOUND | The searched-for text cannot be found. | 0x800A02E8 | 744
CTL_E_REPLACEMENTSTOOLONG | The text replacement is too long. | 0x800A02EA | 746
VFW_E_BAD_KEY | A registry entry is corrupt. | 0x800403F2 | 1010

HRESULT Values Specific to DirectShow Editing Services

In addition to the values listed previously, DirectShow Editing Services defines the following HRESULT values.

Return code | Description | Hexadecimal value | Decimal value (LOWORD)
S_WARN_OUTPUTRESET | The rendering portion of the graph was deleted. The application must rebuild it. | 0x00040404 | 1028
E_NOTINTREE | The object is not contained in the timeline. | 0x80040400 | 1024
E_RENDER_ENGINE_IS_BROKEN | Operation failed because project was not rendered successfully. | 0x80040401 | 1025
E_MUST_INIT_RENDERER | Render engine has not been initialized. | 0x80040402 | 1026
E_NOTDETERMINED | Cannot determine requested value. | 0x80040403 | 1027
E_NO_TIMELINE | There is no timeline object. | 0x80040404 | 1028


Event Notification Codes

Microsoft® DirectShow® supports system-defined events. Filters pass events to the filter graph manager using the IMediaEventSink::Notify method. The filter graph manager handles some events, and passes others to the application. The application can retrieve events by calling the IMediaEvent::GetEvent method. For more information, see Event Notification in DirectShow.

This article describes the DirectShow events that are not specific to DVD. For events that are specific to DVD, see DVD Event Notification Codes.

For each event, this article lists the event code and the meaning of the two event parameters. It also describes the filter graph manager's default handling for the event, if any. To override the default handling, call IMediaEvent::CancelDefaultHandling in your application.

The event notification codes are defined in the header files Evcode.h and Audevcod.h.

Event notification code | Description
EC_ACTIVATE | A video window is being activated or deactivated.
EC_BUFFERING_DATA | The graph is buffering data, or has stopped buffering data.
EC_CLOCK_CHANGED | The reference clock has changed.
EC_COMPLETE | All data from a particular stream has been rendered.
EC_DEVICE_LOST | A Plug and Play device was removed or has become available again.
EC_DISPLAY_CHANGED | The display mode has changed.
EC_END_OF_SEGMENT | The end of a segment has been reached.
EC_ERROR_STILLPLAYING | An asynchronous command to run the graph has failed.
EC_ERRORABORT | An operation was aborted because of an error.
EC_FULLSCREEN_LOST | The video renderer is switching out of full-screen mode.
EC_GRAPH_CHANGED | The filter graph has changed.
EC_NEED_RESTART | A filter is requesting that the graph be restarted.
EC_NOTIFY_WINDOW | Notifies a filter of the video renderer's window.
EC_OLE_EVENT | A filter is passing a text string to the application.
EC_OPENING_FILE | The graph is opening a file, or has finished opening a file.
EC_PALETTE_CHANGED | The video palette has changed.
EC_PAUSED | A pause request has completed.
EC_QUALITY_CHANGE | The graph is dropping samples, for quality control.
EC_REPAINT | A video renderer requires a repaint.
EC_SEGMENT_STARTED | A new segment has started.
EC_SHUTTING_DOWN | The filter graph is shutting down, prior to being destroyed.
EC_SNDDEV_IN_ERROR | An audio device error has occurred on an input pin.
EC_SNDDEV_OUT_ERROR | An audio device error has occurred on an output pin.
EC_STARVATION | A filter is not receiving enough data.
EC_STEP_COMPLETE | A filter performing frame stepping has stepped the specified number of frames.
EC_STREAM_CONTROL_STARTED | A stream-control start command has taken effect.
EC_STREAM_CONTROL_STOPPED | A stream-control start command has taken effect.
EC_STREAM_ERROR_STILLPLAYING | An error has occurred in a stream. The stream is still playing.
EC_STREAM_ERROR_STOPPED | A stream has stopped because of an error.
EC_USERABORT | The user has terminated playback.
EC_VIDEO_SIZE_CHANGED | The native video size has changed.
EC_WINDOW_DESTROYED | The video renderer was destroyed or removed from the graph.

EC_ACTIVATE

A video window is being activated or deactivated.

Parameters

lParam1
TRUE if the window is activated, or FALSE if the window is deactivated.
lParam2
Pointer to the renderer's IBaseFilter interface.

Default Handling

The filter graph manager sets the focus, through the IResourceManager interface. It does not send the event notification to the application.

Remarks

A video renderer sends this event whenever its window is activated or deactivated (that is, when it receives a WM_ACTIVATEAPP message). Window activation or deactivation can occur because the window has gained or lost focus, or because the renderer has switched between full-screen mode and windowed mode.

This event enables the filter graph manager to allocate resources that depend on window focus, such as audio devices.

EC_BUFFERING_DATA

Event Notification Codes

The graph is buffering data, or has stopped buffering data.

Parameters

lParam1
TRUE if the graph is starting to buffer, or FALSE if the graph has stopped buffering.
lParam2
Zero.

Default Handling

None.

Remarks

A filter can send this event if it needs to buffer data from an external source. (For example, it might be loading data from a network.) The application can use this event to adjust its user interface.

EC_CLOCK_CHANGED

Event Notification Codes

The reference clock has changed.

Parameters

lParam1
Zero.
lParam2
Zero.

Default Handling

None.

Remarks

The filter graph manager sends this event when its IMediaFilter::SetSyncSource method is called.

EC_COMPLETE

Event Notification Codes

All data from a particular stream has been rendered.

Parameters

lParam1
HRESULT value; can be S_OK.
lParam2
Zero, or a pointer to the renderer's IBaseFilter interface.

Default Handling

By default, the filter graph manager does not forward this event to the application. However, after all the streams in the graph report EC_COMPLETE, the filter graph manager posts a separate EC_COMPLETE event to the application.

If default handling is disabled for this event, the application receives all of the EC_COMPLETE events from the renderers.

Remarks

A renderer filter sends this event when it receives an end-of-stream notice. (End-of-stream is signaled through the IPin::EndOfStream method.) The filter sends exactly one EC_COMPLETE event for each stream. The filter must process any pending samples before it sends the event. Stopping a renderer resets any end-of-stream state that was cached.

Filters set the lParam2 parameter to an IBaseFilter pointer. If default handling is enabled, the filter graph manager sets this parameter to zero.

EC_DEVICE_LOST

Event Notification Codes

A Plug and Play device was removed or has become available again.

Parameters

lParam1
Pointer to the IUnknown interface of the filter that represents the device.
lParam2
Zero if the device was removed, or 1 if the device is available again.

Default Handling

None.

Remarks

When the device becomes available again, the previous state of the device filter is no longer valid. The application must rebuild the graph in order to use the device.

EC_DISPLAY_CHANGED

Event Notification Codes

The display mode has changed.

Parameters

lParam1
Pointer to the IPin interface of the video renderer's input pin, or zero.
lParam2
Zero.

Default Handling

The filter graph manager temporarily stops the graph, and then disconnects and reconnects the video renderer. It does not pass the event to the application.

Remarks

Video renderers can send this event in response to a WM_DISPLAYCHANGE message. The WM_DISPLAYCHANGE message indicates that the user has changed the display resolution.

During pin connection, most video renderers pick a format based on the current display mode. If the display mode changes, the video renderer might need to choose another format. By sending this message, the renderer signals to the filter graph manager that it needs to be reconnected. During the reconnection, the renderer can select a new format. If the reconnection fails, the filter graph manager sends an EC_ERRORABORT event to the application.

EC_END_OF_SEGMENT

Event Notification Codes

The end of a segment has been reached.

Parameters

lParam1
Pointer to a REFERENCE_TIME value that specifies the accumulated stream time since the start of the segment.
lParam2
DWORD value indicating the segment number (zero-based).

Default Handling

The filter graph manager checks the number of EC_END_OF_SEGMENT events against the number of EC_SEGMENT_STARTED events. If they match, it forwards the EC_END_OF_SEGMENT event to the application.

Remarks

This event code supports seamless looping. When a call to the IMediaSeeking::SetPositions method includes the AM_SEEKING_Segment flag, the source filter sends this event code instead of calling IPin::EndOfStream.

EC_ERROR_STILLPLAYING

Event Notification Codes

An asynchronous command to run the graph has failed.

Parameters

lParam1
HRESULT value of the operation that failed.
lParam2
Zero.

Default Handling

None.

Remarks

If the filter graph manager issues an asynchronous run command that fails, it sends this event to the application. The graph remains in a running state. The state of the underlying filters is indeterminate. Some filters might be running, others might not.

EC_ERRORABORT

Event Notification Codes

An operation was aborted because of an error.

Parameters

lParam1
HRESULT value of the operation that failed.
lParam2
Zero.

Default Handling

None.

EC_FULLSCREEN_LOST

Event Notification Codes

The video renderer is switching out of full-screen mode.

Parameters

lParam1
Zero.
lParam2
Pointer to the video renderer's IBaseFilter interface, or NULL.

Default Handling

None.

Remarks

When the Full Screen Renderer loses activation, it sends this event. When another video renderer switches out of full-screen mode, the filter graph manager sends this event, in response to an EC_ACTIVATE event from the renderer.

EC_GRAPH_CHANGED

Event Notification Codes

The filter graph has changed.

Parameters

lParam1
Zero.
lParam2
Zero.

Default Handling

None.

Remarks

This event code is intended for debugging. It is not sent for all graph changes.

EC_NEED_RESTART

Event Notification Codes

A filter is requesting that the graph be restarted.

Parameters

lParam1
Zero.
lParam2
Zero.

Default Handling

The filter graph manager pauses and restarts the graph. It does not pass the event to the application.

Remarks

If a filter rejects a sample in the middle of a stream, the upstream pin will stop delivering samples. The filter can restart the stream by sending this event. For example, the audio renderer might lose access to the sound device, because a video window has lost focus. At that point, the audio renderer starts rejecting samples. When it regains access to the sound device, it sends this event to restart the audio stream.

EC_NOTIFY_WINDOW

Event Notification Codes

Notifies a filter of the video renderer's window.

Parameters

lParam1
Handle to the window.
lParam2
Zero.

Default Handling

This event is used internally by DirectShow. The filter graph manager does not pass this event to the application. Applications cannot override the default handling for this event.

Remarks

When a video renderer is connected, it checks whether the upstream output pin supports the IMediaEventSink interface. If so, the renderer sends this event to the upstream filter.

EC_OLE_EVENT

Event Notification Codes

A filter is passing a text string to the application.

Parameters

lParam1
String of type BSTR.
lParam2
String of type BSTR.

Default Handling

None.

Remarks

By convention, the first parameter contains type information (for example, Text) and the second parameter contains the text string.

EC_OPENING_FILE

Event Notification Codes

The graph is opening a file, or has finished opening a file.

Parameters

lParam1
TRUE if the graph is starting to open a file, or FALSE if the graph is no longer opening the file.
lParam2
Zero.

Default Handling

None.

Remarks

A filter can send this event if it spends significant time opening a file. (For example, the file might be located on a network.) The application can use this event to adjust its user interface.

Currently, none of the filters included with DirectShow send this event.

EC_PALETTE_CHANGED

Event Notification Codes

The video palette has changed.

Parameters

lParam1
Zero.
lParam2
Zero.

Default Handling

None.

Remarks

Video renderers send this event if they detect a palette change in the stream.

EC_PAUSED

Event Notification Codes

A pause request has completed.

Parameters

lParam1
HRESULT value that indicates the result of the transition. If the value is S_OK, the filter graph is now in a paused state.
lParam2
Zero.

Default Handling

None.

Remarks

The filter graph manager sends this event when it completes an asynchronous pause command.

EC_QUALITY_CHANGE

Event Notification Codes

The graph is dropping samples, for quality control.

Parameters

lParam1
Zero.
lParam2
Zero.

Default Handling

None.

Remarks

A filter sends this event if it drops samples in response to a quality control message. It sends the event only when it adjusts the quality level, not for each sample that it drops. For more information, see Quality Control Management.

EC_REPAINT

Event Notification Codes

A video renderer requires a repaint.

Parameters

lParam1
Pointer to the IPin interface of the video renderer's input pin, or NULL.
lParam2
Zero.

Default Handling

The lParam1 parameter might specify the video renderer's input pin. If so, the filter graph manager finds the output pin connected to that pin and queries it for the IMediaEventSink interface. If the output pin supports IMediaEventSink, the filter graph manager calls IMediaEventSink::Notify with the EC_REPAINT event code. This gives the upstream filter the opportunity to re-send the last sample.

If lParam1 is NULL, or if the pin does not support IMediaEventSink, or if the Notify method fails, the filter graph manager handles the EC_REPAINT event by itself. Its behavior depends on the state of the graph:

  • Running: Ignores the event. (The renderer will receive the next sample in the stream.)
  • Paused: Seeks the graph to its current location, thereby flushing the filter and re-queueing the data.
  • Stopped: Pauses and stops the graph, thereby re-queueing the data.

By default, the filter graph manager does not pass this event to the application.

Remarks

Video renderers send this message when they receive a WM_PAINT message and have no data to display.

EC_SEGMENT_STARTED

Event Notification Codes

A new segment has started.

Parameters

lParam1
Pointer to a REFERENCE_TIME value that specifies the accumulated stream time since the start of the segment.
lParam2
DWORD value indicating the segment number (zero-based).

Default Handling

This event is not sent to the application.

Remarks

If a filter will send an EC_END_OF_SEGMENT at the end of a segment, it sends this event at the start of the segment. The filter graph manager uses this event notification to compute how many EC_END_OF_SEGMENT notifications it should expect at the end of the segment.

By default, filters do not send EC_END_OF_SEGMENT events at the end of segments, and therefore should not send this event. For more information, see AM_SEEKING_Segment and IMediaSeeking::SetPositions.

EC_SHUTTING_DOWN

Event Notification Codes

The filter graph is shutting down, prior to being destroyed.

Parameters

lParam1
Zero.
lParam2
Zero.

Default Handling

This event is not sent to the application. The filter graph manager sends it to plug-in distributors, to notify them that the graph is shutting down. Applications cannot override the default handling of this event.

EC_SNDDEV_IN_ERROR

Event Notification Codes

An audio device error has occurred on an input pin.

Parameters

lParam1
DWORD value from the SNDDEV_ERR enumerated type, indicating how the device was being accessed when the failure occurred.
lParam2
DWORD value indicating the error returned from the sound device call.

Default Handling

None.

EC_SNDDEV_OUT_ERROR

Event Notification Codes

An audio device error has occurred on an output pin.

Parameters

lParam1
DWORD value from the SNDDEV_ERR enumerated type, indicating how the device was being accessed when the failure occurred.
lParam2
DWORD value indicating the error returned from the sound device call.

Default Handling

None.

EC_STARVATION

Event Notification Codes

A filter is not receiving enough data.

Parameters

lParam1
Zero.
lParam2
Zero.

Default Handling

The event is not sent to the application. If the filter graph is running, the filter graph manager pauses the graph and waits for the pause to complete. Then it runs the graph again. The filter sending the event should not complete its transition to paused until it has enough data to resume. If the filter graph is not running, the filter graph manager ignores this event.

Remarks

A parser or source filter can send this event if too little data is arriving.

EC_STEP_COMPLETE

Event Notification Codes

A filter performing frame stepping has stepped the specified number of frames.

Parameters

lParam1
Zero.
lParam2
Zero.

Default Handling

The filter graph manager pauses the graph and passes the event to the application.

See Also

IVideoFrameStep::Step

EC_STREAM_CONTROL_STARTED

Event Notification Codes

A stream-control start command has taken effect.

Parameters

pSender
Pointer to the IPin interface of the pin that started the stream.
dwCookie
User-defined DWORD value.

Default Handling

None.

Remarks

Filters send this event in response to the IAMStreamControl::StartAt method. This method specifies a reference time for a pin to begin streaming. When streaming does begin, the filter sends this event.

The pSender parameter specifies the pin that executes the start command. Depending on the implementation, it might not be the pin that received the StartAt call.

The dwCookie parameter is specified by the application in the StartAt method. This parameter enables the application to track multiple calls to the method.

EC_STREAM_CONTROL_STOPPED

Event Notification Codes

A stream-control start command has taken effect.

Parameters

pSender
Pointer to the IPin interface of the pin that stopped the stream.
dwCookie
User-defined DWORD value.

Default Handling

None.

Remarks

Filters send this event in response to the IAMStreamControl::StopAt method. This method specifies a reference time for a pin to stop streaming. When streaming does halt, the filter sends this event.

The pSender parameter specifies the pin that executes the stop command. Depending on the implementation, it might not be the pin that received the StopAt call.

The dwCookie parameter is specified by the application in the StopAt method. This parameter enables the application to track multiple calls to the method.

EC_STREAM_ERROR_STILLPLAYING

Event Notification Codes

An error has occurred in a stream. The stream is still playing.

Parameters

lParam1
HRESULT of the operation that failed.
lParam2
DWORD value, generally zero.

Default Handling

None. The application must decide whether to stop the graph.

EC_STREAM_ERROR_STOPPED

Event Notification Codes

A stream has stopped because of an error.

Parameters

lParam1
HRESULT of the operation that failed.
lParam2
DWORD value, generally zero.

Default Handling

None.

EC_USERABORT

Event Notification Codes

The user has terminated playback.

Parameters

lParam1
Zero.
lParam2
Zero.

Default Handling

None. The application must decide whether to stop the graph.

Remarks

This event code signals that the user has terminated normal graph playback. For example, video renderers send this event if the user closes the video window.

After sending this event, the filter should reject all samples and not send any EC_REPAINT events, until the filter stops and is reset.

EC_VIDEO_SIZE_CHANGED

Event Notification Codes

The native video size has changed.

Parameters

lParam1
Low-order WORD specifies the new width, in pixels; high-order WORD specifies the new height, in pixels.
lParam2
Zero.

Default Handling

None.

Remarks

Video renderers send this event if they detect a change in the native video size.

EC_WINDOW_DESTROYED

Event Notification Codes

The video renderer was destroyed or removed from the graph.

Parameters

lParam1
Pointer to the video renderer's IBaseFilter interface.
lParam2
Zero.

Default Handling

The filter graph manager releases this window as the focus, through the IResourceManager interface. It does not send the event notification to the application.

Remarks

The video renderer sends this event when it leaves the filter graph, in its IBaseFilter::JoinFilterGraph method. (Sending the event when the filter is destroyed might be too late, because at that point the filter graph manager might also be destroyed.)

This event enables other filters to acquire resources that depend on window focus, such as audio devices.


Filter Categories

The following table lists the CLSIDs for the filter categories. To enumerate the filters in a given category, pass the corresponding CLSID to the ICreateDevEnum::CreateClassEnumerator method. For more information, see Enumerating Devices and Filters.

These categories also appear in GraphEdit when you choose Insert Filters from the Graph menu. For more information, see Simulating Graph Building with GraphEdit.

CLSID | Description
CLSID_AudioInputDeviceCategory | Audio capture filters.
CLSID_AudioCompressorCategory | Audio compressors, audio encoders.
CLSID_AudioRendererCategory | Audio renderers.
CLSID_LegacyAmFilterCategory | Miscellaneous filters, including decoders.
CLSID_MidiRendererCategory | MIDI Renderers.
CLSID_VideoInputDeviceCategory | Video capture filters.
CLSID_VideoCompressorCategory | Video compressors, video encoders.
CLSID_ActiveMovieCategories | Meta-category that contains the list of categories. GraphEdit uses this CLSID to enumerate over all the categories. An application will typically not use it.


Media Types

Microsoft® DirectShow® uses the AM_MEDIA_TYPE structure to describe media samples. This structure includes GUID members for major type, subtype, and format type, as well as fields specifying other sample features, such as whether the samples are compressed. This article summarizes the major type and subtype options registered by DirectShow. These media types are defined in Uuids.h.

This article contains the following sections.

  • Major Types
  • Audio Subtypes
  • Line 21 Subtypes
  • MPEG-2 Subtypes
  • Stream Subtypes
  • Video Subtypes
  • Analog Video Subtypes

Major Types

The following table describes the major media types.

GUID | Description
MEDIATYPE_AnalogAudio | Analog audio.
MEDIATYPE_AnalogVideo | Analog video.
MEDIATYPE_Audio | Audio.
MEDIATYPE_AUXLine21Data | Line 21 data. Used by closed captions.
MEDIATYPE_File | File. Used by closed captions.
MEDIATYPE_Interleaved | Interleaved. Used by Digital Video (DV).
MEDIATYPE_LMRT | Obsolete. Do not use.
MEDIATYPE_Midi | MIDI format.
MEDIATYPE_MPEG2_PES | MPEG-2. Used by DVD.
MEDIATYPE_ScriptCommand | Data is a script command, used by closed captions.
MEDIATYPE_Stream | Byte stream with no time stamps.
MEDIATYPE_Text | Text.
MEDIATYPE_Timecode | Timecode data.
MEDIATYPE_URL_STREAM | Obsolete. Do not use.
MEDIATYPE_Video | Video.

Audio Subtypes

The following table describes the audio media subtypes.

GUID | Description
MEDIASUBTYPE_PCMAudio | PCM audio
MEDIASUBTYPE_PCMAudioObsolete | Obsolete. Do not use.
MEDIASUBTYPE_MPEG1Packet | MPEG1 Audio packet
MEDIASUBTYPE_MPEG1Payload | MPEG1 Audio Payload

The wFormatTag field in the WAVEFORMATEX structure specifies the audio format type. The format type is generally FORMAT_WaveFormatEx. Media samples are generally whole number of samples as specified in the wBitsPerSample field in the WAVEFORMATEX structure. This is not necessarily true for MPEG audio samples that can come from packetized streams and are therefore not necessarily packaged on sample / frame boundaries. For MPEG audio the time stamp in a media sample is the time stamp for the first frame whose first byte is contained in the media sample.

Media subtypes are defined for each wFormatTag as follows:

  • The Data1 subfield of the Media Subtype is the same as the wFormatTag value.
  • The Data 2 field is 0.
  • The Data 3 field is 0x0010.
  • The Data 4 field is 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71.

Thus, for PCM audio the subtype GUID would be:

{00000001-0000-0010-8000-00AA00389B71}

Older filters may use GUID_NULL as the subtype so this should be checked for. However, registration of a filter with the explicit subtype greatly improves the speed of graph loading, especially when the given filter is not required. The CreateAudioMediaType function can be used to create an AM_MEDIA_TYPE structure from a WAVEFORMATEX Structure.

Line 21 Subtypes

The following table describes the line 21 closed captioning media subtypes.

GUID | Description
MEDIASUBTYPE_Line21_BytePair | Line 21 data as byte pairs
MEDIASUBTYPE_Line21_GOPPacket | Line 21 data in DVD GOP Packet
MEDIASUBTYPE_Line21_VBIRawData | Line 21 data in raw VBI format

MPEG-2 Subtypes

The following table describes the MPEG-2 media subtypes.

GUID | Description
MEDIASUBTYPE_DVD_SUBPICTURE | Subpicture data
MEDIASUBTYPE_DOLBY_AC3 | Dolby data
MEDIASUBTYPE_MPEG2_AUDIO | MPEG-2 audio data
MEDIASUBTYPE_DVD_LPCM_AUDIO | DVD audio data
MEDIASUBTYPE_MPEG2_TRANSPORT | MPEG-2 transport stream
MEDIASUBTYPE_MPEG2_PROGRAM | MPEG-2 program stream

Stream Subtypes

The following table describes the stream media subtypes.

GUID | Description
MEDIASUBTYPE_AIFF | Data from AIFF file
MEDIASUBTYPE_Asf | Advanced Streaming Format (ASF)
MEDIASUBTYPE_Avi | Data from AVI file
MEDIASUBTYPE_AU | Data from AU file
MEDIASUBTYPE_DssAudio | Dss Audio
MEDIASUBTYPE_DssVideo | Dss Video
MEDIASUBTYPE_MPEG1Audio | MPEG audio
MEDIASUBTYPE_MPEG1System | MPEG system
MEDIASUBTYPE_MPEG1SystemStream | Obsolete. Do not use.
MEDIASUBTYPE_MPEG1Video | MPEG video
MEDIASUBTYPE_MPEG1VideoCD | MPEG video CD
MEDIASUBTYPE_WAVE | Data from WAV file

Time stamps are byte positions * 10000000 (notionally 1 byte per second) rather than real times.

Video Subtypes

The following table describes the video media subtypes.

GUID | Description
MEDIASUBTYPE_YVU9 | Standard YVU9 format uncompressed data. A planar YUV format. A Y sample at every pixel, a U and V sample at every fourth pixel horizontally on each line; a Y sample on every vertical line, a U and V sample at every fourth vertical line. 9 bits per pixel.
MEDIASUBTYPE_Y411 | YUV 411 format data. Same as Y41P.
MEDIASUBTYPE_Y41P | Y41P format data. A packed YUV format. A Y sample at every pixel, a U and V sample at every fourth pixel horizontally on each line; every vertical line sampled. Byte ordering (lowest first) is U0, Y0, V0, Y1, U4, Y2, V4, Y3, Y4, Y5, Y6, Y7, where the suffix 0 is the leftmost pixel and increasing numbers are pixels increasing left to right. Each 12-byte block is 8 image pixels.
MEDIASUBTYPE_YUY2 | YUY2 format data. Same as UYVY but with different pixel ordering. Byte ordering (lowest first) is Y0, U0, Y1, V0, Y2, U2, Y3, V2, Y4, U4, Y5, V4, where the suffix 0 is the leftmost pixel and increasing numbers are pixels increasing left to right. Each 4-byte block is 2 image pixels.
MEDIASUBTYPE_YVYU | YVYU format data. A packed YUV format. Same as UYVY but with different pixel ordering. Byte ordering (lowest first) is Y0, V0, Y1, U0, Y2, V2, Y3, U2, Y4, V4, Y5, U4, where the suffix 0 is the leftmost pixel and increasing numbers are pixels increasing left to right. Each 4-byte block is 2 image pixels.
MEDIASUBTYPE_UYVY | UYVY format data. A packed YUV format. A Y sample at every pixel, a U and V sample at every second pixel horizontally on each line; every vertical line sampled. Probably the most popular of the various YUV 4:2:2 formats. Byte ordering (lowest first) is U0, Y0, V0, Y1, U2, Y2, V2, Y3, U4, Y4, V4, Y5, where the suffix 0 is the leftmost pixel and increasing numbers are pixels increasing left to right. Each 4-byte block is 2 image pixels.
MEDIASUBTYPE_Y211 | YUV 211 format data. A packed YUV format. A Y sample at every second pixel, a U and V sample at every fourth pixel horizontally on each line; every vertical line sampled. Byte ordering (lowest first) is Y0, U0, Y2, V0, Y4, U4, Y6, V4, Y8, U8, Y10, V8, where the suffix 0 is the leftmost pixel and increasing numbers are pixels increasing left to right. Each 4-byte block is 4 image pixels.
MEDIASUBTYPE_CLJR | Cirrus Logic Jr YUV 411 format with less than 8 bits per Y, U, and V sample. Cinepak can produce it and Cirrus 5440 can produce an overlay with it. A Y sample at every pixel, a U and V sample at every fourth pixel horizontally on each line; every vertical line sampled.
MEDIASUBTYPE_IF09 | Indeo produced YVU9 format with additional information about differences from the last frame. 9.5 bits per pixel but reported as 9.
MEDIASUBTYPE_CPLA | Cinepak UYVY format.
MEDIASUBTYPE_MJPG | Motion JPEG (MJPG) compressed video.
MEDIASUBTYPE_TVMJ | TrueVision MJPG format.
MEDIASUBTYPE_WAKE | MJPG format produced by some cards.
MEDIASUBTYPE_CFCC | MJPG format produced by some cards.
MEDIASUBTYPE_IJPG | Intergraph JPEG format.
MEDIASUBTYPE_Plum | Plum MJPG format.
MEDIASUBTYPE_RGB1 | RGB, 1 bit per pixel. Palettized.
MEDIASUBTYPE_RGB4 | RGB, 4 bits per pixel. Palettized.
MEDIASUBTYPE_RGB8 | RGB, 8 bits per pixel. Palettized.
MEDIASUBTYPE_RGB565 | 565 format of RGB, 16 bits per pixel. Uncompressed RGB samples.
MEDIASUBTYPE_RGB555 | 555 format of RGB, 16 bits per pixel. Uncompressed RGB samples.
MEDIASUBTYPE_RGB24 | RGB, 24 bits per pixel. Uncompressed RGB samples.
MEDIASUBTYPE_RGB32 | RGB, 32 bits per pixel. Uncompressed RGB samples. Do not use the alpha bits with this media type. (Compare MEDIASUBTYPE_ARGB32.)
MEDIASUBTYPE_ARGB32 | ARGB, 32 bits per pixel. Uncompressed RGB samples with valid alpha bits.
MEDIASUBTYPE_Overlay | Video delivered using hardware overlay.
MEDIASUBTYPE_QTMovie | Apple® QuickTime® compression.
MEDIASUBTYPE_QTRpza | QuickTime RPZA compressed data.
MEDIASUBTYPE_QTSmc | QuickTime SMC compressed data.
MEDIASUBTYPE_QTRle | QuickTime RLE compressed data.
MEDIASUBTYPE_QTJpeg | QuickTime JPEG compressed data.
MEDIASUBTYPE_dvsd | Standard DV format.
MEDIASUBTYPE_dvhd | High Definition DV format.
MEDIASUBTYPE_dvsl | Long Play DV format.
MEDIASUBTYPE_MPEG1Packet | MPEG1 Video Packet.
MEDIASUBTYPE_MPEG1Payload | MPEG1 Video Payload.
MEDIASUBTYPE_VideoPort | Video port data, used with DVD.
MEDIASUBTYPE_VPVideo | Video port video data.
MEDIASUBTYPE_VPVBI | Video port vertical blanking interval (VBI) data.

Analog Video Subtypes

The following analog video formats were introduced in Microsoft® ActiveMovie® 1.0 but are now obsolete. Instead, the IAMAnalogVideoDecoder and IAMTVTuner interfaces use the AnalogVideoStandard enumeration.
GUID | Description
MEDIASUBTYPE_AnalogVideo_NTSC_M | (M) NSTC
MEDIASUBTYPE_AnalogVideo_PAL_B | (B) PAL
MEDIASUBTYPE_AnalogVideo_PAL_D | (D) PAL
MEDIASUBTYPE_AnalogVideo_PAL_G | (G) PAL
MEDIASUBTYPE_AnalogVideo_PAL_H | (H) PAL
MEDIASUBTYPE_AnalogVideo_PAL_I | (I) PAL
MEDIASUBTYPE_AnalogVideo_PAL_M | (M) PAL
MEDIASUBTYPE_AnalogVideo_PAL_N | (N) PAL
MEDIASUBTYPE_AnalogVideo_SECAM_B | (B) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_D | (D) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_G | (G) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_H | (H) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_K | (K) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_K1 | (K1) SECAM
MEDIASUBTYPE_AnalogVideo_SECAM_L | (L) SECAM


MPEG-1 Media Types

The following information summarizes the media types used by Microsoft® DirectShow® for MPEG data.

MPEG-1 System Stream
Major type: MEDIATYPE_Stream

Minor type: MEDIASUBTYPE_MPEG1System

Format: None

Sample contents: BYTE stream; no alignment

MPEG-1 System Stream off Video CD
Major type: MEDIATYPE_Stream

Minor type: MEDIASUBTYPE_MPEG1VideoCD

Format: None

Sample contents: BYTE stream; no alignment

MPEG-1 Audio Packet
Major type: MEDIATYPE_Audio

Minor type: MEDIASUBTYPE_MPEG1Packet

Format: MPEG1WAVEFORMAT

Sample contents: Single MPEG-1 packet including packet header

MPEG-1 Audio payload
Major type: MEDIATYPE_Audio

Minor type: MEDIASUBTYPE_MPEG1Payload

Format: MPEG1WAVEFORMAT

Sample contents: Byte-aligned MPEG-1 audio data

MPEG-1 Video Packet
Major type: MEDIATYPE_Video

Minor type: MEDIASUBTYPE_MPEG1Packet

Format: VIDEOINFO + Video sequence header

Sample contents: Single MPEG-1 packet including packet header

MPEG-1 Video payload
Major type: MEDIATYPE_Video

Minor type: MEDIASUBTYPE_MPEG1Payload

Format: VIDEOINFO + Video sequence header

Sample contents: Byte-aligned MPEG-1 video data

MPEG-1 Native Video Stream
Major type: MEDIATYPE_Stream

Minor type: MEDIASUBTYPE_ MPEG1Video

Format: None

Sample contents: Array of video stream bytes (no system layer)

MPEG-1 Native Audio Stream
Major type: MEDIATYPE_Stream

Minor type: MEDIASUBTYPE_ MPEG1Audio

Format: None

Sample contents: Array of audio stream bytes (no system layer)

The various filters will support pins as follows:

Filter | Direction | Media type(s)
System layer splitter | Input | MPEG-1 system stream MPEG-1 system stream off Video CD
System layer splitter | Output | MPEG-1 Audio packet or MPEG-1 Audio data
System layer splitter | Output | MPEG-1 Video packet or MPEG-1 Video data
Software Audio CODEC | Input | MPEG-1 Audio data or MPEG-1 Audio packet
Software Video CODEC | Input | MPEG-1 Video data or MPEG-1 Video packet
Software Audio CODEC | Output | PCM audio mono or stereo, input sampling rate, input sampling rate divided by 2 or input sampling rate divided by 4
Software Video CODEC | Output | Uncompressed video in Y41P, YUY2, UYVY, RGB24, RGB32, RGB565, RGB555 and RGB8 formats

MPEG-1 Video packet and payload media types contain a complete sequence header so that data can be played from the middle of a file without needing a sequence header to initialize the video playback.

The video sequence header is appended to the video data type for MPEG video so that play can begin from the middle of a stream. The length of this field is up to 140 bytes (it includes the sequence header start code—0x000001B3—at the start and any quantization matrices found in the first sequence header encountered).


MPEG-2 Media Types

Microsoft DirectX 8.0

MPEG-2 Splitter Filter Media Types

The MPEG-2 Splitter filter currently supports audio and video. Dolby AC-3 is supported as a substream as defined by DVD. MPEG-2 audio is also supported.

For video the type is as follows:

 | PES output | Payload output
Type | MEDIATYPE_MPEG2_PES | MEDIATYPE_Video
Subtype | MEDIASUBTYPE_MPEG2_VIDEO | MEDIASUBTYPE_MPEG2_VIDEO
Format | FORMAT_MPEG2Video | FORMAT_MPEG2Video
Format block | MPEG2VIDEOINFO | MPEG2VIDEOINFO

For AC-3 audio the type is as follows:

 | PES output | Payload output
Type | MEDIATYPE_MPEG2_PES | MEDIATYPE_Audio
Subtype | MEDIASUBTYPE_DOLBY_AC3 | MEDIASUBTYPE_DOLBY_AC3
Format | FORMAT_WaveFormatEx | FORMAT_WaveFormatEx
Format block | WAVEFORMATEX | WAVEFORMATEX

The WAVEFORMATEX structure's wFormatTag member for AC-3 is currently WAVE_FORMAT_UNKNOWN, but it might change so you should check for it.

For MPEG-2 the type is as follows:

 | PES output | Payload output
Type | MEDIATYPE_MPEG2_PES | MEDIATYPE_Audio
Subtype | MEDIASUBTYE_MPEG2_AUDIO | MEDIASUBTYPE_MPEG2_AUDIO
Format | FORMAT_WaveFormatEx | FORMAT_WaveFormatEx
Format block | WAVEFORMATEX | WAVEFORMATEX

The WAVEFORMATEX structure's wFormatTag member for MPEG-2 Audio is currently WAVE_FORMAT_UNKNOWN, but it might change so you should check for it.

The MPEG-2 Splitter assumes that streams D0-DF are used for the multichannel extension stream, as they are for DVD MPEG-2 audio, so, whenever stream Cx is selected, the splitter forwards the packets for stream Dx as well.

For LPCM audio the type is as follows:

 | PES output | Payload output
Type | MEDIATYPE_MPEG2_PES | MEDIATYPE_Audio
Subtype | MEDIASUBTYPE_DVD_LPCM_AUDIO | MEDIASUBTYPE_DVD_LPCM_AUDIO
Format | FORMAT_WaveFormatEx | FORMAT_WaveFormatEx
Format block | WAVEFORMATEX | WAVEFORMATEX

The WAVEFORMATEX structure's wFormatTag member for LPCM audio is currently WAVE_FORMAT_UNKNOWN, but it might change so you should check for it.


Merit

Defines the order in which the filter graph manager tries filters during graph building. (See Building the Filter Graph.)

Syntax

enum
{
    MERIT_PREFERRED     = 0x800000,
    MERIT_NORMAL        = 0x600000,
    MERIT_UNLIKELY      = 0x400000,
    MERIT_DO_NOT_USE    = 0x200000,
    MERIT_SW_COMPRESSOR = 0x100000,
    MERIT_HW_COMPRESSOR = 0x100050
};

Remarks

Each filter is registered with a merit value. When the filter graph manager builds a graph, it enumerates all the filters registered with the correct media type. Then it tries them in order of merit, from highest to lowest. (It uses additional criteria to choose between filters with equal merit.) It never tries filters with a merit value less than or equal to MERIT_DO_NOT_USE.

A filter that should never be considered for ordinary playback should have a merit of MERIT_DO_NOT_USE or less. Filters can be registered with intermediate values not defined by this enumeration, such as MERIT_NORMAL + 1.


Time Formats

Microsoft DirectX 8.0

Time Format GUIDs

The following globally unique identifiers (GUIDs) define different time formats.

Declaration: Uuids.h.

GUID | Description
TIME_FORMAT_NONE | No format.
TIME_FORMAT_FRAME | Video frames.
TIME_FORMAT_SAMPLE | Samples in the stream.
TIME_FORMAT_FIELD | Interlaced video fields.
TIME_FORMAT_BYTE | Byte offset within the stream.
TIME_FORMAT_MEDIA_TIME | Media time, in 100-nanosecond units.

See Also

IMediaSeeking


Functions

Microsoft® DirectShow® provides the following function:

AMGetErrorText Retrieves the error message text for a given message ID.

AMGetErrorText

Functions

Retrieves the error message for a given return code, using the current language setting.

This function converts HRESULT return codes to error messages. The constant MAX_ERROR_TEXT_LEN specifies the maximum number of characters in an error message.

Note To use this function, your application must link to the library file Quartz.lib.

Syntax

DWORD AMGetErrorText(
    HRESULT hr,
    TCHAR *pBuffer,
    DWORD MaxLen
);

Parameters

hr
HRESULT value.
pBuffer
Pointer to a character buffer that receives the error message.
MaxLen
Number of characters in pBuffer.

Return Value

Returns the number of characters returned in the buffer, or zero if an error occurred.


MSWebDVD Reference Pages

The Microsoft® MSWebDVD ActiveX® control can be used to create a script-based DVD application. It exposes the following objects and events to an application.

  • MSWebDVD
  • MSDVDAdm
  • DVDRect
  • MSWebDVD Events


MSWebDVD Object

The methods, properties, and events of the MSWebDVD object enable an application to control all aspects of DVD-Video navigation and playback, and to retrieve information from the disc. The MSWebDVD object does not perform the actual navigation work; rather, it passes the commands to the DVD Navigator filter, a Microsoft® DirectShow® component that reads DVD-Video discs.

The MSWebDVD methods and properties act on the current state of the DVD Navigator or the information on a disc, or both. To store and retrieve various types of application-specific information in the registry, such as user preferences for parental levels and default language, use the methods of the MSDVDAdm object. Use the DVDAdm property to access this object.

See Also

MSWebDVD Events
Writing a Script-Based DVD Player Application

Methods and Properties by Category

Playback
CanStep | Determines whether the MPEG-2 decoder on the local system can perform frame stepping.
Eject | Ejects or inserts a disc from or into the drive.
FramesPerSecond | Retrieves the video frame rate for the current DVD title.
Pause | Pauses playback at the current location.
Play | Plays the current DVD title.
PlayAtTime | Starts playback in the current title at the specified time.
PlayAtTimeInTitle | Starts playback at the specified time within the specified title.
PlayBackwards | Starts backward playback from the current location at the specified speed.
PlayChapter | Starts playback from the specified chapter in the current title.
PlayChapterInTitle | Plays the specified chapter in the specified title.
PlayChaptersAutoStop | Starts playback at the specified chapter in the specified title, for the number of chapters specified.
PlayForwards | Starts forward playback from the current location at the specified speed.
PlayNextChapter | Starts playback from the next chapter in the current title.
PlayPeriodInTitleAutoStop | Starts playback at the specified time in the specified title until the specified stop time.
PlayPrevChapter | Starts playback from the previous chapter in the current title.
PlayTitle | Starts playback at the beginning of the specified title.
ReplayChapter | Starts playback at the beginning of the current chapter.
Resume | Resumes playback after a menu has been displayed.
StillOff | Resumes playback, canceling still mode.
Step | Advances the DVD-Video stream by the specified number of frames.
Stop | Stops playback.
Menus
ActivateAtPosition | Activates the menu button at the specified position.
ActivateButton | Activates the selected menu button.
ButtonsAvailable | Retrieves the total number of buttons on the current menu.
CurrentButton | Retrieves the number of the selected button.
DefaultMenuLanguage | Retrieves the default menu language from the disc.
GetButtonAtPosition | Retrieves the number of the button at the specified coordinates without selecting or activating it.
GetButtonRect | Retrieves the rectangle for the specified button, in window coordinates.
ReturnFromSubmenu | Returns display from a submenu to its parent menu, or to the current title if the menu is a top-level menu.
SelectAndActivateButton | Selects and activates the specified button.
SelectAtPosition | Selects the menu button at the specified position.
SelectLeftButton | Selects the left directional button from the displayed menu.
SelectLowerButton | Selects the lower directional button from the displayed menu.
SelectRightButton | Selects the right directional button from the displayed menu.
SelectUpperButton | Selects the upper directional button from the displayed menu.
ShowMenu | Displays the specified menu on the screen.
Audio Stream
AudioStreamsAvailable | Retrieves the number of audio streams available in the current title.
Balance | Sets or retrieves the speaker balance for the audio stream output.
CurrentAudioStream | Sets or retrieves the number of the enabled audio stream.
DefaultAudioLanguage | Retrieves the default audio language from the disc.
DefaultAudioLanguageExt | Retrieves the default audio language extension from the disc.
GetAudioLanguage | Retrieves a string indicating which language is available on the specified audio stream.
IsAudioStreamEnabled | Retrieves a value indicating whether the specified audio stream is enabled in the current title.
Mute | Turns the audio stream output on or off.
SelectDefaultAudioLanguage | Sets the current default audio language in the DVD Navigator.
Volume | Sets or retrieves the audio volume level.
Subpicture Stream
CurrentSubpictureStream | Retrieves the selected subpicture stream.
DefaultSubpictureLanguage | Retrieves the default subpicture language from the disc.
DefaultSubpictureLanguageExt | Retrieves the default subpicture language extension from the disc.
GetSubpictureLanguage | Retrieves the language for the specified subpicture stream.
IsSubpictureStreamEnabled | Retrieves a value indicating whether the specified subpicture stream is enabled in the current title.
PreferredSubpictureStream | Sets or retrieves the user's preferred subpicture stream for the current viewing session.
SelectDefaultSubpictureLanguage | Sets the current default subpicture language in the DVD Navigator.
SubpictureOn | Sets or retrieves the current subpicture state (on or off).
SubpictureStreamsAvailable | Retrieves the number of subpicture streams available in the current title.
Video Rectangle
AspectRatio | Retrieves the aspect ratio of the current video stream as authored on the disc.
BackColor | Sets or retrieves the color of the bars that appear around the edges of the video rectangle when the aspect ratio of the native video is not the same as that of the object's display area.
Capture | Captures a still image from the video frame when the MSWebDVD object is in windowless mode.
FullScreenMode | Sets or retrieves a value indicating whether the display is in full-screen mode.
GetClipVideoRect | Retrieves the clipping rectangle defined for the video display.
GetVideoSize | Retrieves the native video dimensions.
SetClipVideoRect | Sets the clipping rectangle occupied by the video display.
Zoom | Zooms the video display in or out, centered on a given set of screen coordinates.
Closed Captioning
CCActive | Sets or retrieves the current status of closed captioning.
ColorKey | Sets or retrieves the color key used in closed captioning.
CurrentCCService | Sets or retrieves the current closed-captioned service.
Angle Blocks
AnglesAvailable | Retrieves the number of angles available.
CurrentAngle | Sets or retrieves the current angle in an angle block.
Karaoke Audio
GetKaraokeChannelAssignment | Retrieves a value that indicates how the karaoke channels are assigned to the left and right speakers.
GetKaraokeChannelContent | Retrieves a value that indicates the type of content in the specified karaoke channel in the specified stream.
KaraokeAudioPresentationMode | Sets or retrieves the right-left speaker mix for the auxiliary karaoke channels.
Text Strings
GetDVDTextLanguageLCID | Retrieves the locale identifier (LCID) for the specified text string block.
GetDVDTextNumberOfLanguages | Retrieves the number of text languages available in the current DVD directory.
GetDVDTextNumberOfStrings | Retrieves the number of text strings available for the specified language.
GetDVDTextString | Retrieves the specified text string from the disc.
GetDVDTextStringType | Retrieves a value that indicates the type of information contained in the specified DVD text string.
GetLangFromLangID | Retrieves a human-readable string when given a primary language identifier (ID).
Parental Management
AcceptParentalLevelChange | Instructs the DVD Navigator to accept or reject the new temporary parental management level.
GetPlayerParentalCountry | Retrieves the current country as set in the DVD Navigator.
GetPlayerParentalLevel | Retrieves the parental management level set in the DVD Navigator.
GetTitleParentalLevels | Retrieves the parental management levels for the specified title.
NotifyParentalLevelChange | Enables or disables the event handling for temporary parental management level commands.
SelectParentalCountry | Sets the specified parental country for subsequent playback.
SelectParentalLevel | Sets the specified parental level for subsequent playback.
Disc Information
CurrentChapter | Retrieves the number of the chapter currently playing.
CurrentDiscSide | Retrieves the current side of the DVD.
CurrentDomain | Retrieves the DVD domain that the DVD Navigator is in.
CurrentTime | Retrieves the current playback time.
CurrentTitle | Retrieves the number of the title currently playing.
CurrentVolume | Retrieves the volume number for the current root directory.
DVDDirectory | Retrieves or sets the root directory of the current DVD volume.
DVDTimeCode2bstr | Retrieves a String indicating the current time on the disc.
DVDUniqueID | Retrieves a system-generated number that uniquely identifies the current DVD.
GetNumberOfChapters | Retrieves the number of chapters in the specified title.
TitlesAvailable | Retrieves the number of titles available on the DVD.
TotalTitleTime | Retrieves the total playback time for the current title.
UOPValid | Retrieves a value that indicates whether the specified user operation is currently valid.
VolumesAvailable | Retrieves a value specifying the number of volumes in the disc set.
Object Initialization and Control
DisableAutoMouseProcessing | Enables or disables the object's mouse-processing functionality.
DVDAdm | Provides access to the MSDVDAdm object containing methods and properties for saving application and user information.
EnableResetOnStop | Sets or retrieves a value that determines how play will resume when the filter graph transitions out of a stopped state.
PlayState | Retrieves the current play state.
ReadyState | Retrieves the ReadyState of the MSWebDVD object.
RegionChange | Displays a system dialog box that enables the user to change the region associated with the DVD drive.
Render | Initializes the DVD filter graph.
WindowlessActivation | Initializes the MSWebDVD object at design time for either windowed or windowless mode.
Bookmarks
DeleteBookmark | Deletes the current bookmark.
RestoreBookmark | Moves the DVD Navigator to the point on the DVD as specified in the current bookmark, with all audio, video and subpicture settings restored.
SaveBookmark | Saves the current disc position and state of the DVD Navigator to disc so that the user can return to the same place later.
Cursors and ToolTips
CursorType | Sets or retrieves the current cursor type.
GetDelayTime | Retrieves the delay time for the ToolTip associated with the MSWebDVD object.
SetDelayTime | Sets the delay time for the ToolTip associated with the MSWebDVD object.
ShowCursor | Makes the mouse pointer visible when the DVD Navigator is in full-screen mode.
ToolTip | Sets the text for the ToolTip that will appear when the mouse pointer is over the MSWebDVD video rectangle.
ToolTipMaxWidth | Sets or retrieves the maximum width for the ToolTip associated with the MSWebDVD object.
GPRMs and SPRMs
GetGPRM | Retrieves the specified general parameter register.
GetSPRM | Retrieves the specified system parameter register.
SetGPRM | Sets the specified general parameter register to the specified value.

AcceptParentalLevelChange Method

MSWebDVD Object

Accepts or rejects the new temporary parental management level.

Syntax

MSWebDVD.AcceptParentalLevelChange(bAccept);

Parameters

bAccept Boolean value specifying whether to accept or reject the new parental level; (true means to accept it.

Return Value

No return value.

Remarks

Call this method in response to an EC_DVD_PARENTAL_LEVEL_CHANGE event notification to specify whether the DVD Navigator should play the content with the new parental level, or branch to where the disc specifies if the new level is rejected.

See Also

Enforcing Parental Management Levels, GetPlayerParentalCountry, GetPlayerParentalLevel, GetTitleParentalLevels, NotifyParentalLevelChange, SelectParentalCountry, SelectParentalLevel

ActivateAtPosition Method

MSWebDVD Object

Activates the menu button under the current mouse pointer position.

Syntax

MSWebDVD.ActivateAtPosition(xPos, yPos);

Parameters

xPos | Integer value specifying the mouse pointer's x-coordinate.
xPos | Integer value specifying the mouse pointer's y-coordinate.

Return Value

No return value.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

See Also

ButtonsAvailable, CurrentButton, GetButtonAtPosition, GetButtonRect, SelectAndActivateButton, SelectAtPosition

ActivateButton Method

MSWebDVD Object

Activates the selected menu button.

Syntax

MSWebDVD.ActivateButton();

Return Value

No return value.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

Use this method to activate a button that has been selected through the SelectLeftButton, SelectLowerButton, SelectUpperButton, or SelectRightButton method.

AnglesAvailable Property

MSWebDVD Object

Retrieves the number of angles currently available.

Syntax

[ iAngles = ] MSWebDVD.AnglesAvailable

Possible Values

iAngles Integer value from 1 through 9 representing the number of angles currently available. If iAngles = 1, there is no angle block at the current location.

This property is read-only with no default value.

Remarks

An angle block is a video segment that was shot from more than one camera angle. There can be up to nine angles in an angle block, numbered from 1 through 9. When the DVD Navigator first enters an angle block, it sends your application an EC_DVD_ANGLES_AVAILABLE event notification with the number of angles in lParam1. A disc can be authored to automatically show a menu for available angles when it enters an angle block, but generally an application must determine the number of angles available and offer the user a way to select one.

See Also

CurrentAngle

AspectRatio Property

MSWebDVD Object

Retrieves the aspect ratio of the current video stream as authored on the disc.

Syntax

[ nAspectRatio = ] MSWebDVD.AspectRatio

Possible Values

nAspectRatio Number value representing the aspect ratio of the current video stream as authored on the disc (1.33 for a 4:3 aspect ratio or 1.78 for a 16:9 aspect ratio).

This property is read-only with no default value.

AudioStreamsAvailable Property

MSWebDVD Object

Retrieves the number of audio streams available in the current title.

Syntax

[ iStreams = ] MSWebDVD.AudioStreamsAvailable

Possible Values

iStreams Integer value from 1 through 8 representing the number of audio streams available in the current title.
This property is read-only with no default value.

Remarks

The primary use of multiple audio streams is to provide movie soundtracks in more than one language. Typically, not every title on a disc has all audio streams enabled. For example, the feature movie might have soundtracks in three different languages, but the trailers might have only an English soundtrack. Before a user can select a stream, the application must determine which streams are available within the current title. Note that particular streams are identified by an index from zero through 7.

Discs generally present a menu showing the available soundtracks, enabling the user to select the audio stream to enable.

See Also

GetAudioLanguage

BackColor Property

MSWebDVD Object

Sets or retrieves the color of the bars that appear around the edges of the video rectangle when the aspect ratio of the native video is not the same as that of the object's display area.

Syntax

[ iBackColor = ] MSWebDVD.BackColor

Possible Values

iBackColor Integer value representing the RGB values of the back color.

This property is read/write with a default value of off-black (0x100010).

Balance Property

MSWebDVD Object

Sets or retrieves the speaker balance for the audio stream output.

Syntax

[ iBalance = ] MSWebDVD.Balance

Possible Values

iBalance Integer value representing the balance levels. The allowable input range is -10,000 to 10,000. A value of 0 sets a neutral balance, that is both left and right speakers are given the same amplitude audio signal.

This property is read/write with a default value of 0, meaning that both speakers receive equivalent audio signals. As with the Volume property, units correspond to .01 decibels (multiplied by 1 when iBalance is a positive value). For example, a value of 1000 indicates 10 dB on the right channel and 90 dB on the left channel.

ButtonsAvailable Property

MSWebDVD Object

Retrieves the total number of buttons on the current menu.

Syntax

[ iButtons = ] MSWebDVD.ButtonsAvailable

Possible Values

iButtons Integer value representing the number of buttons.

This property is read-only with no default value.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

Call this method to retrieve the upper limit for the range of valid button numbers.

See Also

CurrentButton, GetButtonAtPosition, GetButtonRect, SelectAndActivateButton, SelectAtPosition

CanStep Method

MSWebDVD Object

Determines whether the MPEG-2 decoder on the local system can perform frame stepping.

Syntax

[ bCanStep = ] MSWebDVD.CanStep(bBackwards);

Parameters

bBackwards Boolean value specifying whether we are asking if the decoder can step backward. Default is false, meaning forward frame stepping.

Return Value

Returns a Boolean value indicating whether the decoder can step in the specified direction; true means it can.

Remarks

Not all hardware MPEG-2 decoders support the new frame stepping capabilities in DirectShow® 8.0. This method queries the decoder for its frame stepping capabilities. If the decoder can perform frame stepping, an application can use the Step method to step through frames. This method will always return true if a software decoder is being used.

Capture Method

MSWebDVD Object

Captures a still image from the video frame when the MSWebDVD object is in windowless mode.

Syntax

MSWebDVD.Capture();

Remarks

This method captures the current frame from the DVD-Video image and pastes it into a window from which the user can save or edit the image. The MSWebDVD object must be in windowless mode for this method to succeed.

CCActive Property

MSWebDVD Object

Sets or retrieves the current status of closed captioning.

Syntax

[ bCCActive = ] MSWebDVD.CCActive

Possible Values

bCCActive Boolean value indicating whether closed captioning is turned on.

This property is read/write with a default value of false.

See Also

CurrentCCService

ColorKey Property

MSWebDVD Object

Sets or retrieves the color key used in closed captioning.

Syntax

[ iColorKey = ] MSWebDVD.ColorKey

Possible Values

iColorKey Integer value representing the color to use as a transparent background for closed-captioned text. The default value in 256 colors is magenta, and off-black in any other color depth.

This property is read/write.

Remarks

This property applies only to the closed-captions, if any exist, not to the subpicture stream.

CurrentAngle Property

MSWebDVD Object

Sets or retrieves the current angle in an angle block.

Syntax

[ iCurAngle = ] MSWebDVD.CurrentAngle

Possible Values

iCurAngle Integer value representing the angle. Must be a value from 1 through 9.

This property is read/write with no default value.

See Also

AnglesAvailable

CurrentAudioStream Property

MSWebDVD Object

Sets or retrieves the number of the enabled audio stream.

Syntax

[ iStream = ] MSWebDVD.CurrentAudioStream

Possible Values

iStream Integer value from 0 through 7 indicating the current audio stream.

This property is read/write with no default value.

Remarks

Before attempting to set a new audio stream, call IsAudioStreamEnabled to verify that the stream is available.

See Also

AudioStreamsAvailable

CurrentButton Property

MSWebDVD Object

Retrieves the number of the selected menu button.

Syntax

[ iButton = ] MSWebDVD.CurrentButton

Possible Values

iButton Integer value representing the button.

This property is read-only with no default value.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

See Also

ActivateButton, ButtonsAvailable, CurrentButton, GetButtonAtPosition, GetButtonRect, SelectAndActivateButton, SelectAtPosition

CurrentCCService Property

MSWebDVD Object

Sets or retrieves the current closed captioning service.

Syntax

[ iService = ] MSWebDVD.CurrentCCService

Possible Values

iService Integer value indicating the type of closed captioning service enabled.

This property is read/write with a default value of 0x0.

This table lists the possible values for iService.
CC service type | Value
No current service. | 0x0
True captioning, first field. Default service. | 0x1
Captioning for secondary language, second field. Generally not used. | 0x2

See Also

CCActive

CurrentChapter Property

MSWebDVD Object

Retrieves the number of the chapter currently playing.

Syntax

[ iCurChapter = ] MSWebDVD.CurrentChapter

Possible Values

iCurChapter Integer value representing the current chapter in the current title.

This property is read-only with no default value.

CurrentDiscSide Property

MSWebDVD Object

Retrieves the current side of the disc.

Syntax

[ iCurSide = ] MSWebDVD.CurrentDiscSide

Possible Values

iCurSide Integer value representing the current side; Side A = 1 and Side B = 2.

This property is read-only with no default value.

CurrentDomain Property

MSWebDVD Object

Retrieves the DVD domain that the MSWebDVD object is in.

Syntax

[ iDomain = ] MSWebDVD.CurrentDomain

Possible Values

iDomain Integer value from 1 through 5 representing the current domain.

The possible values for iDomain are:
First Play | 1
Video Manager Menu | 2
Video Title Set Menu | 3
Title | 4
Stop | 5

This property is read-only with no default value.

Remarks

Call this method to ensure that the DVD Navigator is in a valid domain for the method you are about to call. For example, before calling PlayTitle, check the CurrentDomain property to make sure that the DVD Navigator is not in the Stop or First Play domain.

CurrentSubpictureStream Property

MSWebDVD Object

Sets or retrieves the current subpicture stream.

Syntax

[ iSPStream = ] MSWebDVD.CurrentSubpictureStream

Possible Values

iSPStream Integer value from 0 through 31 representing the subpicture stream. May also be 63, indicating a muted low-bitrate stream.

This property is read/write with no default value.

Remarks

Before setting a new subpicture stream, call IsSubpictureStreamEnabled to verify that the stream is available.

See Also

SubpictureOn, SubpictureStreamsAvailable

CurrentTime Property

MSWebDVD Object

Retrieves the current playback time.

Syntax

[ sCurTime = ] MSWebDVD.CurrentTime

Possible Values

sCurTime An 11-character string representing the current playback time in the format "hh:mm:ss:ff" (hours, minutes, seconds, frames).

This property is read-only with no default value.

See Also

TotalTitleTime

CurrentTitle Property

MSWebDVD Object

Retrieves the number of the title currently playing.

Syntax

[ iCurTitle = ] MSWebDVD.CurrentTitle

Possible Values

iCurTitle Integer value from 1 through 99 representing the current disc title.

This property is read-only with no default value.

See Also

TitlesAvailable

CurrentVolume Property

MSWebDVD Object

Retrieves the volume number for the current root directory.

Syntax

[ iCurVolume = ] DVD.CurrentVolume

Possible Values

iCurVolume Integer value representing the current DVD volume. If a disc is part of a multivolume set, then iCurVolume should be greater than zero.

This property is read-only with no default value.

See Also

VolumesAvailable

CursorType Property

MSWebDVD Object

Sets or retrieves the current cursor type.

Syntax

[ iCursorType = ] MSWebDVD.CursorType

Possible Values

iCursorType Integer value representing the cursor type.

The possible values for this property are:
Arrow | 0
Zoom In | 1
Zoom Out | 2
Hand | 3
None | -1

This property is read/write with a default value of zero.

Remarks

When the picture is zoomed in, setting CursorType to Hand (0x3) puts the application into drag mode, enabling the user to move the image inside the video display area.

DefaultAudioLanguage Property

MSWebDVD Object

Retrieves the default audio language.

Syntax

[ iLang = ] MSWebDVD.DefaultAudioLanguage

Possible Values

iLang LCID value containing the primary language ID for the default audio language. See Working with LCIDs for a table of some possible values and sample code showing how to extract the primary language ID from an LCID.

This property is read-only with no default value.

See Also

SelectDefaultAudioLanguage

DefaultAudioLanguageExt Property

MSWebDVD Object

Retrieves the default DVD audio language extension.

Syntax

[ iLangExt = ] MSWebDVD.DefaultAudioLanguageExt

Possible Values

iLangExt Integer value indicating the default audio language extension. See Remarks for the possible values.

Remarks

This property is read-only with no default value. The following table shows the possible values for DVD audio language extensions.

Extension | Value
NotSpecified | 0
Captions | 1
VisuallyImpaired | 2
DirectorComments1 | 3
DirectorComments2 | 4

See Also

SelectDefaultAudioLanguage

DefaultMenuLanguage Property

MSWebDVD Object

Retrieves the default menu language.

Syntax

[ iLang = ] MSWebDVD.DefaultMenuLanguage

Possible Values

iLang LCID value containing the primary language ID for the default audio language. See Working with LCIDs for a table of some possible values and sample code showing how to extract the primary language ID from an LCID.

Remarks

This property is read-write with no default value.

DefaultSubpictureLanguage Property

MSWebDVD Object

Retrieves the default subpicture language.

Syntax

[ iLang = ] MSWebDVD.DefaultSubpictureLanguage

Possible Values

iLang LCID value containing the primary language ID for the default audio language. See Working with LCIDs for a table of some possible values and sample code showing how to extract the primary language ID from an LCID.

This property is read-only with no default value.

See Also

SelectDefaultSubpictureLanguage

DefaultSubpictureLanguageExt Property

MSWebDVD Object

Retrieves the default DVD subpicture language extension.

Syntax

[ iLangExt = ] MSWebDVD.DefaultSubpictureLanguageExt

Possible Values

iLangExt Integer value indicating the default DVD subpicture language extension.

Remarks

This property is read-only with no default value. The following table shows the possible values.

Extension | Value
Extension Not Specified | 0
Normal Captions | 1
Big Captions | 2
Children's Captions | 3
Normal Closed Captions | 5
Big Closed Captions | 6
Children's Closed Captions | 7
Forced | 9
Normal Director's Comments | 13
Big Director's Comments | 14
Children's Director's Comments | 15

See Also

SelectDefaultSubpictureLanguage

DeleteBookmark Method

MSWebDVD Object

Deletes the saved bookmark.

Syntax

MSWebDVD.DeleteBookmark();

Return Value

No return value.

Remarks

There can only be one bookmark at a time.

DisableAutoMouseProcessing Property

MSWebDVD Object

Enables or disables the MSWebDVD object's mouse-processing functionality.

Syntax

[ bMouseProcessing = ] MSWebDVD.DisableAutoMouseProcessing

Possible Values

bMouseProcessing Boolean value indicating whether to disable the default mouse processing.

Remarks

This property is read/write with a default value of false.

The MSWebDVD object automatically handles mouse actions for DVD on-screen menus by default; users can highlight and activate menu buttons without special programming by the application. An application can turn off this default mouse-handling functionality by setting this property to true. When the automatic mouse processing is turned off, an application must use the various button-related methods and properties to handle mouse moves and mouse clicks on the on-screen menus. Also, an application can use the button-related methods to override the automatic mouse handling even when when DisableAutoMouseProcessing is set to false.

DVDAdm Property

MSWebDVD Object

Provides access to the MSDVDAdm object that contains methods and properties for saving application and user information.

Syntax

MSWebDVD.DVDAdm

Remarks

This property is read-only with no default value. There is no need to create a separate reference to the MSDVDAdm object. To access the methods and properties of the object, use the DVDAdm property as shown in the following example.

DVD.DVDAdm.DisableScreenSaver = true;

DVDDirectory Property

MSWebDVD Object

Sets or retrieves the current directory of the current DVD volume.

Syntax

[ sDirPath = ] MSWebDVD.DVDDirectory

Possible Values

sDirPath String value indicating the path to the DVD root directory.

Remarks

This property is read/write with no default value. Use this method to set the root path when there is more than one DVD drive on a system. When there is only one drive on the system and its drive letter is higher than "C", the MSWebDVD object finds it automatically. For a standard DVD-Video disc, the root path should include the ts_video directory, for example:

MSWebDVD.DVDDirectory = "e:\\video_ts";

Some DVD volumes may have their video in a directory named something other than "video_ts." The general idea is that an additional "DVD volume" (the set of .IFO. VOB, and .BUP files that would normally be stored in the VIDEO_TS directory) can be placed in a subdirectory on the disc. By changing the root to point to this directory, MSWebDVD will operate on this separate DVD volume. A new set of menus, titles, etc. will be available, independent of the titles in the VIDEO_TS root, which will no longer be accessible. Such directories are called "hidden directories." The following example shows how to set a hidden directory as the root, where "hidden" is a placeholder for whatever name the disc authors have given to the directory.

MSWebDVD.DVDDirectory = "d:\\webdvd\\hidden";

MSWebDVD.DVDTimeCode2bstr Method

MSWebDVD Object

Retrieves a String indicating the current time on the disc.

Syntax

[ sTimeCode = ] MSWebDVD.DVDTimeCode2bstr(nTimeCode);

Parameters

nTimeCode A Number obtained through the EC_DVD_CURRENT_HMSF_TIME event representing the current time on the disc relative to the start of the title.

Return Value

Returns an 11-character String in the format "hh:mm:ss:ff" representing the hours, minutes, seconds and frames that define the current time.

Remarks

This property is read only.

See Also

Handling DVD Event Notifications

DVDUniqueID Property

MSWebDVD Object

Retrieves a system-generated number that uniquely identifies the current disc.

Syntax

[ iDiscID = ] MSWebDVD.DVDUniqueID

Possible Values

iDiscID Integer value that uniquely identifies the current disc.

This property is read-only with no default value.

Remarks

The identifier (ID) number is not absolutely unique, but it is unique for all practical purposes. The ID applies to all replicated copies of a disc. In other words, all copies of a specific movie have the same ID. The ID is based on file sizes, dates, and other information, and not the BCA value.

Eject Method

MSWebDVD Object

Ejects or inserts a disc from or into the DVD drive.

Syntax

MSWebDVD.Eject();

Return Value

No return value.

Remarks

On some DVD drives, this method acts as a toggle, ejecting and inserting on alternate calls. This is hardware-dependent.

EnableResetOnStop Property

MSWebDVD Object

Sets or retrieves a value that determines how play will resume when the filter graph makes a transition from a stopped state.

Syntax

[ bEnableReset = ] MSWebDVD.EnableResetOnStop

Possible Values

bEnableReset Boolean value indicating where the MSWebDVD object will start playing again after the filter graph is stopped. True means the DVD Navigator will reset and start play from the beginning of the disc. False means it will start play where it left off.

Remarks

This property is read/write with a default value of true.

FramesPerSecond Property

MSWebDVD Object

Retrieves the video frame rate for the current DVD title.

Syntax

[ iFramesPerSec = ] MSWebDVD.FramesPerSecond

Possible Values

iFramesPerSec Integer value representing the video frame rate; either 25 or 30 frames per second.

Remarks

This property is read-only with no default value. NTSC video signals are displayed at 30 frames per second. PAL is displayed at 25 frames per second. A disc is encoded to play on either NTSC or PAL, but cannot play on both.

FullScreenMode Property

MSWebDVD Object

Sets or retrieves a value indicating whether the display is in full-screen mode.

Syntax

[ bFullScreen = ] MSWebDVD.FullScreenMode

Possible Values

bFullScreen Boolean value indicating whether to enable or disable full-screen playback; true means to enable full-screen mode.

Remarks

This property is read/write with a default value of false.

GetAudioLanguage Method

MSWebDVD Object

Retrieves a string indicating which language is available on the specified audio stream.

Syntax

[ slang = ] MSWebDVD.GetAudioLanguage(iStream);

Parameters

iStream Integer value specifying the audio stream number in the current title.

Return Value

Returns a human-readable string identifying the language of the audio stream in the current title.

GetButtonAtPosition Method

MSWebDVD Object

Retrieves the number of the button at the specified coordinates without selecting or activating it.

Syntax

[ iButton = ] MSWebDVD.GetButtonAtPosition(xPos, yPos);

Parameters

xPos | Integer value specifying the x-coordinate of the mouse pointer.
yPos | Integer value specifying the y-coordinate of the mouse pointer.

Return Value

Returns an integer value specifying the button, if any, at the specified position.

Remarks

This method returns zero if no button is present at the given coordinates. Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

See Also

ActivateButton, ButtonsAvailable, CurrentButton, GetButtonRect, SelectAndActivateButton, SelectAtPosition

GetButtonRect Method

MSWebDVD Object

Retrieves the rectangle for the specified button, in window coordinates.

Syntax

[ oButton = ] MSWebDVD.GetButtonRect(iButton);

Parameters

iButton Integer value specifying the button number.

Return Value

Returns a DVDRect object that defines the rectangle.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

See Also

ButtonsAvailable, CurrentButton, ActivateButton, SelectAndActivateButton, SelectAtPosition

GetClipVideoRect Method

MSWebDVD Object

Retrieves the clipping rectangle currently defined for the video display.

Syntax

[ oClipRect = ] MSWebDVD.GetClipVideoRect();

Return Value

Returns a DVDRect object that defines the rectangle.

See Also

SetClipVideoRect

GetDelayTime Method

MSWebDVD Object

Retrieves the delay time for the ToolTip associated with the MSWebDVD object.

Syntax

[ iDelay = ] MSWebDVD.GetDelayTime();

Return Value

Returns an integer value indicating the ToolTip delay time, in milliseconds.

See Also

SetDelayTime

GetDVDTextLanguageLCID Method

MSWebDVD Object

Retrieves the locale identifier (LCID) for the specified text string block.

Syntax

[ iLCID = ] MSWebDVD.GetDVDTextLanguageLCID(iLangIndex);

Parameters

iLangIndex Integer value that identifies the text language block on the disc.

Return Value

Returns an LCID value that contains information specifying the language the strings are written in. See Working With LCIDs for information on extracting the primary language code from an LCID.

Remarks

Supplemental text strings are stored in contiguous blocks on the disc. Each language has one block of strings. An application specifies these blocks by an index, which must be less than the value returned by GetDVDTextNumberOfLanguages.

See Also

GetLangFromLangID, Working With DVD Text Strings

GetDVDTextNumberOfLanguages Method

MSWebDVD Object

Retrieves the number of text languages available on the disc.

Syntax

[ iLanguages = ] MSWebDVD.GetDVDTextNumberOfLanguages();

Return Value

Returns an integer value specifying the number of text languages available.

See Also

Working With DVD Text Strings

GetDVDTextNumberOfStrings Method

MSWebDVD Object

Retrieves the number of text strings available for the specified language.

Syntax

[ iStrings = ] MSWebDVD.GetDVDTextNumberOfStrings(iLangIndex);

Parameters

iLangIndex Integer value that identifies the language; must be a value from zero through one less than the value returned by GetDVDTextNumberOfLanguages.

Return Value

Returns an integer value specifying how many strings the disc contains in the specified language.

See Also

Working With DVD Text Strings

GetDVDTextString Method

MSWebDVD Object

Retrieves the specified text string.

Syntax

[ sText = ] MSWebDVD.GetDVDTextString(iLangIndex, iStringIndex);

Parameters

iLangIndex | Integer value specifying the index of the language.
iStringIndex | Integer value specifying the index number of the text string.

Return Value

Returns the String specified by iStringIndex.

See Also

GetDVDTextNumberOfLanguages, Working With DVD Text Strings

GetDVDTextStringType Method

MSWebDVD Object

Retrieves a value that indicates the type of information contained in the specified DVD text string.

Syntax

[ iStringType = ] MSWebDVD.GetDVDTextStringType(iLangIndex, iStringIndex);

Parameters

iLangIndex | Integer value specifying the language of the text string.
iStringIndex | Integer value specifying the index number of the text string.

Return Value

Returns an integer value that indicates the type of information contained in the string.

Remarks

See Working With DVD Text Strings for a table of text string types and their meanings.

GetGPRM Method

MSWebDVD Object

Retrieves the specified general parameter register.

Syntax

[ iGPRM = ] MSWebDVD.GetGPRM(iIndex);

Parameters

iIndex Integer value in the range from 0 through 15 indicating which register to retrieve.

Return Value

Returns an Integer value for the specified register.

Remarks

This method is not required for any DVD navigation or playback functionality using the MSWebDVD object. It is provided for those with a thorough understanding of the DVD specification who want to implement advanced features. GPRMs can be used to hold any values, so they can be freely set and read. But since GPRMs are used to store disc commands as well, changing their values using SetGPRM can result in unpredictable behavior.

See Also

SetGPRM

GetKaraokeChannelAssignment Method

MSWebDVD Object

Retrieves a value that indicates how the karaoke channels are assigned to the speakers.

Syntax

[ iAssignment = ] MSWebDVD.GetKaraokeChannelAssignment(iStream , iChannel);

Parameters

iStream | Integer value specifying the audio stream.
iChannel | Integer value specifying the channel.

Return Value

Returns an integer indicating the speaker assignment for the specified channel. The possible values for iAssignment are:
2 | The channel is assigned to the left and right speakers.
3 | The channel is assigned to the left, right, and middle speakers.
4 | The channel is assigned to the left, right, and audio1 speakers.
5 | the channel is assigned to the left, right, middle, and audio1 speakers.
6 | The channel is assigned to the left, right, and audio2 speakers.
7 | The channel is assigned to the left, right, middle, and audio2 speakers.

See Also

KaraokeAudioPresentationMode

GetKaraokeChannelContent Method

MSWebDVD Object

Retrieves a value that indicates the type of content in the specified karaoke channel in the specified stream.

Syntax

[ iContent = ] MSWebDVD.GetKaraokeChannelContent(iStream, iChannel);

Parameters

iStream | Integer value from zero through seven specifying the audio stream.
iChannel | Integer value specifying the karaoke channel within iStream.

The possible values for each channel are:

Guide Vocal 1 | 0x0001
Guide Vocal 2 | 0x0002
Guide Melody 1 | 0x0004
Guide Melody 2 | 0x0008
Guide Melody A | 0x0010
Guide Melody B | 0x0020
Sound Effect A | 0x0040
Sound Effect B | 0x0080

Return Value

Returns an integer value whose individual bits specify the contents of the karaoke channel.

Remarks

DVD audio channel numbering is zero-based, so channels 2, 3, and 4 are the auxiliary karaoke channels. After the method returns, perform a bitwise AND operation on iContent to determine the contents of each channel. Because a single channel might have more than one type of content recorded on it, you should test for all the possible values even after a match is found.

The following code example demonstrates how to test iContents against each possible value.

        if(iContent & 0x0001)
            {
                // Set a check box or another UI control to
                //  indicate this channel has the Guide Vocal 1.
            }
        if(iContent & 0x0002)
            {
                // Set a check box or another UI control to
                //  indicate this channel has the Guide Vocal 2.
            }
        if(iContent & 0x0004)
            {
                // Set a check box or another UI control to
                //  indicate this channel has the Guide Melody 1.
            }

        // Repeat for each possible value for each channel.

After the user knows the contents of each channel, he or she must be able to adjust the volume or turn the individual channels on or off as needed. Implement this functionality in your application by using the KaraokeAudioPresentationMode property.

Note: To play karaoke discs, the audio decoder on the user's system must be compatible with the DirectShow 8 karaoke implementation.

GetLangFromLangID Method

MSWebDVD Object

Retrieves a human-readable string when given a primary language ID.

Syntax

[ sLanguage = ] MSWebDVD.GetLangFromLangID(iPrimaryLangID)

Parameters

iPrimaryLangID Integer specifying the primary language ID. See Working with LCIDs for a table of some possible values.

Return Value

If iPrimaryLangID is valid, returns a String representation of the language that can be displayed in the application's user interface. If iPrimaryLangID is invalid, an error code is returned.

Remarks

Although this method is named GetLangFromLangID, the parameter that you pass is actually the primary language ID, not the language ID.

See Also

Working with LCIDs, GetAudioLanguage, , GetDVDTextLanguageLCID

GetNumberOfChapters Method

MSWebDVD Object

Retrieves the number of chapters in the specified title.

Syntax

iChapters = MSWebDVD.GetNumberOfChapters(iTitle);

Parameters

iTitle Integer value specifying the title.

Return Value

Returns an integer value from 1 through 999 indicating the number of chapters.

GetPlayerParentalCountry Method

MSWebDVD Object

Retrieves the current country as set in the MSWebDVD object.

Syntax

iCountryCode = MSWebDVD.GetPlayerParentalCountry();

Return Value

Returns an integer value with the country code.

See Also

Enforcing Parental Management Levels, GetPlayerParentalLevel, GetTitleParentalLevels, SelectParentalCountry, SelectParentalLevel

GetPlayerParentalLevel Method

MSWebDVD Object

Retrieves the parental management level set in the MSWebDVD object.

Syntax

[ iLevel = ] MSWebDVD.GetPlayerParentalLevel();

Return Value

Returns an integer value specifying the current parental level in the DVD Navigator, or -1 if parental management is disabled.

Remarks

A player application is responsible for enforcing parental controls. The player parental level is a value set by an application than can be used to indicate the highest parental level the current user can view. When the DVD Navigator encounters a new parental level, use this method to determine whether the new level is greater than the level that was set by the application through SelectParentalLevel.

See Also

Enforcing Parental Management Levels, GetTitleParentalLevels, GetPlayerParentalCountry, SelectParentalCountry, SelectParentalLevel

GetSPRM Method

MSWebDVD Object

Retrieves the specified system parameter register.

Syntax

[ iSPRM = ] MSWebDVD.GetSPRM(iIndex);

Parameters

iIndex Integer value from 0 through 23 specifying the register whose value you want to retrieve.

Return Value

Returns an integer value representing the contents of the specified register.

Remarks

The disc controls system parameter registers (SPRMs). A player application doesn't need to access these registers for any standard navigation functionality. SPRMs represent the status of the player. Each one has a meaning, set by user preferences, disc commands, and other occurrences that an application has no direct control over. An application can read these registers but cannot write to them. To use these registers effectively, you will probably need a more detailed knowledge of the DVD navigation commands than is provided in this documentation. The following table shows the contents of each register. For more detailed information on the register contents, see IDVDInfo2::GetAllSPRMs

Register | Contents | Register | Contents | Register | Contents
0 | Menu lang. code | 1 | Audio stream number | 2 | Subpicture stream number
3 | Current angle number | 4 | Current title number | 5 | Title number
6 | PGC number | 7 | Current chapter number (PTT) | 8 | Highlighted button number
9 | Navigation timer | 10 | PGC jump for nav. timer | 11 | Karaoke audio presentation mode
12 | PML country code | 13 | PML | 14 | Video setting
15 | Audio capability | 16 | Audio lang. | 17 | Audio lang. ext.
18 | Subpicture lang. | 19 | Subpicture lang. ext. | 20 | Player region code
21 | Reserved | 22 | Reserved | 23 | Reserved

See Also

GetGPRM, SetGPRM

GetSubpictureLanguage Method

MSWebDVD Object

Retrieves the language for the specified subpicture stream.

Syntax

[ sLang = ] MSWebDVD.GetSubpictureLanguage(iStream);

Parameters

iStream Integer value specifying the subpicture stream number whose text language you want to retrieve.

Return Value

Returns a human-readable string identifying the language of the audio stream in the current title.

GetTitleParentalLevels Method

MSWebDVD Object

Retrieves the parental management levels for the specified title.

Syntax

[ iLevels = ] MSWebDVD.GetTitleParentalLevels(iTitle);

Parameters

iTitle Integer value specifying the title.

Return Value

Returns an integer value whose individual bits indicate which parental management levels (PML) are set in the specified title.

Remarks

A title may have chapters or even short segments that have a PML different from the overall PML for the title. Use this method to determine all the PMLs that will be encountered when playing a specified title. The returned integer is a set of bit flags that are defined as shown in the table below. Perform a bitwise AND operation on iLevels and each possible value. If the operation returns true, it means that PML will be encountered at some point in this title.

Possible Levels | Hexadecimal value
DVD Parental Level 1 | 0x100
DVD Parental Level 2 | 0x200
DVD Parental Level 3 | 0x400
DVD Parental Level 4 | 0x800
DVD Parental Level 5 | 0x1000
DVD Parental Level 6 | 0x2000
DVD Parental Level 7 | 0x4000
DVD Parental Level 8 | 0x8000
The following code snippet shows how to test for PMLs on Title 1. One use for this information is to compare the highest PML defined for the title to the PML assigned to the current user and determine whether to play the specified title or not.
iLevels = oDVD.GetTitleParentalLevels(1);
if(iLevels & 0x100)
 // PML 1 is defined for this title
if(iLvels & 0x200)
   // PML 2 is defined for this title
if(iLevels & 0x400)
  // PML 3 is defined for this title
...   //  and so on for all eight levels

See Also

Enforcing Parental Management Levels, SelectParentalLevel, GetPlayerParentalCountry, GetPlayerParentalLevel, SelectParentalCountry

IsAudioStreamEnabled Method

MSWebDVD Object

Retrieves a value indicating whether the specified audio stream is enabled in the current title.

Syntax

[ bEnabled = ] MSWebDVD.IsAudioStreamEnabled(iStream)

Parameters

iStream Integer value from 0 through 7 specifying the audio stream.

Return Value

Returns a Boolean value indicating whether the specified audio stream is available for the current title. True means it is available.

Remarks

Although a disc can contain up to eight independent audio streams, each stream is not necessarily available for each title. For example, a main movie title might have three audio streams for English, Spanish, and Japanese, but the "Coming Attractions" title might have only one audio stream in English. Always verify that a stream is available for a title before setting the CurrentAudioStream property.

IsSubpictureStreamEnabled Method

MSWebDVD Object

Retrieves a value indicating whether the specified subpicture stream is enabled in the current title.

Syntax

[ bEnabled = ] MSWebDVD.IsSubpictureStreamEnabled(iStream)

Parameters

iStream Integer value from 0 through 31 (or 63 for muted low-bitrate stream) specifying the subpicture stream.

Return Value

Returns a Boolean value indicating whether the specified audio stream is available in the current title. True means it is available.

Remarks

Although a disc can contain up to 32 subpicture streams, each stream is not necessarily available for each title. Always verify that a stream is available for a title before setting the CurrentSubpictureStream property.

GetVideoSize Method

MSWebDVD Object

Retrieves the native video dimensions.

Syntax

[ oSizeRect = ] MSWebDVD.GetVideoSize();

Return Value

Returns a DVDRect object containing four read/write properties: (top left) x; (top left) y, Width, and Height. The x and y properties are set to zero and the other two properties reflect the width and height of the video rectangle as authored on the disc.

KaraokeAudioPresentationMode Property

MSWebDVD Object

Sets or retrieves the right-left speaker mix for the auxiliary karaoke channels.

Syntax

[iMode ] = MSWebDVD.KaraokeAudioPresentationMode

Possible Values

iMode Integer value containing a set of bit flags specifying how the auxiliary karaoke channels are downmixed to the left and right speakers. See Remarks.

Remarks

This property is read/write with a default value of zero.

Audio channels are zero-based, so channels 0 and 1 generally represent the right and left speaker channels and channels 2 through 4 are the three auxiliary karaoke channels. When the MSWebDVD object enters karaoke mode, it automatically mutes channels 2 and higher. Use bitwise OR operations to set the appropriate bit in order to send an auxiliary channel to the left speaker, right speaker, both speakers (both bits on), or to no speakers (both bits off). These bits are all off by default whenever the DVD Navigator enters karaoke mode. The value of the bits and their corresponding action is given in the following table.

Action | Value
Downmix Channel 2 to the left speaker | 0x0004
Downmix Channel 3 to the left speaker | 0x0008
Downmix Channel 4 to the left speaker | 0x0010
Downmix Channel 2 to the right speaker | 0x0400
Downmix Channel 3 to the right speaker | 0x0800
Downmix Channel 4 to the right speaker | 0x1000

The following code example shows how to send channel 2 to the left speaker and channels 3 and 4 to the right channel by using a bitwise OR operation.

  var iMode = 0;
  iMode = 0x0004 | 0x0800 | 0x1000 ;
  DVD.KaraokeAudioPresentationMode = iMode;

To retrieve the value of KaraokeAudioPresentationMode, use a bitwise AND operation against the possible values, as shown in the following code example.

  if (DVD.KaraokeAudioPresentationMode & 0x0004)
  {
     // Channel 2 is being sent to the left speaker
  }
  if (DVD.KaraokeAudioPresentationMode & 0x0008)
  {
     // Channel 3 is being sent to the left speaker
  }
  // And so on for all possible values

Mute Property

MSWebDVD Object

Turns the audio stream output on or off.

Syntax

[ bMute = ] MSWebDVD.Mute

Possible Values

bMute Boolean value indicating whether the audio stream should be muted.

Remarks

This property is read/write with a default value of false.

NotifyParentalLevelChange Method

MSWebDVD Object

Enables or disables the event handling for temporary parental management level commands.

Syntax

MSWebDVD.NotifyParentalLevelChange(bNotify);

Parameters

bNotify Boolean value specifying whether the application is notified when the MSWebDVD object encounters video segments with a rating more restrictive than the overall rating for the disc.

Return Value

No return value.

Remarks

Parental management notifications are disabled by default. This means that temporary parental commands from the disc are allowed but ignored and disc will play without interruption. Call this method during initialization of your application if you need to handle temporary parental management level commands from the disc. To disable parental management after it is enabled, call this method with an argument of false. For more details on parental management, see AcceptParentalLevelChange.

See Also

Enforcing Parental Management Levels, SelectParentalLevel, GetTitleParentalLevels, GetPlayerParentalCountry, GetPlayerParentalLevel, SelectParentalCountry

Pause Method

MSWebDVD Object

Pauses playback at the current location.

Syntax

MSWebDVD.Pause();

Return Value

No return value.

Remarks

If playback is already paused, this method does nothing.

Play Method

MSWebDVD Object

Plays the current DVD title.

Syntax

MSWebDVD.Play();

Return Value

No return value.

Remarks

If playback is paused or stopped and EnableResetOnStop is true, then calling Play will resume playback at normal speed at the current location. If playback is stopped and EnableResetOnStop is false, then calling Play will cause the disc to start playing at the beginning of the first title.

See Also

Resume

PlayAtTime Method

MSWebDVD Object

Starts playback in the current title at the specified time.

Syntax

MSWebDVD.PlayAtTime(sTime);

Parameters

sTime String value specifying the time at which to start playing; must be in the format "hh:mm:ss:ff" (specifying hours, minutes, seconds, frames).

Return Value

No return value.

See Also

PlayAtTimeInTitle

PlayAtTimeInTitle Method

MSWebDVD Object

Starts playback at the specified time within the specified title.

Syntax

MSWebDVD.PlayAtTimeInTitle(sTime, iTitle);

Parameters

sTime | String value specifying the time at which to start playback; must be in the format "hh:mm:ss:ff" (specifying hours, minutes, seconds, frames).
iTitle | Integer specifying the index of the title.

Return Value

No return value.

See Also

CurrentTitle, PlayAtTime, TitlesAvailable

PlayBackwards Method

MSWebDVD Object

Starts backward playback from the current location at the specified speed.

Syntax

MSWebDVD.PlayBackwards(nSpeed);

Parameters

nSpeed Number value specifying the speed at which to play. This value is a multiplier—1.0 is normal playback speed; 2.0 is double speed, 0.5 is half speed, and so on. When nSpeed does not equal 1.0, audio is muted and the subpicture is turned off.

Return Value

No return value.

See Also

PlayForwards

PlayChapter Method

MSWebDVD Object

Starts playback from the specified chapter within the current title.

Syntax

MSWebDVD.PlayChapter(iChapter);

Parameters

iChapter Integer value specifying the chapter index in the current title.

Return Value

No return value.

Remarks

When the end of the specified chapter is reached, this method continues playing subsequent chapters, if any exist. If you want to play only a specified chapter, use PlayChaptersAutoStop.

See Also

PlayChapterInTitle

PlayChaptersAutoStop Method

MSWebDVD Object

Starts playback at the specified chapter in the specified title and for the number of chapters specified.

Syntax

MSWebDVD.PlayChaptersAutoStop(iTitle, iChapter, iChapterCount);

Parameters

iTitle | Integer value specifying the title.
iChapter | Integer value specifying the start chapter.
iChapterCount | Integer value specifying the number of chapters to play.

Return Value

No return value.

Remarks

When the last chapter has played, this method causes an EC_DVD_CHAPTER_AUTOSTOP event notification to be sent to the application.

PlayChapterInTitle Method

MSWebDVD Object

Plays the specified chapter in the specified title.

Syntax

MSWebDVD.PlayChapterInTitle(iTitle, iChapter);

Parameters

iTitle | Integer value specifying the title.
iChapter | Integer value specifying the chapter.

Remarks

This method starts playback at the specified chapter and then continues playing indefinitely. If you want to play only a particular chapter, use PlayChaptersAutoStop.

Return Value

No return value.

PlayForwards Method

MSWebDVD Object

Starts forward playback from the current location at the specified speed.

Syntax

MSWebDVD.PlayForwards(nSpeed);

Parameters

nSpeed Number value specifying the speed at which to play. This value is a multiplier—1.0 is normal playback speed; 2.0 is double speed, 0.5 is half speed, and so on. When nSpeed does not equal 1.0, audio is muted and the subpicture is turned off.

Return Value

No return value.

See Also

PlayBackwards

PlayNextChapter Method

MSWebDVD Object

Starts playback from the next chapter in the current title.

Syntax

MSWebDVD.PlayNextChapter();

Return Value

No return value.

See Also

PlayPrevChapter

PlayPeriodInTitleAutoStop Method

MSWebDVD Object

Starts playback at the specified time in the specified title until the specified stop time.

Syntax

MSWebDVD.PlayPeriodInTitleAutoStop(iTitle, sStartTime, sEndTime);

Parameters

iTitle | Integer value specifying the title.
sStartTime | String specifying the start time in "hh:mm:ss:ff" format (specifying hours, minutes, seconds, frames).
sEndTime | String specifying the end time in "hh:mm:ss:ff" format.

Return Value

No return value.

See Also

PlayChaptersAutoStop

PlayPrevChapter Method

MSWebDVD Object

Starts playback from the previous chapter in the current title.

Syntax

MSWebDVD.PlayPrevChapter();

Return Value

No return value.

See Also

PlayNextChapter

PlayState Property

MSWebDVD Object

Retrieves the current state of the MSWebDVD object.

Syntax

[ iState = ] MSWebDVD.PlayState

Possible Values

iState Integer value representing the current state of the DVD Navigator. Can be -2 (Undefined), -1 (Uninitialized), 0 (Stopped), 1 (Paused), or 2 (Running).

This property is read-only with no default value.

Remarks

The MSWebDVD object controls the DirectShow DVD Navigator filter, which does the actual work of DVD navigation. It is actually the state of the DVD Navigator that this property refers to. The DVD Navigator can be in one of several states, as described above. The PlayState property can be useful as a diagnostic tool, but generally there should be no reason for a scripting application to monitor the state of the DVD Navigator.

PlayTitle Method

MSWebDVD Object

Starts playback at the beginning of the specified title.

Syntax

MSWebDVD.PlayTitle(iTitle);

Parameters

iTitle Integer value specifying the title.

Return Value

No return value.

See Also

PlayPeriodInTitleAutoStop

PreferredSubpictureStream Property

MSWebDVD Object

Sets or retrieves the preferred subpicture stream for the current viewing session.

Syntax

[ iStream = ] MSWebDVD.PreferredSubpictureStream

Possible Values

iStream Integer value representing the current preferred subpicture stream in the MSWebDVD object, which might not be the same as the current default value for the preferred subpicture stream in the Microsoft® Windows® registry. The preferred subpicture stream is set with DVDAdm.DefaultSubpictureLCID.

ReadyState Property

MSWebDVD Object

Retrieves the ReadyState of the MSWebDVD object.

Syntax

[ iReadyState = ] MSWebDVD.ReadyState

Possible Values

iReadyState Integer value representing the control's ReadyState. Can be one of the following: READYSTATE_UNINITIALIZED = 0; READYSTATE_LOADING = 1; READYSTATE_LOADED = 2; READYSTATE_INTERACTIVE = 3; READYSTATE_COMPLETE = 4.

Remarks

This property is read-only with no default value.

The ReadyState property is exposed by any object embedded in a Web page. The values have the following meanings.

READYSTATE_UNINITIALIZED | Default initialization state.
READYSTATE_LOADING | Object is loading its properties.
READYSTATE_LOADED | Object has been initialized.
READYSTATE_INTERACTIVE | Object is interactive, but not all its data is available.
READYSTATE_COMPLETE | Object has received all its data.

Render Method

MSWebDVD Object

Initializes the DVD filter graph.

Syntax

MSWebDVD. Render(iRender = 0);

Parameters

iRender Integer value specifying whether the filter graph will be destroyed and rebuilt. This defaults to zero if no value is specified, which means that the filter graph will not be destroyed and rebuilt if it already exists. Specify 1 to force the graph to be destroyed and rebuilt.

Return Value

No return value.

Remarks

The Render method enables the MSWebDVD object to fully initialize the underlying DirectShow filter graph on startup. This eliminates the slight delay that otherwise occurs when the user issues the first command to play a disc or show a menu. There is no case in which Render needs to be called before calling any other method. For example, if the application calls PlayTitle before the filter graph has been initialized, the MSWebDVD object calls Render automatically before attempting to play the disc.

ReplayChapter Method

MSWebDVD Object

Starts playback at the beginning of the current chapter.

Syntax

MSWebDVD.ReplayChapter();

Return Value

No return value.

See Also

PlayChapter, PlayChaptersAutoStop

RegionChange Method

MSWebDVD Object

Displays a system dialog box that enables the user to change the region associated with the DVD drive.

Syntax

MSWebDVD.RegionChange();

Remarks

The region for a DVD drive can be changed only five times.

Return Value

No return value.

RestoreBookmark Method

MSWebDVD Object

Moves the MSWebDVD object to the point on the disc as specified in the current bookmark, with all audio, video, and subpicture settings restored.

Syntax

MSWebDVD.RestoreBookmark();

Return Value

No return value.

Resume Method

MSWebDVD Object

Resumes playback after a menu has been displayed.

Syntax

MSWebDVD.Resume();

Return Value

No return value.

ReturnFromSubmenu Method

MSWebDVD Object

Returns display from a submenu to its parent menu, or to the current title if the menu is a top-level menu.

Syntax

MSWebDVD.ReturnFromSubmenu();

Return Value

No return value.

SaveBookmark Method

MSWebDVD Object

Saves the current disc position and state of the MSWebDVD object so the user can return to the same place later.

Syntax

MSWebDVD.SaveBookmark();

Return Value

No return value.

Remarks

A bookmark is a snapshot of the DVD Navigator's current state. This includes information such as where it is playing on the disc, and which audio and subpictures streams are selected. By saving a bookmark, the user can close the application, shut down the computer, and come back later to continue viewing the disc right where he or she left off, with all settings just as they were before. Only one bookmark can be saved at any given time. When you call SaveBookmark, the old bookmark is overwritten.

See Also

RestoreBookmark, Saving and Restoring Bookmarks

SelectAndActivateButton Method

MSWebDVD Object

Selects and activates the specified button.

Syntax

MSWebDVD.SelectAndActivateButton(iButton);

Parameters

iButton Integer value specifying the button.

Return Value

No return value.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

This method highlights the specified button and activate it automatically.

See Also

ButtonsAvailable, CurrentButton, ActivateButton, GetButtonAtPosition, GetButtonRect, SelectAtPosition

SelectAtPosition Method

MSWebDVD Object

Selects the menu button at the specified mouse pointer coordinates.

Syntax

MSWebDVD.SelectAtPosition(xPos, yPos);

Parameters

xPos | Integer value specifying the x-coordinate.
yPos | Integer value specifying the y-coordinate.

Return Value

No return value.

Remarks

Use this method when implementing custom mouse handling after setting DisableAutoMouseProcessing to true.

Selecting merely highlights the button. To send the command associated with a button that has been selected, call ActivateButton.

See Also

ButtonsAvailable, CurrentButton, GetButtonAtPosition, GetButtonRect, SelectAndActivateButton

SelectDefaultAudioLanguage Method

MSWebDVD Object

Sets the current default audio language in the MSWebDVD object.

Syntax

MSWebDVD.SelectDefaultAudioLanguage(iLang, iExt);

Parameters

iLang | Integer LCID value specifying the language. See the table under Working with LCIDs for possible values.
iExt | Integer value specifying the DVD audio language extension. See Remarks for possible values.

Remarks

Extension | Value
NotSpecified | 0
Captions | 1
VisuallyImpaired | 2
DirectorComments1 | 3
DirectorComments2 | 4

Return Value

No return value.

SelectDefaultSubpictureLanguage Method

MSWebDVD Object

Sets the current default subpicture language in the MSWebDVD object.

Syntax

MSWebDVD.SelectDefaultSubpictureLanguage(iLang,iExt);

Parameters

iLang | Integer value specifying the language.
iExt | Integer value specifying the subpicture language extension. See Remarks for possible values.

Return Value

No return value.

Remarks

The subpicture language extension provides further information about the subpicture. The possible values are:

Extension | Value
Extension Not Specified | 0
Normal Captions | 1
Big Captions | 2
Children's Captions | 3
Normal Closed Captions | 5
Big Closed Captions | 6
Children's Closed Captions | 7
Forced | 9
Normal Director's Comments | 13
Big Director's Comments | 14
Children's Director's Comments | 15

SelectLeftButton Method

MSWebDVD Object

Selects the left directional button from the displayed menu.

Syntax

MSWebDVD.SelectLeftButton();

Return Value

No return value.

See Also

ActivateButton, SelectLowerButton, SelectRightButton, SelectUpperButton

SelectLowerButton Method

MSWebDVD Object

Selects the lower directional button from the displayed menu.

Syntax

MSWebDVD.SelectLowerButton();

Return Value

No return value.

See Also

ActivateButton, SelectLeftButton, SelectRightButton, SelectUpperButton

SelectParentalCountry Method

MSWebDVD Object

Set the specified parental country for subsequent playback.

Syntax

MSWebDVD.SelectParentalCountry(iCountry, sUserName, sPassword);

Parameters

iCountry | Integer value specifying the country.
sUserName | String value specifying the current logged-on user. (Currently ignored.)
sPassword | String value specifying the application password.

Return Value

No return value.

Remarks

The parental country determines how the parental levels are interpreted.

See Also

Enforcing Parental Management Levels, SelectParentalLevel, NotifyParentalLevelChange, GetTitleParentalLevels, GetPlayerParentalCountry, GetPlayerParentalLevel, AcceptParentalLevelChange

SelectParentalLevel Method

MSWebDVD Object

Sets the specified parental level for subsequent playback.

Syntax

MSWebDVD.SelectParentalLevel(iLevel, sUserName, sPassword);

Parameters

iLevel | Integer value from 1 through 8 specifying the parental level. To disable parental management, set iLevel to -1.
sUserName | String value specifying the current user. (Currently ignored.)
sPassword | String value specifying the password currently stored in the registry.

Return Value

No return value.

Remarks

This method sets the access level in the MSWebDVD object, which determines what content the user can play back. Higher levels can play lower-level content but lower levels can't play higher-level content. The exact meaning of the eight DVD parental management levels varies depending on the country. In the United States and Canada, the levels are mapped to the Motion Picture Association of America (MPAA) rating categories. Parental management in the DVD Navigator is disabled by default.

See Also

Enforcing Parental Management Levels, SelectParentalCountry, NotifyParentalLevelChange, GetTitleParentalLevels, GetPlayerParentalCountry, GetPlayerParentalLevel, AcceptParentalLevelChange

SelectRightButton Method

MSWebDVD Object

Selects the right directional button from the displayed menu.

Syntax

MSWebDVD.SelectRightButton();

Return Value

No return value.

See Also

Working With Menus

ActivateButton, SelectLeftButton, SelectLowerButton, SelectUpperButton

SelectUpperButton Method

MSWebDVD Object

Selects the upper directional button from the displayed menu.

Syntax

MSWebDVD.SelectUpperButton();

Return Value

No return value.

See Also

ButtonsAvailable, CurrentButton, ActivateButton, GetButtonAtPosition, GetButtonRect, SelectAndActivateButton, SelectAtPosition, SelectLeftButton, SelectLowerButton, SelectRightButton

SetClipVideoRect Method

MSWebDVD Object

Zooms the video display to the specified subrectangle.

Syntax

 DVD.SetClipVideoRect(oRect);

Parameters

oRect DVDRect object specifying the clipping rectangle.

Return Value

No return value.

Remarks

When you set a new clipping rectangle, the object enlarges that area to fit within the application's overall display dimensions. This creates the effect zooming in on a particular area of the screen. To specify the rectangle, create a new DVDRect object and fill in its properties.

The most common rectangle for video display is 720 x 540.

See Also

GetClipVideoRect

SetDelayTime

MSWebDVD Object

Sets the delay time for the ToolTip associated with the MSWebDVD object.

Syntax

MSWebDVD.SetDelayTime(iDelayType, iNewVal)

Parameters

iDelayType | Integer value specifying the type of delay. See Remarks.
iNewVal | Integer value specifying the delay, in milliseconds.

Return Value

No return value.

Remarks

The following table explains the possible values for iDelayType.

TTDT_AUTOPOP = 0 | Set the length of time a ToolTip window remains visible if the pointer is stationary within a tool's bounding rectangle. To reset the autopop delay time to its default value, set iNewVal to -1.
TTDT_INITIAL = 1 | Set the length of time a pointer must remain stationary within a tool's bounding rectangle before the ToolTip window appears. To reset the initial delay time to its default value, set iNewVal to -1.
TTDT_RESHOW = 2 | Set the length of time it takes for subsequent ToolTip windows to appear as the pointer moves from one tool to another. To reset the reshow delay time to its default value, set iNewVal to -1.
TTDT_AUTOMATIC = 3 | Set all three delay times to default proportions. The autopop time is ten times the initial time and the reshow time is one fifth the initial time. If this flag is set, use a positive value of iNewVal to specify the initial time, in milliseconds. Set iNewVal to a negative value to return all three delay times to their default values.

SetGPRM Method

MSWebDVD Object

Sets the specified general parameter register to the specified value.

Syntax

MSWebDVD.SetGPRM(iIndex, nValue)

Parameters

iIndex | Integer value from 0 through 15 specifying the general parameter register to set.
iValue | Integer specifying the new value for the register.

Remarks

General parameter registers, or GPRMs, are 16-bit registers that each disc can use in unique ways for temporary data storage. A player application does not need to access these registers for any standard playback or navigation control using the MSWebDVD object. This method is provided for player applications implementing advanced functionality. Do not attempt to modify the GPRMs directly unless you have a thorough knowledge of the DVD specification and the ways in which the GPRMs are used on the particular disc to be played. Changing these values can result in unpredictable behavior.

ShowCursor Method

MSWebDVD Object

Makes the cursor visible when the MSWebDVD object is in full-screen mode.

Syntax

MSWebDVD.ShowCursor(bShow);

Parameters

bShow Boolean value specifying whether to show the cursor.

Return Value

No return value.

Remarks

When the DVD display goes into full-screen mode, the cursor disappears within 3 to 5 seconds. Use this method to make the cursor visible again if your application's control buttons are visible in full-screen mode.

ShowMenu Method

MSWebDVD Object

Displays the specified menu on the screen.

Syntax

MSWebDVD.ShowMenu(iMenuID);

Parameters

iMenuID Integer value specifying the menu. See Remarks for possible values.

Return Value

No return value.

Remarks

iMenuID must be one of the following values.
Menu type | Value
Title (Top) | 2
Root | 3
Subpicture | 4
Audio | 5
Angle | 6
Chapter | 7

DVD menu names can be somewhat confusing. The title menu is another name for the Video Manager Menu, the main menu for the entire disc; it generally lists all the video title sets available on the disc. The root menu is the menu for one video title set, which can contain one title or a group of titles. All the titles in a title set share the same Subpicture, Audio, and Angle menus.

Step Method

MSWebDVD Object

Advances the DVD-Video stream by the specified number of frames.

Syntax

MSWebDVD.Step(iFrames)

Parameters

iFrames Integer value specifying the number of frames to step.

Return Value

No return value.

Remarks

Before calling this method, call CanStep to determine whether the decoder supports frame stepping.

If the DVD-Video is playing in reverse mode when this method is called, and the decoder supports reverse frame stepping, then the frame stepping is done in reverse.

StillOff Method

MSWebDVD Object

Resumes playback, canceling still mode.

Syntax

MSWebDVD.StillOff();

Return Value

No return value.

Remarks

The DVD Navigator goes into still mode when it encounters a still frame authored on the disc. It notifies your application by sending an EC_DVD_STILL_ON event. Still mode is different from the DVD Navigator being in a paused state because of a user operation. Calling StillOff resumes playback from still mode but does not restart the DVD Navigator when it is in a paused state.

Stop Method

MSWebDVD Object

Stops playback.

Syntax

MSWebDVD.Stop();

Return Value

No return value.

Remarks

If EnableResetOnStop is set to true, calling Stop puts the DVD Navigator, along with the rest of the filter graph, into a stopped state, which means that the next time the user presses the Play button, playback starts at the beginning of the disc. If EnableResetOnStop is set to true, playback resumes where it left off when the user issues the next Play command.

SubpictureOn Property

MSWebDVD Object

Sets or retrieves the current subpicture state (on or off).

Syntax

[ bState = ] MSWebDVD.SubpictureOn

Possible Values

bState Boolean value indicating whether the subpicture is displayed.

Remarks

This property does not affect display of Closed Captions. Closed Captions are embedded within the video stream. DVD subpictures are transported on a separate stream.

This property is read/write with a default value of false.

SubpictureStreamsAvailable Property

MSWebDVD Object

Retrieves the number of subpicture streams available in the current title.

Syntax

[ iStreams = ] MSWebDVD.SubpictureStreamsAvailable

Possible Values

iStreams Integer value representing the number of available streams.

Remarks

This property is read-only with no default value. To query each stream for its language attribute, first call this method to get the upper bound. Stream numbering is zero-based.

TitlesAvailable Property

MSWebDVD Object

Retrieves the number of titles available on the disc.

Syntax

[ iTitles = ] MSWebDVD.TitlesAvailable

Possible Values

iTitles Integer value from 1 through 99 representing the number of available titles.

Remarks

This property is read-only with no default value.

ToolTip Property

MSWebDVD Object

Sets the text for the ToolTip that appears when the mouse pointer is over the MSWebDVD video rectangle.

Syntax

[ sToolTip = ] MSWebDVD.ToolTip

Possible Values

sToolTip String value specifying the ToolTip text.

Remarks

This property is read/write with no default value. If the string is empty, no ToolTip appears.

ToolTipMaxWidth Property

MSWebDVD Object

Sets or retrieves the maximum width for the ToolTip associated with the MSWebDVD object.

Syntax

[ iMaxWidth = ] MSWebDVD.ToolTipMaxWidth

Possible Values

iMaxWidth Integer value representing the maximum width for the application's ToolTip.

Remarks

This property is read/write with a default value of 200 pixels.

TotalTitleTime Property

MSWebDVD Object

Retrieves the total playback time for the current title.

Syntax

[ sTotalTime = ] MSWebDVD.TotalTitleTime

Possible Values

sTotalTime String value representing the total playing time of the current title, in the format "hh:mm:ss:ff".

Remarks

This property is read-only with no default value. The returned string will be 11 characters long in the format "hh:mm:ss:ff" (hours, minutes, seconds, frames).

See Also

PlayAtTime, PlayAtTimeInTitle

UOPValid Method

MSWebDVD Object

Retrieves a value that indicates whether the specified user operation (UOP) is currently valid.

Syntax

[ bIsValid = ] MSWebDVD.UOPValid(iUOP);

Parameters

iUOP Integer value specifying the UOP. See Remarks for possible values.

Return Value

Returns a Boolean value indicating whether the specified operation is permitted by UOP control.

Remarks

The possible values of iUOP are defined as follows:

Value | User function
0x0 | PlayTitle, PlayAtTime PlayAtTimeInTitle
0x1 | PlayChapter
0x2 | PlayTitle
0x4 | Stop
0x8 | ReturnFromSubmenu
0x10 | PlayChapter
0x20 | PlayPrevChapter, ReplayChapter
0x40 | PlayNextChapter
0x80 | PlayForwards
0x100 | PlayBackwards
0x200 | ShowMenu with a parameter value of 2 (DVD_MENU_Title)
0x400 | ShowMenu with a parameter value of 3 (DVD_MENU_Root)
0x800 | ShowMenu with a parameter value of 4 (DVD_MENU_Subpicture)
0x1000 | ShowMenu with a parameter value of 5 (DVD_MENU_Audio)
0x2000 | ShowMenu with a parameter value of 6 (DVD_MENU_Angle)
0x4000 | ShowMenu with a parameter value of 7 (DVD_MENU_Chapter)
0x8000 | Resume
0x10000 | SelectLeftButton, SelectRightButton,SelectUpperButton,SelectLowerButton
0x20000 | StillOff
0x40000 | Pause
0x80000 | CurrentAudioStream
0x100000 | CurrentSubpictureStream
0x200000 | CurrentAngle, SelectParentalLevel
0x400000 | KaraokeAudioPresentationMode

Volume Property

MSWebDVD Object

Sets or retrieves the speaker volume for the audio stream output.

Syntax

[ iVolume = ] MSWebDVD.Volume

Possible Values

iVolume Integer value representing the volume level as attenuation in decibels.

Remarks

This property is read/write with a default value of 0. Full volume is 0, and 10,000 is silence; the scale is logarithmic. Multiply the desired decibel level by 100 (for example 10,000 = 100 dB).

VolumesAvailable Property

MSWebDVD Object

Retrieves the number of volumes in a multivolume set.

Syntax

[ iVolumes = ] MSWebDVD.VolumesAvailable

Possible Values

iVolumes Integer value representing the number of volumes in the set.

Remarks

This property is read-only with no default value. Some DVD titles might be released as a multidisc set or series. Use this method to determine the volume number for the current disc.

WindowlessActivation Property

MSWebDVD Object

Initializes the MSWebDVD object at design time for either windowed or windowless mode.

Syntax

[ bWindowless = ] MSWebDVD.WindowlessActivation

Possible Values

bWindowless Boolean value indicating whether the object is in windowed mode.

Remarks

This property is read/write with a default value of true. Therefore, you only need to set this property if you are running the MSWebDVD object in a windowed container. When contained in a Web page in Microsoft® Internet Explorer, MSWebDVD is always in windowless mode, and you don't need to set this property.

Zoom Method

MSWebDVD Object

Zooms the video display in or out, centered on a given set of screen coordinates.

Syntax

MSWebDVD.Zoom(iXPos, iYPos, iZoomRatio);

Parameters

iXPos | Integer value specifying the x-coordinate at the center of the rectangular zoom area.
iYPos | Integer value specifying the y-coordinate at the center of the rectangle to be zoomed.
iZoomRatio | Number value specifying the magnification factor applied to the current zoom value. The total maximum value depends on what the hardware overlay can support; this is typically a factor of 32 to 64 times the original size.

Return Value

No return value.

Remarks

The new zoom ratio stays in effect until it is restored to the original size or changed again. In other words, two calls to this method specifying an iZoomRatio of two will result in a zoom ratio four times larger than the original video size. If the user tries to zoom beyond what the hardware can support, this method will succeed but do nothing.

The SetClipVideoRect method is another way to zoom in; the only difference between the two methods is the way in which the zoom rectangle is specified.


MSDVDAdm Object

The methods and properties of the MSDVDAdm "administration" object enable a scripting application to modify its default settings in the Microsoft® Windows® registry. The registry is a database on all Windows systems where applications can store information about themselves to be used on initialization or during run time.

Most of these methods and properties do not set or retrieve the current values in the MSWebDVD object itself. This means, for example, that when you call GetParentalLevel the returned value is not the current parental level stored in the object. Rather, it is the default parental level stored in the registry. To get the current parental level, call the MSWebDVD method GetPlayerParentalLevel. Calling SaveParentalLevel simply writes a new default parental access level to the registry; you still need to call the MSWebDVD method SelectParentalLevel to make the change take effect immediately in the MSWebDVD object. The default locale identifier (LCID) methods work in a similar way.

On the other hand, the BookmarkOnStop and BookmarkOnClose methods take effect immediately because the MSWebDVD object checks these settings just before the user stops playback or closes the application, rather than during initialization.

You access the MSDVDAdm object through the DVDAdm property of MSWebDVD. So, for example, if the MSWebDVD object is named "DVD," call ChangePassword as shown in the following code example.

DVD.DVDAdm.ChangePassword(sUserName, sOld, sNew);

Methods and Properties

The following table lists the methods and properties exposed by the MSDVDAdm object.
Methods
ChangePassword | Saves a new application password in the registry.
SaveParentalLevel | Saves a new default parental level to the registry.
SaveParentalCountry | Saves the application's new parental country to the registry.
ConfirmPassword | Tests whether the specified password matches the previously saved password.
GetParentalLevel | Retrieves the parental level that was last saved to the registry.
GetParentalCountry | Retrieves the parental country that was last saved to the registry.
RestoreScreenSaver | Restores the system screen saver settings.
Properties
DisableScreenSaver | Turns the system screen saver on or off.
DefaultAudioLCID | Sets or retrieves the registry setting for the user-specified default LCID for the audio stream.
DefaultSubpictureLCID | Sets or retrieves the registry setting for the user-specified default LCID for the subpicture stream.
DefaultMenuLCID | Sets or retrieves the registry setting for the user-specified default LCID for menus.
BookmarkOnStop | Sets or retrieves a value that tells the MSDVDAdm object whether to automatically save a bookmark of the current location and settings when the user clicks the Stop button.
BookmarkOnClose | Sets or retrieves a value that tells the MSDVDAdm object whether to automatically save a bookmark of the current location and settings when the user closes the application.

BookmarkOnClose Property

MSDVDAdm Object

Sets or retrieves a value that tells the MSDVDAdm object whether to automatically save a bookmark of the current location and settings when the user closes the application.

Syntax

[ bBookmarkOnClose = ] DVD.DVDAdm.BookmarkOnClose

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | MSWebDVD object's DVDAdm property.
bBookmarkOnClose | Boolean value that indicates whether the MSDVDAdm control will save a bookmark of all DVD settings including position on disc, parental level, and parental country when the user closes the DVD player application.

Remarks

This property is read/write with a default value of true.

See Also

BookmarkOnStop, Saving and Restoring Bookmarks

BookmarkOnStop Property

MSDVDAdm Object

Sets or retrieves a value that tells the MSWebDVD object whether to automatically save a bookmark of the current location and settings when the user clicks the Stop button.

Syntax

[ bBookmarkOnStop = ] DVD.DVDAdm.BookmarkOnStop

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | MSWebDVD object's DVDAdm property.
bBookmarkOnStop | Boolean value indicating whether the MSDVDAdm object will save a bookmark of all DVD settings including position on disc, parental level and parental country.

Remarks

This property is read/write with a default value of false.

Bookmarks are valid only for a particular machine. A user cannot save a bookmark and then send it to someone else to read on a different machine.

See Also

BookmarkOnClose

ChangePassword Method

MSDVDAdm Object

Saves a new application password in the registry.

Syntax

DVD.DVDAdm.ChangePassword(sUserName, sOld, sNew );

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | The MSWebDVD object's DVDAdm property.
sUserName | String value specifying the current user's logon name. The MSDVDAdm object ignores this parameter. See Remarks.
sOld | String value specifying the user's old password.
sNew | String value specifying the user's new password. Cannot be NULL.

Return value

No return value.

Remarks

Currently, the sUserName parameter is ignored on this and all related methods. This means that whoever knows the password can set the parental level. There is only one password and one parental level for the application. There is no support for individual user logon names or multiple password management. To enforce parental management levels, parents should set the password and then set the parental level appropriate for younger members of the family. When parents want to view a disc with adult-rated content, they can change the level, and then change it back when they are done viewing. As long as the children do not know the password, they can only watch content at or below the level set for them.

See Also

ConfirmPassword

ConfirmPassword Method

MSDVDAdm Object

Tests whether the specified password matches the previously saved password.

Syntax

[ bIsConfirmed = ] DVD.DVDAdm.ConfirmPassword(sUserName, sPassword);

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | The MSWebDVD object's DVDAdm property.
sUserName | String value specifying the user's name. See Remarks.
sPassword | String value specifying the new password.

Return value

Returns true if the specified password matches the existing password, false otherwise.

Remarks

Currently, the sUserName parameter is ignored on this and all related methods.

See Also

ChangePassword

DefaultAudioLCID Property

MSDVDAdm Object

Sets or retrieves the registry setting for the user-specified default LCID for the audio stream.

Syntax

[ iAudioLCID = ] DVD.DVDAdm.DefaultAudioLCID

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | The MSWebDVD object's DVDAdm property.
iAudioLCID | Integer value representing the user-specified default audio LCID as stored in the registry settings for the DVD application. This value is not necessarily the same as the default audio stream as authored on the DVD. For the range of valid LCIDs, see the Microsoft® Win32® documentation in the Platform SDK.

This property is read/write with no default value. If no default audio LCID is specified, the MSDVDAdm object will play the audio stream that is marked as the default stream on the disc.

DefaultMenuLCID Property

MSDVDAdm Object

Sets or retrieves the registry setting for the user-specified default LCID for menus.

Syntax

[ iMenuLCID = ] DVD.DVDAdm.DefaultMenuLCID

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | The MSWebDVD object's DVDAdm property.
iMenuLCID | Integer value representing the LCID as stored in the registry settings for the DVD application. This value is not necessarily the same as the default menu language as authored on the DVD. For the range of valid LCIDs, see the Win32 documentation in the Platform SDK.

This property is read/write with no default value. If no default menu LCID is specified, the MSDVDAdm object will use the language that is marked as the default menu language on the disc.

DefaultSubpictureLCID Property

MSDVDAdm Object

Sets or retrieves the registry setting for the user-specified default LCID for the subpicture stream.

Syntax

[ iSubpictureLCID = ] DVD.DVDAdm.DefaultSubpictureLCID

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | The MSWebDVD object's DVDAdm property.
iSubpictureLCID | Integer value representing the user-specified default subpicture LCID as stored in the registry settings for the DVD application. This value is not necessarily the same as the default subpicture stream as authored on the DVD. For the range of valid LCIDs, see the Win32 documentation in the Platform SDK.

This property is read/write with no default value. If no default subpicture LCID is specified, the MSDVDAdm object will play the subpicture stream that is marked as the default stream on the disc.

DisableScreenSaver Property

MSDVDAdm Object

Turns the system screen saver on or off.

Syntax

[ bDisabled = ] DVD.DVDAdm.DisableScreenSaver

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | The MSWebDVD object's DVDAdm property.
bDisabled | Boolean value indicating whether the system's screen saver settings are disabled for the DVD player application; TRUE means the settings are disabled.

This property is read/write with a default value of true.

Remarks

When viewing a DVD-Video disc, a user typically does not use the mouse or keyboard for extended periods of time. The MSWebDVD ActiveX® control therefore disables the system screen saver by default.

See Also

RestoreScreenSaver

GetParentalCountry Method

MSDVDAdm Object

Retrieves the parental country that was last saved to the registry.

Syntax

[ iParentalCountry = ] DVD.DVDAdm.GetParentalCountry();

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | The MSWebDVD object's DVDAdm property.

Return value

Returns an integer indicating the default country code stored in the registry.

Remarks

The parental country this method retrieves is not necessarily the same country currently stored in the MSWebDVD object.

GetParentalLevel Method

MSDVDAdm Object

Retrieves the parental level that was last saved to the registry.

Syntax

[ iParentalLevel = ] DVD.DVDAdm.GetParentalLevel();

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | The MSWebDVD object's DVDAdm property.

Return value

Returns an integer from 1 through 8 indicating the default parental level.

Remarks

The parental level this method retrieves is not necessarily the same level currently stored in the MSWebDVD control; to get the level currently stored in the control, call MSWebDVD.GetPlayerParentalLevel. A value of -1 indicates that parental management is disabled.

RestoreScreenSaver Method

MSDVDAdm Object

Restores the system screen saver settings.

Syntax

DVD.DVDAdm.RestoreScreenSaver();

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | The MSWebDVD object's DVDAdm property.

Return value

No return value.

Remarks

Generally, a DVD application will disable the system's screen saver on startup by setting the DisableScreenSaver property to true, and then re-enable the screen saver again when the DVD application is closed by calling RestoreScreenSaver. If an application does not use the system's screen saver settings, it does not have to call this method or set the DisableScreenSaver property.

SaveParentalCountry Method

MSDVDAdm Object

Saves the application's new parental country to the registry.

Syntax

DVD.DVDAdm.SaveParentalCountry( iCountry,  sUserName, sPassword);

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | The MSWebDVD object's DVDAdm property.
iCountry | Integer value specifying the parental country.
sUserName | String value specifying the user name. Currently ignored.
sPassword | String value specifying the password.

Return value

No return value.

Remarks

This method enables a user who knows the current password to save a new parental country setting to the registry. As with all the methods of MSDVDAdm, this method does not affect the current level in the player; it changes only the registry setting, so that the next time the MSWebDVD object is created, it will open with the new country. To change the parental country in the player, call MSWebDVD.SelectParentalCountry, which does not change the registry setting.

See Also

SaveParentalLevel

SaveParentalLevel Method

MSDVDAdm Object

Saves a new default parental level to the registry.

Syntax

DVD.DVDAdm.SaveParentalLevel( iLevel, sUserName, sPassword);

Parts

DVD | Object that resolves to an MSWebDVD object.
DVDAdm | The MSWebDVD object's DVDAdm property.
iLevel | Integer value from 1 through 8 specifying the parental level.
sUserName | String value specifying the user name. Currently ignored.
sPassword | String value specifying the password.

Return value

No return value.

Remarks

This method enables a user who knows the current password to save a new parental level setting to the registry. As with all the methods of MSDVDAdm, this method does not affect the current level in the player; it changes only the registry setting, so that the next time the MSWebDVD object is started, it will open with the new level. Specify -1 to disable parental management. To change the parental level in the player, call MSWebDVD.SelectParentallevel, which does not change the registry setting.


DVDRect Object

The properties of the DVDRect object enable a scripting application to specify and receive rectangle coordinates in MSWebDVD methods such as GetButtonRect, GetClipVideoRect, GetVideoSize and SetClipVideoRect.

Properties

Properties
x | Sets or retrieves the x position of the rectangle's upper-left corner.
y | Sets or retrieves the y position of the rectangle's upper-left corner.
Width | Sets or retrieves the width of the rectangle, in pixels.
Height | Sets or retrieves the height of the rectangle, in pixels.

Height Property

Sets or retrieves the height of the rectangle.

Syntax

[ iHeight = ] DVDRect.Height

Parts

DVDRect | Object that resolves to an MSWebDVD object.
iHeight | Height, in pixels, of the rectangle.

Remarks

This property is read/write with no default value.

Width Property

Sets or retrieves the width of the rectangle.

Syntax

[ iWidth = ] DVDRect.Width

Parts

DVDRect | Object that resolves to an MSWebDVD object.
iWidth | Width, in pixels, of the rectangle.

Remarks

This property is read/write with no default value.

x Property

Sets or retrieves the x position of the rectangle's upper-left corner.

Syntax

[ iXPos = ] DVDRect.x

Parts

DVDRect | Object that resolves to an MSWebDVD object.
iXPos | X position of the rectangle's upper-left corner.

Remarks

This property is read/write with no default value.

y Property

Sets or retrieves the y position of the rectangle's upper-left corner.

Syntax

[ iYPos = ] DVDRect.y

Parts

DVDRect | Object that resolves to an MSWebDVD object.
iYPos | Y position of the rectangle's upper-left corner.

Remarks

This property is read/write with no default value.


MSWebDVD Events

The MSWebDVD Microsoft® ActiveX® control notifies your application when various types of internal events occur or when certain information is encountered on the disc.

Most of the events relate to user operation (UOP) controls. DVD authors can encode the disc so that any DVD command (such as PlayForwards, Pause, ShowMenu, and so on) can be disabled at any time. For example, most discs will not allow users to fast forward or show a menu while the FBI warning is playing. After the warning is over, the disc permits these operations. By handling the UOP events, your application can update its user interface to show the user which commands are currently permitted by the disc. The most common way to do this is by disabling a button. For example, if your application received a PlayForwards event with bEnabled set to false, you could disable the Play button. When it received that event with bEnabled set to true, you could enable the button again.

There are three events that do not relate to UOP controls. The DVDNotify event notifies your application of many different types of DVD-related events, which are identified in the EventCode parameter. Some events have additional information in he Param1 and Param2 parameters. The ReadyStateChange event notifies your application of changes in the MSWebDVD ReadyState property, which is a property common to all ActiveX controls. The UpdateOverlay event is sent to applications only if they are hosting MSWebDVD in windowless mode. Applications need to respond to this event only if they are displaying floating buttons over the video rectangle in full screen mode.

For code samples showing how to handle events, see Handling DVD Event Notifications.

MSWebDVD Methods and Properties

Events

Event | Description
ChangeCurrentAngle | Sent when the disc enables or disables changing the angle.
ChangeCurrentAudioStream | Sent when the disc enables or disables changing the audio stream.
ChangeCurrentSubpictureStream | Sent when the ChangeCurrentSubpictureStream command has been enabled or disabled.
DVDNotify | Notifies an application of many different DVD events and disc instructions.
PauseOn | Sent when the Pause command has been enabled or disabled.
PlayAtTime | Sent when the PlayAtTime command has been enabled or disabled.
PlayAtTimeInTitle | Sent when the PlayAtTimeInTitle command has been enabled or disabled.
PlayBackwards | Sent when the PlayBackwards command has been enabled or disabled.
PlayChapter | Sent when the PlayChapter command has been enabled or disabled.
PlayChapterInTitle | Sent when the PlayChapterInTitle command has been enabled or disabled.
PlayForwards | Sent when the PlayForwards command has been enabled or disabled.
PlayNextChapter | Sent when the PlayNextChapter command has been enabled or disabled.
PlayPrevChapter | Sent when the PlayPrevChapter command has been enabled or disabled.
PlayTitle | Sent when the ReturnFromSubmenu command has been enabled or disabled.
ReadyStateChange | Sent when the ReadyState property of the MSWebDVD control has changed.
ReplayChapter | Sent when the ReplayChapter command has been enabled or disabled.
Resume | Sent when the Resume command has been enabled or disabled.
ReturnFromSubmenu | Sent when the ReturnFromSubmenu command has been enabled or disabled.
SelectOrActivatButton | Sent when the disc enables or disables the selection or activation of menu buttons.
ShowMenu | Sent when the disc enables or disables the showing of a menu.
StillOff | Sent when the StillOff command has been enabled or disabled.
Stop | Sent when the Stop command has been enabled or disabled.
UpdateOverlay | Sent when the overlay surface has been moved or resized or its color key has changed.

ChangeCurrentAngle

MSWebDVD Events

Sent when the disc enables or disables changing the angle.

Syntax

ChangeCurrentAngle(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

ChangeCurrentAudioStream

MSWebDVD Events

Sent when the disc enables or disables changing the audio stream.

Syntax

ChangeCurrentAudioStream(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

ChangeCurrentSubpictureStream

MSWebDVD Events

Sent when the disc enables or disables changing the subpicture stream.

Syntax

ChangeCurrentSubpictureStream(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

DVDNotify

MSWebDVD Events

Notifies an application of many different DVD events and disc instructions.

Syntax

DVDNotify(EventCode, Param1, Param2)

Parameters

EventCode | Specifies the DVD event.
Param1 | Can contain additional information related to the event.
param2 | Can contain additional information related to the event.

See Also

DVD Event Notification Codes gives a full explanation of all DVD event notification codes and their parameters.

PauseOn

MSWebDVD Events

Sent when the PauseOn command has been enabled or disabled.

Syntax

PauseOn(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

PlayAtTime

MSWebDVD Events

Sent when the PlayAtTime command has been enabled or disabled.

Syntax

PlayAtTime(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

PlayAtTimeInTitle

MSWebDVD Events

Sent when the PlayAtTimeInTitle command has been enabled or disabled.

Syntax

PlayAtTimeInTitle(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

PlayBackwards

MSWebDVD Events

Sent when the PlayBackwards command has been enabled or disabled.

Syntax

PlayBackwards(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

PlayChapter

MSWebDVD Events

Sent when the PlayChapter command has been enabled or disabled.

Syntax

PlayChapter(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

PlayChapterInTitle

MSWebDVD Events

Sent when the PlayChapterInTitle command has been enabled or disabled.

Syntax

PlayChapterInTitle(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

PlayForwards

MSWebDVD Events

Sent when the PlayForwards command has been enabled or disabled.

Syntax

PlayForwards(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

PlayNextChapter

MSWebDVD Events

Sent when the PlayNextChapter command has been enabled or disabled.

Syntax

PlayNextChapter(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

PlayPrevChapter

MSWebDVD Events

Sent when the PlayPrevChapter command has been enabled or disabled.

Syntax

PlayPrevChapter(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

PlayTitle

MSWebDVD Events

Sent when the PlayTitle command has been enabled or disabled.

Syntax

PlayTitle(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

ReadyStateChange

MSWebDVD Events

Sent when the ReadyState property of the MSWebDVD control has changed.

Syntax

ReadyStateChange(ReadyState)

Parameters

ReadyState Indicates the new value of the ReadyState property. Can be one of the following values: READYSTATE_UNINITIALIZED = 0; READYSTATE_LOADING = 1; READYSTATE_LOADED = 2; READYSTATE_INTERACTIVE = 3; READYSTATE_COMPLETE = 4.

ReplayChapter

MSWebDVD Events

Sent when the ReplayChapter command has been enabled or disabled.

Syntax

ReplayChapter(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

Resume

MSWebDVD Events

Sent when the Resume command has been enabled or disabled.

Syntax

Resume(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

ReturnFromSubmenu

MSWebDVD Events

Sent when the ReturnFromSubmenu command has been enabled or disabled.

Syntax

ReturnFromSubmenu(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

SelectOrActivatButton

MSWebDVD Events

Sent when the disc enables or disables the selection or activation of menu buttons.

Syntax

SelectOrActivatButton(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

ShowMenu

MSWebDVD Events

Sent when the disc enables or disables the showing of a menu.

Syntax

ShowMenu(DVDMenuIDConstants, bEnabled)

Parameters

DVDMenuIDConstants Number value specifying which menu has been enabled or disabled. Can be one of the following values:
2 | Title
3 | Root
4 | Subpicture
5 | Audio
6 | Angle
7 | Chapter
bEnabled Boolean value that indicates whether the operation is enabled or disabled.

StillOff

MSWebDVD Events

Sent when the StillOff command has been enabled or disabled.

Syntax

StillOff(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

Stop

MSWebDVD Events

Sent when the Stop command has been enabled or disabled.

Syntax

Stop(bEnabled)

Parameters

bEnabled Boolean value that indicates whether the operation is enabled or disabled.

UpdateOverlay

MSWebDVD Events

Sent when the overlay surface has been moved or resized or its color key has changed.

Syntax

UpdateOverlay()

Remarks

Applications should never be concerned about the overlay surface being resized or moved. This is all handled internally. But this event is also sent when the color key changes. That means that if an application is hosting MSWebDVD as a windowless control and displaying floating buttons on top of the video surface in full-screen mode, it should respond to this event by getting the new value of the ColorKey property so that it can draw the buttons properly.


Property Sets

Microsoft® DirectShow® uses property sets to support extended services offered by hardware and its associated drivers and filters. Hardware and filter vendors can define new capabilities as properties, arrange them in property sets, and publish the specification for these property sets. As the application developer, you can use the methods of the IKsPropertySet interface to determine whether a driver or filter supports a particular set of properties, and retrieve or set those properties.

All the methods exposed by IKsPropertySet require a GUID that identifies the property set (the guidPropSet parameter) and a DWORD that identifies the property within the property set (the dwPropID parameter). The dwPropID parameter is typically a member of an enumerated data type.

Individual properties can also have associated data that you specify in the pPropData parameter in the IKsPropertySet::Set and IKsPropertySet::Get methods. IKsPropertySet intentionally leaves these parameters undefined (data type LPVOID), enabling the property set's designer to use them in a way most beneficial to the individual property. The definition of each property provides the purpose of the property data.

DirectShow provides property sets for DVD and capture. The following sections provide more information about these property sets.

  • DVD Copy Protection Property Set
  • DVD Karaoke Property Set
  • DVD Subpicture Property Set
  • Frame Stepping Property Set
  • Pin Property Set


DVD Copy Protection Property Set

The DVD Copy Protection property set provides authentication of copy protection information from hardware or software decrypters. Use this property set to prevent unauthorized copying from prerecorded DVD-Video.

Microsoft provides software that facilitates the authentication process required by the encryption scheme, thus enabling a DVD-ROM drive to authenticate and transfer keys with a DVD decrypter. Microsoft has no current plans to ship a DVD decrypter and, instead, is providing operating system code that will act as the agent to enable authentication of either hardware or software decrypters.

The DVD navigator initiates and controls the key exchange process. The DVD minidriver needs only to implement the following properties. Other components handle the rest.

Each DVD input stream will receive copy protection properties. This is true even if the same hardware controls all DVD streams.

The following information presents the necessary constants and data types to use for this property set in calls to IKsPropertySet methods. It provides values for the GUID (guidPropSet), property ID (dwPropID), and property data type (pPropData) parameters.

Property Set GUID: AM_KSPROPSETID_CopyProt
Property ID | Data type used by the specified property
AM_PROPERTY_COPY_MACROVISION | AM_COPY_MACROVISION
AM_PROPERTY_DVDCOPY_CHLG_KEY | AM_DVDCOPY_CHLGKEY
AM_PROPERTY_DVDCOPY_DEC_KEY2 | AM_DVDCOPY_BUSKEY
AM_PROPERTY_DVDCOPY_DISC_KEY | AM_DVDCOPY_DISCKEY
AM_PROPERTY_DVDCOPY_DVD_KEY1 | AM_DVDCOPY_BUSKEY
AM_PROPERTY_DVDCOPY_REGION | The DVD_REGION structure.
AM_PROPERTY_DVDCOPY_SET_COPY_STATE | AM_DVDCOPY_SET_COPY_STATE
AM_PROPERTY_DVDCOPY_TITLE_KEY | AM_DVDCOPY_TITLEKEY

The following list provides the DVD Copy Protection property IDs and descriptions.

AM_PROPERTY_COPY_MACROVISION
This is a set-only property. This property sets the Macrovision level for the NTSC encoder on the output end of the receiving pin.
AM_PROPERTY_DVDCOPY_CHLG_KEY
Both get and set operations are supported on this property. A get operation requests the decoder to provide its bus challenge key. A set operation provides the decoder with the bus challenge key from the DVD drive. The data passed in this property will be a structure of type AM_DVDCOPY_CHLGKEY.
AM_PROPERTY_DVDCOPY_DEC_KEY2
This is a get-only property. This property requests that the decoder's bus key 2 be transferred to the DVD drive. The data passed will be a structure of type AM_DVDCOPY_BUSKEY.
AM_PROPERTY_DVDCOPY_DISC_KEY
Set-only property. This provides disc key. The key is a structure of type AM_DVDCOPY_DISCKEY.
AM_PROPERTY_DVDCOPY_DVD_KEY1
This is a set-only property. This property provides the DVD drive bus key 1 to the decoder. The data passed will be a structure of type AM_DVDCOPY_BUSKEY.
AM_PROPERTY_DVDCOPY_SET_COPY_STATE
Both get and set are supported on this property. Get is called first to determine if authentication is required. The set properties are indications as to which phase of copy protection negotiation the filter is entering. The data passed will be a structure of type AM_DVDCOPY_SET_COPY_STATE.
AM_PROPERTY_DVDCOPY_REGION
Region code requests the region definition that the decoder is allowed to play in as defined by the DVD consortium. This region is defined by the following structure:
typedef struct _DVD_REGION {
   UCHAR CopySystem;   //specifies whether the disk is copy protected
   UCHAR RegionData;    //information about the region from decoder
   UCHAR SystemRegion;  //information about region from DVD drive
   UCHAR Reserved; //reserved
} DVD_REGION, *PDVD_REGION;
AM_PROPERTY_DVDCOPY_TITLE_KEY
This is a set-only property. This provides title key from current content. The key is a structure of type AM_DVDCOPY_TITLEKEY.

Use the IKsPropertySet interface to set, retrieve, and query for support of these properties.

This property set uses the following data types.
Data type | Description
AM_COPY_MACROVISION | Macrovision level for the NTSC encoder.
AM_COPY_MACROVISION_LEVEL | Macrovision level. The AM_COPY_MACROVISION structure uses this data type.
AM_DVDCOPY_BUSKEY | DVD bus key.
AM_DVDCOPY_CHLGKEY | DVD challenge key.
AM_DVDCOPY_DISCKEY | DVD disc key.
AM_DVDCOPY_SET_COPY_STATE | Determines the copy protection state of the filter.
AM_DVDCOPYSTATE | Copy protection state. The AM_DVDCOPY_SET_COPY_STATE structure uses this data type.
AM_DVDCOPY_TITLEKEY | DVD title key from the current content.

AM_COPY_MACROVISION

DVD Copy Protection Property Set

Macrovision level for the NTSC encoder.

Syntax

typedef struct _AM_COPY_MACROVISION {
    ULONG MACROVISIONLevel;
} AM_COPY_MACROVISION, *PAM_COPY_MACROVISION;

Members

MACROVISIONLevel
Macrovision level for the NTSC encoder. Member of the AM_COPY_MACROVISION_LEVEL enumerated data type.

Remarks

The AM_PROPERTY_COPY_MACROVISION property uses this structure.

AM_COPY_MACROVISION_LEVEL

DVD Copy Protection Property Set

Macrovision level.

Syntax

typedef enum {
    AM_MACROVISION_DISABLED,
    AM_MACROVISION_LEVEL1,
    AM_MACROVISION_LEVEL2,
    AM_MACROVISION_LEVEL3
} AM_COPY_MACROVISION_LEVEL, *PAM_COPY_MACROVISION_LEVEL;

Elements

AM_MACROVISION_DISABLED
Disabled.
AM_MACROVISION_LEVEL1
Level 1.
AM_MACROVISION_LEVEL2
Level 2.
AM_MACROVISION_LEVEL3
Level 3.

Remarks

The AM_COPY_MACROVISION structure uses this data type.

AM_DVDCOPY_BUSKEY

DVD Copy Protection Property Set

DVD bus key.

Syntax

 typedef struct _AM_DVDCOPY_BUSKEY {
    BYTE BusKey[5];
    BYTE Reserved[1];
} AM_DVDCOPY_BUSKEY, *PAM_DVDCOPY_BUSKEY;

Members

BusKey
DVD drive bus key.
Reserved
Reserved.

Remarks

The AM_PROPERTY_DVDCOPY_DVD_KEY1 and AM_PROPERTY_DVDCOPY_DEC_KEY2 properties use this structure.

A bus key is used for the DVD CSS key exchange for decryption. Implementors should get a CSS license and further instructions from CSS. See DVD-Video specification for contact information.

AM_DVDCOPY_CHLGKEY

DVD Copy Protection Property Set

DVD challenge key.

Syntax

 typedef struct _AM_DVDCOPY_CHLGKEY {
    BYTE ChlgKey[10];
    BYTE Reserved[2];
} AM_DVDCOPY_CHLGKEY, *PAM_DVDCOPY_CHLGKEY;

Members

ChlgKey
Challenge key.
Reserved
Reserved.

Remarks

The AM_PROPERTY_DVDCOPY_CHLG_KEY property uses this structure.

A challenge key is used for the DVD CSS key exchange for decryption. Implementors should get a CSS license and further instructions from CSS. See DVD-Video specification for contact information.

AM_DVDCOPY_DISCKEY

DVD Copy Protection Property Set

DVD disc key.

Syntax

 typedef struct _AM_DVDCOPY_DISCKEY {
    BYTE DiscKey[2048];
} AM_DVDCOPY_DISCKEY, *PAM_DVDCOPY_DISCKEY;

Members

DiscKey
DVD disc key.

Remarks

The AM_PROPERTY_DVDCOPY_DISC_KEY property uses this structure.

A disc key is used for the DVD CSS key exchange for decryption. Implementors should get a CSS license and further instructions from CSS. See DVD-Video specification for contact information.

AM_DVDCOPY_SET_COPY_STATE

DVD Copy Protection Property Set

Determines the copy protection state of the filter.

Syntax

typedef struct AM_DVDCOPY_SET_COPY_STATE {
    ULONG DVDCopyState;
} AM_DVDCOPY_SET_COPY_STATE, *PAM_DVDCOPY_SET_COPY_STATE;

Members

DVDCopyState
Copy protection state of the filter. Member of the AM_DVDCOPYSTATE enumerated data type.

Remarks

Both the IKsPropertySet::Get and IKsPropertySet::Set methods are supported on this property. The IKsPropertySet::Get method is called first to determine if authentication is required. If a filter provides multiple pins that use the same authenticator, such as a hardware DVD decoder, the decoder might respond with AM_DVDCOPYSTATE_AUTHENTICATION_NOT_REQUIRED on some pins to indicate that the key exchange algorithm only needs to be applied once. The filter should respond with AM_DVDCOPYSTATE_AUTHENTICATION_REQUIRED to get the copy protection state property on the first pin where this property is issued.

The IKsPropertySet::Set method is used to indicate which phase of copy protection negotiation the filter is entering. Specify these by setting the required flag in the AM_DVDCOPYSTATE enumerated type.

The AM_PROPERTY_DVDCOPY_SET_COPY_STATE property uses this structure.

AM_DVDCOPYSTATE

DVD Copy Protection Property Set

Copy protection state.

Syntax

typedef enum {
    AM_DVDCOPYSTATE_INITIALIZE,
AM_DVDCOPYSTATE_INITIALIZE_TITLE,
    AM_DVDCOPYSTATE_AUTHENTICATION_NOT_REQUIRED,
    AM_DVDCOPYSTATE_AUTHENTICATION_REQUIRED,
    AM_DVDCOPYSTATE_DONE
} AM_DVDCOPYSTATE;

Elements

AM_DVDCOPYSTATE_INITIALIZE
Starting a full key-exchange algorithm.
AM_DVDCOPYSTATE_INITIALIZE_TITLE
Starting a title key-exchange algorithm.
AM_DVDCOPYSTATE_AUTHENTICATION_NOT_REQUIRED
Authentication is not required.
AM_DVDCOPYSTATE_AUTHENTICATION_REQUIRED
Authentication required.
AM_DVDCOPYSTATE_DONE
Key exchange negotiation is complete.

Remarks

The AM_DVDCOPY_SET_COPY_STATE structure uses this data type.

AM_DVDCOPY_TITLEKEY

DVD Copy Protection Property Set

DVD title key from the current content.

Syntax

 typedef struct AM_DVDCOPY_TITLEKEY {
    ULONG KeyFlags;
    UCHAR TitleKey[6];
    UCHAR Reserved[2];
} AM_DVDCOPY_TITLEKEY, *PAM_DVDCOPY_TITLEKEY;

Members

KeyFlags
Key flags.
TitleKey
Title key.
Reserved
Reserved.

Remarks

The AM_PROPERTY_DVDCOPY_TITLE_KEY property uses this structure.

A title key is used for the DVD CSS key exchange for decryption. Implementors should get a CSS license and further instructions from CSS. See DVD-Video specification for contact information.


DVD Karaoke Property Set

When the DVD Navigator filter goes into karaoke mode, it informs the audio decoder through the AM_PROPERTY_DVDKARAOKE_ENABLE property. The decoder should then mute audio channels 2 through 5 until it receives from the DVD Navigator an AM_PROPERTY_DVDKARAOKE_DATA property with a pointer to an AM_DvdKaraokeData data structure indicating how the auxiliary channels are to be mixed.

AM_PROPERTY_DVDKARAOKE

DVD Karaoke Property Set

Syntax

typedef enum {
    AM_PROPERTY_DVDKARAOKE_ENABLE = 0,  // BOOL
    AM_PROPERTY_DVDKARAOKE_DATA = 1,
} AM_PROPERTY_DVDKARAOKE;

Elements

AM_PROPERTY_DVDKARAOKE_ENABLE
The DVD Navigator sends the decoder an AM_PROPERTY_DVDKARAOKE_ENABLE with a value of true to enable karaoke downmixing or false to disable it.
AM_PROPERTY_DVDKARAOKE_DATA
The DVD Navigator sends the decoder an AM_PROPERTY_DVDKARAOKE_DATA property with a pointer to an AM_DvdKaraokeData structure to change the downmix configuration; that is, to turn certain karaoke channels on or off and direct them to the right or left output channel.

AM_DvdKaraokeData

DVD Karaoke Property Set

Syntax

typedef struct tagAM_DvdKaraokeData
{
    DWORD   dwDownmix;
    DWORD   dwSpeakerAssignment;
} AM_DvdKaraokeData;

Members

dwDownmix
A bitwise OR of DVD_KARAOKE_DOWNMIX flags telling the decoder which channels are downmixed to channels 0 or 1.
dwSpeakerAssignment
A valid DVD_KARAOKE_ASSIGNMENT value that indicates which speakers the output is going to.

See Also

SelectKaraokeAudioPresentationMode


DVD Subpicture Property Set

DVD Subpicture properties control the color, contrast, and output of the subpicture display.

The following information presents the necessary constants and data types to use for this property set in calls to IKsPropertySet methods. It provides values for the GUID (guidPropSet), property ID (dwPropID), and property data type (pPropData) parameters.

Property Set GUID: AM_KSPROPSETID_DvdSubPic

Property ID | Data type used by the specified property
AM_PROPERTY_DVDSUBPIC_COMPOSIT_ON | AM_PROPERTY_COMPOSIT_ON
AM_PROPERTY_DVDSUBPIC_HLI | AM_PROPERTY_SPHLI
AM_PROPERTY_DVDSUBPIC_PALETTE | AM_PROPERTY_SPPAL

The following list provides the Subpicture property IDs and descriptions.

AM_PROPERTY_DVDSUBPIC_COMPOSIT_ON
Set-only property that enables or disables subpicture display. Microsoft® DirectShow® defines the AM_PROPERTY_COMPOSIT_ON Boolean data type for this property, as well as PAM_PROPERTY_COMPOSIT_ON as a pointer to this data type. TRUE indicates display the subpicture, FALSE indicates disable it. See the WDM portion of the Windows 98 DDK for more information.
AM_PROPERTY_DVDSUBPIC_HLI
Set-only property that specifies a rectangle of subpicture or screen whose color or contrast will be changed. Data type is AM_PROPERTY_SPHLI.

The AM_PROPERTY_DVDSUBPIC_HLI property is set-only. It specifies a rectangle of subpicture or screen whose color or contrast will be changed. This differs from the DVD-Video specification, in that the Microsoft DVD navigator parses all button and keyboard information and passes only one highlight rectangle to the subpicture decoder at any given time. As a result, highlight information is sent to the decoder more often than it is present in the DVD stream.

The highlight information arrives asynchronously to the data stream. The decoder uses the highlight Start and End time stamps to correlate the highlight information to the relevant subpicture information, if any. If the decoder has not received any subpicture stream information for the requested time stamps, the decoder assumes that the highlight information is stand-alone and does not apply to a subpicture. In this case, the decoder assumes the color and contrast information is all the same color.

The data is not entirely in DVD disc format. Microsoft provides an additional structure of type AM_PROPERTY_SPHLI that is passed as the parameter to this property. This structure describes the currently selected button from the DVD highlight information.

The DVD navigator processes all keystroke information and sends new highlight information each time a button state changes. The information describes only one mode of one button at a time. It includes a display rectangle in pixel coordinates of the screen, or a display of the subpicture, if present. The structure also contains color and contrast information, but only for the present state of the currently selected button. The format is defined in the DVD specification.

Highlight information contains Start and End time stamps. These are in the same units as other time stamps, with two exceptions: A Start time stamp of 0xFFFFFFFF means the highlight property is effective upon receipt, and an End time stamp of 0xFFFFFFFF means the highlight property is valid until next highlight received.

The HLISS field is as defined in the DVD specification. A value of zero indicates that all highlights are invalid and the decoder should disable all highlights.

AM_PROPERTY_DVDSUBPIC_PALETTE
Sets the palette for a subpicture. Data type is AM_PROPERTY_SPPAL.

Use the IKsPropertySet interface to set, retrieve, and query for support of these properties.

This property set uses the following data types.

Data type | Description
AM_COLCON | Specifies the color contrast. Substructure of the AM_PROPERTY_SPHLI structure.
AM_DVD_YUV | Specifies DVD YUV subpicture data. Substructure of the AM_PROPERTY_SPPAL structure.
AM_PROPERTY_COMPOSIT_ON | Boolean data used by the AM_PROPERTY_DVDSUBPIC_COMPOSIT_ON property.
AM_PROPERTY_SPHLI | Describes the currently selected button from the DVD highlight information.
AM_PROPERTY_SPPAL | Specifies the DVD subpicture palette.

AM_COLCON

DVD Subpicture Property Set

Indicates the color contrast description from the DVD highlight (HLI) structure.

Syntax

 typedef struct _AM_COLCON {
    UCHAR emph1col:4;
    UCHAR emph2col:4;
    UCHAR backcol:4;
    UCHAR patcol:4;
    UCHAR emph1con:4;
    UCHAR emph2con:4;
    UCHAR backcon:4;
    UCHAR patcon:4;
} AM_COLCON, *PAM_COLCON;

Members

emph1col
Emphasis color 1.
emph2col
Emphasis color 2.
backcol
Background color.
patcol
Pattern color.
emph1con
Emphasis contrast 1.
emph2con
Emphasis contrast 2.
backcon
Background contrast.
patcon
Pattern contrast.

Remarks

This structure is contained within the AM_PROPERTY_SPHLI structure.

AM_DVD_YUV

DVD Subpicture Property Set

DVD YUV subpicture data.

Syntax

 typedef struct _AM_DVD_YUV {
    UCHAR   Reserved;
    UCHAR   Y;
    UCHAR   U;
    UCHAR   V;
} AM_DVD_YUV, *PAM_DVD_YUV;

Members

Reserved
Reserved.
Y
Y color data.
U
U color data.
V
V color data.

Remarks

This structure is contained within the AM_PROPERTY_SPPAL structure.

AM_PROPERTY_SPHLI

DVD Subpicture Property Set

Describes the currently selected button from the DVD highlight information.

Syntax

 typedef struct _AM_PROPERTY_SPHLI {
    USHORT  HLISS;
    USHORT  Reserved;
    ULONG   StartPTM;
    ULONG   EndPTM;
    USHORT  StartX;
    USHORT  StartY;
    USHORT  StopX;
    USHORT  StopY;
    AM_COLCON  ColCon;
} AM_PROPERTY_SPHLI, *PAM_PROPERTY_SPHLI;

Members

HLISS
Highlight status of current selection.
Reserved
Reserved for internal use. Do not use or set.
StartPTM
Start presentation time divided by 90,000.
EndPTM
End presentation time divided by 90,000.
StartX
Start x-coordinate pixel of the current highlight button.
StartY
Start y-coordinate pixel of the current highlight button.
StopX
Ending x-coordinate pixel of the current highlight button.
StopY
Ending y-coordinate pixel of the current highlight button.
ColCon
Color contrast description of type AM_COLCON.

Remarks

The AM_PROPERTY_DVDSUBPIC_HLI property uses this structure.

AM_PROPERTY_SPPAL

DVD Subpicture Property Set

Specifies the DVD subpicture palette.

Syntax

 typedef struct _AM_PROPERTY_SPPAL {
    AM_DVD_YUV sppal[16];
} AM_PROPERTY_SPPAL, *PAM_PROPERTY_SPPAL;

Members

sppal
Array of 16 YUV elements that correspond to the 4-bit color numbers requested within the subpicture command stream. The YUV elements are of type AM_DVD_YUV.

Remarks

The AM_PROPERTY_DVDSUBPIC_PALETTE property uses this structure.


Frame Stepping Property Set

Decoders that implement frame-accurate seeking under Microsoft® DirectShow® must implement the AM_KSPROPSETID_FrameStep property set, which is used in conjunction with the IVideoFrameStep interface. This property set consists of two properties. AM_PROPERTY_FRAMESTEP is used to pass the step commands and stepping-capability information, and AM_FRAMESTEP_STEP is used to specify the number of frames to step.

Syntax

typedef enum {
        AM_PROPERTY_FRAMESTEP_STEP   = 0x01,
        AM_PROPERTY_FRAMESTEP_CANCEL = 0x02,
        AM_PROPERTY_FRAMESTEP_CANSTEP = 0x03,
        AM_PROPERTY_FRAMESTEP_CANSTEPMULTIPLE = 0x04
} AM_PROPERTY_FRAMESTEP;

Members

AM_PROPERTY_FRAMESTEP_STEP
Instructs the decoder to begin a step operation.
AM_PROPERTY_FRAMESTEP_CANCEL
Instructs the decoder to cancel the current step operation.
AM_PROPERTY_FRAMESTEP_CANSTEP
The decoder returns S_OK on this instruction to indicate that it can perform frame stepping, S_FALSE otherwise.
AM_PROPERTY_FRAMESTEP_CANSTEPMULTIPLE
The decoder returns S_OK on this instruction to indicate that it can step multiple frames at a time, S_FALSE otherwise.
typedef struct _AM_FRAMESTEP_STEP
{
    DWORD dwFramesToStep;
} AM_FRAMESTEP_STEP;

AM_FRAMESTEP_STEP Members

dwFramesToStep
DWORD value specifying to the decoder the number of frames to step. Must be at least 1. If greater than one, this instruction means to skip (n - 1) frames and show the nth.


Pin Property Set

The pin property set enables you to retrieve the category to which a pin belongs, if any. The category is set by the filter when it creates the pin; the category indicates what type of data the pin is streaming. The most commonly used categories are for the capture and preview pins on a capture filter. The AMCap sample in the [SDK Root]/samples/multimedia/DirectShow/Capture/AMCap directory illustrates how to use this property set when building filter graphs based on video capture devices that conform to the Windows Driver Model (WDM).

The following information presents the necessary constants and data types to use for this property set in calls to IKsPropertySet methods. It provides values for the GUID (guidPropSet), property ID (dwPropID), and property data type (pPropData) parameters.

Property Set GUID: AMPROPSETID_Pin

The AMPROPERTY_PIN_CATEGORY pin category property is the only property in this property set. This property uses a GUID data type. Microsoft® DirectShow® defines the following pin categories in Uuids.h, which you can find in the SDK Include directory.

Category | Description
PIN_CATEGORY_ANALOGVIDEOIN | Input pin of the capture filter that takes analog and digitizes it.
PIN_CATEGORY_CAPTURE | Capture pin.
PIN_CATEGORY_CC | Pin providing closed captioning data from Line 21.
PIN_CATEGORY_EDS | Pin providing Extended Data Services (Line 21, even fields).
PIN_CATEGORY_NABTS | Pin providing North American Videotext Standard data.
PIN_CATEGORY_PREVIEW | Preview pin.
PIN_CATEGORY_STILL | Pin providing a still image.
PIN_CATEGORY_TELETEXT | Pin providing teletext (a closed captioning variant).
PIN_CATEGORY_TIMECODE | Pin providing timecode data.
PIN_CATEGORY_VBI | Pin providing vertical blanking interval data.
PIN_CATEGORY_VIDEOPORT | Video output pin to be connected to input pin zero on the Overlay Mixer.
PIN_CATEGORY_VIDEOPORT_VBI | Pin to be connected to VBISurf, the VBI surface allocator filter that is needed to allocate the correct video memory for things like closed captioning overlays in scenarios where a video port is being used. PCI, IEEE 1394, and USB scenarios do not use this filter. For more information, see Microsoft TV Technologies.

Use the IKsPropertySet interface to set, retrieve, and query for support of these properties.


DirectShow Components

This topic contains reference entries for the COM components included with Microsoft® DirectShow®, other than filters. For a list of filters included with DirectShow, see Filters.

Component | Description
Capture Graph Builder | Builds video capture graphs.
DVD Graph Builder | Builds DVD playback graphs.
Filter Graph Manager | Builds and controls filter graphs.
Filter Mapper | Searches the registry for registered filters.
Media Property Bag | Sets or retrieves INFO and DISP chunks in AVI files.
Memory Allocator | Allocates buffers for media samples.
SeekingPassThru | Helper object that implements seeking for filters with one input pin.
System Reference Clock | Implements a reference clock.
System Device Enumerator | Enumerates filters and hardware devices installed on the system.

Capture Graph Builder

Builds video capture graphs. Video capture or editing applications can use this component to construct filter graphs.

Class Identifier | CLSID_CaptureGraphBuilder2
Interfaces | ICaptureGraphBuilder2
See Also | Video Capture, Video Editing Services

DVD Graph Builder

Builds DVD playback graphs. Applications can use this component to build filter graphs for DVD playback and navigation.

Class Identifier | CLSID_DvdGraphBuilder
Interfaces | IDvdGraphBuilder
See Also | DVD Application Development in DirectShow

Filter Graph Manager

Builds and controls filter graphs. The filter graph manager is the central component in DirectShow. Applications use it to build and control filter graphs. The filter graph manager also handles synchronization, event notification, and other aspects of the filter graph.

Class Identifier | CLSID_FilterGraph
Interfaces | IAMGraphStreams, IBasicAudio, IBasicVideo, IBasicVideo2, IFilterChain, IFilterGraph, IFilterGraph2, IFilterMapper2, IGraphBuilder, IGraphConfig, IGraphVersion, IMediaControl, IMediaEvent, IMediaEventEx, IMediaEventSink, IMediaFilter, IMediaPosition, IMediaSeeking, IQueueCommand, IResourceManager, IVideoFrameStep, IVideoWindow

Filter Mapper

Searches the registry for registered filters. The filter graph manager uses this component to build filter graphs. Applications can use it to find filters that match specified search criteria.

Class Identifier | CLSID_FilterMapper2
Interfaces | IFilterMapper2
See Also | Enumerating Devices and Filters

Media Property Bag

Sets or retrieves INFO and DISP chunks in AVI files.

Class Identifier | CLSID_MediaPropertyBag
Interfaces | IMediaPropertyBag
See Also | IPersistMediaPropertyBag

Memory Allocator

Allocates buffers for media samples. Filters use this component to allocate shared memory buffers.

Class Identifier | CLSID_MemoryAllocator
Interfaces | IMemAllocator

SeekingPassThru

Helper object that implements seeking for filters with one input pin. One-input filters can use this object to implement the IMediaSeeking and IMediaPosition interfaces.

Class Identifier | CLSID_SeekingPassThru
Interfaces | ISeekingPassThru
See Also | CPosPassThru, CRendererPosPassThru

System Reference Clock

Implements a reference clock. If none of the filters in the graph provides a reference clock, the filter graph manager uses this component to synchronize the graph.

Class Identifier | CLSID_SystemClock
Interfaces | IAMClockAdjust, IReferenceClock
See Also | Time and Clocks in DirectShow

System Device Enumerator

Enumerates filters and hardware devices installed on the system. Applications can use this component to locate filters and devices in a given category.

Class Identifier | CLSID_SystemDeviceEnum
Interfaces | ICreateDevEnum
See Also | Filter Categories, Enumerating Devices and Filters


DirectShow Base Classes

The Microsoft® DirectShow® base classes are a set of C++ classes and utility functions designed for implementing DirectShow filters. Several of the helper classes are also useful for application developers.

This section describes the base classes. It contains the following sections:

  • Using the DirectShow Base Classes
  • Base Class Reference
  • Utility Functions
  • Debugging Utilities


Using the DirectShow Base Classes

To use the base classes in Microsoft® DirectShow®, you must build and link the base class library, located in the following directory:

(SDK root)\Samples\Multimedia\DirectShow\BaseClasses

Note Previous versions of the SDK included the libary as a binary file. With Microsoft® DirectX® 8.0, you must build this library yourself if you plan to use the base classes.

The project workspace for the base classes is named BaseClasses.dsw. The project builds two versions of the library—a retail version, Strmbase.lib, and a debug version, Strmbasd.lib. In your own project, include the header file Streams.h. Link your project either to Strmbase.lib or to Strmbasd.lib, depending on whether you are making a retail build or a debug build. For debug builds, define the preprocessor symbol DEBUG before including the header file.

The table that follows summarizes the files you need.

Workspace | BaseClasses.dsw
Retail Library | Strmbase.lib
Debug Library | Strmbasd.lib
Header File | Streams.h

For more information on setting up your build environment, see Setting Up the Build Environment.

Preprocessor Symbols

When you include the header file Streams.h, the following preprocessor symbols have special meaning:

  • DEBUG: Debug build. This preprocessor symbol enables a number of debugging utilities. For more information, see Debugging Utilities
  • PERF: Reserved. Do not use this preprocessor symbol.
  • VFWROBUST: Enables pointer validation. For more information, see Pointer Validation Macros. If DEBUG is defined, it is not necessary to define VFWROBUST.


Base Class Reference

This section contains reference entries for all the Microsoft® DirectShow® C++ classes, their data members, and their functions.

  • Introduction to the Filter Base Classes
Class | Description
CAggDirectDraw | Aggregates an IDirectDraw interface
CAggDrawSurface | Aggregates an IDirectDrawSurface interface.
CAMEvent | Wrapper class for manual- and auto-reset events.
CAMMsgEvent | Wrapper class for event objects that perform message processing.
CAMSchedule | Scheduler for reference clocks.
CAMThread | Bass class for managing worker threads.
CAutoLock | Holds a critical section for the scope of a block.
CAutoUsingOutputPin | Obtains and releases access to a CDynamicOutputPin object.
CBaseAllocator | Bass class for allocators.
CBaseBasicVideo | Handles the IDispatch component of the IBasicVideo interface.
CBaseControlVideo | Implements the IBasicVideo interface for a generic video window
CBaseControlWindow | Implements the IVideoWindow interface.
CBaseDispatch | Base class for implementing the IDispatch interface.
CBaseFilter | Base class for filters.
CBaseInputPin | Base class for input pins.
CBaseList | Base class for generic lists.
CBaseMediaFilter | Implements the IMediaFilter interface.
CBaseObject | Base class for implementing DirectShow objects.
CBaseOutputPin | Base class for output pins.
CBasePin | Base class for pins.
CBasePropertyPage | Base class for implementing property pages.
CBaseReferenceClock | Implements a reference clock.
CBaseRenderer | Base class for implementing renderer filters.
CBaseStreamControl | Implements the IAMStreamControl interface.
CBaseVideoRenderer | Base class for video renderers.
CBaseVideoWindow | Handles the IDispatch component of the IVideoWindow interface.
CBaseWindow | Base class for managing windows.
CBasicAudio | Handles the IDispatch interface component of the IBasicAudio interface.
CCmdQueue | Helper class for implementing the IQueueCommand interface.
CCritSec | Provides a thread lock.
CCrossbar | Helper class for manipulating cross bar filters.
CDeferredCommand | Implements the IDeferredCommand interface.
CDispParams | Wrapper class for the DISPPARAMS structure.
CDrawImage | Helper class for drawing to a window.
CDynamicOutputPin | Output pin that supports dyanamic reconnections and format changes.
CEnumMediaTypes | Enumerator for preferred media types.
CEnumPins | Enumerator for pins.
CFactoryTemplate | Class that provides information for a class factory.
CGenericList | Class template that implements a type-specific list.
CImageAllocator | Allocator for DIB sections.
CImageDisplay | Helper class for managing image display formats.
CImagePalette | Helper class for managing palettes.
CImageSample | Media sample that uses DIB sections.
CLoadDirectDraw | Helper class for loading and unloading the Microsoft® DirectDraw® library.
CMediaControl | Handles the IDispatch methods of the IMediaControl interface.
CMediaEvent | Handles the IDispatch methods of the IMediaEvent interface.
CMediaPosition | Handles the IDispatch methods of the IMediaPosition interface
CMediaSample | Media sample.
CMediaType | Class for managing media types.
CMemAllocator | Memory allocator.
CMsg | Helper class for managing requests made to a CMsgThread object.
CMsgThread | Worker thread that queues requests to the queuing thread for asynchronous completion.
COARefTime | Converts reference times between seconds and 100-nanosecond units.
COutputQueue | Object that queues media samples for delivery.
CPersistStream | Base class for implementing the IPersistStream interface.
CPosPassThru | Handles seek commands for filters with one input pin.
CPullPin | Helper class that pulls data from an output pin that supports the IAsyncReader interface.
CQueue | Class template that implements a simple, statically sized queue.
CRefTime | Helper class to manage reference times.
CRenderedInputPin | Input pin for renderer filters that support multiple inputs.
CRendererInputPin | Input pin for the CBaseRenderer class.
CRendererPosPassThru | Handles seek commands for renderer filters.
CSeekingPassThru | Helper object that creates CPosPassThru and CRendererPosPassThru objects.
CSource | Base class for implementing source filters.
CSourcePosition | Abstract class for implementing the IMediaPosition interface. Obsolete.
CSourceSeeking | Abstract class for implementing seeking in source filters with one output pin
CSourceStream | Output pin for the CSource class.
CSystemClock | System clock.
CTransformFilter | Base class for implementing transform filters.
CTransformInputPin | Input pin used by the CTransformFilter class.
CTransformOutputPin | Output pin used by the CTransformFilter class.
CTransInPlaceFilter | Class for implementing transform filters that do not copy data.
CTransInPlaceInputPin | Input pin for the CTransInPlaceFilter class.
CTransInPlaceOutputPin | Output pin for the CTransInPlaceFilter class.
CUnknown | Implements the IUnknown interface.
CVideoTransformFilter | Base class for video transform filters.
FOURCCMap | Helper class for converting between GUIDs and FOURCCs.


Introduction to the Filter Base Classes

This article provides a general description of the Microsoft® DirectShow® class library, the relationship of the base classes to the DirectShow Component Object Model (COM) interfaces that they implement, and describes the utility classes that are not directly associated with interfaces. This article does not provide low-level descriptions of each class, nor does it provide specific instructions on how to use them to build a filter or run the filter graph manager.

The DirectShow C++ class library can help you implement the required interfaces on filters that you write. Most base classes correspond directly to interfaces, while other utility classes allow integration of Microsoft Win32® functionality, such as critical sections and thread management.

This article contains the following sections.

  • Base Classes
  • Utility Classes

Base Classes

Most of the base classes in the DirectShow class library implement DirectShow COM interfaces. These classes produce C++ objects that provide an IUnknown interface so external components can access the interfaces the objects support.

This section contains the following topics.

  • CBaseObject and CUnknown Classes
  • Base Classes that Implement Interfaces

CBaseObject and CUnknown Classes

The CBaseObject class is the root of all base classes. It exists primarily to provide debugging assistance by keeping a count of all DirectShow objects that are active. All derived base class constructors provide a debugging object name as the first parameter and call the CBaseObject constructor. You can view the debugging object name sent to this base class on a debugging monitor.

CUnknown class hierarchy

All DirectShow classes that implement interfaces derive from a base class called CUnknown, which is derived from CBaseObject. CUnknown implements the INonDelegatingUnknown interface which, like the IUnknown interface, provides methods to request an interface, and to add or release references to that interface.

Why are there two interfaces that implement the services of IUnknown? Because of aggregation. Aggregation is the COM term for the combining of more than one object into a single larger object. Although filter graph objects, such as filters and pins, are rarely aggregated, the design is available for future extensibility and also for implementing plug-in distributors (PID), which are objects that are aggregated with the filter graph manager. In an aggregated object, the outer object (the one containing the other objects) uses the IUnknown interface to communicate outside the object. The IUnknown interface on the outer object passes out references to the IUnknown interfaces of its internal objects. That is, when an application calls the IUnknown interface on the outer object and asks for the interface belonging to one of its internal objects, the outer object calls the IUnknown interface of the internal object to retrieve the requested interface.

Because the internal objects must delegate IUnknown interfaces to the IUnknown of the outer object, the IUnknown interface of the internal object should not be accessed privately (that is, without going through the outer object's IUnknown interface). The internal object's IUnknown is reserved exclusively for communicating through the outer object. However, it is possible that objects will want to connect to other objects privately, without knowledge of the outer object. For example, pins on filters are likely to need to query interfaces on pins of other objects privately.

The INonDelegatingUnknown interface provides direct, private access to interfaces, regardless of whether or not the object is aggregated. Direct access is important in most of the communication between the DirectShow objects such as pins, allocators, and filters, and is the default method of communication. In fact, the base classes implement the IUnknown interface on nonaggregated objects (which includes almost every object in the filter graph) to call the nondelegating interface directly.

Base Classes that Implement Interfaces

The majority of classes in the DirectShow class library implement COM interfaces and can be categorized as follows:

  • Filter base classes implement the IBaseFilter interface, and include CBaseFilter and classes derived from it.
  • Pin classes implement the IPin interface, and include CBasePin and derived classes.
  • Enumerator classes include CEnumPins and CEnumMediaTypes.
  • Transport base classes include CMediaSample, CBaseAllocator, CMemAllocator, and their derived classes. These classes share memory between pins and pass media samples using that memory.
  • Control and position classes include CBaseFilter, CMediaPosition, CMediaControl, CBaseMediaFilter, CSourceSeeking, and CBaseStreamControl.
  • Clock base classes include CBaseReferenceClock and CSystemClock.

This topic contains the following subtopics.

  • Filter Base Classes
  • Pin Base Classes
  • Enumerator Base Classes
  • Transport Base Classes
  • Media Control and Positioning Classes
  • Clock Base Classes

Filter Base Classes

The DirectShow stream architecture is based on filters and pins. Filters communicate with the filter graph manager and with the pins on the filter. Pins connect filters and handle transporting the data down the stream.

Hierarchy of filter base classes

CBaseFilter is the base class for all filter classes. It implements the IBaseFilter interface, which specifies methods that allow the filter graph manager to create and enumerate pins, retrieve filter information, and notify the filter that it has been added to a filter graph. CBaseFilter also implements the IMediaFilter interface (from which IBaseFilter derives) to allow the filter to receive run, pause, and stop commands from the filter graph manager. This base class adds member functions to retrieve the pin count, retrieve pointers to individual pins, and retrieve the pin version.

The CBaseMediaFilter class also implements the IMediaFilter interface. However, because IMediaFilter is also implemented by CBaseFilter, this class is seldom used except to write a plug-in distributor (PID).

Several classes are derived directly from CBaseFilter. Each of these classes provides a base class for implementing a specific type of filter. These include:

  • CSource, a base class for source filters.
  • CTransformFilter, a base class for transform filters.
  • CBaseRenderer, a base class for renderer filters.

The CSource filter class works in conjunction with the CSourceStream pin class to help create a source filter. Most of the work is done in the pin class, and CSource adds pin creation and deletion member functions. The CSourcePosition class implements a source filter.

The CTransformFilter class implements a transform filter. Derive your transform class from CTransformFilter if you want to make a copy of the data. The CTransInPlaceFilter class, derived from CTransformFilter, allows in-place transforms that do not copy the data. These transform filter classes work in conjunction with similarly named pin classes (for example, CTransformOutputPin and CTransformInputPin). Most member functions in the pin classes are implemented to call member functions in the transform filter class, so typically you need only to derive your filter from the filter class and override a few member functions to implement a transform filter.

CTransformFilter adds several member functions to those inherited from CBaseFilter. Some of these are pure virtual member functions that the derived class must override. One example is the CTransformFilter::Transform member function, which is called when the input pin receives a sample. This member function provides the core of the transform functionality. Other member functions to be overridden also involve implementations that are specific to the derived class, such as verifying media types on pins and allocating the correct amount of memory. Additionally, several CTransformFilter member functions are called at various points in the connection or streaming process; the derived class can override these to handle requirements such as adding or releasing references to interfaces.

The CVideoTransformFilter class derives from the CTransformFilter class and is used as a base class for filters that can affect the quality of a rendered video by dropping frames when the video renderer sends quality-control messages. This class is primarily used by video decompressors.

The CBaseRenderer class and its derived class, CBaseVideoRenderer, are the base filter classes that implement a video renderer filter. The video renderer filter used in DirectShow is derived from CBaseVideoRenderer. There are other renderer classes that work in conjunction with these classes but are not derived from CBaseFilter. These classes are:

  • CRendererInputPin
  • CBaseControlVideo and its base class CBaseBasicVideo
  • CBaseControlWindow, and its base classes CBaseVideoWindow and CBaseWindow
  • CAggDirectDraw
  • CAggDrawSurface

The following illustration shows all the classes that support renderers that are not derived from either CBaseFilter or CBasePin.

Hierarchy of classes that support renderers that aren't derived from CBaseFilter or CBasePin

Pin Base Classes

Pins have a greater share of the work than filters. A pin must expose methods so that the filter graph manager can connect it with a pin on another filter. Pins also expose methods so that connected pins can negotiate what media type they will pass between them, and which pin will provide the shared memory allocator for transporting the media sample. Additionally, the output pin is responsible for passing each media sample to its connected input pin; the input pin is responsible for receiving it. Finally, pins must support interfaces so that quality-control messages and position information can be passed through the stream from pin to pin.

The following illustration shows the pin classes. All pin classes are derived from CBasePin, a base class derived from CUnknown.

Hierarchy of pin base classes

CBasePin implements the IPin interface. The IPin interface specifies methods for connecting to other pins, negotiating the media type to be used with the connected pin, querying internal connections on the pin, and informing the pin of stream activity.

Besides implementing the IPin methods, CBasePin also implements IQualityControl methods so that quality-control messages can be passed through the filter graph from one pin to the next. Quality-control messages allow a filter, such as a renderer, to request another filter to adjust its sample rate. Typically, quality-control messages travel upstream from renderer to source filter. However, in cases such as a video capture filter, the source filter (for example, a VCR reader) can send quality-control messages downstream to the renderer filter to adjust its rate.

The CBasePin class provides several virtual member functions that can be overridden to provide handling of the connection, media type negotiation, and disconnection processes. Two base classes derive from CBasePin to provide default handling for many of these tasks:

  • CBaseOutputPin implements an output pin.
  • CBaseInputPin implements an input pin.

CBaseOutputPin is the base class for the CTransformOutputPin and CSourceStream classes. Likewise, CBaseInputPin is the base class for the CTransformInputPin class. Before looking at these derived base pin classes, it is helpful to understand the basic model the CBaseOutputPin and CBaseInputPin classes use.

In the connection and transport model used by two pins, the input pin supports the IMemInputPin interface so that it can receive a media sample. The CBaseInputPin class implements the IMemInputPin interface. Also, one of the two pins must supply a shared memory allocator object, which is an object that contains the IMemAllocator interface that generates media sample objects passed between pins. An IMemInputPin method, implemented by the CBaseInputPin class, supplies this allocator object, implemented by the CMemAllocator class. The connected output pin also has the option of supplying its own allocator; if this is the case, it notifies the input pin (through another IMemInputPin method) of the final decision of which allocator is used.

The CBaseOutputPin class provides extra member functions to set the size and count of samples in the allocator, retrieve a media sample from the allocator, deliver that media sample to the connected input pin, and deliver end-of-stream and end-flush messages downstream. It also implements many of the IPin methods.

CPullPin is a class that is used on the input pin of a parser filter. It is derived from the CAMThread class as shown in the following illustration.

CPullPin class hierarchy

A parser filter pulls information from the disk, using the asynchronous file reader filter, or from the Internet, using the URL moniker filter. CPullPin works with the IAsyncReader interface, which is implemented on the source reader filter upstream. CPullPin starts the thread, pulls data from the upstream filter, and then pushes the data downstream. That is, it can simply call its own IMemInputPin::Receive method after pulling the sample from the source (or perform the equivalent routines elsewhere).

Enumerator Base Classes

An enumerator is an interface that provides methods for traversing a list of elements. Enumerators are used in COM programming, and the DirectShow model follows the COM model in enumerating objects. Two enumerator classes are provided in the class library: CEnumPins, which implements the IEnumPins interfaces, and CEnumMediaTypes, which implements the IEnumMediaTypes interface. Two other DirectShow enumerator interfaces, IEnumFilters and IEnumRegFilters, are not represented by base classes because they are implemented only by the filter graph manager.

Hierarchy of enumerator base classes

The CEnumPins class creates an enumerator when the IBaseFilter::EnumPins method is called. The enumerator returned by this method is a pointer to the IEnumPins interface, which is implemented by the CEnumPins class. The CEnumPins member functions can then be called to retrieve pointers to each of the pins on the filter, which this enumerator accomplishes by calling the CBaseFilter::GetPin member function on the filter. The filter must override the base class CBaseFilter::GetPin member function to supply the enumerator with the next pin in the list each time it is called.

The CEnumMediaTypes class creates an enumerator when the IPin::EnumMediaTypes method is called. Pins store a list of the media types that they support. During negotiation of the media type, one pin typically calls the EnumMediaTypes method on its connected pin, retrieves the enumerator, and uses it to select a media type. Both of these enumerator classes support the Next, Skip, Reset, and Clone methods familiar to COM programmers. The media type enumerators call the CBasePin::GetMediaType member function, which must be overridden by the derived pin class, to return the next media type in a list of media types accepted by the pin.

Enumerators operate as threads, and must have synchronized access to the pin media type list. For this reason, the classes that implement enumerators inherit (through multiple inheritance) from the CCritSec class, which provides critical section management. For more information about the CCritSec class, see Win32 Classes.

Transport Base Classes

Transport classes share memory between pins and pass media samples using that memory. DirectShow provides four classes to help implement local memory transport:

  • CBaseAllocator
  • CMemAllocator
  • CMediaSample
  • CImageSample

CBaseAllocator is a class that provides member functions to implement the IMemAllocator interface, as shown in the following illustration.

Hierarchy of transport base classes

The IMemAllocator interface on the input pin specifies methods to set the number and size of the buffers to allocate, allocates that memory, frees that memory, and returns a single buffer that contains an IMediaSample interface. The output pin connected to the input pin calls the IMemAllocator methods. CBaseAllocator provides the member functions Alloc and Free that are called from the Commit and Decommit methods. Derived classes override the Alloc and Free member functions to provide their own routines to allocate and free memory.

Because CBaseAllocator performs very little implementation by itself, most pins use the CMemAllocator class, which is derived from CBaseAllocator. CMemAllocator overrides the CBaseAllocator::Free member function to provide allocation of media samples based on system memory. It provides its own member function, called ReallyFree, to be called when the allocator is finally released.

CMediaSample is a class that contains the media sample data and also provides member functions to access properties on the media sample, such as data type or beginning and ending time stamps. This class implements the IMediaSample interface, which provides the method specification. CImageSample derives from CMediaSample and is used by the video renderer when the renderer's allocator is being used. It uses all the CMediaSample interface methods and adds two methods to set and retrieve the DIBSECTION information. This makes it easy for the renderer to cast the CMediaSample pointer it receives from an upstream filter to a CImageSample pointer, and obtain a handle to the bitmap of the video frame.

Media Control and Positioning Classes

Media control interfaces pass commands such as Run, Stop, or Pause from an application through the filter graph manager to the individual filters. From the filter's perspective, the only control interface necessary is IMediaFilter, which exposes methods to accept and implement these commands. The CBaseFilter class implements this interface. All other interfaces that expose media control methods are handled by the filter graph manager and are therefore already implemented. Although a CMediaControl class exists and implements the IMediaControl interface, it is not often used because the filter graph manager is responsible for this functionality. The following illustration shows the relationship between these classes and interfaces.

Hierarchy of media control and positioning base classes

Media positioning interfaces start the media stream at a specified position, play the stream for a specified period of time, or change the rate of the media stream. The IMediaPosition interface is the primary interface supporting this functionality. The CMediaPosition class implements this interface and serves as a base class for two other classes: CPosPassThru and CSourcePosition.

Typically, the filter graph manager calls the IMediaPosition interface on the renderer filters when it wants to position the media stream. The renderer acknowledges the sample times that it will be expected to display and then passes the media positioning data upstream, destined for a seekable filter, such as a source file filter, that can provide the properly positioned source stream. To pass that information upstream, output pins must be able to receive the positioning information.

The CPosPassThru class implements the IMediaPosition interface and the IMediaSeeking interface on the output pins of filters and, for the most part, does nothing but call the corresponding interface on the output pin of the next upstream filter, thereby passing through the positioning data. IMediaSeeking is different than IMediaPosition in that it allows the media stream to be seeked to units other than time, such as frames, samples, or indexed fields in an MPEG format. The CRendererPosPassThru class, implemented on a video renderer, sets the start and end reference times on individual samples, so that samples can be queried at any time for this information. This is helpful when dealing with seeking using IMediaSeeking, which seeks to media time, and does not keep track of the sample's reference time.

The reason for serially informing every filter in the graph of the new position is to allow filters that might be concerned with media positioning to be prepared for the new position. Certain stream splitters, for example, might be splitting off streams with media positions relative to the main media stream. This is why the filter graph manager does not simply call the source filter's IMediaPosition or IMediaSeeking interface directly.

CSourcePosition is the class that helps the source filter implement its IMediaPosition interface.

The CSourceSeeking class helps the source filter implement its IMediaSeeking interface. This class enables a source filter to handle calls that change the start and stop positions in the media stream, and the playback rate.

The CBaseStreamControl class helps the source filter implement its IAMStreamControl interface. This class is used primarily by capture filters. The following illustration shows the relationship between CBaseStreamControl and the interfaces from which it inherits.

Hierarchy of CBaseStreamControl base class

Clock Base Classes

DirectShow provides two classes, CBaseReferenceClock and CSystemClock to help implement clocks in the filter graph. The following illustration shows the relationship between these classes and the interfaces they implement.

Hierarchy of clock base classes

CBaseReferenceClock implements IReferenceClock, and so provides the ability to return the correct reference time when requested, and to advise registered objects of specific times or time intervals through event notification and semaphores.

CSystemClock implements a system clock that provides time information and timing signals to an application. It uses the CBaseReferenceClock base class to provide most of that functionality, overriding the actual time calls.

Utility Classes

The Microsoft® DirectX® SDK includes several utility classes that provide C++ class encapsulation of many of the required Win32 functions, multimedia data structures, and object list and queue manipulation. These classes are briefly described in this section, which contains the following topics.

  • Win32 Classes
  • List and Queue Classes
  • Multimedia Data Type Classes
  • COM Utility Classes
  • Debugging Classes

Win32 Classes

DirectShow implements several classes to handle Win32 threads, events, and critical sections. These include the following classes.

  • CAMEvent
  • CCritSec
  • CAutoLock
  • CAMThread
  • CMsgThread
  • CMsg

The following diagram illustrates these classes.

Hierarchy of Win32 utility classes

CAMEvent handles a Win32 event as a C++ object. The methods in this class allow events to be put into the signaled state or reset to a nonsignaled state, and also allow a caller to block until an event is signaled. Events can also be cast to handles and passed to the Win32 WaitForMultipleObjects function.

CCritSec handles a Win32 critical section as a C++ object to provide intraprocess synchronization. Methods of this class allow you to create, lock, and unlock a critical section.

CAutoLock holds a critical section (a CCritSec object) for the scope of a block or function. The critical section is locked in the constructor and unlocked in the destructor.

CAMThread provides an abstract worker thread class enabling creation, synchronization, and communication with a worker thread.

CMsgThread provides support for a worker thread to which requests can be posted asynchronously instead of being sent directly. Messages, in the form of a CMsg object, can be posted to a CMsgThread object.

CMsg creates an object containing a message to be passed to a CMsgThread object.

List and Queue Classes

DirectShow implements the CBaseList, CGenericList, and COutputQueue classes for handling lists and queues as illustrated in the following diagram.

Hierarchy of list and queue utility classes

CBaseList represents a linked list data structure of typeless pointers to objects derived from CBaseObject.

CGenericList implements a template class derived from CBaseList that calls CBaseList member functions and adds type checking for the type specified in the template.

COutputQueue supports the queuing of media samples from the output pin of a filter. The output pin calls member functions of this class instead of calling methods on the connected input pin to receive the media sample. The output pin is then free to continue without blocking, while the COutputQueue class handles the passing of the media samples downstream.

Multimedia Data Type Classes

DirectShow implements the CMediaType, CRefTime, and FOURCCMap multimedia data type classes as shown in the following illustration.

Hierarchy of multimedia data type classes

CMediaType provides a C++ class object containing the media type data structure and methods that provide access to each of the members of the structure.

CRefTime provides a C++ class object containing the methods used to access the reference time, and operators used to perform Boolean tests or arithmetical operations on two CRefTime objects.

FOURCCMap provides conversion between the older-style FOURCC media tags used to identify and register media types and the GUID media subtypes used by DirectShow.

COM Utility Classes

COM interface classes in DirectShow fall into two groups: object creation and interface implementation. Class factory classes are provided for object creation, and other classes are provided to implement existing COM interfaces.

The COM utility classes include the following:

  • CClassFactory
  • CFactoryTemplate
  • CPersistStream
  • CBasePropertyPage

The following illustration shows the relationship between the COM classes and the interfaces they implement.

Hierarchy of COM utility classes CClassFactory and CFactoryTemplate are implemented by the base classes to handle automatic instantiation of filters, pins, and other DirectShow COM objects. These classes provide a scaffolding for object construction which wraps the actual COM elements required to construct an object. CPersistStream and CBasePropertyPage help with implementing COM persistent storage and property page interfaces.

CClassFactory, located in Dllentry.cpp, inherits from CBaseObject and implements the COM IClassFactory interface. This interface is used by CoCreateInstance, which instantiates a COM object by calling IClassFactory::CreateInstance, which, in turn, calls the static CreateInstance member function in your derived class.

The base classes use CFactoryTemplate to provide CClassFactory with a template containing the CLSID of your object and a pointer to the static CreateInstance function for your object class.

CPersistStream implements COM IPersistStream for the storage and retrieval of filter properties in a saved filter graph. This enables a stored filter graph to have filters set to predefined property values. This class also provides a special member function to handle versioning of data in a stream.

CBasePropertyPage implements the COM IPropertyPage interface, which provides a framework for a property page associated with a filter.

Debugging Classes

DirectShow provides many debugging functions and macros as described in the Debugging reference section. It also includes three classes that aid in debugging filter development:

  • CDispBasic
  • CDisp
  • CGuidNameList

The following diagram illustrates these classes.

Hierarchy of debugging utility classes

CDispBasic converts the m_PString data member to the proper string size.

CDisp provides a constructor that sets the CDispBasic class's m_PString data member to a string describing some relevant debugging information about the object used as a parameter to the constructor. For example, when constructed with an IPin pointer, m_PString returns the name of the pin; when constructed with a CLSID, m_PString returns a string representation of it, and so on. The class also provides an LPCTSTR cast operator that returns the value of m_PString, so the class can simply be cast as an LPCTSTR value to return the string when constructed.

CGuidNameList implements an array of globally unique identifier (GUID) names in the Uuids.h include file. This enables you to retrieve the GUID name for a media type, for example.


CAggDirectDraw Class

CAggDirectDraw class hierarchy

The CAggDirectDraw class aggregates an IDirectDraw interface. Although Microsoft® DirectDraw® interfaces (IDirectDraw and IDirectDrawSurface) potentially have the ability to be aggregated, this feature is not yet implemented. Various parts of Microsoft DirectShow® require aggregation of the DirectDraw interfaces. In particular, the video renderer passes out media samples that expose IDirectDraw and IDirectDrawSurface. This class and the CAggDrawSurface class republish the methods of the DirectDraw class so that they can be aggregated.

Each member function in this class, with the exception of the constructor, SetDirectDraw, and NonDelegatingQueryInterface, simply calls the corresponding method on the IDirectDraw interface with the parameters passed to it.

Protected Data Members

m_pDirectDraw DirectDraw object.

Member Functions

CAggDirectDraw | Constructs a CAggDirectDraw object.
SetDirectDraw | Sets the DirectDraw object to be aggregated by this class.

Overridable Member Functions

NonDelegatingQueryInterface Retrieves an interface and increments the reference count.

Implemented IDirectDraw Methods

The following IDirectDraw methods are implemented. For more information, refer to the DirectDraw documentation.

Compact | Moves all the pieces of surface memory on the video card to a contiguous block to make the largest chunk of free memory available.
CreateClipper | Creates a DirectDrawClipper object.
CreatePalette | Creates a DirectDrawPalette object for this DirectDraw object.
CreateSurface | Creates a DirectDrawSurface object for this DirectDraw object.
DuplicateSurface | Duplicates a DirectDrawSurface object.
EnumDisplayModes | Enumerates all the display modes the hardware exposes through the DirectDraw object that are compatible with a provided surface description.
EnumSurfaces | Enumerates all the existing or possible surfaces that meet the search criterion specified.
FlipToGDISurface | Makes the surface that GDI writes to the primary surface.
GetCaps | Fills in the raw (not remaining) capabilities of the device driver (the hardware) and/or the Hardware Emulation Layer (HEL).
GetDisplayMode | Retrieves the current display mode.
GetFourCCCodes | Retrieves the FOURCC codes supported by the DirectDraw object.
GetGDISurface | Retrieves the DirectDrawSurface object that currently represents the surface memory that GDI treats as the primary surface.
GetMonitorFrequency | Retrieves the frequency of the monitor being driven by the DirectDraw object.
GetScanLine | Retrieves the scan line that the monitor is currently updating to the display.
GetVerticalBlankStatus | Retrieves the status of the vertical blank.
Initialize | Initializes the DirectDraw object.
RestoreDisplayMode | Resets the mode of the display device hardware for the primary surface to what it was before the CAggDirectDraw::SetDisplayMode member function was called.
SetCooperativeLevel | Determines the top-level behavior of the application.
SetDisplayMode | Sets the mode of the display device hardware.
WaitForVerticalBlank | Helps the caller synchronize itself with the vertical blank interval.

CAggDirectDraw::CAggDirectDraw

CAggDirectDraw Class

Constructs a CAggDirectDraw object.

Syntax

CAggDirectDraw(
    TCHAR *pName,
    LPUNKNOWN pUnk
    );

Parameters

pName
Pointer to the object's name; used for debugging purposes.
pUnk
Pointer to the owner of this object. If non-NULL, IUnknown calls are delegated to this object.

Return Value

No return value.

Remarks

This member function calls the CUnknown::CUnknown base class constructor and sets the m_pDirectDraw member variable to NULL.

CAggDirectDraw::NonDelegatingQueryInterface

CAggDirectDraw Class

Retrieves an interface and increments the reference count.

Syntax

HRESULT NonDelegatingQueryInterface(
    REFIID riid,
    void **ppv
    );

Parameters

riid
Reference identifier.
ppv
Address of a pointer to the interface.

Return Value

Returns E_POINTER if ppv is invalid. Returns NOERROR if the query is successful or E_NOINTERFACE if it is not.

Remarks

This member function provides an implementation of the INonDelegatingUnknown::NonDelegatingQueryInterface method. By default it passes out references to IDirectDraw and then calls the CUnknown::NonDelegatingQueryInterface member function for base class interface references. Override this class to return interfaces added in the derived class.

CAggDirectDraw::SetDirectDraw

CAggDirectDraw Class

Sets the DirectDraw object to be aggregated by this class.

Syntax

void SetDirectDraw(
    LPDIRECTDRAW pDirectDraw
    );

Parameters

pDirectDraw
Pointer to the IDirectDraw object to be aggregated.

Return Value

No return value.

Remarks

This member function sets the m_pDirectDraw data member to the pDirectDraw parameter.


CAggDrawSurface Class

CAggDrawSurface class hierarchy

The CAggDrawSurface class aggregates an IDirectDrawSurface interface. Although Microsoft® DirectDraw® interfaces (IDirectDraw and IDirectDrawSurface) potentially can be aggregated, this feature is not yet implemented. Various parts of Microsoft® DirectShow® require aggregation of the DirectDraw interfaces. In particular, the video renderer passes out media samples that expose IDirectDraw and IDirectDrawSurface. This class and the CAggDirectDraw class republish the methods of the DirectDraw class so that they can be aggregated.

Each member function in this class, with the exception of the constructor, SetDirectDrawSurface, and NonDelegatingQueryInterface, simply calls the corresponding method on the IDirectDrawSurface interface with the parameters passed to it.

Protected Data Members

m_pDirectDrawSurface DirectDraw surface.

Member Functions

CAggDrawSurface | Constructs a CAggDrawSurface object.
SetDirectDrawSurface | Sets the DirectDraw object to be aggregated by this class. This must be called before any of the IDirectDrawSurface interface methods can be called.

Overridable Member Functions

NonDelegatingQueryInterface Retrieves an interface and increments the reference count.

Implemented IDirectDrawSurface Methods

The following IDirectDrawSurface methods are implemented. For more information, consult the DirectDraw documentation.

AddAttachedSurface | Attaches a surface to another surface. Examples of possible attachments include z-buffers, alpha channels, and back buffers.
AddOverlayDirtyRect | Builds up the list of the rectangles that must be updated the next time the UpdateOverlayDisplay member function is called.
Blt | Performs a bit-block transfer.
BltBatch | Performs a sequence of CAggDrawSurface::Blt operations from several sources to a single destination.
BltFast | Performs a source copy bit-block transfer or transparent bit-block transfer using a source or destination color key.
DeleteAttachedSurface | Detaches two attached surfaces.
EnumAttachedSurfaces | Enumerates all the surfaces attached to a given surface.
EnumOverlayZOrders | Enumerates the overlays on the specified destination. The overlays can be enumerated in front-to-back or back-to-front order.
Flip | Makes the surface memory associated with the DDSCAPS_BACKBUFFER surface become associated with the FRONTBUFFER surface.
GetAttachedSurface | Finds the attached surface that has the specified capabilities.
GetBltStatus | Retrieves the status of a bit block transfer.
GetCaps | Retrieves the capabilities of the surface.
GetClipper | Retrieves the DirectDrawClipper object associated with this surface.
GetColorKey | Retrieves the color key value for the DirectDrawSurface object.
GetDC | Creates a GDI-compatible hDC for the surface.
GetFlipStatus | Returns OK if the surface that it is called on has finished its flipping process; otherwise, returns DDERR_WASSTILLDRAWING.
GetOverlayPosition | Retrieves the display coordinates of the surface, given a visible, active overlay surface (DDSCAPS_OVERLAY set).
GetPalette | Retrieves the DirectDrawPalette structure associated with this surface.
GetPixelFormat | Retrieves the color and pixel format of the surface.
GetSurfaceDesc | Retrieves a DDSURFACEDESC structure describing the surface in its current condition.
Initialize | Initializes a DirectDrawSurface object.
IsLost | Determines if the surface memory associated with a DirectDrawSurface object has been freed.
Lock | Obtains a valid pointer to the surface memory.
ReleaseDC | Releases a GDI-compatible hDC previously obtained through CAggDrawSurface::GetDC.
Restore | Restores a surface that has been "lost." The surface memory associated with the DirectDrawSurface object has been freed.
SetClipper | Attaches a DirectDrawClipper object to a DirectDrawSurface object.
SetColorKey | Sets the color key value for the DirectDrawSurface object if the hardware supports color keys on a per-surface basis.
SetOverlayPosition | Changes the display coordinates of an overlay surface.
SetPalette | Attaches the DirectDrawPalette object specified to a DirectDrawSurface.
Unlock | Notifies DirectDraw that the direct surface manipulations are complete.
UpdateOverlay | Repositions and/or modifies the visual attributes of an overlay surface. These surfaces must have the DDSCAPS_OVERLAY bit set.
UpdateOverlayDisplay | Repaints the rectangles in the dirty rectangle lists of all active overlays.
UpdateOverlayZOrder | Sets an overlay's z-order. The z-order determines which overlay should be occluded when multiple overlays are displayed simultaneously.

CAggDrawSurface::CAggDrawSurface

CAggDrawSurface Class

Creates a CAggDrawSurface object.

Syntax

CAggDrawSurface(
  TCHAR *pName,
  LPUNKNOWN pUnk
  );

Parameters

pName
Pointer to the name of the object; used for debugging purposes.
pUnk
Pointer to the owner of this object. If non-NULL, IUnknown interface calls are delegated to this object.

Return Value

No return value.

Remarks

This member function calls the CUnknown::CUnknown base class constructor and sets the m_pDirectDrawSurface member variable to NULL.

CAggDrawSurface::NonDelegatingQueryInterface

CAggDrawSurface Class

Retrieves an interface and increments the reference count.

Syntax

HRESULT NonDelegatingQueryInterface(

  REFIID riid,

  void **ppv

  );

Parameters

riid
Reference identifier.
ppv
Address of a pointer to the interface.

Return Value

Returns E_POINTER if ppv is invalid. Returns NOERROR if the query is successful or E_NOINTERFACE if it is not.

Remarks

This member function provides an implementation of the INonDelegatingUnknown::NonDelegatingQueryInterface method. By default it passes out references to IDirectDrawSurface and then calls the CUnknown::NonDelegatingQueryInterface member function for base class interface references. Override this class to return interfaces added in the derived class.

CAggDrawSurface::SetDirectDrawSurface

CAggDrawSurface Class

Called by the owner of this aggregation object to set the actual DirectDraw surface it is aggregating upon.

Syntax

void SetDirectDrawSurface(
  LPDIRECTDRAWSURFACE pDirectDrawSurface
  );

Parameters

pDirectDrawSurface
Pointer to the DirectDraw surface to be set.

Return Value

No return value.

Remarks

This member function must be called before any of the IDirectDrawSurface interface methods can be called.


CAMEvent Class

CAMEvent class hierarchy

Wrapper class for manual-reset and auto-reset events.

Declaration: Wxutil.h

This class provides a convenient way to manage events, rather than calling Microsoft® Win32® functions such as CreateEvent, WaitForSingleObject, and ResetEvent.

Protected Member Variables
m_hEvent | Event handle.
Public Methods
CAMEvent | Constructor method.
~CAMEvent | Destructor method.
Check | Checks whether the event is set, without blocking.
Reset | Sets the state of the event to nonsignaled.
Set | Signals the event.
Wait | Blocks until the event is signaled, or until a time-out occurs.
Operators
HANDLE | Retrieves the event handle.

CAMEvent.m_hEvent

CAMEvent Class

Event handle.

Syntax

HANDLE m_hEvent;

CAMEvent::CAMEvent

CAMEvent Class

Constructor method.

Syntax

CAMEvent(
    BOOL fManualReset = FALSE
);

Parameters

fManualReset
Boolean value that specifies whether the object is a manual-reset event or an auto-reset event. If TRUE, the object is a manual-reset event. Otherwise, it is an auto-reset event.

Remarks

The event begins in a nonsignaled state.

With an auto-reset event, the CAMEvent::Wait method resets the event to nonsignaled when the method returns. With a manual-reset event, the event remains signaled until you call the CAMEvent::Reset method.

CAMEvent::~CAMEvent

CAMEvent Class

Destructor method.

Syntax

~CAMEvent(void);

CAMEvent::Check

CAMEvent Class

Checks whether the event is set, without blocking.

Syntax

BOOL Check(void);

Remarks

Returns TRUE if the event is set, or FALSE otherwise.

Remarks

This method calls the Wait method with a time-out of zero. If the object is an auto-reset event, this method resets the event.

CAMEvent::Reset

CAMEvent Class

Sets the state of the event to nonsignaled.

Syntax

void Reset(void);

CAMEvent::Set

CAMEvent Class

Signals the event.

Syntax

void Set(void);

Remarks

The behavior depends on whether the object is an auto-reset event or a manual-reset event:

  • Auto-reset: If any threads are waiting on this event, one thread is released and the event is reset. If no threads are waiting on this event, the event remains signaled.
  • Manual-reset: All the threads waiting on this event are released. The event remains signaled.

CAMEvent::Wait

CAMEvent Class

Blocks until the event is signaled, or until a time-out occurs.

Syntax

BOOL Wait(
    DWORD dwTimeout = INFINITE
);

Parameters

dwTimeout
Optional time-out value, represented in milliseconds.

Return Value

Returns TRUE if the event is signaled. Otherwise, returns FALSE.

Remarks

For auto-reset events, the event is reset to a nonsignaled state when this method returns.

CAMEvent::operator HANDLE

CAMEvent Class

Retrieves the event handle. This operator is not supported as an L-value.

Syntax

operator HANDLE () const;

Return Value

Returns the m_hEvent member variable.


CAMMsgEvent Class

CAMMsgEvent class hierarchy

Wrapper class for event objects that perform message processing.

Declaration: Wxutil.h

This class derives from the CAMEvent object. It adds one method, WaitMsg, which dispatches incoming messages while waiting.

Public Methods
WaitMsg Waits for the event to be signaled, while dispatching sent messages.

CAMMsgEvent::WaitMsg

CAMMsgEvent Class

Waits for the event to be signaled, while dispatching sent messages.

Syntax

BOOL WaitMsg(
    DWORD dwTimeOut = INFINITE
);

Parameters

dwTimeOut
Optional time-out value, in milliseconds.

Return Value

Returns TRUE if the event is signaled, or FALSE if the time-out occurred.

Remarks

This method calls the PeekMessage function to process messages. Call this method instead of CAMEvent::Wait if your thread needs to process messages while waiting for an event. If the thread does not process messages and another thread sends a message, deadlock could occur.

For example, suppose you create a thread and then block until the thread initializes. If the thread sends a message to your window by calling the SendMessage function, it will result in a deadlock. This is because SendMessage does not return until the message has been processed. Calling WaitMsg allows the SendMessage call to return, preventing the deadlock.


CAMSchedule Class

Scheduler for reference clocks.

Declaration: Schedule.h.

This helper object maintains a list of advise requests for a reference clock. The CBaseReferenceClock class uses it to help schedule advise requests. Clocks use this object in the following manner:

  1. The clock creates a worker thread to handle scheduling.
  2. The worker thread calls the GetEvent method to retrieve an event handle from the scheduler. It waits on this event, initially with an infinite time-out.
  3. To shedule a new advise request, the clock calls the AddAdvisePacket method. An advise request can be one-shot or periodic. The scheduler keeps the list of requests in time order.
  4. If a request is added to the front of the list, the scheduler signals the event. (The list is empty at first, so the first request is guaranteed to signal the event.)
  5. When the event is signaled, the worker thread calls the Advise method, specifying the current reference time. If any pending requests have expired, the scheduler dispatches them.
  6. The Advise method returns the time of the next request. The worker thread uses this value to calculate a new time-out value.
  7. Steps 2–6 repeat indefinitely.
  8. To terminate the worker thread, the clock sets an internal flag and signals the event.

In step 2, either the event is signaled, or the wait times out. If the event is signaled, it means that a new request was added to the front of the list. The worker thread must calculate a new time-out value. On the other hand, if the wait times out, it means that an advise request has come due and must be dispatched. The call to Advise in step 5 handles both cases.

Public Methods
CAMSchedule | Constructor method.
~CAMSchedule | Destructor method. Virtual.
GetAdviseCount | Retrieves the number of pending advise requests.
GetNextAdviseTime | Retrieves the time of the next advise request.
AddAdvisePacket | Adds an advise request to the list of pending requests.
Unadvise | Removes an advise request.
Advise | Dispatches all requests that are scheduled for a specified time or earlier.
GetEvent | Retrieves an event handle, which is used to signal a change in the next advise time.

CAMSchedule::AddAdvisePacket

CAMSchedule Class

Adds an advise request to the list of pending requests.

Syntax

DWORD AddAdvisePacket(
    const REFERENCE_TIME& time1,
    const REFERENCE_TIME& time2,
    HANDLE hNotify,
    BOOL bPeriodic
);

Parameters

time1
Requested time for the advise.
time2
For periodic advise requests, the time between notifications. This parameter is ignored if bPeriodic is FALSE.
hNotify
Handle to a semaphore if bPeriodic is TRUE, or handle to an event if bPeriodic is FALSE.
bPeriodic
Boolean value that specifies whether to add a periodic notification or a one-shot notification. If TRUE, the notification is periodic; the time2 parameter specifies the time between notifications. If FALSE, the notification occurs only once.

Return Value

Returns an identifier for the advise request (the "cookie"). If the method fails, the return value is zero.

CAMSchedule::Advise

CAMSchedule Class

Dispatches all requests that are scheduled for a specified time or earlier.

Syntax

REFERENCE_TIME Advise(
    const REFERENCE_TIME& rtTime
);

Parameters

rtTime
Value that specifies the current reference time.

Return Value

Returns the reference time of the next scheduled advise request, or MAX_TIME if there are none left.

Remarks

When the clock calls this method, it specifies the current reference time. The scheduler determines which advise requests have expired, if any, and dispatches them. If a one-shot request expires, the scheduler deletes it. If a periodic request expires, the scheduler re-schedules it for the next advise time. The method returns the time of the next pending request.

To dispatch an advise request, the scheduler signals the event or semaphore given in the hNotify parameter of the AddAdvisePacket method.

CAMSchedule::CAMSchedule

CAMSchedule Class

Constructor method.

Syntax

CAMSchedule(
    HANDLE hEvent
);

Parameters

hEvent
Handle to an auto-reset event.

CAMSchedule::~CAMSchedule

CAMSchedule Class

Destructor method.

Syntax

~CAMSchedule(void);

CAMSchedule::GetAdviseCount

CAMSchedule Class

Retrieves the number of pending advise requests.

Syntax

DWORD GetAdviseCount(void);

Return Value

Returns the number of pending advise requests.

CAMSchedule::GetEvent

CAMSchedule Class

Retrieves an event handle, which is used to signal a change in the next advise time.

Syntax

HANDLE GetEvent(void);

Return Value

Returns a handle to an event.

Remarks

If the next advise time changes—in other words, if a new advise request is added to the front of the list—the scheduler signals this event. The clock should call the Advise method to determine the next advise time.

CAMSchedule::GetNextAdviseTime

CAMSchedule Class

Retrieves the time of the next advise request.

Syntax

REFERENCE_TIME GetNextAdviseTime(void);

Return Value

Returns the reference time of the next advise request, or MAX_TIME no requests are scheduled.

CAMSchedule::Unadvise

CAMSchedule Class

Removes an advise request.

Syntax

HRESULT Unadvise(
    DWORD dwAdviseCookie
);

Parameters

dwAdviseCookie
Identifier of the advise request, returned by the AddAdvisePacket method.

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | Not found
S_OK | Success


CAMThread Class

CAMThread class hierarchy

Abstract class for managing worker threads.

Declaration: Wxutil.h

This class provides methods for creating a worker thread, passing requests to the thread, and waiting for the thread to exit. To use this class, do the following:

  • Derive a class from CAMThread and override the pure virtual method ThreadProc. This method is the thread procedure that gets called at the start of the thread.
  • In your application, create an instance of your derived class. Creating the object does not create the thread. To create the thread, call the Create method.
  • To send requests to the thread, call the CallWorker method. This method takes a DWORD parameter, whose meaning is defined by your class. The method blocks until the thread responds (see below).
  • In your thread procedure, respond to requests by calling either GetRequest or CheckRequest. The GetRequest method blocks until another thread calls CallWorker. The CheckRequest method is non-blocking, which enables the thread to check for new requests while working asynchronously.
  • When the thread receives a request, call Reply to unblock the calling thread. The Reply method takes a DWORD parameter, which is passed to the calling thread as the return value for CallWorker.

When you are done with the thread, call the Close method. This method waits for the thread to exit, and then closes the thread handle. Your ThreadProc message must be guaranteed to exit, either on its own or in response to a CallWorker request. The destructor method also calls Close.

The following example illustrates these steps:

class MyThread : public CAMThread
{
protected:
    DWORD ThreadProc(void);
};

DWORD MyThread::ThreadProc()
{
    BOOL bShutDown = FALSE;
    while (!bShutDown)
    {
        DWORD req = GetRequest();
        printf("Request: %d\n", req);
        bShutDown = (req == 0);
        Reply(bShutDown ? S_FALSE : S_OK);
    }
    printf("Quitting Thread\n");
    return 1;
}

void main()
{
    MyThread thread;
    DWORD reply;

    thread.Create();
    reply = thread.CallWorker(3);
    reply = thread.CallWorker(0); // Thread exits.
}

In your derived class, you can also define member functions that validate the parameters to CallWorker. The following example shows a typical way to do this:

enum Command {CMD_INIT, CMD_RUN, CMD_STOP, CMD_EXIT};

HRESULT Init(void)  { return CallWorker(CMD_INIT); }
HRESULT Run(void)   { return CallWorker(CMD_RUN); }
HRESULT Stop(void)  { return CallWorker(CMD_STOP); }
HRESULT Exit(void)  { return CallWorker(CMD_EXIT); }

The CAMThread class provides two critical sections as public member variables. Use m_AccessLock to lock the thread from being accessed by other threads. (For example, the Create and CallWorker methods hold this lock, to serialize operations on the thread.) Use m_WorkerLock to lock data that is shared among threads.

Protected Member Variables
m_hThread | Handle to the thread.
Public Member Variables
m_AccessLock | Critical section that locks the thread from being accessed by other threads.
m_WorkerLock | Critical section that locks data shared among threads.
Public Methods
CAMThread | Constructor method.
~CAMThread | Destructor method. Virtual.
InitialThreadProc | Calls the ThreadProc method when the thread is created.
Create | Creates the thread.
CallWorker | Signals the thread with a request.
Close | Waits for the thread to exit, then releases its resources.
ThreadExists | Queries whether the thread exists.
GetRequest | Waits for the next request.
CheckRequest | Checks if there is a request, without blocking.
Reply | Replies to a request.
GetRequestHandle | Retrieves a handle to the event signaled by the CallWorker method.
GetRequestParam | Retrieves the latest request.
CoInitializeHelper | Calls CoInitializeEx at the start of the thread.
Pure Virtual Methods
ThreadProc | Thread procedure.

CAMThread.m_AccessLock

CAMThread Class

Critical section that locks the thread from being accessed by other threads.

Syntax

CCritSec m_AccessLock;

Remarks

The Create and CallWorker methods hold this lock, to serialize operations on the thread.

CAMThread.m_WorkerLock

CAMThread Class

Critical section that locks data shared among threads.

Syntax

CCritSec m_WorkerLock;

CAMThread.m_hThread

CAMThread Class

Handle to the thread.

Syntax

HANDLE m_hThread;

Remarks

This variable is initialized as NULL. The Create method sets this variable to the thread handle. To determine whether the thread exists, call the ThreadExists method.

CAMThread::CAMThread

CAMThread Class

Constructor method.

Syntax

CAMThread(void);

Remarks

The constructor method does not create the thread. To create the thread, call the Create method.

CAMThread::~CAMThread

CAMThread Class

Destructor method.

Syntax

virtual ~CAMThread(void);

Remarks

The destructor method calls the Close method, which waits for the thread to exit.

CAMThread::CallWorker

CAMThread Class

Signals the thread with a request.

Syntax

DWORD CallWorker(
    DWORD dwParam
);

Parameters

dwParam
Request parameter. The derived class defines the meaning of the parameter.

Return Value

Returns a value that is defined by the derived class.

Remarks

The GetRequest and CheckRequest methods retrieve the value of the dwParam parameter. The GetRequest method blocks until CallWorker is called.

This method blocks until the Reply method is called. The return value is the parameter given to Reply.

This method holds the m_AccessLock lock to serialize requests. Therefore, do call this method from the thread itself or from any member function that executes in the context of the thread.

CAMThread::CheckRequest

CAMThread Class

Checks if there is a request, without blocking.

Syntax

BOOL CheckRequest(
    DWORD *pParam
);

Parameters

pParam
Pointer to a variable that receives the value passed in the last call to the CallWorker method.

Return Value

Returns TRUE if there is a pending request, or FALSE otherwise.

Remarks

This method is a non-blocking version of the GetRequest method.

If another thread is waiting on a call to CallWorker, this method retrieves the request parameter and returns TRUE. Otherwise, it returns FALSE. If the method returns TRUE, call the Reply method to release the requesting thread.

CAMThread::Close

CAMThread Class

Waits for the thread to exit, then releases its resources.

Syntax

void Close(void);

Return Value

No return value.

Remarks

Before calling this method, you must provide a way for the thread to exit. For example, in your ThreadProc method, define a request that signals the thread to exit. Then call the CAMThread::CallWorker method with that value.

The ~CAMThread destructor method calls this method.

CAMThread::Create

CAMThread Class

Creates the thread.

Syntax

BOOL Create(void);

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

This method creates the thread, using the InitialThreadProc method for the thread procedure and this for the thread argument.

The method fails if the thread already exists.

CAMThread::CoInitializeHelper

CAMThread Class

Calls the CoInitializeEx function at the start of the thread.

Syntax

static HRESULT CoInitializeHelper(void);

Return Value

Returns an HRESULT value. The following are possible values.

S_FALSE | The CoInitializeEx function is not available.
S_OK | Success.
E_FAIL | Failure.

Remarks

The InitialThreadProc method calls this helper method, which calls the CoInitializeEx function. It uses the COINIT_DISABLE_OLE1DDE flag, to disable Dynamic Data Exchange (DDE). For more information, see the Platform SDK.

CAMThread::GetRequest

CAMThread Class

Waits for the next request.

Syntax

DWORD GetRequest(void);

Return Value

Returns a value that is defined by the derived class.

Remarks

This method blocks until another thread calls the CallWorker method. Then it returns the parameter that was passed to CallWorker. Call the Reply method to release the requesting thread.

CAMThread::GetRequestHandle

CAMThread Class

Retrieves a handle to the event signaled by the CallWorker method.

Syntax

HANDLE GetRequestHandle(void) const;

Return Value

Returns an event handle.

Remarks

The CAMEvent class keeps a private manual-reset event, which is set by CallWorker and reset by the Reply method.

If you call a function such as WaitForMultipleObjects, use GetRequestHandle to retrieve the event handle.

CAMThread::GetRequestParam

CAMThread Class

Retrieves the latest request.

Syntax

DWORD GetRequestParam(void) const;

Return Value

Returns the value of the parameter that was passed most recently to the CallWorker method.

CAMThread::InitialThreadProc

CAMThread Class

Calls the ThreadProc method when the thread is created.

Syntax

DWORD InitialThreadProc(
    LPVOID pv
);

Parameters

pv
this pointer.

Return Value

Returns the DWORD returned by CAMThread::ThreadProc. The derived class defines this value.

Remarks

The Create method uses this method for the thread procedure when it creates the thread. It uses the this pointer as the thread argument.

This method calls the CoInitializeHelper method and then ThreadProc.

CAMThread::Reply

CAMThread Class

Replies to a request.

Syntax

void Reply(
    DWORD dw
);

Parameters

dw
Value to return in the CallWorker method.

Remarks

The CallWorker method blocks until this method is called. The dw parameter supplies the return value for CallWorker. Call this method in your thread procedure after you retrieve a request, to release the requesting thread.

CAMThread::ThreadExists

CAMThread Class

Queries whether the thread exists.

Syntax

BOOL ThreadExists(void);

Return Value

Returns TRUE if the thread exists, or FALSE if the thread does not exist.

CAMThread::ThreadProc

CAMThread Class

Thread procedure.

Syntax

virtual DWORD ThreadProc(void) = 0;

Return Value

Returns a DWORD value whose meaning is defined by the derived class.

Remarks

This is a pure virtual method. Implement this method in your derived class to supply a thread procedure. When the Create method creates a thread, it gives the address of the InitialThreadProc method, which in turn calls your ThreadProc method.

Typically, your ThreadProc method will enter a loop that retrieves requests (by calling the GetRequest or CheckRequest methods) and processes data.

When this method returns, the thread exits.


CAutoLock Class

Holds a critical section for the scope of a block.

Declaration: Wxutil.h

This class works in conjunction with the CCritSec class, which is a wrapper for critical section objects. The CAutoLock constructor locks the critical section, and the destructor unlocks it. By using a CAutoLock object as a local variable, you can lock a critical section with the guarantee that all code paths will unlock the critical section.

The following code example shows how to use this class:

CCritSec csMyLock;  // Critical section is not locked yet.

{
    CAutoLock cObjectLock(&csMyLock);  // Lock the critical section.

    // Protected section of code.

} // Lock goes out of scope here.

The methods in this class are not designed to be overridden.

Protected Member Variables
m_pLock | Critical section for this lock.
Public Methods
CAutoLock | Constructor method. Locks the specified critical section object.
~CAutoLock | Destructor method. Unlocks the critical section object.

CAutoLock.m_pLock

CAutoLock Class

Critical section for this lock.

Syntax

CCritSec *m_pLock;

CAutoLock::CAutoLock

CAutoLock Class

Constructor method. Locks the specified critical section object.

Syntax

CAutoLock(
    CCritSec *plock
);

Parameters

plock
Pointer to a CCritSec object, which contains a critical section object.

CAutoLock::~CAutoLock

CAutoLock Class

Destructor method. Unlocks the critical section object.

Syntax

CAutoLock(void);


CAutoUsingOutputPin Class

Obtains and releases access to a CDynamicOutputPin object.

Declaration: Amfilter.h

When certain methods are called on CDynamicOutputPin, the caller must obtain access to the pin and then release that access. To obtain access, the caller uses the CDynamicOutputPin::StartUsingOutputPin method. To release access, it calls the CDynamicOutputPin::StopUsingOutputPin method. The CAutoUsingOutputPin class is a helper class that handles these tasks in its constructor and destructor methods. The following code example shows how to use this class:

CDynamicOutputPin *pPin;
HRESULT hr = S_OK;  // Important! Initialize to S_OK.

// Obtain a pointer to the pin (not shown).
{
    CAutoUsingOutputPin UsingPin(pPin, &hr)
    if (SUCCEEDED(hr)) {
        // Safe to use the pin.
        pPin->Deliver(pSample);
    }
} // Object goes out of scope here.

// No longer safe to use the pin.

Public Methods
CAutoUsingOutputPin | Constructor method. Obtains access to the specified pin.
~CAutoUsingOutputPin | Destructor method. Releases access to the pin.

CAutoUsingOutputPin

CAutoUsingOutputPin Class

Constructor method. Obtains access to the specified pin.

Syntax

CAutoUsingOutputPin(
    CDynamicOutputPin *pOutputPin,
    HRESULT *phr
);

Parameters

pOutputPin
Pointer to a CDynamicOutputPin object.
phr
Pointer to a variable that contains an HRESULT value. The value must be S_OK.

Remarks

When the method returns, the value of *phr indicates the success or failure of the method.

CAutoLock::~CAutoUsingOutputPin

CAutoUsingOutputPin Class

Destructor method. Releases access to the pin.

Syntax

~CAutoUsingOutputPin(void);


CBaseAllocator Class

CBaseAllocator class hierarchy

Abstract base class that implements an allocator. Allocators expose the IMemAllocator interface.

Declaration: Amfilter.h

An allocator is an object that allocates memory buffers. The allocator maintains a list of available buffers. When a client (generally a filter) requests a buffer, the allocator retrieves one from the list. The client fills the buffer with data, and might pass the buffer to another object. Eventually the buffer is released and the allocator returns it to the list of available buffers.

Each buffer is encapsulated by an object called a media sample. Media samples are a way to package pointers to memory blocks within the Component Object Model (COM) framework. Media samples expose the IMediaSample interface, and are implemented using the CMediaSample class. A media sample contains a pointer to the associated buffer, which can be accessed by calling the IMediaSample::GetPointer method.

Typically, the allocator will allocate a contiguous block of memory. Then it creates media samples that contain pointers to addresses within that block. The following illustration shows the relationship between the allocator, the media samples, and the memory block.

How an Allocator Delivers Samples

To use an allocator, perform the following steps:

  1. Call the SetProperties method to specify the buffer requirements, including the number of buffers and the size of each buffer.
  2. Call the Commit method to allocate the buffers.
  3. Call the GetBuffer method to retrieve media samples. This method blocks until the next sample becomes available.
  4. When you are done with each sample, call the IUnknown::Release method on the sample. The sample is not deleted when its reference count reaches zero. Instead, the sample returns to the allocator's free list.
  5. When you are done using the allocator, call the Decommit method to free the memory for the buffers.

The Commit method calls the virtual method Alloc, which allocates the memory for the buffers. The Decommit method calls the pure virtual method Free, which frees the memory. Derived classes must override these two methods.

The CMemAllocator base class derives from CBaseAllocator. The filter base classes use the CMemAllocator class.

Protected Member Variables
m_lFree | Pointer to a list of available (free) media samples.
m_hSem | Semaphore that is signaled when a sample becomes available.
m_lWaiting | Count of threads waiting for samples.
m_lCount | Number of buffers to provide.
m_lAllocated | Number of buffers currently allocated.
m_lSize | Size of each buffer.
m_lAlignment | Alignment of each buffer.
m_lPrefix | Prefix of each buffer.
m_bChanged | Flag indicating whether the buffer requirements have changed.
m_bCommitted | Flag indicating whether the allocator has been committed.
m_bDecommitInProgress | Flag indicating whether a decommit operation is in progress.
m_pNotify | Pointer to a callback interface, which is called when samples are released.
m_fEnableReleaseCallback | Flag indicating whether the release callback is enabled.
Protected Methods
Alloc | Allocates memory for the buffers. Virtual.
Public Methods
CBaseAllocator | Constructor method.
~CBaseAllocator | Destructor method.
SetNotify | Specifies a callback method to be called each time a sample is released.
GetFreeCount | Retrieves the number of media samples that are not in use.
NotifySample | Releases any threads that are waiting for samples.
SetWaiting | Increments the count of waiting threads.
Pure Virtual Methods
Free | Releases the buffer memory during a decommit operation, after the last media sample is released.
IMemAllocator Methods
SetProperties | Specifies the number of buffers to allocate and the size of each buffer.
GetProperties | Retrieves the number of buffers that the allocator will create, and the buffer properties.
Commit | Allocates the memory for the buffers.
Decommit | Decommits the buffers.
GetBuffer | Retrieves a media sample that contains a buffer.
ReleaseBuffer | Returns a media sample to the list of free media samples.

CBaseAllocator.m_lFree

CBaseAllocator Class

Pointer to a list of available (free) media samples.

Syntax

CSampleList m_lFree;

CBaseAllocator.m_hSem

CBaseAllocator Class

Semaphore that is signaled when a sample becomes available.

Syntax

HANDLE m_hSem;

CBaseAllocator.m_lWaiting

CBaseAllocator Class

Count of threads waiting for samples.

Syntax

long m_lWaiting

CBaseAllocator.m_lCount

CBaseAllocator Class

Number of buffers to provide. The SetProperties method sets this value. The buffers are not allocated until the Commit method is called. The current number of allocated buffers is specifies by the m_lAllocated member variable.

Syntax

long m_lCount;

CBaseAllocator.m_lAllocated

CBaseAllocator Class

Number of buffers currently allocated.

Syntax

long m_lAllocated;

CBaseAllocator.m_lSize

CBaseAllocator Class

Size of each buffer.

Syntax

long m_lSize;

CBaseAllocator.m_lAlignment

CBaseAllocator Class

Alignment of each buffer. The address of each buffer must be an even multiple of this value. The prefix must be calculated into the alignment; see m_lPrefix.

Syntax

long m_lAlignment;

CBaseAllocator.m_lPrefix

CBaseAllocator Class

Prefix of each buffer, in bytes. If the value is non-zero, each buffer pointer returned by the GetBuffer method is preceded by a block of bytes of size m_lPrefix. This memory block is called the prefix. The m_lSize member variable does not include the prefix value.

Syntax

long m_lPrefix;

CBaseAllocator.m_bChanged

CBaseAllocator Class

Flag indicating whether the buffer requirements have changed. The SetProperties method sets the value to TRUE. In a derived class, the pure virtual method Alloc should set the value back to FALSE. Once buffers have been allocated, there is no need to re-allocate them while m_bChanged is FALSE.

Syntax

BOOL m_bChanged;

CBaseAllocator.m_bCommitted

CBaseAllocator Class

Flag indicating whether the allocator has been committed.

Syntax

BOOL m_bCommitted;

CBaseAllocator.m_bDecommitInProgress

CBaseAllocator Class

Flag indicating whether a decommit operation is in progress. The value is TRUE after the Decommit method is called, but before all the buffers have been released. If the value is TRUE, the GetBuffer method fails. Also, the allocator should not deleted itself while the value is TRUE.

Syntax

BOOL m_bDecommitInProgress;

CBaseAllocator.m_pNotify

CBaseAllocator Class

Pointer to a callback interface, which is called when samples are released.

Syntax

IMemAllocatorNotifyCallbackTemp *m_pNotify;

CBaseAllocator.m_fEnableReleaseCallback

CBaseAllocator Class

Flag indicating whether the release callback is enabled. This flag is set in the constructor method. If the value is FALSE, calling the SetNotify method causes an assertion to fire (in debug builds).

Syntax

BOOL m_fEnableReleaseCallback;

CBaseAllocator::Alloc

CBaseAllocator Class

Allocates memory for the buffers.

Syntax

virtual HRESULT Alloc(void);

Return Value

Returns one of the following HRESULT values.

S_FALSE | Buffer requirements have not changed.
S_OK | Buffer requirements have changed.
VFW_E_SIZENOTSET | Buffer requirements were not set.

Remarks

This method is called by the Commit method.

In the base class, this method does not allocate any memory. It returns an error if the buffer requirements were not set, S_FALSE if the requirements have not changed, and S_OK if the requirements have changed.

A derived class should override this method to perform the actual memory allocation. Typically, the derived class will perform the following steps:

  1. Call the base class implementation, to determine whether the memory truly needs allocating.
  2. Allocate memory.
  3. Create CMediaSample objects that contain chunks of memory from step 2.
  4. Add each CMediaSample object to the list of free samples (m_lFree).

For an example, see CMemAllocator::Alloc.

CBaseAllocator::CBaseAllocator

CBaseAllocator Class

Constructor method.

Syntax

CBaseAllocator(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    BOOL bEvent = TRUE,
    BOOL fEnableReleaseCallback  = FALSE
);

Parameters

pName
Pointer to a string containing the name of the allocator.
pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.
bEvent
Boolean value indicating whether to create a semaphore. If TRUE, the allocator creates a semaphore (m_hSem), which is signaled whenever a sample becomes available. Set the value to FALSE if you are implementing a derived class that does not require a semaphore.
fEnableReleaseCallback
Boolean value indicating whether the release callback mechanism is enabled. Set the value to TRUE if you want to supply a callback interface, which is called when buffers are released. Specify the callback by calling the SetNotify method.

CBaseAllocator::~CBaseAllocator

CBaseAllocator Class

Destructor method.

Syntax

~CBaseAllocator(void);

Syntax

Always call the Decommit method before destroying the object. The base-class destructor cannot call Decommit, because that method calls the pure virtual method Free. Derived classes should override this destructor and call Decommit.

CBaseAllocator::Commit

CBaseAllocator Class

Allocates the memory for the buffers. Implements the IMemAllocator::Commit method.

Syntax

HRESULT Commit(void);

Return Value

Returns an HRESULT value. Possible values include those in the following list.

S_OK | Success.
VFW_E_SIZENOTSET | Buffer requirements were not specified.

Remarks

Before calling this method, call the SetProperties method to specify the buffer requirements.

This method calls the virtual method Alloc to allocate the memory for the buffers. Derived classes can override Alloc. If a decommit operation is pending, it is cancelled.

You must call this method before calling the GetBuffer method.

CBaseAllocator::Decommit

CBaseAllocator Class

Decommits the buffers. Implements the IMemAllocator::Decommit method.

Syntax

HRESULT Decommit(void);

Return Value

Returns S_OK.

Remarks

After this method is called, calls to the GetBuffer method will fail. As samples are released, they get returned to the free list. When the last sample is returned, the allocator calls the Free method, which releases the allocated memory. (In the base class, Free is a pure virtual method.)

In addition, this method releases any threads that are blocked on GetBuffer calls. The calls to GetBuffer fail.

CBaseAllocator::Free

CBaseAllocator Class

Releases the buffer memory during a decommit operation, after the last media sample is released.

Syntax

virtual void Free(void) PURE;

Remarks

After the Decommit method is called, the allocator calls this method when it releases the last media sample. The derived class must implement this method.

CBaseAllocator::GetBuffer

CBaseAllocator Class

Retrieves a media sample that contains a buffer. Implements the IMemAllocator::GetBuffer method.

Syntax

HRESULT GetBuffer(
    IMediaSample **ppBuffer,
    REFERENCE_TIME *pStartTime,
    REFERENCE_TIME *pEndTime,
    DWORD dwFlags
);

Parameters

ppBuffer
Address of a variable that receives a pointer to the buffer's IMediaSample interface.
pStartTime
Pointer to the start time of the sample.
pEndTime
Pointer to the end time of the sample.
dwFlags
Bitwise combination of zero or more flags. The base class supports the following flag:
  • AM_GBF_NOWAIT: Do not wait for a buffer to become available.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
VFW_E_NOT_COMMITTED | Allocator was not committed.
VFW_E_TIMEOUT | Timed out.

Remarks

Unless the caller specifies the AM_GBF_NOWAIT flag in dwFlags, this method blocks until the next sample is available.

The retrieved media sample has a valid pointer to the allocated buffer. The caller is responsible for setting any other properties on the sample, such as the time stamps, the media times, or the sync-point property. For more information, see IMediaSample.

In the base class, the pStartTime and pEndTime parameters are ignored. Derived classes can use these values. For example, the allocator for the Video Renderer filter uses these values to synchronize switching between Microsoft® DirectDraw® surfaces.

If the method needs to wait on a sample, it increments the count of waiting objects (m_lCount) and the calls WaitForSingleObject function on the semaphore (m_hSem). When a sample becomes available, it calls the IBaseAllocator::ReleaseBuffer method on the allocator, which increases the semaphore count by m_lCount (thereby releasing the waiting threads) and sets m_lCount back to zero.

CBaseAllocator::GetFreeCount

CBaseAllocator Class

Retrieves the number of media samples that are not in use.

Syntax

HRESULT GetFreeCount(
    LONG *plBuffersFree
);

Parameters

plBuffersFree
Address of a variable that receives the number of samples that are not in use.

Return Value

Returns S_OK.

Remarks

This value includes samples on the free list (m_lFree) and samples that were deleted.

CBaseAllocator::GetProperties

CBaseAllocator Class

Retrieves the number of buffers that the allocator will create, and the buffer properties. Implements the IMemAllocator::GetProperties method.

Syntax

HRESULT GetProperties(
    ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps
Pointer to an ALLOCATOR_PROPERTIES structure that receives the allocator properties.

Return Value

Returns S_OK.

CBaseAllocator::NotifySample

CBaseAllocator Class

Releases any threads that are waiting for samples.

Syntax

void NotifySample(void);

Remarks

When there are threads waiting for samples, the value of m_lWaiting is greater than zero. If m_lWaiting is greater than zero, this method calls the ReleaseSemaphore function on the m_hSem semaphore, activating any waiting threads. It also resets m_lWaiting to zero.

This method is called from within the ReleaseBuffer method, when a sample is returned to the free list; and from the Decommit method, when the allocator is decommitted.

CBaseAllocator::ReleaseBuffer

CBaseAllocator Class

Returns a media sample to the list of free media samples. Implements the IMemAllocator::ReleaseBuffer method.

Syntax

HRESULT ReleaseBuffer(
    IMediaSample *pSample
);

Parameters

pSample
Pointer to the IMediaSample interface of the media sample object.

Return Value

Returns S_OK.

Remarks

When a media sample's reference count reaches zero, the sample calls ReleaseBuffer with itself as the parameter. This method performs the following actions.

  • Returns the media sample to the free list (m_lFree).
  • Calls the NotifySample method, which releases any threads that are blocked on calls to the GetBuffer method.
  • If the SetNotify method was called previously, calls the IMemAllocatorNotifyCallbackTemp::NotifyRelease method.
  • When the last sample is released, if there is a pending Decommit call, calls the Free method to release the buffer memory. (In the base class, Free is a pure virtual method.)

CBaseAllocator::SetNotify

CBaseAllocator Class

Specifies a callback method to be called each time a sample is released.

Syntax

HRESULT SetNotify(
    IMemAllocatorNotifyCallbackTemp *pNotify
);

Parameters

pNotify
Pointer to an IMemAllocatorNotifyCallbackTemp interface, implemented by the caller.

Return Value

Returns S_OK.

Remarks

This method sets the m_pNotify member variable equal to pNotify and increments the reference count on the interface. If m_pNotify is non-NULL, the ReleaseBuffer method calls IMemAllocatorNotifyCallbackTemp::NotifyRelease. The call can occur in any context, so when you implement the NotifyRelease method, be careful not to make calls that could block. For example, limit the method to setting an event or posting a message for another thread.

CBaseAllocator::SetProperties

CBaseAllocator Class

Specifies the number of buffers to allocate and the size of each buffer. Implements the IMemAllocator::SetProperties method.

Syntax

HRESULT SetProperties(
    ALLOCATOR_PROPERTIES *pRequest,
    ALLOCATOR_PROPERTIES *pActual
);

Parameters

pRequest
Pointer to an ALLOCATOR_PROPERTIES structure that contains the buffer requirements.
pActual
Pointer to an ALLOCATOR_PROPERTIES structure that receives the actual buffer properties.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_ALREADY_COMMITTED | Cannot change allocated memory while the filter is active.
VFW_E_BADALIGN | An invalid alignment was specified.
VFW_E_BUFFERS_OUTSTANDING | One or more buffers are still active.

Remarks

This method specifies the buffer requirements, but does not allocate any buffers. Call the Commit method to allocate buffers.

The caller allocates two ALLOCATOR_PROPERTIES structures. The pRequest parameter contains the caller's buffer requirements, including the number of buffers and the size of each buffer. When the method returns, the pActual parameter contains the actual buffer properties, as set by the allocator. In the base class, assuming that the method succeeds, the actual properties always match the requested properties. Derived classes might override this behavior.

The allocator must not be committed, and must not have outstanding buffers. In the base class, the alignment must equal 1. The CMemAllocator class overrides this requirement.

CBaseAllocator::SetWaiting

CBaseAllocator Class

Increments the count of waiting threads.

Syntax

void SetWaiting(void);

Remarks

This method increments the m_lWaiting member variable. If a thread is blocked in the CBaseAllocator::GetBuffer method, the allocator calls SetWaiting and then waits for the m_hSem semaphore to be signalled. The ReleaseBuffer method signals the semaphore and sets m_lWaiting back to zero.


CBaseBasicVideo Class

CBaseBasicVideo class hierarchy

The CBaseBasicVideo class handles the IDispatch component of the IBasicVideo interface and leaves the properties and methods pure virtual.

The IDispatch::GetIDsOfNames, IDispatch::GetTypeInfo, IDispatch::GetTypeInfoCount, and IDispatch::Invoke methods are standard implementations of the IDispatch interface using the CBaseDispatch class (and a type library) to parse the commands and pass them to the pure virtual methods of the IBasicVideo interface.

Member Functions

CBaseBasicVideo Constructs a CBaseBasicVideo object.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface Returns a specified reference-counted interface.

Implemented IDispatch Methods

GetIDsOfNames | Maps a single member and an optional set of parameters to a corresponding set of integer dispatch identifiers, which can be used during subsequent calls to the IDispatch::Invoke method.
GetTypeInfo | Retrieves a type-information object, which can retrieve the type information for an interface.
GetTypeInfoCount | Retrieves the number of type-information interfaces provided by an object.
Invoke | Provides access to properties and methods exposed by an object.

CBaseBasicVideo::CBaseBasicVideo

CBaseBasicVideo Class

Constructs a CBaseBasicVideo object.

Syntax

CBaseBasicVideo(

  const TCHAR *pName,

  LPUNKNOWN pUnk

  );

Parameters

pName
Pointer to the name of the object for debugging purposes.
pUnk
Pointer to the owner of this object.

Return Value

No return value.

Remarks

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.

CBaseBasicVideo::GetIDsOfNames

CBaseBasicVideo Class

Maps a single member function and an optional set of parameters to a corresponding set of integer dispatch identifiers, which can be used upon subsequent calls to the CBaseBasicVideo::Invoke member function.

Syntax

HRESULT GetIDsOfNames(

  REFIID riid,

  OLECHAR **rgszNames,

  UINT cNames,

  LCID lcid,

  DISPID *rgdispid

  );

Parameters

riid
Reference identifier. Reserved for future use. Must be NULL.
rgszNames
Address of a pointer to a passed-in array of names to be mapped.
cNames
Count of the names to be mapped.
lcid
Locale context in which to interpret the names.
rgdispid
Pointer to a caller-allocated array, each element of which contains an ID corresponding to one of the names passed in the rgszNames array. The first element represents the member name; the subsequent elements represent each of the member's parameters.

Return Value

Returns one of the following values.
S_OK | Success.
E_OUTOFMEMORY | Out of memory.
DISP_E_UNKNOWNNAME | One or more of the names were not known. The returned DISPIDs contain DISPID_UNKNOWN for each entry that corresponds to an unknown name.
DISP_E_UNKNOWN_CLSID | The CLSID was not recognized.

CBaseBasicVideo::GetTypeInfo

CBaseBasicVideo Class

Retrieves a type-information object, which can retrieve the type information for an interface.

Syntax

HRESULT GetTypeInfo(

  UINT itinfo,

  LCID lcid,

  ITypeInfo **pptinfo

  );

Parameters

itinfo
Type information to return. Pass zero to retrieve type information for the IDispatch implementation.
lcid
Locale ID for the type information. For classes that support localized member names, an object might be able to return different type information for different languages. For classes that do not support localized member names, this parameter can be ignored.
pptinfo
Address of a pointer to the type-information object requested.

Return Value

Returns an E_POINTER if pptinfo is invalid. Returns TYPE_E_ELEMENTNOTFOUND if itinfo is not zero. Returns S_OK if is successful. Otherwise, returns an HRESULT from one of the calls to retrieve the type. The HRESULT indicates the error and can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.

CBaseBasicVideo::GetTypeInfoCount

CBaseBasicVideo Class

Retrieves the number of type-information interfaces provided by an object.

Syntax

HRESULT GetTypeInfoCount(

  UINT *pctinfo

  );

Parameters

pctinfo
Pointer to the location that receives the number of type-information interfaces that the object provides. If the object provides type information, this number is 1; otherwise, the number is 0.

Return Value

Returns E_POINTER if pctinfo is invalid; otherwise, returns S_OK.

CBaseBasicVideo::Invoke

CBaseBasicVideo Class

Provides access to properties and methods exposed by an object.

Syntax

HRESULT Invoke(

  DISPID dispidMember,

  REFIID riid,

  LCID lcid,

  WORD wFlags,

  DISPPARAMS *pdispparams,

  VARIANT *pvarResult,

  EXCEPINFO *pexcepinfo,

  UINT *puArgErr

  );

Parameters

dispidMember
Identifier of the member. Use CBaseBasicVideo::GetIDsOfNames or the object's documentation to obtain the dispatch identifier.
riid
Reserved for future use. Must be IID_NULL.
lcid
Locale context in which to interpret arguments.
wFlags
Flags describing the context of the CBaseBasicVideo::Invoke call.
pdispparams
Pointer to a structure containing an array of arguments, an array of argument dispatch IDs for named arguments, and counts for number of elements in the arrays.
pvarResult
Pointer to where the result is to be stored, or NULL if the caller expects no result.
pexcepinfo
Pointer to a structure containing exception information.
puArgErr
Pointer to the index of the first argument, within the rgvarg array, that has an error.

Return Value

Returns DISP_E_UNKNOWNINTERFACE if riid is not IID_NULL. Returns one of the error codes from CBaseBasicVideo::GetTypeInfo if the call fails. Otherwise, returns the HRESULT from the call to IDispatch::Invoke.

CBaseBasicVideo::NonDelegatingQueryInterface

CBaseBasicVideo Class

Returns a specified reference-counted interface.

Syntax

HRESULT NonDelegatingQueryInterface(
  REFIID riid,
  void **ppv
  );

Parameters

riid
Reference identifier.
ppv
Address of a pointer to the interface.

Return Value

Returns E_POINTER if ppv is invalid. Returns NOERROR if the query is successful or E_NOINTERFACE if it is not.

Remarks

Returns pointers to the IBasicVideo and IUnknown interfaces by default. Override this method to publish any additional interfaces implemented by the derived class.


CBaseControlVideo Class

CBaseControlVideo class hierarchy

The CBaseControlVideo class implements the IBasicVideo dual interface and controls the video properties of a generic video window. Generally, a CBaseControlVideo object is a video renderer that draws video into a window on the display.

The CBaseControlVideo class supports both properties and methods. Properties are more easily accessible from many Automation controllers (such as the Microsoft® Visual Basic® programming system). However, some operations require applications to be able to change several properties simultaneously; for this reason, methods are provided that enable a number of related properties to be changed.

Many CBaseControlVideo member functions require only that the video renderer be connected to a filter graph. If it is not connected, member functions will return VFW_E_NOT_CONNECTED. Properties set on a video renderer persist between successive connections and disconnections. All applications should ensure that they reset the renderer properties before starting a presentation.

When working with video, the application can select a portion of the video to use. This portion is the source rectangle that the CBaseControlVideo object controls. CBaseControlVideo enables your application to set and retrieve the source rectangle. All the rectangles that CBaseControlVideo uses employ top, left, width, and height rather than top, left, right, and bottom, which is favored in Microsoft Win32® programming. When no source rectangle has been set, the properties of the source rectangle return the full, native video size.

Protected Data Members

m_pFilter | Pointer to an owning media filter.
m_pInterfaceLock | Externally defined critical section.
m_pPin | Control of the media types for connection.

Member Functions

CBaseControlVideo | Constructs a CBaseControlVideo object.
CopyImage | Creates a memory copy of a video image.
GetImageSize | Retrieves video image size information.
SetControlVideoPin | Sets the pin with which this object should synchronize.

Overridable Member Functions

CheckSourceRect | Determines if a source rectangle is valid.
CheckTargetRect | Determines if a target rectangle is valid.
GetSourceRect | Retrieves the current source video rectangle (pure virtual).
GetStaticImage | Returns the current image in a memory buffer (pure virtual).
GetTargetRect | Retrieves the current target video rectangle (pure virtual).
GetVideoFormat | Retrieves the VIDEOINFOHEADER structure containing the video format.
IsDefaultSourceRect | Determines if the renderer is using the default source rectangle (pure virtual).
IsDefaultTargetRect | Determines if the renderer is using the default target rectangle (pure virtual).
OnUpdateRectangles | Called when the source or target rectangle changes.
OnVideoSizeChange | Passes EC_VIDEO_SIZE_CHANGED to the application.
SetDefaultSourceRect | Sets the default source video rectangle (pure virtual).
SetDefaultTargetRect | Sets the default target video rectangle (pure virtual).
SetSourceRect | Sets the current source video rectangle (pure virtual).
SetTargetRect | Sets the current target rectangle (pure virtual).

Implemented IBasicVideo Methods

get_AvgTimePerFrame | Retrieves an approximate average time per frame.
get_BitErrorRate | Retrieves an approximate bit error rate.
get_BitRate | Retrieves an approximate bit rate for the video.
GetCurrentImage | Retrieves a memory rendering of the current image.
get_DestinationHeight | Retrieves the current destination rectangle's height.
get_DestinationLeft | Retrieves the current destination rectangle's left coordinate.
GetDestinationPosition | Retrieves the current destination position.
get_DestinationTop | Retrieves the current destination rectangle's top coordinate.
get_DestinationWidth | Retrieves the current destination rectangle's width.
get_SourceHeight | Retrieves the current source rectangle's height.
get_SourceLeft | Retrieves the current source rectangle's left coordinate.
GetSourcePosition | Retrieves the current source position.
get_SourceTop | Retrieves the current source rectangle's top coordinate.
get_SourceWidth | Retrieves the current source rectangle's width.
get_VideoHeight | Retrieves the native video height.
GetVideoPaletteEntries | Retrieves a range of palette entries for the video.
GetVideoSize | Retrieves the width and height of the native video.
get_VideoWidth | Retrieves the native video width.
IsUsingDefaultDestination | Determines if the renderer is using the default destination window.
IsUsingDefaultSource | Determines if the renderer is using the default source window.
put_DestinationHeight | Sets the destination rectangle's height.
put_DestinationLeft | Sets the destination rectangle's left coordinate.
put_DestinationTop | Sets the destination rectangle's top coordinate.
put_DestinationWidth | Sets the destination rectangle's width.
put_SourceHeight | Sets the source rectangle's height.
put_SourceLeft | Sets the source rectangle's left coordinate.
put_SourceTop | Sets the source rectangle's top coordinate.
put_SourceWidth | Sets the source rectangle's width.
SetDefaultDestinationPosition | Sets the default destination position again.
SetDefaultSourcePosition | Sets the default source position again.
SetDestinationPosition | Sets the destination rectangle position.
SetSourcePosition | Sets the source rectangle position.

CBaseControlVideo::CBaseControlVideo

CBaseControlVideo Class

Constructs a CBaseControlVideo object.

Syntax

CBaseControlVideo(
    CBaseFilter *pFilter,
    CCritSec *pInterfaceLock,
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr
    );

Parameters

pFilter
Pointer to the owning media filter object.
pInterfaceLock
Pointer to the critical section to use for locking.
pName
Pointer to the object description.
pUnk
Pointer to the controlling IUnknown interface, if the object is part of an aggregate; otherwise, must be NULL.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the constructor method.

Return Value

No return value.

Remarks

The object implements the IBasicVideo control interface.

All the interface methods from IBasicVideo that this class implements require that the filter be connected correctly. For this reason, the class is passed a pin with which it should synchronize with. Whenever an interface method is called, the object determines that the pin is still connected.

CBaseControlVideo::CheckSourceRect

CBaseControlVideo Class

Determines if a source rectangle is valid.

Syntax

virtual HRESULT CheckSourceRect(
    RECT *pSourceRect
    );

Parameters

pSourceRect
Pointer to the source rectangle to check.

Return Value

Returns E_INVALIDARG if not valid; otherwise, returns NOERROR (S_OK).

Remarks

This member function checks that the source rectangle requested does not exceed the available source video. The left and top coordinates cannot be negative, and the width and height cannot exceed the right and bottom of the video.

CBaseControlVideo::CheckTargetRect

CBaseControlVideo Class

Determines if a target rectangle is valid.

Syntax

virtual HRESULT CheckTargetRect(
    RECT *pTargetRect
    );

Parameters

pTargetRect
Pointer to the target rectangle to check.

Return Value

Returns E_INVALIDARG if not valid; otherwise, returns NOERROR (S_OK).

Remarks

This member function determines if the target rectangle requested is valid. Because the destination rectangle specifies a position in the logical client of the window, the coordinates can be negative, although the overall width and height cannot be zero or a negative value.

CBaseControlVideo::CopyImage

CBaseControlVideo Class

Creates a memory copy of an image.

Syntax

HRESULT CopyImage(
    IMediaSample *pMediaSample,
    VIDEOINFOHEADER *pVideoInfo,
    LONG *pBufferSize,
    BYTE *pVideoImage,
    RECT *pSourceRect
    );

Parameters

pMediaSample
Pointer to the sample containing the video image.
pVideoInfo
Pointer to the format representing the video image.
pBufferSize
Pointer to the size of the output buffer.
pVideoImage
Pointer to the output buffer.
pSourceRect
Pointer to the source video rectangle.

Return Value

If the pVideoImage parameter is NULL, the pBufferSize parameter is filled in with the number of bytes the output buffer requires to store the image. If the buffer passed in is too small or the member function fails to allocate sufficient memory, the member function returns E_OUTOFMEMORY.

Remarks

The member function retrieves the image from the sample and copies it into the output buffer. The section of video copied into the output buffer reflects the source rectangle that is set through the IBasicVideo interface (although it does not reflect the destination rectangle).

CBaseControlVideo::get_AvgTimePerFrame

CBaseControlVideo Class

Retrieves the average time per frame.

Syntax

HRESULT get_AvgTimePerFrame(
    REFTIME *pAvgTimePerFrame
    );

Parameters

pAvgTimePerFrame
Pointer to the average time per frame.

Return Value

Returns NOERROR if successful or E_OUTOFMEMORY if there is not enough memory available.

Remarks

This member function implements the IBasicVideo::get_AvgTimePerFrame method. It calls the pure virtual CBaseControlVideo::GetVideoFormat member function to retrieve the VIDEOINFOHEADER structure from the derived class.

CBaseControlVideo::get_BitErrorRate

CBaseControlVideo Class

Retrieves an approximate bit error rate for the video.

Syntax

HRESULT get_BitErrorRate(
    long *pBitErrorRate
    );

Parameters

pBitErrorRate
Pointer to the bit error rate (one error for approximately this many bits).

Return Value

Returns NOERROR if successful or E_OUTOFMEMORY if there is not enough memory available.

Remarks

This member function implements the IBasicVideo::get_BitErrorRate method. It calls the pure virtual CBaseControlVideo::GetVideoFormat to retrieve the VIDEOINFOHEADER structure from the derived class.

CBaseControlVideo::get_BitRate

CBaseControlVideo Class

Retrieves an approximate bit rate for the video.

Syntax

HRESULT get_BitRate(
    long *pBitRate
    );

Parameters

pBitRate
Pointer to the bit rate, in bits per second.

Return Value

Returns NOERROR if successful or E_OUTOFMEMORY if not enough memory is available.

Remarks

This member function implements the IBasicVideo::get_BitRate method. It calls the pure virtual CBaseControlVideo::GetVideoFormat to retrieve the VIDEOINFOHEADER structure from the derived class.

CBaseControlVideo::GetCurrentImage

CBaseControlVideo Class

Retrieves a copy of the current image at the renderer.

Syntax

HRESULT GetCurrentImage(
    long *pBufferSize,
    long *pVideoImage
    );

Parameters

pBufferSize
Pointer to the size of the output buffer.
pVideoImage
Pointer to the output buffer for the image.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Out of memory. Returned when the pVideoInfo parameter is NULL.
NOERROR | Success.
VFW_E_NOT_PAUSED | The operation could not be performed because the filter is not paused.

Remarks

This member function retrieves the image from the sample and copies it into the output buffer. The section of video copied into the output buffer reflects the source rectangle set through the IBasicVideo interface. It does not reflect the destination rectangle.

CBaseControlVideo::get_DestinationHeight

CBaseControlVideo Class

Retrieves the current destination rectangle height.

Syntax

HRESULT get_DestinationHeight(
    long *pDestinationHeight
    );

Parameters

pDestinationHeight
Pointer to the destination height.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_DestinationHeight method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where it will be played. The destination rectangle is relative to the client area of the window that it is playing in. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::get_DestinationLeft

CBaseControlVideo Class

Retrieves the left coordinate of the current destination rectangle.

Syntax

HRESULT get_DestinationLeft(
    long *pDestinationLeft
    );

Parameters

pDestinationLeft
Pointer to the left coordinate of the destination rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_DestinationLeft method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::GetDestinationPosition

CBaseControlVideo Class

Retrieves the destination rectangle in one atomic operation.

Syntax

HRESULT GetDestinationPosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
    );

Parameters

pLeft
Pointer to the left coordinate of the destination rectangle.
pTop
Pointer to the top coordinate of the destination rectangle.
pWidth
Pointer to the width of the destination rectangle.
pHeight
Pointer to the height of the destination rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function can be used in place of separate calls to the CBaseControlVideo::get_DestinationLeft, CBaseControlVideo::get_DestinationTop, CBaseControlVideo::get_DestinationWidth, and CBaseControlVideo::get_DestinationHeight member functions. An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::get_DestinationTop

CBaseControlVideo Class

Retrieves the top coordinate of the current destination rectangle.

Syntax

HRESULT get_DestinationTop(
    long *pDestinationTop
    );

Parameters

pDestinationTop
Pointer to the top coordinate of the destination rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_DestinationTop method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::get_DestinationWidth

CBaseControlVideo Class

Retrieves the width of the current destination rectangle.

Syntax

HRESULT get_DestinationWidth(
    long *pDestinationWidth
    );

Parameters

pDestinationWidth
Pointer to the destination width.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_DestinationWidth method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::GetImageSize

CBaseControlVideo Class

Retrieves video image size information.

Syntax

HRESULT GetImageSize(
    VIDEOINFOHEADER *pVideoInfo,
    long *pBufferSize,
    RECT *pSourceRect
    );

Parameters

pVideoInfo
Pointer to a VIDEOINFOHEADER structure to be filled in.
pBufferSize
Pointer to the size of the video buffer.
pSourceRect
Pointer to the rectangle dimensions of the source video.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument. The data format is not compatible.
E_UNEXPECTED | Unexpected error occurred. One or more arguments are NULL.
NOERROR | Success.

Remarks

This member function is a helper function used for creating memory image renderings of DIB images. It is called from the base class implementation of CBaseControlVideo::GetCurrentImage when a null pVideoImage parameter is passed to that member function. As a result, this member function constructs and returns a VIDEOINFOHEADER structure, using the information in pBufferSize and pSourceRect.

CBaseControlVideo::get_SourceHeight

CBaseControlVideo Class

Retrieves the height of the current source rectangle.

Syntax

HRESULT get_SourceHeight(
    long *pSourceHeight
    );

Parameters

pSourceHeight
Pointer to the height of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_SourceHeight method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::get_SourceLeft

CBaseControlVideo Class

Retrieves the left coordinate of the current source rectangle.

Syntax

HRESULT get_SourceLeft(
    long *pSourceLeft
    );

Parameters

pSourceLeft
Pointer to the left coordinate of the current source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::GetSourcePosition

CBaseControlVideo Class

Retrieves the position and dimensions of the source rectangle in one atomic operation.

Syntax

HRESULT GetSourcePosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
    );

Parameters

pLeft
Pointer to the left coordinate of the source rectangle.
pTop
Pointer to the top coordinate of the source rectangle.
pWidth
Pointer to the width of the source rectangle.
pHeight
Pointer to the height of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::GetSourceRect

CBaseControlVideo Class

Retrieves the source rectangle. This is an internal method.

Syntax

virtual HRESULT GetSourceRect(
    RECT *pSourceRect
    ) PURE;

Parameters

pSourceRect
Pointer to the retrieved source rectangle.

Return Value

Returns an HRESULT value.

Remarks

This member function must be overridden in the derived class to return the source rectangle held by the video renderer. It is called from the following CBaseControlVideo member functions.

  • CBaseControlVideo::GetSourcePosition
  • CBaseControlVideo::put_SourceLeft
  • CBaseControlVideo::get_SourceLeft
  • CBaseControlVideo::put_SourceWidth
  • CBaseControlVideo::get_SourceWidth
  • CBaseControlVideo::put_SourceTop
  • CBaseControlVideo::get_SourceTop
  • CBaseControlVideo::put_SourceHeight
  • CBaseControlVideo::get_SourceHeight

The following example demonstrates an implementation of this function in a derived class.

// Return the current source rectangle

HRESULT CVideoText::GetSourceRect(RECT *pSourceRect)
{
    ASSERT(pSourceRect);
    m_pRenderer->m_DrawImage.GetSourceRect(pSourceRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object.

CBaseControlVideo::get_SourceTop

CBaseControlVideo Class

Retrieves the top coordinate of the current source rectangle.

Syntax

HRESULT get_SourceTop(
    long *pSourceTop
    );

Parameters

pSourceTop
Pointer to the top coordinate of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_SourceTop method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::get_SourceWidth

CBaseControlVideo Class

Retrieves the width of the current source rectangle.

Syntax

HRESULT get_SourceWidth(
    long *pSourceWidth
    );

Parameters

pSourceWidth
Pointer to the width of the current source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

Remarks

This member function implements the IBasicVideo::get_SourceWidth method.

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::GetStaticImage

CBaseControlVideo Class

Pure virtual method that derived classes override.

Syntax

virtual HRESULT GetStaticImage(
    long *pBufferSize,
    long *pDIBImage
    ) PURE;

Parameters

pBufferSize
Pointer to the size of the output buffer.
pDIBImage
Pointer to the output buffer.

Return Value

Returns an HRESULT value.

Remarks

Through the IBasicVideo interface, an application can request that it be given a copy of the current image in a memory buffer (some renderers can return E_NOTIMPL to this if they do not support it). The derived class determines how to retrieve the image. When the application calls CBaseControlVideo::GetStaticImage, it calls this pure virtual method that the derived class should override to implement it. This is also called by the CBaseControlVideo::GetCurrentImage member function.

The class provides a helper member function, CBaseControlVideo::CopyImage, that can be given a sample that contains an image, and the member function will copy the relevant section of it (based on the current source rectangle) into the output buffer supplied by the application.

The following example demonstrates an implementation of this member function in a derived class. In this example, m_pRenderer holds an object of a class derived from CBaseVideoRenderer.

// Return a copy of the current image in the video renderer

HRESULT CVideoText::GetStaticImage(long *pBufferSize,long *pDIBImage)
{
    // Get any sample the renderer may be holding.

    IMediaSample *pMediaSample = m_pRenderer->GetCurrentSample();
    if (pMediaSample == NULL) {
        return E_UNEXPECTED;
    }

    // Call the base class helper method to do the work.

    HRESULT hr = CopyImage(pMediaSample,          // Buffer containing image
                           &m_pRenderer->m_mtIn,                // Type representing bitmap
                           pBufferSize,                                     // Size of buffer for DIB
                           (BYTE*) pDIBImage);                   // Data buffer for output

    pMediaSample->Release();
    return hr;
}

CBaseControlVideo::GetTargetRect

CBaseControlVideo Class

Retrieves the destination rectangle. This is an internal helper member function.

Syntax

virtual HRESULT GetTargetRect(
    RECT *pTargetRect
    ) PURE;

Parameters

pTargetRect
Pointer to the destination rectangle.

Return Value

Returns an HRESULT value.

Remarks

This member function must be overridden in the derived class to return the target rectangle held by the video renderer. It is called from the following CBaseControlVideo member functions.

  • CBaseControlVideo::GetDestinationPosition
  • CBaseControlVideo::put_DestinationLeft
  • CBaseControlVideo::get_DestinationLeft
  • CBaseControlVideo::put_DestinationWidth
  • CBaseControlVideo::get_DestinationWidth
  • CBaseControlVideo::put_DestinationTop
  • CBaseControlVideo::get_DestinationTop
  • CBaseControlVideo::put_DestinationHeight
  • CBaseControlVideo::get_DestinationHeight

The following example demonstrates an implementation of this function in a derived class.

// Return the current destination rectangle.

HRESULT CVideoText::GetTargetRect(RECT *pTargetRect)
{
    ASSERT(pTargetRect);
    m_pRenderer->m_DrawImage.GetTargetRect(pTargetRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object.

CBaseControlVideo::GetVideoFormat

CBaseControlVideo Class

Retrieves a video sample that represents the current video format.

Syntax

virtual VIDEOINFOHEADER * GetVideoFormat(void) PURE;

Return Value

Returns a pointer to a VIDEOINFOHEADER structure that contains the current video format.

Remarks

To return and check certain information through IBasicVideo, the object must know the current video format. It gets this information by calling this pure virtual method that derived classes must override. This member function is called by the following CBaseControlVideo member functions.

  • CBaseControlVideo::OnVideoSizeChange
  • CBaseControlVideo::get_AvgTimePerFrame
  • CBaseControlVideo::get_BitRate
  • CBaseControlVideo::get_BitErrorRate
  • CBaseControlVideo::get_VideoWidth
  • CBaseControlVideo::get_VideoHeight
  • CBaseControlVideo::GetVideoPaletteEntries
  • CBaseControlVideo::GetVideoSize

CBaseControlVideo::get_VideoHeight

CBaseControlVideo Class

Retrieves the height of the native video.

Syntax

HRESULT get_VideoHeight(
    long *pVideoHeight
    );

Parameters

pVideoHeight
Pointer to the height of the native video, in pixels.

Return Value

Returns NOERROR if successful or E_OUTOFMEMORY if there is not enough memory available.

Remarks

This member function implements the IBasicVideo::get_VideoHeight method. It calls the pure virtual CBaseControlVideo::GetVideoFormat to retrieve the VIDEOINFOHEADER structure from the derived class.

CBaseControlVideo::GetVideoPaletteEntries

CBaseControlVideo Class

Retrieves a range of palette entries for the video.

Syntax

HRESULT GetVideoPaletteEntries(
    long StartIndex,
    long Entries,
    long *pRetrieved,
    long *pPalette
    );

Parameters

StartIndex
Zero-based start palette entry.
Entries
Number of entries required.
pRetrieved
Pointer to the number of colors obtained.
pPalette
Pointer to output buffer for colors.

Return Value

Returns NOERROR if successful, VFW_E_NO_PALETTE_AVAILABLE if the video samples has no color palette, E_OUTOFMEMORY if there is not enough memory available, E_INVALIDARG if StartIndex is invalid, or S_FALSE if there are no colors in the palette.

Remarks

This member function returns the current palette of the video as an array allocated by the user. To remain consistent, use the members in the Win32 PALETTEENTRY structure to return the colors, rather than the members in the RGBQUAD structure (although the parameter is a LONG). The memory is allocated by the caller, so simply copy each in turn. Determine that the number of entries requested and the start position offset are both valid. If the number of entries evaluates to zero, return an S_FALSE code.

CBaseControlVideo::GetVideoSize

CBaseControlVideo Class

Retrieves the native video's width and height.

Syntax

HRESULT GetVideoSize(
    long *pWidth,
    long *pHeight
    );

Parameters

pWidth
Pointer to the video width.
pHeight
Pointer to the video height.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_OUTOFMEMORY | Out of memory.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.
NOERROR | Success.

CBaseControlVideo::get_VideoWidth

CBaseControlVideo Class

Retrieves the width of the native video.

Syntax

HRESULT get_VideoWidth(
    long *pVideoWidth
    );

Parameters

pVideoWidth
Pointer to the width of the native video, in pixels.

Return Value

Returns NOERROR if successful or E_OUTOFMEMORY if there is not enough memory available.

Remarks

This member function implements the IBasicVideo::get_VideoWidth method. It calls the pure virtual CBaseControlVideo::GetVideoFormat to retrieve the VIDEOINFOHEADER structure from the derived class.

CBaseControlVideo::IsDefaultSourceRect

CBaseControlVideo Class

Determines if the renderer is using the default source rectangle (pure virtual).

Syntax

virtual HRESULT IsDefaultSourceRect(void) PURE;

Return Value

Returns an HRESULT value. Returns S_OK if the renderer is using the default source; otherwise, returns S_FALSE.

Remarks

This member function must be implemented in the derived class. It is called by the CBaseControlVideo::IsUsingDefaultSource member function.

The following example demonstrates an implementation of this function in a derived class.

// Return S_OK if using the default source; otherwise, S_FALSE.

HRESULT CVideoText::IsDefaultSourceRect()
{
    RECT SourceRect;

    VIDEOINFO *pVideoInfo = (VIDEOINFO *) m_pRenderer->m_mtIn.Format();
    BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo);
    m_pRenderer->m_DrawImage.GetSourceRect(&SourceRect);

    // Check the coordinates that match the video dimensions.

    if (SourceRect.left != 0 || SourceRect.top != 0 ||
            SourceRect.right != pHeader->biWidth ||
                SourceRect.bottom != pHeader->biHeight) {
                    return S_FALSE;
    }
    return S_OK;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object. The m_mtIn data member, also defined in the derived class, holds a CMediaType object with the media type of the input pin.

CBaseControlVideo::IsDefaultTargetRect

CBaseControlVideo Class

Determines if the renderer is using the default target rectangle (pure virtual).

Syntax

virtual HRESULT IsDefaultTargetRect(void) PURE;

Return Value

Returns an HRESULT value. Returns S_OK if the renderer is using the default target; otherwise, returns S_FALSE.

Remarks

This member function must be implemented in the derived class. It is called by the CBaseControlVideo::IsUsingDefaultDestination member function.

The following example demonstrates an implementation of this function in a derived class.

// Return S_OK if using the default target; otherwise, S_FALSE.

HRESULT CVideoText::IsDefaultTargetRect()
{
    RECT TargetRect;

    VIDEOINFO *pVideoInfo = (VIDEOINFO *) m_pRenderer->m_mtIn.Format();
    BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo);
    m_pRenderer->m_DrawImage.GetTargetRect(&TargetRect);

    // Check the destination that matches the initial client area.

    if (TargetRect.left != 0 || TargetRect.top != 0 ||
            TargetRect.right != m_Size.cx ||
                TargetRect.bottom != m_Size.cy) {
                    return S_FALSE;
    }
    return S_OK;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object. The m_mtIn data member, also defined in the derived class, holds a CMediaType object with media type of the input pin.

CBaseControlVideo::IsUsingDefaultSource

CBaseControlVideo Class

Determines if the renderer is using the default source window.

Syntax

virtual HRESULT IsUsingDefaultSource(void);

Return Value

Returns an HRESULT value. Returns S_OK if the renderer is using the default source; otherwise, returns S_FALSE.

CBaseControlVideo::IsUsingDefaultDestination

CBaseControlVideo Class

Determines if the renderer is using the default destination window.

Syntax

virtual HRESULT IsUsingDefaultDestination(void);

Return Value

Returns an HRESULT value. Returns S_OK if using the default destination; otherwise, returns S_FALSE.

CBaseControlVideo::OnUpdateRectangles

CBaseControlVideo Class

Called when either the source or destination rectangle changes.

Syntax

virtual HRESULT OnUpdateRectangles(void);

Return Value

Returns NOERROR.

CBaseControlVideo::OnVideoSizeChange

CBaseControlVideo Class

Passes an EC_VIDEO_SIZE_CHANGED message to the filter graph manager.

Syntax

virtual HRESULT OnVideoSizeChange(void);

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_OUTOFMEMORY | Out of memory.

Remarks

A video renderer should call this member function each time the video size is changed; this will typically be called once after initial connection. If the renderer can support dynamic format changes (from 320 x 240 to 160 x 120), it should also call it after each change.

CBaseControlVideo::put_DestinationHeight

CBaseControlVideo Class

Sets the destination rectangle height.

Syntax

HRESULT put_DestinationHeight(
    long DestinationHeight
    );

Parameters

DestinationHeight
New destination height.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::put_DestinationLeft

CBaseControlVideo Class

Sets the left coordinate of the destination rectangle.

Syntax

HRESULT put_DestinationLeft(
    long DestinationLeft
    );

Parameters

DestinationLeft
New left coordinate of destination rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::put_DestinationTop

CBaseControlVideo Class

Sets the top coordinate of the destination rectangle.

Syntax

HRESULT put_DestinationTop(
    long DestinationTop
    );

Parameters

DestinationTop
New top coordinate of the destination rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::put_DestinationWidth

CBaseControlVideo Class

Sets the width of the destination rectangle.

Syntax

HRESULT put_DestinationWidth(
    long DestinationWidth
    );

Parameters

DestinationWidth
New destination width.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::put_SourceHeight

CBaseControlVideo Class

Sets the source rectangle height.

Syntax

HRESULT put_SourceHeight(
    long SourceHeight
    );

Parameters

SourceHeight
Source height.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::put_SourceLeft

CBaseControlVideo Class

Sets the source rectangle left coordinate.

Syntax

HRESULT put_SourceLeft(
    long SourceLeft
    );

Parameters

SourceLeft
New left coordinate of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::put_SourceTop

CBaseControlVideo Class

Sets the top coordinate of the source rectangle.

Syntax

HRESULT put_SourceTop(
    long SourceTop
    );

Parameters

SourceTop
New top coordinate of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::put_SourceWidth

CBaseControlVideo Class

Sets the width of the source rectangle.

Syntax

HRESULT put_SourceWidth(
    long SourceWidth
    );

Parameters

SourceWidth
New width of the source rectangle.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::SetControlVideoPin

CBaseControlVideo Class

Sets the pin used by the filter.

Syntax

void SetControlVideoPin(
    CBasePin *pPin
    );

Parameters

pPin
Pointer to the pin with which the interface is synchronized.

Return Value

No return value.

Remarks

The interface can be called only when the filter has been connected successfully. The object is passed through this method to the pin with which it is synchronized; in most cases it will determine if the pin is connected when it has an interface method called and will return VFW_E_NOT_CONNECTED if it fails.

CBaseControlVideo::SetDefaultDestinationPosition

CBaseControlVideo Class

Sets the renderer back to using the default destination position (typically the entire window client area).

Syntax

HRESULT SetDefaultDestinationPosition(void);

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::SetDefaultSourcePosition

CBaseControlVideo Class

Sets the renderer back to using the default source position (typically all the native video).

Syntax

HRESULT SetDefaultSourcePosition(void);

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::SetDefaultSourceRect

CBaseControlVideo Class

Sets the default source video rectangle (pure virtual). This in an internal member function that gets called when the source rectangle is reset.

Syntax

virtual HRESULT SetDefaultSourceRect(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

Derived classes should override this to reset the source rectangle. It is called from CBaseControlVideo::SetDefaultSourcePosition.

The following example demonstrates an implementation of this function in a derived class.

// This is called when you reset the default source rectangle.

HRESULT CVideoText::SetDefaultSourceRect()
{
    VIDEOINFO *pVideoInfo = (VIDEOINFO *) m_pRenderer->m_mtIn.Format();
    BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo);
    RECT SourceRect = {0,0,pHeader->biWidth,pHeader->biHeight};
    m_pRenderer->m_DrawImage.SetSourceRect(&SourceRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object. The m_mtIn data member, also defined in the derived class, holds a CMediaType object with media type of the input pin.

CBaseControlVideo::SetDefaultTargetRect

CBaseControlVideo Class

Sets the default target video rectangle (pure virtual). This is an internal member function that gets called when the source rectangle is reset.

Syntax

virtual HRESULT SetDefaultTargetRect(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

Derived classes should override this to reset the destination video rectangle. It is called from the CBaseControlVideo::SetDefaultDestinationPosition member function.

The following example demonstrates an implementation of this function in a derived class.

// This is called when you reset the default target rectangle.

HRESULT CVideoText::SetDefaultTargetRect()
{
    VIDEOINFO *pVideoInfo = (VIDEOINFO *) m_pRenderer->m_mtIn.Format();
    BITMAPINFOHEADER *pHeader = HEADER(pVideoInfo);
    RECT TargetRect = {0,0,m_Size.cx,m_Size.cy};
    m_pRenderer->m_DrawImage.SetTargetRect(&TargetRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object. The m_mtIn data member, also defined in the derived class, holds a CMediaType object with the media type of the input pin.

CBaseControlVideo::SetDestinationPosition

CBaseControlVideo Class

Sets the destination rectangle for the video.

Syntax

HRESULT SetDestinationPosition(
    long Left,
    long Top,
    long Width,
    long Height
    );

Parameters

Left
New left coordinate.
Top
New top coordinate.
Width
New width.
Height
New height.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::SetSourcePosition

CBaseControlVideo Class

Sets a new source position for the video.

Syntax

HRESULT SetSourcePosition(
    long Left,
    long Top,
    long Width,
    long Height
    );

Parameters

Left
New left coordinate.
Top
New top coordinate.
Width
New width.
Height
New height.

Return Value

Returns an HRESULT value that depends on the implementation; can be one of the following values, or other values not listed.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | Null pointer argument.
NOERROR | Success.
VFW_E_NOT_CONNECTED | The operation cannot be performed because the pins are not connected.

Remarks

An application can change the source and destination rectangles for the video through the IBasicVideo interface. The source rectangle affects which section of the native video source will appear on the display; the destination rectangle affects where the video will appear when played. The destination rectangle is relative to the client area of the window in which it is playing. The upper-left corner of the window is coordinate (0,0).

CBaseControlVideo::SetSourceRect

CBaseControlVideo Class

Sets the current source video rectangle (pure virtual). This is an internal member function that gets called when the source rectangle changes.

Syntax

virtual HRESULT SetSourceRect(
    RECT *pSourceRect
    ) PURE;

Parameters

pSourceRect
Pointer to the source rectangle.

Return Value

Returns an HRESULT value.

Remarks

Derived classes should override this member function to know when the source rectangle changes. It is called from the following member functions.

  • CBaseControlVideo::SetSourcePosition
  • CBaseControlVideo::put_SourceLeft
  • CBaseControlVideo::put_SourceWidth
  • CBaseControlVideo::put_SourceTop
  • CBaseControlVideo::put_SourceHeight

The following example demonstrates an implementation of this function in a derived class.

HRESULT CVideoText::SetSourceRect(RECT *pSourceRect)
{
    m_pRenderer->m_DrawImage.SetSourceRect(pSourceRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object.

CBaseControlVideo::SetTargetRect

CBaseControlVideo Class

Sets the current target rectangle (pure virtual). This is an internal member function that gets called when the destination rectangle changes.

Syntax

virtual HRESULT SetTargetRect(
    RECT *pTargetRect
    ) PURE;

Parameters

pTargetRect
Pointer to the destination rectangle.

Return Value

Returns an HRESULT value.

Remarks

Derived classes should override this to know when the destination rectangle changes. It is called from the following member functions.

  • CBaseControlVideo::SetDestinationPosition
  • CBaseControlVideo::put_DestinationLeft
  • CBaseControlVideo::put_DestinationWidth
  • CBaseControlVideo::put_DestinationTop
  • CBaseControlVideo::put_DestinationHeight

The following example demonstrates an implementation of this function in a derived class.

HRESULT CVideoText::SetTargetRect(RECT *pTargetRect)
{
    m_pRenderer->m_DrawImage.SetTargetRect(pTargetRect);
    return NOERROR;
}

In this example, CVideoText is a class derived from CBaseControlVideo, m_pRenderer holds an object of a class derived from CBaseVideoRenderer, and the m_DrawImage data member, defined in the derived class, holds a CDrawImage object.


CBaseControlWindow Class

CBaseControlWindow class hierarchy

The CBaseControlWindow class implements the IVideoWindow interface and controls external access to its associated filter. You must synchronize the CBaseControlWindow object with the filter by passing it a pointer to a critical section synchronization object. For more information about critical section synchronization objects, see the Platform SDK. The CBaseControlWindow class provides a number of methods that return property settings without dealing with this critical section. For example, calling CBaseControlWindow::get_AutoShow to retrieve the value of the m_bAutoShow data member locks the critical section. The filter might already have a locked internal critical section, however, which could violate the filter's lock hierarchy. Instead, calling the CBaseControlWindow::IsAutoShowEnabled member function returns the required value without affecting the critical section.

All CBaseControlWindow implemented IVideoWindow methods require that the filter be connected correctly with its upstream filter. For this reason, class objects require a synchronization pin, which you set by calling the CBaseControlWindow::SetControlWindowPin method. Whenever you call an IVideoWindow method, the CBaseControlWindow object checks that the pin is still connected.

Protected Data Members

m_bAutoShow | Result when the state changes.
m_bCursorHidden | Determination of whether the cursor is displayed or hidden.
m_BorderColour | Color of the current window border.
m_hwndDrain | Window handle to which messages received are posted.
m_hwndOwner | Owning window.
m_pFilter | Pointer to the owning media filter.
m_pInterfaceLock | Externally defined critical section.
m_pPin | Control of the media types for connection.

Member Functions

CBaseControlWindow | Constructs a CBaseControlWindow object.
DoGetWindowStyle | Retrieves either the typical or extended window styles.
DoSetWindowStyle | Sets the typical or extended window styles.
GetBorderColour | Retrieves the current border color. This is a helper member function.
GetOwnerWindow | Retrieves the owning window. This is a helper member function.
IsAutoShowEnabled | Retrieves information about whether the video window automatically appears when the rendering filter pauses or runs.
IsCursorHidden | Retrieves the current state of the m_bCursorHidden data member without locking the critical section. This is a helper member function.
PossiblyEatMessage | Distributes messages to the parent window.
SetControlWindowPin | Notifies the object of the pin to which it applies.

Implemented IVideoWindow Methods

get_AutoShow | Retrieves the current AutoShow flag setting.
get_BackgroundPalette | Retrieves the realized palette in the background flag.
get_BorderColor | Retrieves the current border color.
get_Caption | Retrieves the current window caption.
get_FullScreenMode | Retrieves the current full-screen mode.
get_Height | Retrieves the current window height.
get_Left | Retrieves the current left window coordinate.
GetMaxIdealImageSize | Retrieves the maximum size of the ideal image.
get_MessageDrain | Retrieves the current message drain.
GetMinIdealImageSize | Retrieves the minimum size of the ideal image.
get_Owner | Retrieves the Microsoft® Win32® parent window handle.
GetRestorePosition | Retrieves the position to which the window will be restored when maximized or minimized.
get_Top | Retrieves the y-coordinate for the top of the window.
get_Visible | Retrieves the current visibility setting of the window.
get_Width | Retrieves the width of the window.
GetWindowPosition | Retrieves the current window coordinates.
get_WindowState | Retrieves the current state of the window.
get_WindowStyle | Retrieves the standard window styles.
get_WindowStyleEx | Retrieves the extended window styles.
HideCursor | Hides or displays the cursor.
IsCursorHidden | Retrieves the current state of the m_bCursorHidden data member.
NotifyOwnerMessage | Passes on messages that are sent to owning windows.
put_AutoShow | Sets the AutoShow property.
put_BackgroundPalette | Sets a flag to realize the palette in the background.
put_BorderColor | Sets the current border color.
put_Caption | Sets the current window caption.
put_FullScreenMode | Sets the full-screen mode.
put_Height | Sets the current window height.
put_Left | Sets the left coordinate for the window.
put_MessageDrain | Sets the message drain window.
put_Owner | Sets the Microsoft Win32 parent window handle.
put_Top | Sets the position for the top of the window.
put_Visible | Hides or shows the window.
put_Width | Sets the width of the window.
put_WindowState | Sets the state of the window.
put_WindowStyle | Sets the standard window styles.
put_WindowStyleEx | Sets the extended window styles.
SetWindowForeground | Sets the window in the foreground.
SetWindowPosition | Sets the window position.

CBaseControlWindow::CBaseControlWindow

CBaseControlWindow Class

Constructs a CBaseControlWindow object.

Syntax

CBaseControlWindow(
    CBaseMediaFilter *pFilter,
    CCritSec *pInterfaceLock,
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pFilter
Pointer to the owning media filter object.
pInterfaceLock
Pointer to the critical section to use for locking.
pName
Pointer to the object description.
pUnk
Pointer to the controlling IUnknown interface, if the object is part of an aggregate; otherwise, must be NULL.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the constructor method.

Return Value

No return value.

CBaseControlWindow::DoGetWindowStyle

CBaseControlWindow Class

Retrieves the current normal or extended window styles.

Syntax

HRESULT DoGetWindowStyle(
    long *pStyle,
    long WindowLong
);

Parameters

pStyle
Pointer to a variable that receives the style information.
WindowLong
Value specifying which styles to retrieve. Must be one of the following:
GWL_STYLE | Retrieve the window styles.
GWL_EXSTYLE | Retrieve the extended window styles.

Return Value

Returns an HRESULT value.

Remarks

This member function calls the Win32 GetWindowLong function to retrieve the window style. It is called by the CBaseControlWindow::get_WindowStyle and CBaseControlWindow::get_WindowStyleEx member functions.

CBaseControlWindow::DoSetWindowStyle

CBaseControlWindow Class

Changes the typical or extended window styles.

Syntax

HRESULT DoSetWindowStyle(
    long Style,
    long WindowLong
);

Parameters

Style
Appropriate window styles.
WindowLong
Value specifying which styles to set. Must be one of the following:
GWL_STYLE | Retrieve the window styles.
GWL_EXSTYLE | Retrieve the extended window styles.

Return Value

Returns an HRESULT value.

Remarks

This member function calls the Win32 SetWindowLong function to set the window style, and then redisplays the window in the current position. This member function is called by the CBaseControlWindow::put_WindowStyle and CBaseControlWindow::put_WindowStyleEx member functions.

CBaseControlWindow::get_AutoShow

CBaseControlWindow Class

Retrieves the current AutoShow state flag.

Syntax

HRESULT get_AutoShow(
    long *AutoShow
);

Parameters

AutoShow
Pointer to an Automation Boolean flag (0 is off, –1 is on).

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IVideoWindow::get_AutoShow method. This property simplifies window display access for applications. If this is set to –1 (on), the window, which is typically hidden after connection of the filter, will be displayed automatically when the filter pauses or runs. The window should not be hidden when the filter stops, however. If this parameter is set to 0 (off), the window is made visible only when the application calls CBaseControlWindow::put_Visible or CBaseControlWindow::put_WindowState with the appropriate parameters.

This member function is meant to be called by external objects through the IVideoWindow interface, and therefore locks the critical section to synchronize with the associated filter. Call the CBaseControlWindow::IsAutoShowEnabled member function to retrieve this property if you are not calling from an external object.

CBaseControlWindow::get_BackgroundPalette

CBaseControlWindow Class

Retrieves the realized palette in the background flag.

Syntax

HRESULT get_BackgroundPalette(
    long *pBackgroundPalette
);

Parameters

pBackgroundPalette
Pointer to an Automation Boolean flag (0 is off, –1 is on).

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IVideoWindow::get_BackgroundPalette method. If a video will be played within another application or document, the application might want to use its own palette. It can ask that the video use the current foreground palette rather than its own by setting this flag to –1. If this is set to 0, the window will install and realize its own preferred palette. Note that asking the window to use a different palette will cause severe performance penalties.

CBaseControlWindow::get_BorderColor

CBaseControlWindow Class

Retrieves the current border color.

Syntax

HRESULT get_BorderColor(
    long *Color
);

Parameters

Color
Pointer to the current border color.

Return Value

Returns an HRESULT value.

Remarks

An application can set a destination rectangle in which the video should be displayed. This rectangle is relative to the client area for the window. If this is done (the default is to always paint the entire window), there is a border surrounding the video. This property affects the color used by the border. Although the parameter is specified as a LONG type, it is actually a COLORREF value.

This member function is meant to be called by external objects through the IVideoWindow interface, and therefore locks the critical section to synchronize with the associated filter. Call the CBaseControlWindow::GetBorderColour member function to retrieve this property if not calling from an external object.

CBaseControlWindow::GetBorderColour

CBaseControlWindow Class

Retrieves the current window border color, m_BorderColour.

Syntax

COLORREF GetBorderColour(void);

Return Value

Returns the color of the border.

Remarks

An application can set a destination rectangle to display the video. This rectangle should be relative to the client area for the window. If this is done (the default is to always paint the entire window), there is an area that surrounds the video; that is, the border. The border color can be set through the CBaseControlWindow::put_BorderColor member function. This property affects the color of the border. Use this member function instead of CBaseControlWindow::get_BorderColor, unless you are calling this externally through the IVideoWindow::get_BorderColor method.

CBaseControlWindow::get_Caption

CBaseControlWindow Class

Retrieves the current window caption.

Syntax

HRESULT get_Caption(
    BSTR *pstrCaption
);

Parameters

pstrCaption
Pointer to the current window caption.

Return Value

Returns an HRESULT value.

Remarks

Most top-level windows on a Windows-based desktop have a title (caption) associated with them. This property can be queried and set through the IVideoWindow interface. Any caption set will be visible only if the window has the WS_CAPTION style applied. If it does not, the caption can still be set (and retrieved), although it will not be visible to the user.

CBaseControlWindow::get_FullScreenMode

CBaseControlWindow Class

Retrieves the current full-screen mode.

Syntax

HRESULT get_FullScreenMode(
    long *FullScreenMode
);

Parameters

FullScreenMode
Pointer to the current full-screen mode.

Return Value

Returns an HRESULT value.

Remarks

This member function returns E_NOTIMPL by default. This informs the IVideoWindow plug-in distributor that this renderer does not implement a full-screen renderer.

CBaseControlWindow::get_Height

CBaseControlWindow Class

Retrieves the current window height.

Syntax

HRESULT get_Height(
    long *pHeight
);

Parameters

pHeight
Pointer to the current window height, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in Microsoft® DirectShow®. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

CBaseControlWindow::get_Left

CBaseControlWindow Class

Retrieves the current left window coordinate.

Syntax

HRESULT get_Left(
    long *pLeft
);

Parameters

pLeft
Pointer to the left coordinate, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This position is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left and up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height have no effect on the left and top coordinates.

CBaseControlWindow::GetMaxIdealImageSize

CBaseControlWindow Class

Retrieves the maximum ideal image size.

Syntax

HRESULT GetMaxIdealImageSize(
    long *pWidth,
    long *pHeight
);

Parameters

pWidth
Pointer to the maximum ideal width, in pixels.
pHeight
Pointer to the maximum ideal height, in pixels.

Return Value

Returns an HRESULT value.

Remarks

Various renderers have performance restrictions on the size of images they can display. Although they should still function properly when requested to display images larger than the specified maximum, renderers can nominate the minimum and maximum ideal sizes through the IVideoWindow interface. This interface can be called only when the filter graph is paused or running, because it is not until then that resources are allocated and the renderer can recognize its restrictions. If no restrictions exist, the renderer fills in the pWidth and pHeight parameters with the native video dimensions and returns S_FALSE. If restrictions do exist, the restricted width and height are entered, and the member function returns S_OK.

The dimensions apply to the size of the destination video and not to the overall window size. So, when calculating the size of the window to set, account for the current window styles (for example, WS_CAPTION and WS_BORDER).

CBaseControlWindow::get_MessageDrain

CBaseControlWindow Class

Retrieves the current message drain.

Syntax

HRESULT get_MessageDrain(
    OAHWND *Drain
);

Parameters

Drain
Pointer to the current window receiving window messages.

Return Value

Returns an HRESULT value.

Remarks

Messages sent to the video renderer filter can be posted to another window. The window registered to receive these messages (using the CBaseControlWindow::get_MessageDrain member function) is the current message drain.

CBaseControlWindow::GetMinIdealImageSize

CBaseControlWindow Class

Retrieves the minimum ideal image size.

Syntax

HRESULT GetMinIdealImageSize(
    long *pWidth,
    long *pHeight
);

Parameters

pWidth
Pointer to the minimum ideal width, in pixels.
pHeight
Pointer to the minimum ideal height, in pixels.

Return Value

Returns an HRESULT value.

Remarks

Various renderers have performance restrictions on the size of images they can display. Although they should still function properly when requested to display images larger than the specified maximum, renderers can nominate the minimum and maximum ideal sizes through the IVideoWindow interface. This interface can be called only when the filter graph is paused or running, because it is not until then that resources are allocated and the renderer can recognize its restrictions. If no restrictions exist, the renderer fills in the pWidth and pHeight parameters with the native video dimensions and returns S_FALSE. If restrictions do exist, the restricted width and height are entered, and the member function returns S_OK.

The dimensions apply to the size of the destination video and not to the overall window size. So, when calculating the size of the window to set, account for the current window styles (for example, WS_CAPTION and WS_BORDER).

CBaseControlWindow::get_Owner

CBaseControlWindow Class

Retrieves the current window owner.

Syntax

HRESULT get_Owner(
    OAHWND *Owner
);

Parameters

Owner
Pointer to the window owner.

Return Value

Returns an HRESULT value.

Remarks

The video window can play back within a document environment. To do this, the window must be made a child of another window (so that it is clipped and moved appropriately). This property allows the owner of the window to be set and retrieved. When the window is owned by another window, it simply calls the Microsoft Win32 SetParent function. An application calling this function will change the window styles to set the WS_CHILD bit on.

When the window is owned by another window, it will automatically forward certain sets of messages (in particular, mouse and keyboard messages). This allows an application to do simple hot-spot editing and other interactions.

This member function is meant to be called by external objects through the IVideoWindow interface, and therefore locks the critical section to synchronize with the associated filter. Call the CBaseControlWindow::GetOwnerWindow member function to retrieve this property if not calling from an external object.

CBaseControlWindow::GetOwnerWindow

CBaseControlWindow Class

Retrieves the owning window handle, m_hwndOwner.

Syntax

HWND GetOwnerWindow(void);

Return Value

Returns an internal method to return the owner window.

Remarks

Retrieves the owning window without calling the interface method. Use this member function instead of CBaseControlWindow::get_Owner, unless you are calling this externally through the IVideoWindow::get_Owner method.

CBaseControlWindow::GetRestorePosition

CBaseControlWindow Class

Retrieves the position to which the window will be restored when it is not maximized or minimized.

Syntax

HRESULT GetRestorePosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft
Pointer to the value for leftmost coordinate.
pTop
Pointer to the value for top of the window.
pWidth
Pointer to the value for width of the window.
pHeight
Pointer to the value for height of window.

Return Value

Returns an HRESULT value.

Remarks

This is the same as the values returned by the CBaseControlWindow::GetWindowPosition function when the window is neither maximized nor minimized.

CBaseControlWindow::get_Top

CBaseControlWindow Class

Retrieves the top window coordinate.

Syntax

HRESULT get_Top(
    long *pTop
);

Parameters

pTop
Pointer to the top coordinate, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

CBaseControlWindow::get_Visible

CBaseControlWindow Class

Retrieves the current window visibility.

Syntax

HRESULT get_Visible(
    long *pVisible
);

Parameters

pVisible
Pointer to an Automation Boolean flag (0 is off, –1 is on).

Return Value

Returns an HRESULT value.

Remarks

This member function returns –1 if the window has the WS_VISIBLE style; 0 otherwise.

CBaseControlWindow::get_Width

CBaseControlWindow Class

Retrieves the current window width.

Syntax

HRESULT get_Width(
    long *pWidth
);

Parameters

pWidth
Pointer to the window width, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

CBaseControlWindow::GetWindowPosition

CBaseControlWindow Class

Retrieves the current coordinates for the window.

Syntax

HRESULT GetWindowPosition(
    long *pLeft,
    long *pTop,
    long *pWidth,
    long *pHeight
);

Parameters

pLeft
Pointer to the left coordinate, in screen coordinates.
pTop
Pointer to the top coordinate, in screen coordinates.
pWidth
Pointer to the window width, in screen coordinates.
pHeight
Pointer to the window height, in screen coordinates.

Return Value

Returns an HRESULT value.

CBaseControlWindow::get_WindowState

CBaseControlWindow Class

Retrieves the current window state.

Syntax

HRESULT get_WindowState(
    long *pWindowState
);

Parameters

pWindowState
Pointer to the window state.

Return Value

Returns an HRESULT value.

Remarks

This member function returns a subset of the parameters of the Microsoft Win32 ShowWindow function. In particular, it returns SW_SHOW and SW_HIDE, depending on the current visibility of the window. It also returns SW_MINIMIZE and SW_MAXIMIZE, depending on whether the window is an icon or is expanded.

CBaseControlWindow::get_WindowStyle

CBaseControlWindow Class

Retrieves the standard window styles.

Syntax

HRESULT get_WindowStyle(
    long *pWindowStyle
);

Parameters

pWindowStyle
Pointer to window styles.

Return Value

Returns an HRESULT value.

Remarks

This member function returns the standard window styles, such as WS_CHILD and WS_VISIBLE. It calls the CBaseControlWindow::DoGetWindowStyle member function.

CBaseControlWindow::get_WindowStyleEx

CBaseControlWindow Class

Retrieves the extended window styles.

Syntax

HRESULT get_WindowStyleEx(
    long *pWindowStyleEx
);

Parameters

pWindowStyleEx
Pointer to extended window styles.

Return Value

Returns an HRESULT value.

Remarks

This member function retrieves the extended window styles. It calls the CBaseControlWindow::DoGetWindowStyle member function.

CBaseControlWindow::HideCursor

CBaseControlWindow Class

Hides or displays the cursor.

Syntax

HRESULT HideCursor(
    long HideCursor
);

Parameters

HideCursor
Value specifying whether to show the cursor. Set to OATRUE to hide the cursor, or OAFALSE to display the cursor.

Return Value

Returns an HRESULT value.

CBaseControlWindow::IsCursorHidden

CBaseControlWindow Class

Retrieves the current state of the m_bCursorHidden data member.

Syntax

HRESULT IsCursorHidden(
    long *CursorHidden
);

BOOL IsCursorHidden(void);

Parameters

CursorHidden
Pointer to the value of m_bCursorHidden.

Return Value

When called without a parameter, returns OATRUE if the cursor is hidden, or OAFALSE if the cursor is visible.

When called with a parameter, returns an HRESULT value.

Remarks

Internal objects should call this member function without the CursorHidden parameter to avoid locking the critical section. External objects access this member function with the CursorHidden parameter through the IVideoWindow::IsCursorHidden method.

CBaseControlWindow::IsAutoShowEnabled

CBaseControlWindow Class

Retrieves information about whether the video window automatically appears when the rendering filter pauses or runs.

Syntax

BOOL IsAutoShowEnabled(void);

Return Value

Returns TRUE if the m_bAutoShow member is set to –1 or FALSE if it is set to 0.

Remarks

If the m_bAutoShow member is set to –1 on a video window that is hidden, the window becomes visible when the filter pauses or runs. If this member is set to 0, the window will appear only if you use the CBaseControlWindow::put_Visible or CBaseControlWindow::put_WindowState member function with the appropriate parameters.

This member function retrieves the m_bAutoShow member setting and has the same result as using the IVideoWindow::get_AutoShow method.

CBaseControlWindow::NotifyOwnerMessage

CBaseControlWindow Class

Passes along specific messages to the video window.

Syntax

HRESULT NotifyOwnerMessage(
    long hwnd,
    long uMsg,
    long wParam,
    long lParam
);

Parameters

hwnd
Handle to the video window.
uMsg
Message details.
wParam
First message parameter.
lParam
Second message parameter.

Return Value

Returns NO_ERROR.

Remarks

When the video window is a child of another window, it does not receive certain top-level window messages. These messages can be valuable to a renderer, because they could affect its behavior. NotifyOwnerMessage passes any of the following messages to the video window.

  • WM_ACTIVATEAPP
  • WM_DEVMODECHANGE
  • WM_DISPLAYCHANGE
  • WM_PALETTECHANGED
  • WM_PALETTEISCHANGING
  • WM_QUERYNEWPALETTE
  • WM_SYSCOLORCHANGE

You can request that the IVideoWindow plug-in distributor (PID) make a window become a child of another window. When this occurs, the PID will look for certain messages that might be sent to the owning window. The PID will then forward those messages to the owned window. The default processing for the messages is to send them to the owned window procedure synchronously by calling the Win32 SendMessage function.

CBaseControlWindow::PossiblyEatMessage

CBaseControlWindow Class

Forwards keyboard and mouse messages to a specified window.

Syntax

BOOL WINAPI PossiblyEatMessage(
    HWND hwndDrain,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam
    )

Parameters

hwndDrain
Handle of the window to which messages will be forwarded.
uMsg
Message that was forwarded.
wParam
First message parameter.
lParam
Second message parameter.

Return Value

Returns TRUE if the message was posted or FALSE if it wasn't.

Remarks

When the window is owned, it will pass certain classes of messages to the owning window (such as keyboard and mouse events). In this case, the Win32 PostMessage function is used to post messages to any window specified by hwndDrain which is set in CBaseControlWindow::put_MessageDrain. If a certain message cannot be posted, this message will return FALSE.

The following is a list of messages that will get passed on untranslated and return TRUE.
WM_CHAR | WM_DEADCHAR
WM_KEYDOWN | WM_KEYUP
WM_LBUTTONDBLCLK | WM_LBUTTONDOWN
WM_LBUTTONUP | WM_MBUTTONDBLCLK
WM_MBUTTONDOWN | WM_MBUTTONUP
WM_MOUSEACTIVATE | WM_MOUSEMOVE
WM_NCHITTEST | WM_NCLBUTTONDBLCLK
WM_NCLBUTTONDOWN | WM_NCLBUTTONUP
WM_NCMBUTTONDBLCLK | WM_NCMBUTTONDOWN
WM_NCMBUTTONUP | WM_NCMOUSEMOVE
WM_NCRBUTTONDBLCLK | WM_NCRBUTTONDOWN
WM_NCRBUTTONUP | WM_RBUTTONDBLCLK
WM_RBUTTONDOWN | WM_RBUTTONUP
WM_SYSCHAR | WM_SYSDEADCHAR
WM_SYSKEYDOWN | WM_SYSKEYUP

CBaseControlWindow::put_AutoShow

CBaseControlWindow Class

Sets the AutoShow state flag.

Syntax

HRESULT put_AutoShow(
    long AutoShow
);

Parameters

AutoShow
Automation Boolean flag (0 is off, –1 is on).

Return Value

Returns an HRESULT value.

Remarks

This property simplifies window display access for applications. If this is set to –1 (on), the window, which is typically hidden after the filter is connected, will be displayed automatically when the filter pauses or runs. The window should not be hidden when the filter stops, however. If this is set to 0 (off), the window is made visible only when the application calls CBaseControlWindow::put_Visible or CBaseControlWindow::put_WindowState with the appropriate parameters.

CBaseControlWindow::put_BackgroundPalette

CBaseControlWindow Class

Sets a flag to realize the palette in the background.

Syntax

HRESULT put_BackgroundPalette(
    long BackgroundPalette
);

Parameters

BackgroundPalette
Automation Boolean flag (0 is off, –1 is on).

Return Value

Returns an HRESULT value.

Remarks

To play a video within another application or document, the application might want to use its own palette. It can ask that the video use the current foreground palette rather than its own as the background palette by setting this flag to –1. If this is set to 0, the window will install and realize its own preferred palette. Asking the window to use a different palette will cause severe performance penalties.

CBaseControlWindow::put_BorderColor

CBaseControlWindow Class

Changes the border color.

Syntax

HRESULT put_BorderColor(
    long Color
);

Parameters

Color
New border color.

Return Value

Returns an HRESULT value.

Remarks

An application can establish a destination rectangle in which the video should be displayed. This rectangle is relative to the client area for the window. If this is done (the default is to always paint the entire window), there is a border surrounding the video. This property affects the color used by the border. Although the parameter is specified as a LONG type, it is actually a COLORREF value.

CBaseControlWindow::put_Caption

CBaseControlWindow Class

Sets the window title or caption.

Syntax

HRESULT put_Caption(
    BSTR strCaption
);

Parameters

strCaption
New window caption.

Return Value

Returns an HRESULT value.

Remarks

Most top-level windows on a Windows-based desktop have a title (caption) associated with them. This property can be queried and set through the IVideoWindow interface. Any caption set will be visible only if the window has the WS_CAPTION style applied. If it does not, the caption can still be set (and retrieved), although it will not be visible to the user.

CBaseControlWindow::put_FullScreenMode

CBaseControlWindow Class

Sets the full-screen mode of the renderer.

Syntax

HRESULT put_FullScreenMode(
    long FullScreenMode
);

Parameters

FullScreenMode
Full-screen mode to apply.

Return Value

Returns an HRESULT value. The current implementation returns E_NOTIMPL.

Remarks

A video renderer that implements a full-screen mode should override this member function and implement whatever modes it supports.

CBaseControlWindow::put_Height

CBaseControlWindow Class

Sets the window height.

Syntax

HRESULT put_Height(
    long Height
);

Parameters

Height
New window height, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

CBaseControlWindow::put_Left

CBaseControlWindow Class

Sets the left coordinate for the window.

Syntax

HRESULT put_Left(
    long Left
);

Parameters

Left
New left coordinate, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

CBaseControlWindow::put_MessageDrain

CBaseControlWindow Class

Sets the window to receive window messages sent to the video renderer.

Syntax

HRESULT put_MessageDrain(
    OAHWND Drain
);

Parameters

Drain
Window to post messages to.

Return Value

Returns an HRESULT value.

Remarks

Messages sent to the video renderer filter can be posted to another window. This member function registers the window to receive these messages. Unlike the CBaseControlWindow::put_Owner member function, this member function does not make the video window a child of another window. It is particularly useful for full-screen video renderers, which cannot be child windows.

CBaseControlWindow::put_Owner

CBaseControlWindow Class

Sets the video window's parent window; the parent window then forwards certain messages to the video window.

Syntax

HRESULT put_Owner(
    OAHWND Owner
);

Parameters

Owner
Handle to the parent window.

Return Value

Returns NOERROR.

Remarks

Internally, this method calls the Microsoft Win32 SetParent function to set the new owner and sets the parent window's style to WS_CHILD. The parent window will then forward certain sets of messages (in particular, mouse and keyboard messages) to the video window.

After you set the video window's owner, you must set the owner to NULL and the owner's window style to WS_OVERLAPPED and WS_CLIPCHILDREN before releasing the filter graph. When you set the owner to NULL, this method turns off the parent window's WS_CHILD bit. If you don't set the owner to NULL, the parent window will continue to pass messages to the video window and errors will likely occur when the application closes.

CBaseControlWindow::put_Top

CBaseControlWindow Class

Sets the top window coordinate.

Syntax

HRESULT put_Top(
    long Top
);

Parameters

Top
New top coordinate, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels, and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up, respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

CBaseControlWindow::put_Visible

CBaseControlWindow Class

Makes the window either visible or hidden.

Syntax

HRESULT put_Visible(
    long Visible
);

Parameters

Visible
Automation Boolean flag (0 means window is hidden, –1 means window is shown).

Return Value

Returns an HRESULT value.

CBaseControlWindow::put_Width

CBaseControlWindow Class

Sets the window width.

Syntax

HRESULT put_Width(
    long Width
);

Parameters

Width
New window width, in pixels.

Return Value

Returns an HRESULT value.

Remarks

The window has a position on the desktop. This is expressed in pixels by four coordinates (left, top, right, and bottom). Interfaces that are automated by OLE typically express this position through left, top, width, and height; this is the convention used in DirectShow. All coordinates are expressed in pixels and changing any coordinate will update the window immediately.

Setting the left or top coordinates moves the window left or up respectively; these coordinates have no effect on the width and height of the window. Likewise, setting the width and height does not affect the left and top coordinates.

CBaseControlWindow::put_WindowState

CBaseControlWindow Class

Sets the window state.

Syntax

HRESULT put_WindowState(
    long WindowState
);

Parameters

WindowState
New window state.

Return Value

Returns an HRESULT value.

Remarks

This member function takes the same parameters as the Microsoft Win32 ShowWindow function (for example, WS_SHOWNORMAL, WS_SHOWMINNOACTIVATE, and WS_SHOWMAXIMIZED).

CBaseControlWindow::put_WindowStyle

CBaseControlWindow Class

Sets the standard Windows-based styles.

Syntax

HRESULT put_WindowStyle(
    long WindowStyle
);

Parameters

WindowStyle
New window styles.

Return Value

Returns an HRESULT value.

Remarks

Take care when changing the window styles. In most cases, an application should retrieve the current style and then add or remove the inappropriate bits. This procedure allows various internal window styles used by Windows® to remain intact.

CBaseControlWindow::put_WindowStyleEx

CBaseControlWindow Class

Sets the style of the control window.

Syntax

HRESULT put_WindowStyleEx(
    long WindowStyleEx
);

Parameters

WindowStyleEx
[in] Value that specifies the style of the control window.

Return Value

Returns NOERROR.

Remarks

This method uses EX (extended) window styles. For a complete list of extended window styles, see the Microsoft Win32 CreateWindowEx function. To change the window style, retrieve the current window style, and then add or remove the necessary bit fields.

Do not use the following window styles because they are not validated.

  • WS_DISABLED
  • WS_HSCROLL
  • WS_ICONIC
  • WS_MAXIMIZE
  • WS_MINIMIZE
  • WS_VSCROLL

With some exceptions (noted here), the acceptable flags are the same as those allowed by the Win32 CreateWindow function.

CBaseControlWindow::SetControlWindowPin

CBaseControlWindow Class

Sets the pin with which to synchronize.

Syntax

void SetControlWindowPin(
    CBasePin *pPin
);

Parameters

pPin
Pointer to the pin with which the interface is synchronized.

Return Value

No return value.

Remarks

This member function sets the m_pPin variable equal to the pPin parameter. As described in the constructor, the interface can be called only when the filter has been connected successfully. The object is passed in through this member function to the pin with which it should synchronize; in most cases, it will determine if the pin is connected whenever it has an interface method called and will return VFW_E_NOT_CONNECTED if it fails.

CBaseControlWindow::SetWindowForeground

CBaseControlWindow Class

Moves the video window to the foreground and optionally gives it focus.

Syntax

HRESULT SetWindowForeground(
    long Focus
);

Parameters

Focus
Value that specifies whether the video window will get focus. A value of –1 gives the window focus and 0 does not.

Return Value

Returns one of the following values.
NOERROR | The method succeeded.
E_INVALIDARG | Focus doesn't equal –1 or 0.
VFW_E_NOT_CONNECTED | The current filter isn't connected to a complete filter graph.

CBaseControlWindow::SetWindowPosition

CBaseControlWindow Class

Sets the window position on the desktop.

Syntax

HRESULT SetWindowPosition(
    long Left,
    long Top,
    long Width,
    long Height
);

Parameters

Left
New left coordinate.
Top
New top coordinate.
Width
Width of the window.
Height
Height of the window.

Return Value

Returns an HRESULT value.


CBaseDispatch Class

CBaseDispatch class hierarchy

Base class for implementing the IDispatch interface.

Declaration: Ctlutil.h

This class is limited to supporting the Automation-compatible interfaces exported by the DirectShow type library, QuartzTypeLib. For example, the CMediaControl and CMediaPosition classes use CBaseDispatch to implement IMediaControl and IMediaPosition, respectively. Because of this limitation, there is probably no reason to use CBaseDispatch directly in your own filters.

To use this class, do the following:

  • Declare a new class that supports IDispatch.
  • Give your new class a private member variable of type CBaseDispatch.
  • Implement the IDispatch methods. In your IDispatch methods, call the CBaseDispatch methods.

For more details, refer to the source code for any of the sample classes declared in Ctlutil.h.

For more information about the IDispatch methods, see the COM documentation included with the Microsoft® Platform SDK.
Public Methods
CBaseDispatch | Constructor method.
~CBaseDispatch | Destructor method.
GetIDsOfNames | Maps a set of names to a corresponding set of DISPIDs.
GetTypeInfo | Retrieves the type information for the object, which can then be used to get the type information for an interface.
GetTypeInfoCount | Retrieves the number of type information interfaces the object provides.

CBaseDispatch::CBaseDispatch

CBaseDispatch Class

Constructor method.

Syntax

CBaseDispatch(void);

CBaseDispatch::~CBaseDispatch

CBaseDispatch Class

Destructor method.

Syntax

~CBaseDispatch(void);

CBaseDispatch::GetIDsOfNames

CBaseDispatch Class

Maps a set of names to a corresponding set of DISPIDs.

Syntax

HRESULT GetIDsOfNames(
    REFIID riid,
    OLECHAR **rgszNames,
    UINT cNames,
    LCID lcid,
    DISPID *rgdispid
);

Parameters

riid
Reference to an interface identifier (IID) that specifies the interface.
rgszNames
Address of an array of wide-character strings that contain the names to be mapped.
cNames
Size of the array given by the rgszNames parameter.
lcid
Locale context in which to interpret the names. Can be NULL.
rgdispid
Pointer to an array that receives the DISPIDs. Each element of receives an identifier that corresponds to one of the names passed in the rgszNames parameter.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
DISP_E_UNKNOWNNAME | One or more of the names were not known.

Remarks

This method behaves like the IDispatch::GetIDsOfNames method, but the riid parameter specifies the interface on which to retrieve DISPIDs. (In the IDispatch version, the riid parameter is reserved.)

If the method returns DISP_E_UNKNOWNNAME, the returned DISPIDs contain DISPID_UNKNOWN for each entry that corresponds to an unknown name.

CBaseDispatch::GetTypeInfo

CBaseDispatch Class

Retrieves the type information for the object, which can then be used to get the type information for an interface.

Syntax

HRESULT GetTypeInfo(
    REFIID riid,
    UINT itinfo,
    LCID lcid,
    ITypeInfo **pptinfo
);

Parameters

riid
Reference to an interface identifier (IID) that specifies the interface.
itinfo
Type information to return. Must be zero.
lcid
Locale identifier.
pptinfo
Address of a variable that receives an ITypeInfo pointer.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_POINTER | Null pointer argument.
TYPE_E_ELEMENTNOTFOUND | The itinfo parameter is not zero.

Remarks

This method behaves like the IDispatch::GetTypeInfo method. However, it includes an additional parameter, riid, which specifies the interface for which to retrieve type information.

CBaseDispatch::GetTypeInfoCount

CBaseDispatch Class

Retrieves the number of type information interfaces the object provides.

Syntax

HRESULT GetTypeInfoCount(
    UINT *pctinfo
);

Parameters

pctinfo
Pointer to a variable that receives the number of type-information interfaces provided by the object. When the method returns, the value is 1.

Return Value

Returns one of the following values.

S_OK | Success.
E_POINTER | Null pointer argument.


CBaseFilter Class

CBaseFilter class hierarchy

Abstract class for implementing filters.

Declaration: Amfilter.h

To implement a filter using CBaseFilter, you must perform at least the following steps:

  • Derive a new class from CBaseFilter.
  • Include member variables that define the pins on the filter. The pins must inherit from the CBasePin class.
  • Override the pure virtual method GetPin, which retrieves pins on the filter.
  • Override the pure virtual method GetPinCount, which retrieves the number of pins.
  • Provide methods for generating, processing, or rendering media samples.

Several base classes derive from CBaseFilter, including CSource, CBaseRenderer, and CTransformFilter. It is usually easier to implement a filter with one of these specialized classes, rather than use CBaseFilter directly.

Protected Member Variables
m_State | Current state of the filter.
m_pClock | Pointer to the filter's reference clock.
m_tStart | Reference time that corresponds to stream time 0.
m_clsid | Class identifier (CLSID) of the filter.
m_pLock | Pointer to a critical section.
m_pName | Filter name.
m_pGraph | Pointer to the filter graph manager.
m_pSink | Pointer to the IMediaEventSink interface on the filter graph manager.
m_PinVersion | Current version of the set of pins on this filter.
Public Methods
CBaseFilter | Constructor method.
~CBaseFilter | Destructor method.
StreamTime | Retrieves the current stream time. Virtual.
IsActive | Determines whether the filter is currently active (running or paused).
IsStopped | Determines whether the filter is currently stopped.
NotifyEvent | Sends an event notification to the filter graph manager.
GetFilterGraph | Retrieves a pointer to the filter graph manager.
ReconnectPin | Breaks an existing pin connection and reconnects it to the same pin, using a specified media type.
GetPinVersion | Retrieves a version number for the set of pins on this filter. Virtual.
IncrementPinVersion | Increments the version number on the set of pins.
GetSetupData | Retrieves the registration data for the filter. Virtual.
Pure Virtual Methods
GetPinCount | Retrieves the number of pins.
GetPin | Retrieves a pin.
IPersist Methods
GetClassID | Retrieves the class identifier.
IMediaFilter Methods
GetState | Retrieves the filter's state (running, stopped, or paused).
SetSyncSource | Sets a reference clock for the filter.
GetSyncSource | Retrieves the reference clock that the filter is using.
Stop | Stops the filter.
Pause | Pauses the filter.
Run | Runs the filter.
IBaseFilter Methods
EnumPins | Enumerates the pins on this filter.
FindPin | Retrieves the pin with the specified identifier.
QueryFilterInfo | Retrieves information about the filter.
JoinFilterGraph | Notifies the filter that it has joined or left a filter graph.
QueryVendorInfo | Retrieves a string containing vendor information.
IAMovieSetup Merthods
Register | Adds the filter to the registry.
Unregister | Removes the filter from the registry.

CBaseFilter.m_State

CBaseFilter Class

Current state of the filter.

Syntax

FILTER_STATE m_State;

CBaseFilter.m_pClock

CBaseFilter Class

Pointer to the filter's reference clock.

Syntax

IReferenceClock *m_pClock;

CBaseFilter.m_tStart

CBaseFilter Class

Reference time that corresponds to stream time 0.

Syntax

CRefTime m_tStart;

CBaseFilter.m_clsid

CBaseFilter Class

Class identifier (CLSID) of the filter.

Syntax

CLSID m_clsid;

CBaseFilter.m_pLock

CBaseFilter Class

Pointer to a critical section.

Syntax

CCritSec *m_pLock;

Remarks

Hold this critical section during state transitions, or when a method accesses the state over several operations. The base class holds the critical section in the following methods:

  • FindPin
  • GetSyncSource
  • JoinFilterGraph
  • IsActive
  • SetSyncSource
  • Pause
  • Run
  • Stop

Do not hold this critical section during streaming operations (that is, when delivering samples to a downstream filter). Serialize streaming operations using a different critical section. Otherwise, it can cause deadlock.

CBaseFilter.m_pName

CBaseFilter Class

Filter name.

Syntax

WCHAR *m_pName;

CBaseFilter.m_pGraph

CBaseFilter Class

Pointer to the filter graph manager.

Syntax

IFilterGraph *m_pGraph;

CBaseFilter.m_pSink

CBaseFilter Class

Pointer to the IMediaEventSink interface on the filter graph manager.

Syntax

IMediaEventSink *m_pSink;

CBaseFilter.m_PinVersion

CBaseFilter Class

Current version of the set of pins on this filter. For more information, see GetPinVersion.

Syntax

LONG m_PinVersion;

CBaseFilter::CBaseFilter

CBaseFilter Class

Constructor method.

Syntax

CBaseFilter(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    CCritSec *pLock,
    REFCLSID clsid
);

Parameters

pName
Pointer to a string containing the name of the filter, for debugging purposes.
pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
pLock
Pointer to a CCritSec lock, used to serialize state changes.
clsid
Class identifier of the object.

Remarks

For the critical section object, you would typically do one of the following:

  • Derive a class that inherits both CBaseFilter and CCritSec. For pLock, pass the this pointer.
  • Derive a class that inherits CBaseFilter and contains a CCritSec member variable. For pLock, pass the address of that variable.

CBaseFilter::~CBaseFilter

CBaseFilter Class

Destructor method.

Syntax

CBaseFilter(void);

Remarks

Always stop the filter before destroying it.

CBaseFilter::EnumPins

CBaseFilter Class

Enumerates the pins on this filter. Implements the IBaseFilter::EnumPins method.

Syntax

HRESULT EnumPins(
    IEnumPins **ppEnum
);

Parameters

ppEnum
Address of a variable that receives a pointer to the IEnumPins interface.

Return Value

Returns one of the following HRESULT values.

S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

This method creates an instance of the CEnumPins base class, and returns a pointer to that object, of type IEnumPins. If the method succeeds, the IEnumPins interface has an outstanding reference count. Be sure to release it when you are done.

CBaseFilter::FindPin

CBaseFilter Class

Retrieves the pin with the specified identifier. Implements the IBaseFilter::FindPin method.

Syntax

HRESULT FindPin(
    LPCWSTR Id,
    IPin **ppPin
);

Parameters

Id
Pointer to a constant, null-terminated Unicode™ string that identifies the pin.
ppPin
Address of a variable that receives a pointer to the pin's IPin interface.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NOT_FOUND | Could not find a matching pin.

Remarks

This method calls the CBasePin::Name method to compare each pin's name against the string specified by the Id parameter.

If the method succeeds, the IPin interface has an outstanding reference count. Be sure to release it when you are done.

CBaseFilter::GetClassID

CBaseFilter Class

Retrieves the class identifier. Implements the IPersist::GetClassID method.

Syntax

HRESULT GetClassID(
    CLSID *pClsID
    );

Parameters

pClsID
Pointer to a variable that receives the class identifier.

Return Value

Returns S_OK or E_POINTER.

CBaseFilter::GetFilterGraph

CBaseFilter Class

Retrieves a pointer to the filter graph manager.

Syntax

IFilterGraph *GetFilterGraph(void);

Return Value

Returns the value of m_pGraph.

CBaseFilter::GetPin

CBaseFilter Class

Retrieves a pin.

Syntax

virtual CBasePin *GetPin(
    int n
) PURE;

Parameters

n
Number of the specified pin.

Return Value

Returns a pointer to the CBasePin object that implements the pin.

Remarks

The derived class must implement this pure virtual method. Return a pointer to the nth pin on this filter, indexed from zero.

CBaseFilter::GetPinCount

CBaseFilter Class

Retrieves the number of pins.

Syntax

virtual int GetPinCount(void) PURE;

Return Value

Returns the number of pins.

Remarks

The derived class must implement this pure virtual method. Return the number of pins that are currently available on this filter. Filters can dynamically create or destroy pins.

CBaseFilter::GetPinVersion

CBaseFilter Class

Retrieves a version number for the set of pins on this filter.

Syntax

virtual long GetPinVersion(void);

Return Value

Returns the m_PinVersion member variable.

Remarks

The CBaseFilter constructor initializes the pin version to 1. In the base class, this number never changes. If the filter dynamically creates or destroys pins, it should increment the pin version whenever the pins change. To increment the version number, call the IncrementPinVersion method.

The pin enumerator object, which is implemented by the CEnumPins class, uses the pin version to keep itself synchronized with the filter.

CBaseFilter::GetSetupData

CBaseFilter Class

Retrieves the registration data for the filter.

Note This method is obsolete. It is called by the Register and Unregister methods.

Syntax

virtual LPAMOVIESETUP_FILTER GetSetupData(void);

Return Value

Returns a pointer to an AMOVIESETUP_FILTER structure containing registration information for the filter.

Remarks

The base class returns NULL.

CBaseFilter::GetState

CBaseFilter Class

Retrieves the filters's state (running, stopped, or paused). Implements the IMediaFilter::GetState method.

Syntax

HRESULT GetState(
    DWORD dwMilliSecsTimeout,
    FILTER_STATE *State
);

Parameters

dwMilliSecsTimeout
Time-out interval, in milliseconds.
State
Pointer to a variable that receives a member of the FILTER_STATE enumerated type, indicating the filter's state.

Return Value

Returns S_OK or E_POINTER.

Remarks

In the base class, all state transitions are synchronous and the dwMilliSecsTimeout parameter is ignored. If a derived class performs asynchronous state transitions, it should override this method to wait during state transitions, with a time-out of dwMilliSecsTimeout milliseconds.

CBaseFilter::GetSyncSource

CBaseFilter Class

Retrieves the reference clock that the filter is using. Implements the IMediaFilter::GetSyncSource method.

Syntax

HRESULT GetSyncSource(
    IReferenceClock **pClock
    );

Parameters

pClock
Address of a variable that receives a pointer to the clock's IReferenceClock interface.

Return Value

Returns S_OK or E_POINTER.

Remarks

If the filter is not using a reference clock, *pClock is set to NULL. When the method returns, if *pClock is non-NULL, the IReferenceClock interface has an outstanding reference count. Be sure to release it when you are done.

CBaseFilter::IncrementPinVersion

CBaseFilter Class

Increments the version number on the set of pins.

Syntax

void IncrementPinVersion(void);

Remarks

This method increments the m_PinVersion member variable. If the filter dynamically creates or destroys pins, call this method whenever the pins change. For more information, see GetPinVersion.

CBaseFilter::IsActive

CBaseFilter Class

Determines whether the filter is currently active (running or paused).

Syntax

BOOL IsActive(void);

Return Value

Returns TRUE if the filter is paused or running, or FALSE if it is stopped.

CBaseFilter::IsStopped

CBaseFilter Class

Determines whether the filter is currently stopped.

Syntax

BOOL IsStopped(void);

Return Value

Returns TRUE if the filter is stopped, or FALSE otherwise.

CBaseFilter::JoinFilterGraph

CBaseFilter Class

Notifies the filter that it has joined or left a filter graph. Implements the IBaseFilter::JoinFilterGraph method.

Syntax

HRESULT JoinFilterGraph(
    IFilterGraph *pGraph,
    LPCWSTR pName
);

Parameters

pGraph
Pointer to the filter graph manager's IFilterGraph interface, or NULL if the filter is leaving the graph.
pName
[in, string] Pointer to a Unicode string containing a name for the filter.

Return Value

Returns S_OK.

Remarks

This method sets the m_pGraph member variable equal to the pGraph parameter. It also queries for an IMediaEventSink interface pointer and stores it in the m_pSink member variable. However, the filter does not keep a reference count on either of these interfaces. Doing so would create a circular reference count, because the filter graph manager keeps a reference count on the filter.

The method copies the string specified by pName into the m_pName member variable.

CBaseFilter::NotifyEvent

CBaseFilter Class

Sends an event notification to the filter graph manager.

Syntax

HRESULT NotifyEvent(
    long EventCode,
    LONG_PTR EventParam1,
    LONG_PTR EventParam2
);

Parameters

EventCode
Event notification code.
EventParam1
First parameter of the event.
EventParam2
Second parameter of the event.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_FALSE | The filter graph manager is not accepting event notifications.
S_OK | Success.
E_NOTIMPL | Filter does not have a pointer to the IMediaEventSink interface.

Remarks

For a list of notification codes and parameter values, see Event Notification Codes.

In the base class, if the event code is EC_COMPLETE, the method sets the EventParam2 parameter to a pointer to the filter's IBaseFilter interface.

CBaseFilter::Pause

CBaseFilter Class

Pauses the filter. Implements the IMediaFilter::Pause method.

Syntax

HRESULT Pause(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method calls the CBasePin::Active method on each of the filter's connected pins.

CBaseFilter::QueryFilterInfo

CBaseFilter Class

Retrieves information about the filter. Implements the IBaseFilter::QueryFilterInfo method.

Syntax

HRESULT QueryFilterInfo(
    FILTER_INFO *pInfo
);

Parameters

pInfo
Pointer to a FILTER_INFO structure.

Return Value

Returns S_OK or E_POINTER.

Remarks

This method copies the filter's name from the m_pName member variable into the achName member of the FILTER_INFO structure. If m_pName is NULL, the method sets achName to L'\0'.

The method sets the pGraph member of the FILTER_INFO structure equal to the m_pGraph member variable, and increments the reference count. The caller must release the interface.

CBaseFilter::QueryVendorInfo

CBaseFilter Class

Retrieves a string containing vendor information.

Syntax

HRESULT QueryVendorInfo(
    LPWSTR *pVendorInfo
    );

Parameters

pVendorInfo
Address of a variable that receives a pointer to a wide-character string containing the vendor information.

Return Value

Returns E_NOTIMPL.

Remarks

To provide vendor information for a filter, override this method. If you implement this method, use the CoTaskMemAlloc function to allocate memory for the string. The caller is responsible for calling the CoTaskMemFree function.

CBaseFilter::ReconnectPin

CBaseFilter Class

Breaks an existing pin connection and reconnects it to the same pin, using a specified media type.

Syntax

HRESULT ReconnectPin(
    IPin *pPin,
    AM_MEDIA_TYPE const *pmt
);

Parameters

pPin
Pointer to the pin's IPin interface.
pmt
Pointer to an AM_MEDIA_TYPE structure that specifies the media type, or NULL.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
E_NOINTERFACE | m_pGraph member variable is NULL.

Remarks

This method calls the IFilterGraph2::ReconnectEx method on the filter graph manager. If the IFilterGraph2 interface is not available, the method calls IFilterGraph::Reconnect.

CBaseFilter::Register

CBaseFilter Class

Adds the filter to the registry. Implements the IAMovieSetup::Register method.

Note The IAMovieSetup interface is obsolete. New filters should be registered using the AMovieDllRegisterServer2 function, which does not require IAMovieSetup. For more information, see How to Register DirectShow Filters.

Syntax

HRESULT Register(void);

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success.
S_FALSE | No registration information is available.

Remarks

This method calls the AMovieSetupRegisterFilter function to register the filter.

CBaseFilter::Run

CBaseFilter Class

Runs the filter. Implements the IMediaFilter::Run method.

Syntax

HRESULT Run(
    REFERENCE_TIME tStart
);

Parameters

tStart
Reference time corresponding to stream time 0.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

If the filter is stopped, this method pauses the filter by calling the CBaseFilter::Pause method. It then calls the CBasePin::Run method on each of the filter's connected pins. Finally, it sets the m_State member variable to State_Running.

Stream time is calculated as the current reference time minus tStart. A media sample with a time stamp of zero should be rendered at time tStart.

CBaseFilter::SetSyncSource

CBaseFilter Class

Sets a reference clock for the filter. Implements the IMediaFilter::SetSyncSource method.

Syntax

HRESULT SetSyncSource(
    IReferenceClock *pClock
    );

Parameters

pClock
Pointer to the clock's IReferenceClock interface, or NULL.

Return Value

Returns S_OK.

CBaseFilter::Stop

CBaseFilter Class

Stops the filter. Implements the IMediaFilter::Stop method.

Syntax

HRESULT Stop(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method calls the CBasePin::Inactive method on each of the filter's connected pins.

CBaseFilter::StreamTime

CBaseFilter Class

Retrieves the current stream time.

Syntax

virtual HRESULT StreamTime(
    CRefTime& rtStream
);

Parameters

rtStream
Reference to a CRefTime object that receives the current stream time.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_NO_CLOCK | No reference clock is available.

Remarks

Stream time is defined as the current reference time (as given by the reference clock) minus the start time (specified by m_tStart). A media sample's time stamp specifies the stream time when it should be rendered. If a sample with a time stamp less than the current stream time has not yet been rendered, it is late.

CBaseFilter::Unregister

CBaseFilter Class

Removes the filter from the registry. Implements the IAMovieSetup::Unregister method.

Note The IAMovieSetup interface is obsolete. New filters should be unregistered using the AMovieDllRegisterServer2 function, which does not require IAMovieSetup. For more information, see How to Register DirectShow Filters.

Syntax

HRESULT Unregister(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method calls the AMovieSetupRegisterFilter function to unregister the filter.


CBaseInputPin Class

CBaseInputPin class hierarchy

Abstract base class that implements an input pin.

Declaration: Amfilter.h

This class adds support for the IMemInputPin interface, in addition to the IPin interface support provided by CBasePin.

To use this class, derive a new class and override at least the following methods:

  • BeginFlush
  • EndFlush
  • Receive
Protected Member Variables
m_pAllocator | Pointer to the memory allocator.
m_bReadOnly | Flag that indicates whether the allocator produces read-only media samples.
m_bFlushing | Flag that indicates whether the pin is currently flushing.
m_SampleProps | Properties of the most recent sample.
Public Methods
CBaseInputPin | Constructor method.
~CBaseInputPin | Destructor method.
BreakConnect | Releases the pin from a connection.
IsReadOnly | Queries whether the allocator uses read-only media samples.
IsFlushing | Queries whether the filter is currently flushing.
CheckStreaming | Determines whether the pin can accept samples. Virtual.
PassNotify | Passes a quality-control message to the appropriate object.
Inactive | Notifies the pin that the filter is no longer active. Virtual.
SampleProps | Retrieves the properties of the most recent sample.
IPin Methods
BeginFlush | Begins a flush operation.
EndFlush | Ends a flush operation.
IMemInputPin Methods
GetAllocator | Retrieves the memory allocator proposed by this pin.
NotifyAllocator | Specifies an allocator for the connection.
GetAllocatorRequirements | Retrieves the allocator properties requested by the input pin.
Receive | Receives the next media sample in the stream.
ReceiveMultiple | Receives multiple samples in the stream.
ReceiveCanBlock | Determines whether calls to the Receive method might block.
IQualityControl Methods
Notify | Receives a quality-control message.

CBaseInputPin.m_pAllocator

CBaseInputPin Class

Pointer to the memory allocator.

Syntax

IMemAllocator *m_pAllocator;

CBaseInputPin.m_bReadOnly

CBaseInputPin Class

Flag that indicates whether the allocator produces read-only media samples. If TRUE, the allocator produces read-only samples.

Syntax

BYTE m_bReadOnly;

CBaseInputPin.m_bFlushing

CBaseInputPin Class

Flag that indicates whether the pin is currently flushing. If TRUE, the pin is flushing.

Syntax

BYTE m_bFlushing;

CBaseInputPin.m_SampleProps

CBaseInputPin Class

Properties of the most recent sample.

Syntax

AM_SAMPLE2_PROPERTIES m_SampleProps;

CBaseInputPin::BeginFlush

CBaseInputPin Class

Begins a flush operation. Implements the IPin::BeginFlush method.

Syntax

HRESULT BeginFlush(void);

Return Value

Returns S_OK.

Remarks

This method sets the m_bFlushing flag to TRUE, which causes the Receive method to reject any more samples.

The derived class must override this method and perform the following steps:

  1. Call the IPin::BeginFlush method on downstream input pins. If the pin has not yet delivered any media samples downstream, you can skip this step. If your output pins derive from the CBaseOutputPin class, you can call the CBaseOutputPin::DeliverBeginFlush method.
  2. Call the base class method.
  3. Begin discarding queued data.
  4. Return from any blocked calls to the Receive method.

CBaseInputPin::BreakConnect

CBaseInputPin Class

Releases the pin from a connection.

Syntax

HRESULT BreakConnect(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method overrides the CBasePin::BreakConnect method. It decommits the allocator and releases the IMemAllocator interface.

If you override this method, call the base-class method from your overriding method. Otherwise, you might cause memory leaks.

CBaseInputPin::CBaseInputPin

CBaseInputPin Class

Constructor method.

Syntax

CBaseInputPin(
    TCHAR *pObjectName,
    CBaseFilter *pFilter,
    CCritSec *pLock,
    HRESULT *phr,
    LPCWSTR pPinName
);

Parameters

pObjectName
String containing the debug name of the object. For more information, see CBaseObject.
pFilter
Pointer to the filter that created this pin.
pLock
Pointer to a CCritSec lock, used to serialize state changes. This can be the same critical section as the filter lock, CBaseFilter.m_pLock.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.
pPinName
Unicode™ string containing the pin name (also used as the pin identifier).

Remarks

All of the parameters are passed directly to the CBasePin constructor.

CBaseInputPin::~CBaseInputPin

CBaseInputPin Class

Destructor method.

Syntax

~CBaseInputPin(void);

CBaseInputPin::CheckStreaming

CBaseInputPin Class

Determines whether the pin can accept samples.

Syntax

virtual HRESULT CheckStreaming(void);

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success.
S_FALSE | Pin is currently flushing.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

The derived class can override this method to perform further checks. In the overriding method, also call the base class implementation.

The CBasePin::Receive method calls this method. You should override the CBasePin::EndOfStream method to call this method as well.

CBaseInputPin::EndFlush

CBaseInputPin Class

Ends a flush operation. Implements the IPin::EndFlush method.

Syntax

HRESULT EndFlush(void);

Return Value

Returns S_OK.

Remarks

This method sets the m_bFlushing flag to TRUE, which enables the Receive method to accept samples.

The derived class must override this method and perform the following steps:

  1. Free any buffered data and wait for all queued samples to be discarded.
  2. Clear any pending EC_COMPLETE notifications.
  3. Call the base class method.
  4. Call IPin::EndFlush on downstream input pins. If the pin has not yet delivered any media samples downstream, you can skip this step. If your output pins derive from the CBaseOutputPin class, you can call the CBaseOutputPin::DeliverEndFlush method.

CBaseInputPin::GetAllocator

CBaseInputPin Class

Retrieves the memory allocator proposed by this pin. Implements the IMemInputPin::GetAllocator method.

Syntax

HRESULT GetAllocator(
    IMemAllocator **ppAllocator
);

Parameters

ppAllocator
Address of a variable that receives a pointer to the allocator's IMemAllocator interface.

Return Value

Returns S_OK if successful, or an error code from the CoCreateInstance function.

Remarks

This method creates a CMemAllocator object. Override this method if your filter uses an allocator from a downstream pin, or a custom allocator.

If the method succeeds, the IMemAllocator interface has an outstanding reference count. Be sure to release it when you are done.

CBaseInputPin::GetAllocatorRequirements

CBaseInputPin Class

Retrieves the allocator properties requested by the input pin.

Syntax

HRESULT GetAllocatorRequirements(
    ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps
Pointer to an ALLOCATOR_PROPERTIES structure, which is filled in with the requirements.

Return Value

Returns E_NOTIMPL.

Remarks

When an output pin initializes a memory allocator, it can call this method to determine whether the input pin has any buffer requirements. For more information, see CBaseOutputPin::DecideAllocator.

Implementing this method is optional. If the filter has specific alignment or prefix requirements, override this method.

CBaseInputPin::Inactive

CBaseInputPin Class

Notifies the pin that the filter is no longer active.

Syntax

HRESULT Inactive(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_NO_ALLOCATOR | No memory allocator is available.

Remarks

This method overrides the CBasePin::Inactive method. It calls the IMemAllocator::Decommit method to decommit the memory allocator.

If you override this method, call the base-class method from your overriding method.

CBaseInputPin::IsFlushing

CBaseInputPin Class

Queries whether the filter is currently flushing.

Syntax

BOOL IsFlushing(void);

Return Value

Returns the m_bFlushing member variable.

CBaseInputPin::IsReadOnly

CBaseInputPin Class

Queries whether the allocator uses read-only media samples.

Syntax

BOOL IsReadOnly(void);

Return Value

Returns the m_bReadOnly member variable.

CBaseInputPin::Notify

CBaseInputPin Class

Notifies the pin that a quality change is requested. Implements the IQualityControl::Notify method.

Syntax

HRESULT Notify(
    IBaseFilter *pSelf,
    Quality q
);

Parameters

pSelf
Pointer to the filter that is sending the quality-control message.
q
Quality structure that contains the quality-control message.

Return Value

Returns S_OK.

Remarks

Filters usually pass quality-control messages to an upstream output pin, not to an input pin. Therefore, this method returns S_OK without doing anything.

For more information, see Quality-Control Management.

CBaseInputPin::NotifyAllocator

CBaseInputPin Class

Specifies an allocator for the connection. Implements the IMemInputPin::NotifyAllocator method.

Syntax

HRESULT NotifyAllocator(
    IMemAllocator *pAllocator,
    BOOL bReadOnly
);

Parameters

pAllocator
Pointer to the allocator's IMemAllocator interface.
bReadOnly
Flag that specifies whether samples from this allocator are read-only. If TRUE, samples are read-only.

Return Value

Returns S_OK.

Remarks

During the pin connection, the output pin chooses an allocator and calls this method to notify the input pin. The output pin can use the allocator that the input pin proposed in the IMemInputPin::GetAllocator method, or it can provide its own allocator.

CBaseInputPin::PassNotify

CBaseInputPin Class

Passes a quality-control message to the appropriate object.

Syntax

HRESULT PassNotify(
    Quality q
);

Parameters

q
Quality structure that contains the quality-control message.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_NOT_FOUND | Could not find an object to accept the message.

Remarks

Call this method if the filter does not handle quality-control messages. This method passes the message to one of the following objects, in order of preference:

  • An external quality-control manager, if the IQualityControl::SetSink method was called.
  • The upstream output pin.

For more information, see Quality-Control Management.

CBaseInputPin::Receive

CBaseInputPin Class

Receives the next media sample in the stream. Implements the IMemInputPin::Receive method.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
S_FALSE | Pin is currently flushing; sample was rejected.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

The upstream output pin calls this method to deliver a sample to the input pin. The input pin must do one of the following:

  • Process the sample before returning.
  • Return, and process the sample in a worker thread.
  • Reject the sample.

If the pin uses a worker thread to process the sample, add a reference count to the sample inside this method. After the method returns, the upstream pin releases the sample. When the sample's reference count reaches zero, the sample returns to the allocator for re-use.

This method is synchronous and can block. If the method might block, the pin's ReceiveCanBlock method should return S_OK.

In the base class, this method performs the following steps:

  1. Calls the CheckStreaming method to verify that the pin can process samples now. If it cannot—for example, if the pin is stopped—the method fails.
  2. Retrieves the sample properties and checks whether the format has changed (see below).
  3. If the format has changed, the method calls the CBasePin::CheckMediaType method to determine whether the new format is acceptable.
  4. If the new format is not acceptable, the method calls the CBasePin::EndOfStream method, posts an EC_ERRORABORT event, and returns an error code.
  5. Assuming there were no errors, the method returns S_OK.

Test for a format change as follows:

  • If the sample supports the IMediaSample2 interface, check the dwSampleFlags member of the AM_SAMPLE2_PROPERTIES structure. If the AM_SAMPLE_TYPECHANGED flag is present, the format has changed.
  • Otherwise, if the sample does not support IMediaSample2, call the IMediaSample::GetMediaType method. If the method returns a non-NULL value, the format has changed.

In the base class, this method does not process the sample. The derived class must override this method to perform the processing. (What this entails depends entirely on the filter.) The derived class should call the base-class method, to check for the errors described previously.

CBaseInputPin::ReceiveCanBlock

CBaseInputPin Class

Determines whether calls to the IMemInputPin::Receive method might block. Implements the IMemInputPin::ReceiveCanBlock method.

Syntax

HRESULT ReceiveCanBlock(void);

Return Value

Returns an HRESULT value. Possible value include those listed in the following table.

S_FALSE | The pin will not block on a call to Receive.
S_OK | The pin might block on a call to Receive.

Remarks

Return S_FALSE if calls to the Receive method are guaranteed not to block. Otherwise, return S_OK or an error code. If the Receive method calls Receive on a downstream pin, the downstream pin might block; ReceiveCanBlock must take that factor into account.

An upstream filter can use this method to determine its threading strategy. If the Receive method might block, the upstream filter might decide to use a worker thread that buffers data. See the COutputQueue class for an implementation of this strategy.

In the base class, this method returns S_OK when any of the following are true:

  • The filter has no output pins.
  • An input pin connected to this filter signals that it might block.
  • An input pin connected to this filter does not support the IMemInputPin interface.

CBaseInputPin::ReceiveMultiple

CBaseInputPin Class

Receives multiple samples in the stream. Implements the IMemInputPin::ReceiveMultiple method.

Syntax

HRESULT ReceiveMultiple(
    IMediaSample **pSamples,
    long nSamples,
    long *nSamplesProcessed
);

Parameters

pSamples
Address of an array of IMediaSample pointers, of size nSamples.
nSamples
Number of samples to process.
nSamplesProcessed
Pointer to a variable that receives the number of samples that were processed.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
S_FALSE | Pin is currently flushing; sample was rejected.
E_POINTER | NULL pointer argument.
VFW_E_INVALIDMEDIATYPE | Invalid media type.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

This method behaves like the Receive method, but receives an array of samples. In the base class, the method loops through the array and calls Receive with each sample. Override this function if your filter can process batches of samples more efficiently than processing them one at a time.

CBaseInputPin::SampleProps

CBaseInputPin Class

Retrieves the properties of the most recent sample, as an AM_SAMPLE2_PROPERTIES structure.

Syntax

AM_SAMPLE2_PROPERTIES *SampleProps(void);

Return Value

Returns the address of the m_SampleProps member variable.


CBaseList Class

CBaseList class hierarchy

Implements an abtract list. The CGenericList class template, which derives from CBaseList, provides type checking and a simpler API than the CBaseList class.

Declaration: Wxlist.h

The CBaseList class is modeled after the CObList class in the Microsoft® Foundation Classes (MFC) library. Positions within the list are represented by a POSITION structure. The caller should not access the internal members of the POSITION structure; treat it as a pointer to a list node. The position of an object in the list remains valid until the object is deleted.

The list does not require any support by the objects it contains. It performs no storage management or copying on the objects. Objects can be in multiple lists.

Roughly half of the methods in this class act on single objects. These methods have the suffix -I in the method name. The other methods act on entire lists. For example, the AddAfter method appends a list to another list. Single-object operations return POSITION values, or NULL on failure. List operations return TRUE if successful or FALSE otherwise.

Protected Member Variables
m_Count | Number of items in the list.
m_pFirst | Pointer to the first node in the list.
m_pLast | Pointer to the last node in the list.
Protected Methods
GetNextI | Retrieves the item at the specified position, and advances the position.
GetI | Retrieves the item at the specified position.
FindI | Retrieves the first position that holds the specified item.
RemoveHeadI | Removes the first item in the list.
RemoveTailI | Removes the last item in the list.
RemoveI | Removes the item at the specified position.
AddTailI | Adds an item to the end of the list.
AddHeadI | Adds an item to the front of the list.
AddAfterI | Inserts an item after the specified position.
AddBeforeI | Inserts an item before the specified position.
Public Methods
CBaseList | Constructor method.
~CBaseList | Destructor method.
RemoveAll | Removes all nodes from the list.
GetHeadPositionI | Retrieves the position of the first item in the list.
GetTailPositionI | Retrieves the position of the last item of the list.
GetCountI | Retrieves the number of items in the list.
Next | Retrieves the next position in the list.
Prev | Retrieves the previous position in the list.
AddHead | Inserts another list at the front of this list.
AddTail | Appends another list to the end of this list.
AddAfter | Inserts a list after the specified position.
AddBefore | Inserts a list before the specified position.
MoveToTail | Splits the list and appends the head portion to the tail of another list.
MoveToHead | Splits the list and inserts the tail portion at the head of another list.
Reverse | Reverses the order of the list.

CBaseList.m_Count

CBaseList Class

Number of items in the list.

Syntax

LONG m_Count;

CBaseList.m_pFirst

CBaseList Class

Pointer to the first node in the list.

Syntax

CNode *m_pFirst;

CBaseList.m_pLast

CBaseList Class

Pointer to the last node in the list.

Syntax

CNode *m_pLast;

CBaseList::AddAfter

CBaseList Class

Inserts a list after the specified position.

Syntax

BOOL AddAfter(
    POSITION pos,
    CBaseList *pList
);

Parameters

pos
Position after which to insert the list.
pList
Pointer to the list to insert.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Return Remarks

Existing position indicators, including the one specified in the pos parameter, remain valid. If the method fails, some of the items might have been added.

CBaseList::AddAfterI

CBaseList Class

Inserts an item after the specified position.

Syntax

POSITION AddAfterI(
    POSITION pos,
    void *pObj
);

Parameters

pos
Position after which to add the item.
pObj
Pointer to the item to add.

Return Value

Returns the position indicator of the inserted item.

Remarks

If pos is NULL, this method adds the item to the head of the list (equivalent to calling the AddHeadI method.)

CBaseList::AddBefore

CBaseList Class

Inserts a list before the specified position.

Syntax

BOOL AddBefore(
    POSITION pos,
    CBaseList *pList
);

Parameters

pos
Position before which to insert the list.
pList
Pointer to the list to insert.

Return Value

Returns TRUE if successful. Otherwise, returns FALSE.

Remarks

Existing position indicators, including the one specified in the pos parameter, remain valid. If the method fails, some of the items might have been added.

CBaseList::AddBeforeI

CBaseList Class

Inserts an item before the specified position.

Syntax

POSITION AddBeforeI(
    POSITION pos,
    void *pObj
);

Parameters

pos
Position before which to add the item.
pObj
Pointer to the item.

Return Value

Returns the position indicator for the inserted item.

Remarks

If pos is NULL, this method adds the item to the tail of the list (equivalent to calling the AddTailI method).

CBaseList::AddHead

CBaseList Class

Inserts another list at the front of this list.

Syntax

BOOL AddHead(
    CBaseList *pList
);

Parameters

pList
Pointer to the list of items to add.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

If the method fails, some items might have been added to the list.

CBaseList::AddHeadI

CBaseList Class

Adds an item to the front of the list.

Syntax

POSITION AddHeadI(
    void *pObj
);

Parameters

pObj
Pointer to the item.

Return Value

Returns a POSITION value indicating the new head position.

Remarks

If the method fails, the return value is NULL.

CBaseList::AddTail

CBaseList Class

Appends another list to the end of this list.

Syntax

BOOL AddTail(
    CBaseList *pList
);

Parameters

pList
Pointer to the list to append.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

If the method fails, some items may have been added to the list.

CBaseList::AddTailI

CBaseList Class

Adds an item to the end of the list.

Syntax

POSITION AddTailI(
    void *pObj
);

Parameters

pObj
Pointer to the item.

Return Value

Returns a POSITION value for the new tail position.

Remarks

If the method fails, it returns NULL.

CBaseList::CBaseList

CBaseList Class

Constructor method.

Syntax

CBaseList(
    TCHAR *pName,
    INT iItems
);

CBaseList(
    TCHAR *pName
);

Parameters

pName
Pointer to the name of the list.
iItems
Size of the node cache.

Remarks

For efficiency, the CBaseList class maintains a cache of list nodes. If you know approximately how many items the list will hold, use the first version of the constructor. The second version uses a default cache size.

CBaseList::~CBaseList

CBaseList Class

Destructor method.

Syntax

~CBaseList(void);

CBaseList::FindI

CBaseList Class

Retrieves the first position that holds the specified item.

Syntax

POSITION FindI(
    void *pObj
);

Parameters

pObj
Pointer to the item.

Return Value

Returns a POSITION value, or NULL if the item is not in the list.

CBaseList::GetCountI

CBaseList Class

Retrieves the number of items in the list.

Syntax

int GetCountI(void);

Return Value

Returns the number of items in the list.

CBaseList::GetHeadPositionI

CBaseList Class

Retrieves the position of the first item in the list.

Syntax

POSITION GetHeadPositionI(void);

Return Value

Returns a POSITION value, or NULL if the list is empty.

CBaseList::GetI

CBaseList Class

Retrieves the item at the specified position.

Syntax

void *GetI(
    POSITION pos
);

Parameters

pos
Position indicator for the item to retrieve.

Return Value

Returns a pointer to the item.

Remarks

If pos is NULL, the method returns NULL.

CBaseList::GetNextI

CBaseList Class

Retrieves the item at the specified position, and advances the position.

Syntax

void *GetNextI(
    POSITION& rp
);

Parameters

rp
Reference to a POSITION value.

Return Value

Returns a pointer to the item.

Remarks

This method advances the position indicator to the next position. If the position indicator moves past the end of the list, the method sets it to NULL.

If rp is NULL, the method returns NULL.

CBaseList::GetTailPositionI

CBaseList Class

Retrieves the position of the last item of the list.

Syntax

POSITION GetTailPositionI(void);

Return Value

Returns a POSITION value, or NULL if the list is empty.

CBaseList::MoveToHead

CBaseList Class

Splits the list and inserts the tail portion at the head of another list.

Syntax

BOOL MoveToHead(
    POSITION pos,
    CBaseList *pList
);

Parameters

pos
Position indicator that marks the split in the list.
pList
Pointer to another list.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

This method splits the list before the position specified by the pos parameter. The head portion remains in the list. The tail portion is inserted at the head of the other list.

CBaseList::MoveToTail

CBaseList Class

Splits the list and appends the head portion to the tail of another list.

Syntax

BOOL MoveToTail(
    POSITION pos,
    CBaseList *pList
);

Parameters

pos
Position indicator that marks the split in the list.
pList
Pointer to another list.

Return Value

Returns TRUE if successful, or FALSE otherwise.

Remarks

This method splits the list after the position specified by the pos parameter. The tail portion remains in the list. The head portion is appended to the tail of the other list.

CBaseList::Next

CBaseList Class

Retrieves the next position in the list.

Syntax

POSITION Next(
    POSITION pos
);

Parameters

pos
POSITION value.

Return Value

Returns the position indicator that follows the position specified by pos.

Remarks

If pos is the last position in the list, the method returns NULL. If pos is NULL, the method returns the first position in the list.

CBaseList::Prev

CBaseList Class

Retrieves the previous position in the list.

Syntax

POSITION Prev(
    POSITION pos
);

Parameters

pos
POSITION value.

Return Value

Returns the position indicator that is previous to the position specified in pos.

Remarks

If pos is the first position in the list, the method returns NULL. If pos is NULL, the method returns the last position in the list.

CBaseList::RemoveAll

CBaseList Class

Removes all the nodes from the list.

Syntax

void RemoveAll(void);

Remarks

It is the caller's responsibility to delete the items contained in all the nodes.

CBaseList::RemoveHeadI

CBaseList Class

Removes the first item in the list.

Syntax

void *RemoveHeadI(void);

Return Value

Returns a pointer to the item, or NULL if the list is empty.

Remarks

This method deletes the list node, but not the item that the node contains.

CBaseList::RemoveI

CBaseList Class

Removes the item at the specified position.

Syntax

void *RemoveI(
    POSITION pos
);

Parameters

pos
POSITION value indicating the item to remove.

Return Value

Returns a pointer to the item.

Remarks

This method deletes the node from the list, but does not delete the item contained in that node.

If pos is NULL, the method returns NULL.

CBaseList::RemoveTailI

CBaseList Class

Removes the last item in the list.

Syntax

void *RemoveTailI(void);

Return Value

Returns a pointer to the item, or NULL if the list is empty.

Remarks

This method deletes the list node, but not the item that is contained in the node.

CBaseList::Reverse

CBaseList Class

Reverses the order of the list.

Syntax

void Reverse(void);


CBaseMediaFilter Class

CBaseMediaFilter class hierarchy

Base class that implements the IMediaFilter interface. Use this class for plug-in distributors or other objects that need to support IMediaFilter without supporting the IBaseFilter interface. Do not use this class for filters. Instead, use the CBaseFilter class, or a base class derived from CBaseFilter.

Declaration: Amfilter.h

Protected Member Variables
m_State | Current state of the object.
m_pClock | Pointer to the object's reference clock.
m_tStart | Reference time that corresponds to stream time 0.
m_clsid | Class identifier (CLSID) of the object.
m_pLock | Pointer to a critical section.
Public Methods
CBaseMediaFilter | Constructor method.
~CBaseMediaFilter | Destructor method. Virtual.
StreamTime | Retrieves the current stream time. Virtual.
IsActive | Determines whether the object is active (running or paused).
IPersist Methods
GetClassID | Retrieves the class identifier.
IMediaFilter Methods
GetState | Retrieves the object's state (running, stopped, or paused).
SetSyncSource | Sets a reference clock for the object.
GetSyncSource | Retrieves the reference clock that the object is using.
Stop | Stops the object.
Pause | Pauses the object.
Run | Runs the object.

CBaseMediaFilter.m_State

CBaseMediaFilter Class

Current state of the object.

Syntax

FILTER_STATE m_State;

CBaseMediaFilter.m_pClock

CBaseMediaFilter Class

Pointer to the object's reference clock.

Syntax

IReferenceClock *m_pClock;

CBaseMediaFilter.m_tStart

CBaseMediaFilter Class

Reference time that corresponds to stream time 0.

Syntax

CRefTime m_tStart;

CBaseMediaFilter.m_clsid

CBaseMediaFilter Class

Class identifier (CLSID) of the object.

Syntax

CLSID m_clsid;

CBaseMediaFilter.m_pLock

CBaseMediaFilter Class

Pointer to a critical section.

Syntax

CCritSec *m_pLock;

Remarks

The critical section is held during state transitions (Run, Pause, Stop), when accessing the reference clock (SetSyncSource, GetSyncSource), and in the IsActive method.

CBaseMediaFilter::CBaseMediaFilter

CBaseMediaFilter Class

Constructor method.

Syntax

CBaseMediaFilter(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    CCritSec *pLock,
    REFCLSID clsid
);

Parameters

pName
Pointer to a string containing the name of the object.
pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
pLock
Pointer to a CCritSec lock, used to serialize state changes.
clsid
Class identifier of the object.

Remarks

If another object contains or aggregates the CBaseMediaFilter object, the CCritSec lock might be external to the CBaseMediaFilter object. In that case, pass a pointer to the lock in pLock.

Otherwise, you can:

  • Derive a class that inherits both CBaseMediaFilter and CCritSec. For pLock, pass the this pointer.
  • Derive a class that inherits CBaseMediaFilter and contains a CCritSec member variable. For pLock, pass the address of that variable.

CBaseMediaFilter::~CBaseMediaFilter

CBaseMediaFilter Class

Destructor method.

Syntax

CBaseMediaFilter(void);

Remarks

Always stop the object before destroying it.

CBaseMediaFilter::GetClassID

CBaseMediaFilter Class

Retrieves the class identifier. Implements the IPersist::GetClassID method.

Syntax

HRESULT GetClassID(
    CLSID *pClsID
);

Parameters

pClsID
Pointer to a variable that receives the class identifier.

Return Value

Returns S_OK or E_POINTER.

CBaseMediaFilter::GetState

CBaseMediaFilter Class

Retrieves the object's state (running, stopped, or paused). Implements the IMediaFilter::GetState method.

Syntax

HRESULT GetState(
    DWORD dwMilliSecsTimeout,
    FILTER_STATE *State
);

Parameters

dwMilliSecsTimeout
Time-out interval, in milliseconds.
State
Pointer to a variable that receives a member of the FILTER_STATE enumerated type, indicating the object's state.

Return Value

Returns S_OK or E_POINTER.

Remarks

In the base class, all state transitions are synchronous and the dwMilliSecsTimeout parameter is ignored. If a derived class performs asynchronous state transitions, it should override this method to wait during state transitions, with a time-out of dwMilliSecsTimeout milliseconds.

CBaseMediaFilter::GetSyncSource

CBaseMediaFilter Class

Retrieves the reference clock that the object is using. Implements the IMediaFilter::GetSyncSource method.

Syntax

HRESULT GetSyncSource(
    IReferenceClock **pClock
);

Parameters

pClock
Address of a variable that receives a pointer to the clock's IReferenceClock interface.

Return Value

Returns S_OK or E_POINTER.

Remarks

If the object is not using a reference clock, *pClock is set to NULL. When the method returns, if *pClock is non-NULL, the IReferenceClock interface has an outstanding reference count. Be sure to release it when you are done.

CBaseMediaFilter::IsActive

CBaseMediaFilter Class

Determines whether the object is active (running or paused).

Syntax

BOOL IsActive(void);

Return Value

Returns TRUE if the object is paused or running, or FALSE if it is stopped.

CBaseMediaFilter::Pause

CBaseMediaFilter Class

Pauses the object. Implements the IMediaFilter::Pause method.

Syntax

HRESULT Pause(void);

Return Value

Returns S_OK.

Remarks

In the base class, this method sets the m_State member variable to State_Paused but does nothing else.

CBaseMediaFilter::Run

CBaseMediaFilter Class

Runs the object. Implements the IMediaFilter::Run method.

Syntax

HRESULT Run(
    REFERENCE_TIME tStart
);

Parameters

tStart
Reference time corresponding to stream time 0.

Return Value

Returns S_OK.

Remarks

If the object is stopped, this method pauses the object by calling the CBaseMediaFilter::Pause method. It then sets the m_State member variable to State_Running.

Stream time is calculated as the current reference time minus tStart. A media sample with a time stamp of zero should be rendered at time tStart.

CBaseMediaFilter::SetSyncSource

CBaseMediaFilter Class

Sets a reference clock for the object. Implements the IMediaFilter::SetSyncSource method.

Syntax

HRESULT SetSyncSource(
    IReferenceClock *pClock
);

Parameters

pClock
Pointer to the clock's IReferenceClock interface, or NULL.

Return Value

Returns S_OK.

CBaseMediaFilter::Stop

CBaseMediaFilter Class

Stops the object. Implements the IMediaFilter::Stop method.

Syntax

HRESULT Stop(void);

Return Value

Returns S_OK.

Remarks

In the base class, this method sets the m_State member variable to State_Stopped but does nothing else.

CBaseMediaFilter::StreamTime

CBaseMediaFilter Class

Retrieves the current stream time.

Syntax

virtual HRESULT StreamTime(
    CRefTime& rtStream
);

Parameters

rtStream
Reference to a CRefTime object that receives the current stream time.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_NO_CLOCK | No reference clock is available.

Remarks

Stream time is defined as the current reference time (as given by the reference clock) minus the start time (specified by m_tStart). A media sample's time stamp specifies the stream time when it should be rendered. If a sample with a time stamp less than the current stream time has not yet been rendered, it is late.


CBaseObject Class

CBaseObject class hierarchy

Abstract class for implementing Microsoft® DirectShow® objects.

Declaration: Combase.h

This class maintains a static, process-wide count of the number of active objects. The DllCanUnloadNow function uses this count to determine when a DirectShow DLL can be unloaded. Your application can use this count to detect memory leaks caused by undeleted objects.

To implement Component Object Model (COM) objects, use the CUnknown class, which derives from CBaseObject.

Class Methods
CBaseObject | Constructor method.
~CBaseObject | Destructor method.
ObjectsActive | Retrieves the count of active objects.

CBaseObject::CBaseObject

CBaseObject Class

Constructor method.

Syntax

CBaseObject(
    const TCHAR *pName
);

Parameters

pName
String that contains the name of the object, for debugging purposes.

Remarks

This method increments the active-object count. (See ObjectsActive.)

Allocate the pName parameter in static memory:

// Correct.
CBaseObject *pObject = new CBaseObject(NAME("My Object"));

// Incorrect.
TCHAR ObjectName[] = TEXT("My Object");
CBaseObject *pObject = new CObject(ObjectName);

The NAME macro compiles to NULL in retail builds, so that static strings appear only in debug builds. For more information, see DbgDumpObjectRegister.

CBaseObject::~CBaseObject

CBaseObject Class

Destructor method.

Syntax

~CBaseObject(void);

Remarks

This method decrements the active-object count. (See ObjectsActive.)

CBaseObject::ObjectsActive

CBaseObject Class

Retrieves a process-wide count of active objects.

Syntax

static LONG ObjectsActive(void);

Return Value

Returns the number of active objects.


CBaseOutputPin Class

CBaseOutputPin class hierarchy

Abstract base class that implements an output pin.

Declaration: Amfilter.h

This class derives from CBasePin. It differs from CBasePin in the following respects:

  • Connects only to input pins that support the IMemInput interface.
  • Supports local memory transport through the IMemAllocator interface.
  • Rejects end-of-stream, flush, and new-segment notifications. (These should not be sent to an output pin.)
  • Provides methods for delivering samples downstream.

When the pin connects, it requests a memory allocator from the input pin. Failing that, it creates a new allocator object. The output pin is responsible for setting the allocator properties. It does this through the pure virtual method DecideBufferSize. Override this method in your derived class. If the input pin has any buffer requirements, they are passed to the DecideBufferSize method.

Call the GetDeliveryBuffer method to obtain an empty media sample. Call the Deliver method to deliver samples downstream.

Protected Member Variables
m_pAllocator | Pointer to the memory allocator.
m_pInputPin | Pointer to the input pin connected to this pin.
Public Methods
CBaseOutputPin | Constructor method.
CompleteConnect | Completes a connection to an input pin. Virtual.
DecideAllocator | Selects a memory allocator. Virtual.
GetDeliveryBuffer | Retrieves a media sample that contains an empty buffer. Virtual.
Deliver | Delivers a media sample to the connected input pin. Virtual.
InitAllocator | Creates a memory allocator. Virtual.
CheckConnect | Determines whether a pin connection is suitable.
BreakConnect | Releases the pin from a connection.
Active | Notifies the pin that the filter is now active.
Inactive | Notifies the pin that the filter is no longer active.
DeliverEndOfStream | Delivers an end-of-stream notification to the connected input pin. Virtual.
DeliverBeginFlush | Requests the connected input pin to begin a flush operation. Virtual.
DeliverEndFlush | Requests the connected input pin to end a flush operation. Virtual.
DeliverNewSegment | Delivers a new-segment notification to the connected input pin. Virtual.
Pure Virtual Methods
DecideBufferSize | Sets the buffer requirements.
IPin Methods
BeginFlush | Begins a flush operation.
EndFlush | Ends a flush operation.
EndOfStream | INotifies the pin that no additional data is expected.

CBaseOutputPin.m_pAllocator

CBaseOutputPin Class

Pointer to the memory allocator.

Syntax

IMemAllocator *m_pAllocator;

CBaseOutputPin.m_pInputPin

CBaseOutputPin Class

Pointer to the input pin connected to this pin.

Syntax

IMemInputPin *m_pInputPin;

CBaseOutputPin::Active

CBaseOutputPin Class

Notifies the pin that the filter is now active.

Syntax

HRESULT Active(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_NO_ALLOCATOR | No memory allocator is available.

Remarks

This method overrides the CBasePin::Active method. It calls the IMemAllocator::Commit method on the allocator, to allocate memory for buffers.

If you override this method, call the base-class method from your overriding method.

CBaseOutputPin::BeginFlush

CBaseOutputPin Class

Begins a flush operation. Implements the IPin::BeginFlush method.

Syntax

HRESULT BeginFlush(void);

Return Value

Returns E_UNEXPECTED.

Remarks

This method should only be called on input pins, so the CBaseOutputPin implementation returns E_UNEXPECTED.

CBaseOutputPin::BreakConnect

CBaseOutputPin Class

Releases the pin from a connection.

Syntax

HRESULT BreakConnect(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method overrides the CBasePin::BreakConnect method. It decommits the allocator and releases the IMemAllocator and IPin interfaces.

If you override this method, call the base-class method from your overriding method. Otherwise, you might cause memory leaks.

CBaseOutputPin::CBaseOutputPin

CBaseOutputPin Class

Constructor method.

Syntax

CBaseOutputPin(
    TCHAR *pObjectName,
    CBaseFilter *pFilter,
    CCritSec *pLock,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName
String containing the debug name of the object. For more information, see CbaseObject.
pFilter
Pointer to the filter that created this pin.
pLock
Pointer to a CCritSec lock, used to serialize state changes. This can be the same critical section as the filter lock, CBaseFilter.m_pLock.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.
pName
Unicode™ string containing the pin name (also used as the pin identifier).

Remarks

All of the parameters are passed directly to the CBasePin constructor.

CBaseOutputPin::CheckConnect

CBaseOutputPin Class

Determines whether a pin connection is suitable.

Syntax

HRESULT CheckConnect(
    IPin *pPin
);

Parameters

pPin
Pointer to the input pin's IPin interface.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_NOINTERFACE | Input pin does not support IMemInputPin.
VFW_E_INVALID_DIRECTION | Pin directions are not compatible.

Remarks

This method calls the base-class CBasePin::CheckConnect method, and then queries the input pin for its IMemInputPin interface.

CBaseOutputPin::CompleteConnect

CBaseOutputPin Class

Completes a connection to an input pin.

Syntax

virtual HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin
Pointer to the input pin.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method overrides the CBasePin::CompleteConnect method. It calls the DecideAllocator method, which selects the memory allocator to use for this connection.

CBaseOutputPin::DecideAllocator

CBaseOutputPin Class

Selects a memory allocator.

Syntax

virtual HRESULT DecideAllocator(
    IMemInputPin *pPin,
    IMemAllocator **pAlloc
);

Parameters

pPin
Pointer to the input pin's IMemInputPin interface.
pAlloc
Address of a variable that receives a pointer to the allocator's IMemAllocator interface.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method is called at the end of the pin connection process. It performs the following steps:

  1. Calls the IMemInputPin::GetAllocatorRequirements method to retrieve the input pin's buffer requirements, if any.
  2. Calls the IMemInputPin::GetAllocator method to request an allocator from the input pin. If the input pin does not provide an allocator, the output pin creates one by calling the InitAllocator class method.
  3. Calls the DecideBufferSize class method, which sets the allocator properties. This is a pure virtual method; the derived class must implement it.
  4. Calls the IMemInputPin::NotifyAllocator method, which notifies the input pin of the allocator being used.

CBaseOutputPin::DecideBufferSize

CBaseOutputPin Class

Sets the buffer requirements.

Syntax

virtual HRESULT DecideBufferSize(
    IMemAllocator *pAlloc,
    ALLOCATOR_PROPERTIES *ppropInputRequest
) PURE;

Parameters

pAlloc
Pointer to the allocator's IMemAllocator interface.
ppropInputRequest
Pointer to an ALLOCATOR_PROPERTIES structure that contains the input pin's buffer requirements. If the input pin did not specify any requirements, the caller should zero out the members of this structure.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

Override this method in your derived class. Call the IMemAllocator::SetProperties method to specify your buffer requirements. Typically, the derived class will honor the input pin's buffer requirements, but it is not required to.

CBaseOutputPin::Deliver

CBaseOutputPin Class

Delivers a media sample to the connected input pin.

Syntax

virtual HRESULT Deliver(
    IMediaSample *pSample
);

Parameters

pSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

This method calls the IMemInputPin::Receive method on the input pin. Receive can block if the IMemInputPin::ReceiveCanBlock method returns S_OK.

Release the sample after calling this method. The input pin might hold a reference count on the sample, so do not reuse the sample. Always call the GetDeliveryBuffer method to obtain a new sample.

Hold the filter's critical section before calling this method. Otherwise, the pin might get disconnected during the method call. If the filter uses a worker thread to deliver samples, hold the critical section when the filter is ready to deliver a sample. Otherwise, you can hold the critical section in the filter's IMemInputPin::Receive method, where the filter processes samples.

Worker threads can create a potential deadlock. When the thread holds the critical section, it might wait on a state change in the filter. At the same time, the state change might be waiting for the thread to complete. To prevent this, the state-change code should signal an event that terminates the thread, and then wait for the thread to signal completion.

CBaseOutputPin::DeliverBeginFlush

CBaseOutputPin Class

Requests the connected input pin to begin a flush operation.

Syntax

virtual HRESULT DeliverBeginFlush(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

This method calls the IPin::BeginFlush method on the input pin.

CBaseOutputPin::DeliverEndFlush

CBaseOutputPin Class

Requests the connected input pin to end a flush operation.

Syntax

virtual HRESULT DeliverEndFlush(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

This method calls the IPin::EndFlush method on the input pin.

CBaseOutputPin::DeliverEndOfStream

CBaseOutputPin Class

Delivers an end-of-stream notification to the connected input pin.

Syntax

virtual HRESULT DeliverEndOfStream(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

This method calls the IPin::EndOfStream method on the input pin.

CBaseOutputPin::DeliverNewSegment

CBaseOutputPin Class

Delivers a new-segment notification to the connected input pin.

Syntax

virtual HRESULT DeliverNewSegment(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop,
    double dRate
);

Parameters

tStart
Starting media position of the segment, in 100-nanosecond units.
tStop
End media position of the segment, in 100-nanosecond units.
dRate
Rate at which this segment should be processed, as a percentage of the original rate.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

This method calls the IPin::NewSegment method on the input pin.

CBaseOutputPin::EndFlush

IPin Interface

Ends a flush operation. Implements the IPin::EndFlush method.

Syntax

HRESULT EndFlush(void);

Return Value

Returns E_UNEXPECTED.

Remarks

This method should only be called on input pins, so the CBaseOutputPin implementation returns E_UNEXPECTED.

CBaseOutputPin::EndOfStream

IPin Interface

Notifies the pin that no additional data is expected. Implements the IPin::EndOfStream method.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns E_UNEXPECTED.

Remarks

This method should only be called on input pins, so the CBaseOutputPin implementation returns E_UNEXPECTED.

CBaseOutputPin::GetDeliveryBuffer

CBaseOutputPin Class

Retrieves a media sample that contains an empty buffer.

Syntax

virtual HRESULT GetDeliveryBuffer(
    IMediaSample **ppSample,
    REFERENCE_TIME *pStartTime,
    REFERENCE_TIME *pEndTime,
    DWORD dwFlags
);

Parameters

ppSample
Address of a variable that receives a pointer to the buffer's IMediaSample interface.
pStartTime
Pointer to the start time of the sample, or NULL.
pEndTime
Pointer to the ending time of the sample, or NULL.
dwFlags
Bitwise combination of flags supported by the IMemAllocator::GetBuffer interface.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
E_NOINTERFACE | No allocator available.

Remarks

This method calls the IMemAllocator::GetBuffer method on the allocator, and passes the parameters to that method.

CBaseOutputPin::Inactive

CBaseOutputPin Class

Notifies the pin that the filter is no longer active.

Syntax

HRESULT Inactive(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_NO_ALLOCATOR | No memory allocator is available.

Remarks

This method overrides the CBasePin::Inactive method. It calls the IMemAllocator::Decommit method to decommit the memory allocator.

If you override this method, call the base-class method from your overriding method.

CBaseOutputPin::InitAllocator

CBaseOutputPin Class

Creates a memory allocator.

Syntax

virtual HRESULT InitAllocator(
    IMemAllocator **ppAlloc
);

Parameters

ppAlloc
Address of a variable that receives a pointer to the allocator's IMemAllocator interface.

Return Value

Returns S_OK if successful, or an error code from the CoCreateInstance function.

Remarks

If the input pin does not provide a memory allocator, the DecideAllocator method calls this method to create an allocator.


CBasePin Class

CBasePin class hierarchy

Abstract class that implements a generic pin.

Declaration: Amfilter.h

  • Connection Process
  • How CBasePin Implements IPin::Connect
  • Filter State Changes

Connection Process

The filter graph manager initiates all pin connections. If an application needs to connect two pins, it should call the filter graph manager's IFilterGraph::ConnectDirect method.

When two pins connect, there is a connecting pin and a receiving pin. The filter graph manager calls the connecting pin's IPin::Connect method. It specifies the receiving pin and possibly a media type for the connection. The connecting pin completes the connection by calling the receiving pin's IPin::ReceiveConnection method. The receiving pin can accept or reject the connection.

If the filter graph manager specifies a media type, the pins try to connect with that type. Otherwise, the pins negotiate an acceptable type. If they cannot agree on a type, the connection fails. The filter graph manager might also specify a partial media type. A partial media type has a value of GUID_NULL for the major type, the subtype, or the format. In that case, the pins try to match the specified portions of the type, and GUID_NULL acts as a wildcard.

In the Microsoft® DirectShow® implementation, the connecting pin is always an output pin, and the receiving pin is always an input pin.

How CBasePin Implements IPin::Connect

The CBasePin::Connect method starts by verifying that the pin can accept a connection. For example, it checks that the pin is not already connected. Then it delegates the rest of the connection process to AgreeMediaType, a protected class method. Everything that follows is performed by AgreeMediaType.

If the media type is fully specified, the pin calls the AttemptConnection method. Otherwise, the pin tries media types in the following order:

  1. The receiving pin's preferred types.
  2. The connecting pin's preferred types.

Note You can reverse the order by setting the m_bTryMyTypesFirst flag to TRUE.

In each case, the pin calls IPin::EnumMediaTypes, which retrieves an enumerator object. It passes the enumerator object to the TryMediaTypes method. This method loops through all the media types provided by the enumerator, and calls AttemptConnection with each type.

Within the AttemptConnection method, the connecting pin calls the following methods:

  • CheckConnect: Checks whether the receiving pin is suitable.
  • CheckMediaType: Validates the media type.
  • IPin::ReceiveConnection (on the receiving pin): Determines whether the receiving pin accepts the connection.
  • CompleteConnect: Completes the connection.

Note the following:

  • CheckConnect is a virtual method. In the base class, it checks whether the pin directions are compatible. Output pins can connect only to input pins, and vice versa. A derived class might override this method to perform other checks. For example, it might query the other pin for an interface, and reject any pins that do not support the interface.
  • CheckMediaType is a pure virtual method, which the derived class must implement.
  • CompleteConnect is a virtual method that does nothing in the base class. Derived classes can override this method to perform any additional work needed to complete the connection, such as deciding a memory allocator.

If any of these steps fails, the pin calls the BreakConnect method to undo whatever steps were taken by CheckConnect.

On the receiving side, ReceiveConnection calls the receiving pin's CheckConnect, CheckMediaType, and CompleteConnect methods. If any of these fail, the connection attempt also fails.

Filter State Changes

The pin is notified whenever the state of the owning filter changes. For each state transition, the filter calls a corresponding method on the pin, as shown in the following table.

Filter State | CBasePin Method
Stop | Inactive
Pause | Active
Run | Run

The derived class should override these methods to respond to the state change. Depending on the filter, the pin might start a worker thread that delivers samples, commit or decommit its memory allocator, and so forth.

Deriving from CBasePin

To implement a pin using CBasePin, you must derive a new class from the base class and override several of its methods. You must override the following methods:

  • CheckMediaType
  • GetMediaType

You will probably need to override these additional methods:

  • Active
  • BreakConnect
  • CheckConnect
  • CompleteConnect
  • EndOfStream
  • Inactive
  • Notify
  • Run

Finally, you must must implement the IPin::BeginFlush and IPin::EndFlush methods.

Some of these methods are implemented in base classes that derive from CBasePin, such as CBaseInputPin and CBaseOutputPin.

Protected Member Variables
m_pName | Pin name.
m_Connected | Pointer to the pin that is connected to this pin.
m_dir | Direction of the pin.
m_pLock | Pointer to a critical section object.
m_bRunTimeError | Flag that indicates whether a run-time error has occurred.
m_bCanReconnectWhenActive | Flag that indicates whether the pin supports dynamic reconnection.
m_bTryMyTypesFirst | Flag that indicates whether the pin tries its own preferred media types before those of the receiving pin.
m_pFilter | Pointer to the filter that created the pin.
m_pQSink | Pointer to the object that handles quality messages.
m_TypeVersion | Current version of the set of preferred media types.
m_mt | Media type for the current pin connection.
m_tStart | Segment start time.
m_tStop | Segment stop time.
m_dRate | Segment rate.
Protected Methods
DisplayPinInfo | Traces a pin connection during debugging.
DisplayTypeInfo | Displays media type information during debugging.
AttemptConnection | Connects to another pin using a specified media type.
TryMediaTypes | Given a list of media types, tries to complete a connection using one of those types.
AgreeMediaType | Searches for a media type to make a pin connection.
DisconnectInternal | Breaks the current pin connection.
Public Methods
CBasePin | Constructor method.
~CBasePin | Destructor method. Virtual.
IsConnected | Determines whether the pin is connected to another pin.
GetConnected | Retrieves the pin that is connected to this pin.
IsStopped | Determines whether the filter containing this pin is stopped.
GetMediaTypeVersion | Retrieves a version number for the set of preferred media types. Virtual.
IncrementTypeVersion | Increments the version number on the set of preferred media types.
Active | Notifies the pin that the filter is now active. Virtual.
Inactive | Notifies the pin that the filter is no longer active. Virtual.
Run | Notifies the pin that the filter is now running. Virtual.
SetMediaType | Sets the media type for the connection. Virtual.
CheckConnect | Determines whether a pin connection is suitable. Virtual.
BreakConnect | Releases the pin from a connection. Virtual.
CompleteConnect | Completes a connection to another pin. Virtual.
GetMediaType | Retrieves a preferred media type, by index value. Virtual.
CurrentStopTime | Retrieves the segment stop time.
CurrentStartTime | Retrieves the segment start time.
CurrentRate | Retrieves the segment rate.
Name | Retrieves the pin identifier.
SetReconnectWhenActive | Specifies whether the pin supports dynamic reconnections.
CanReconnectWhenActive | Queries whether the pin supports dynamic reconnections.
Pure Virtual Methods
CheckMediaType | Determines if the pin accepts a specific media type.
IBasePin methods
Connect | Connects the pin to another pin.
ReceiveConnection | Accepts a connection from another pin.
Disconnect | Breaks the current pin connection.
ConnectedTo | Retrieves the pin connected to this pin.
ConnectionMediaType | Retrieves the media type for the current pin connection, if any.
QueryPinInfo | Retrieves information about the pin.
QueryDirection | Retrieves the direction of the pin (input or output).
QueryId | Retrieves the pin identifier.
QueryAccept | Determines whether the pin accepts a specified media type.
EnumMediaTypes | Enumerates the pin's preferred media types.
QueryInternalConnections | Retrieves the pins that are connected internally to this pin (within the filter).
EndOfStream | Notifies the pin that no additional data is expected.
NewSegment | Notifies the pin that media samples received after this call are grouped as a segment.
IQualityControl methods
Notify | Notifies the pin that a quality change is requested.
SetSink | Sets an external quality manager.

CBasePin.m_pName

CBasePin Class

Pin name.

Syntax

WCHAR *m_pName;

Remarks

The QueryPinInfo method returns this string as the pin name, and the QueryId method returns it as the pin identifier. In general, however, the pin name and the pin identifier are not required to be the same. The pin identifier is used for graph persistence. For more information, see IBaseFilter::FindPin.

CBasePin.m_Connected

CBasePin Class

Pointer to the pin that is connected to this pin.

Syntax

IPin *m_Connected;

CBasePin.m_dir

CBasePin Class

Direction of the pin.

Syntax

PIN_DIRECTION m_dir;

CBasePin.m_pLock

CBasePin Class

Pointer to a critical section object.

Syntax

CCritSec *m_pLock;

CBasePin.m_bRunTimeError

CBasePin Class

Flag that indicates whether a run-time error has occurred.

Syntax

bool m_bRunTimeError;

Remarks

This flag defaults to FALSE. Set the flag to TRUE if a run-time error occurs during streaming. The Inactive method resets the flag to FALSE.

CBasePin.m_bCanReconnectWhenActive

CBasePin Class

Flag that indicates whether the pin supports dynamic reconnection.

Syntax

bool m_bCanReconnectWhenActive;

Remarks

This flag defaults to FALSE.

CBasePin.m_bTryMyTypesFirst

CBasePin Class

Flag that indicates whether the pin tries its own preferred media types before those of the receiving pin.

Syntax

bool m_bTryMyTypesFirst;

Remarks

This flag defaults to FALSE. If the flag is TRUE, the AgreeMediaType method reverses the order in which it tries media types.

CBasePin.m_pFilter

CBasePin Class

Pointer to the filter that created the pin.

Syntax

CBaseFilter *m_pFilter;

CBasePin.m_pQSink

CBasePin Class

Pointer to the object that handles quality messages.

Syntax

IQualityControl *m_pQSink;

CBasePin.m_TypeVersion

CBasePin Class

Current version of the set of preferred media types.

Syntax

LONG m_TypeVersion;

CBasePin.m_mt

CBasePin Class

Media type for the current pin connection.

Syntax

CMediaType m_mt;

CBasePin.m_tStart

CBasePin Class

Segment start time.

Syntax

CRefTime m_tStart;

CBasePin.m_tStop

CBasePin Class

Segment stop time.

Syntax

CRefTime m_tStop;

CBasePin.m_dRate

CBasePin Class

Segment rate.

Syntax

double m_dRate;

CBasePin::Active

CBasePin Class

Notifies the pin that the filter is now active.

Syntax

virtual HRESULT Active(void);

Return Value

Returns S_OK.

Remarks

When the filter goes from stopped to paused, the CBaseFilter class calls this method on all of the filter's connected pins.

This method does nothing in the base class. Derived classes can override this method; for example, a pin might commit allocators or obtain hardware resources.

The filter graph manager's internal state is not updated until after this member function returns, so do not test the state from this method.

CBasePin::AgreeMediaType

CBasePin Class

Searches for a media type to make a pin connection.

Syntax

virtual HRESULT AgreeMediaType(
    IPin *pReceivePin,
    const CMediaType *pmt
);

Parameters

pReceivePin
Pointer to the receiving pin's IPin interface.
pmt
Pointer to a CMediaType object that specifies a media type, or NULL.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | Success.
VFW_E_NO_ACCEPTABLE_TYPES | No acceptable media type was found.

Remarks

If the pmt parameter is non-NULL and fully specifies a media type, this method attempts a connection using that media type. If the attempt fails, the method returns an error.

If the pmt parameter is NULL or specifies a partial media type, this method tries media types in the following order:

  1. The receiving pin's preferred media types.
  2. This pin's preferred media types.

Preferred media types are enumerated with the EnumMediaTypes method, and the resulting enumerator is passed to the TryMediaTypes method.

CBasePin::AttemptConnection

CBasePin Class

Connects to another pin using a specified media type.

Syntax

virtual HRESULT AttemptConnection(
    IPin *pReceivePin,
    const CMediaType *pmt
);

Parameters

pReceivePin
Pointer to the receiving pin's IPin interface.
pmt
Pointer to a CMediaType object that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | Success.
VFW_E_TYPE_NOT_ACCEPTED | The media type is not acceptable.

Remarks

This method attempts to connect the two pins with a specific media type. If the type is not acceptable, the method fails without trying other media types.

If the media type is acceptable, this method calls the receiving pin's IPin::ReceiveConnection method. Then it calls the CompleteConnect method to complete the connection.

CBasePin::BreakConnect

CBasePin Class

Releases the pin from a connection.

Syntax

virtual HRESULT BreakConnect(void);

Return Value

Returns S_OK.

Remarks

This method is called during pin disconnection by the Disconnect method. It is also called during a connection attempt if the CheckConnect method fails.

This method must free any resources that were obtained by the CheckConnect method. For example, if CheckConnect allocates memory, BreakConnect should free the memory. If CheckConnect queries the connecting pin for an interface, BreakConnect should free the interface.

CBasePin::CanReconnectWhenActive

CBasePin Class

Queries whether the pin supports dynamic reconnections.

Syntax

bool CanReconnectWhenActive(void);

Return Value

Returns a Boolean value that specifies whether the pin can dynamically reconnect. If TRUE, the pin can dynamically reconnect.

Remarks

By default, you must stop a filter before reconnecting any of its pins. If a pin supports dynamic reconnection, however, it can reconnect while the filter is active. For more information, see Dynamic Graph Building.

CBasePin::CBasePin

CBasePin Class

Constructor method.

Syntax

CBasePin(
    TCHAR *pObjectName,
    CBaseFilter *pFilter,
    CCritSec *pLock,
    HRESULT *phr,
    LPCWSTR pName,
    PIN_DIRECTION dir
);

Parameters

pObjectName
String containing the debug name for the object. For more information, see CBaseObject.
pFilter
Pointer to the filter that created this pin.
pLock
Pointer to a CCritSec lock, used to serialize state changes. Can be the same critical section as the filter lock, CBaseFilter.m_pLock.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.
pName
Unicode™ string containing the name of the pin. For more information, see QueryPinInfo.
dir
Member of the PIN_DIRECTION enumeration specifying the direction of the pin.

Remarks

The critical section specified by pLock serializes the pin's state, including its connection status, choice of allocator, media type, and the status of flush operations. Do not use this critical section to serialize streaming operations. For more information, see Data Flow in the Filter Graph.

A filter might create pins in its constructor method, so at this point the pFilter pointer might not refer to a valid object. Store the pointer, but do not dereference it while inside the pin's constructor.

CBasePin::~CBasePin

CBasePin Class

Destructor method.

Syntax

CBasePin(void);

CBasePin::CheckConnect

CBasePin Class

Determines whether a pin connection is suitable.

Syntax

virtual HRESULT CheckConnect(
    IPin *pPin
);

Parameters

pPin
Pointer to the other pin's IPin interface.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
VFW_E_INVALID_DIRECTION | Pin directions are not compatible.

Remarks

This method is called on both pins at the start of the connection process. The connecting pin calls it from within the CBasePin::Connect method, and the receiving pin calls it from within the CBasePin::ReceiveConnection method.

Use this method to determine whether the pin specified by the pPin parameter is suitable for a connection. The base class returns an error if both pins have the same direction (both input, or both output). Derived classes can override this method to verify other features in the pin. For example, the CBaseOutputPin class queries the input pin for its IMemInputPin interface.

If this method fails, the connection fails and the pin calls the BreakConnect method. Use BreakConnect to free any resources obtained in CheckConnect. For example, if CheckConnect calls the QueryInterface method, BreakConnect must release the interface.

CBasePin::CheckMediaType

CBasePin Class

Determines if the pin accepts a specific media type.

Syntax

virtual HRESULT CheckMediaType(
    const CMediaType *pmt
) PURE;

Parameters

pmt
Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns S_OK if the proposed media type is acceptable. Otherwise, returns S_FALSE or an error code.

Remarks

The derived class must override this pure virtual method.

CBasePin::CompleteConnect

CBasePin Class

Completes a connection to another pin.

Syntax

virtual HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin
Pointer to the other pin's IPin interface.

Return Value

Returns S_OK.

Remarks

This method is called on both pins at the end of the connection process. The connecting pin calls it from within the CBasePin::Connect method, and the receiving pin calls it from within the CBasePin::ReceiveConnection method.

In the base class, this method simply returns S_OK. If a derived class has any requirements for completing a connection, it should override this method. For example, the CBaseOutputPin class uses this method to decide the memory allocator.

If this method fails, the overall connection attempt also fails, and the pin disconnects from the receiving pin.

CBasePin::Connect

CBasePin Class

Connects the pin to another pin. Implements the IPin::Connect method.

Syntax

HRESULT Connect(
    IPin *pReceivePin,
    const AM_MEDIA_TYPE *pmt
);

Parameters

pReceivePin
Pointer to the receiving pin's IPin interface.
pmt
Pointer to an AM_MEDIA_TYPE structure that specifies the media type for the connection.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | Success.
VFW_E_ALREADY_CONNECTED | The pin is already connected.
VFW_E_NO_ACCEPTABLE_TYPES | Could not find an acceptable media type.
VFW_E_NOT_STOPPED | The filter is active and the pin does not support dynamic reconnection.
VFW_E_TYPE_NOT_ACCEPTED | The specified media type is not acceptable.

Remarks

The pmt parameter can be NULL. It can also specify a partial media type, with a value of GUID_NULL for the major type, subtype, or format.

In the base class, this method tests whether the pin is already connected and whether the filter is stopped. It delegates the rest of the connection process to the AgreeMediaType method.

CBasePin::ConnectedTo

CBasePin Class

Retrieves a pointer to the connected pin, if any. Implements the IPin::ConnectedTo method.

Syntax

HRESULT ConnectedTo(
    IPin **ppPin
);

Parameters

ppPin
Address of a variable that receives a pointer to the IPin interface of the other pin.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

If the method succeeds, the IPin interface that it returns has an outstanding reference count. Be sure to release it when you are done.

CBasePin::ConnectionMediaType

CBasePin Class

Retrieves the media type for the current pin connection, if any. Implements the IPin::ConnectionMediaType method.

Syntax

HRESULT ConnectionMediaType(
    AM_MEDIA_TYPE *pmt
);

Parameters

pmt
Pointer to an AM_MEDIA_TYPE structure that receives the media type.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_NOT_CONNECTED | Pin is not connected.

Remarks

If the pin is connected, this method copies the media type into the AM_MEDIA_TYPE structure specified by pmt. The caller must free the media type's format block. You can use the Microsoft® Win32® CoTaskMemFree function, or the FreeMediaType helper function.

If the pin is not connected, this method zeroes the memory block specified by pmt and returns an error code.

CBasePin::CurrentRate

CBasePin Class

Retrieves the segment rate, set by the CBasePin::NewSegment method.

Syntax

double CurrentRate(void);

Return Value

Returns the value of m_dRate.

CBasePin::CurrentStartTime

CBasePin Class

Retrieves the segment start time, set by the CBasePin::NewSegment method.

Syntax

REFERENCE_TIME CurrentStartTime(void);

Return Value

Returns the value of m_tStart.

CBasePin::CurrentStopTime

CBasePin Class

Retrieves the segment stop time, set by the CBasePin::NewSegment method.

Syntax

REFERENCE_TIME CurrentStopTime(void);

Return Value

Returns the value of m_tStop.

CBasePin::Disconnect

CBasePin Class

Breaks the current pin connection. Implements the IPin::Disconnect method.

Syntax

HRESULT Disconnect(void);

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_FALSE | The pin was not connected.
S_OK | Success.
VFW_E_NOT_STOPPED | The filter is active and the pin does not support dynamic reconnection.

Remarks

The base class delegates most of the work to the DisconnectInternal method.

CBasePin::DisconnectInternal

CBasePin Class

Breaks the current pin connection.

Syntax

HRESULT DisconnectInternal(void);

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_FALSE | The pin was not connected.
S_OK | Success.
VFW_E_NOT_STOPPED | The filter is active and the pin does not support dynamic reconnection.

Remarks

The Disconnect method delegates the disconnect process to this method. This method calls the BreakConnect method. It also releases the reference count on the other pin, which is held by the m_Connected member variable.

CBasePin::DisplayPinInfo

CBasePin Class

Traces a pin connection during debugging.

Syntax

void DisplayPinInfo(
    IPin *pReceivePin
);

Parameters

pReceivePin
Pointer to the receiving pin.

Remarks

In debug builds, this method calls the DbgLog function to trace a connection attempt. In retail builds, this method does nothing.

CBasePin::DisplayTypeInfo

CBasePin Class

Displays media type information during debugging.

Syntax

void DisplayTypeInfo(
    IPin *pPin,
    const CMediaType *pmt
);

Parameters

pPin
Ignored.
pmt
Pointer to a CMediaType object that specifies the media type.

Remarks

In debug builds, this method calls the DbgLog function to display the specified media type. In retail builds, this method does nothing.

CBasePin::EndOfStream

IPin Interface

Notifies the pin that no additional data is expected. Implements the IPin::EndOfStream method. Call this method only on input pins.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns S_OK.

Remarks

The filter should pass end-of-stream notifications downstream, to the input pins of connected filters. If the filter is a renderer, it should post an EC_COMPLETE event notification to the filter graph manager. For more information, see Data Flow in the Filter Graph.

In the base class, this method does nothing. Derived classes should override this method.

CBasePin::EnumMediaTypes

CBasePin Class

Enumerates the pin's preferred media types. Implements the IPin::EnumMediaTypes method.

Syntax

HRESULT EnumMediaTypes(
    IEnumMediaTypes **ppEnum
);

Parameters

ppEnum
Address of a variable that receives a pointer to the IEnumMediaTypes interface.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

Input pins are not required to enumerate any preferred types. Output pins must enumerate at least one preferred type. Otherwise, both pins could lack a preferred type, making a connection impossible.

The IEnumMediaTypes interface works like a standard COM enumerator. For more information, see Enumerating Objects in a Filter Graph. If the method succeeds, the IEnumMediaTypes interface has an outstanding reference count. Be sure to release it when you are done.

The CEnumMediaTypes base class implements IEnumMediaTypes. It calls the pin's CBasePin::GetMediaType method to enumerate the media types.

CBasePin::GetConnected

CBasePin Class

Retrieves the pin connected to this pin.

Syntax

IPin *GetConnected(void);

Return Value

Returns a pointer to the other pin's IPin interface.

Remarks

If the pin is not connected, this method returns NULL. Call the CBasePin::IsConnected method to determine whether the pin is connected.

CBasePin::GetMediaType

CBasePin Class

Retrieves a preferred media type, by index value.

Syntax

virtual HRESULT GetMediaType(
    int iPosition,
    CMediaType *pMediaType
);

Parameters

iPosition
Zero-based index value.
pMediaType
Pointer to a CMediaType object that receives the media type.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | Success.
VFW_S_NO_MORE_ITEMS | Index out of range.
E_INVALIDARG | Index less than zero.
E_UNEXPECTED | Unexpected error.

Remarks

From the pin's list of preferred media types, this method returns the type with an index value of iPosition. The CEnumMediaTypes class calls this method to enumerate preferred media types.

The base class returns E_UNEXPECTED. Override this method in your derived class.

CBasePin::GetMediaTypeVersion

CBasePin Class

Retrieves a version number for the set of preferred media types.

Syntax

virtual LONG GetMediaTypeVersion(void);

Return Value

Returns the m_TypeVersion member variable.

Remarks

The CBasePin constructor initializes the version number to 1. In the base class, this number never changes. If the pin dynamically changes its list of preferred media types, it should increment the version number whenever the list changes. To increment the version number, call the IncrementTypeVersion method.

The media type enumerator, which is implemented by the CEnumMediaTypes class, uses the version number to keep itself synchronized with the pin.

CBasePin::Inactive

CBasePin Class

Notifies the pin that the filter is no longer active.

Syntax

virtual HRESULT Inactive(void);

Return Value

Returns S_OK.

Remarks

When the filter stops, the CBaseFilter class calls this method on all of the filter's connected pins.

This method does nothing in the base class. Derived classes should override this method to free any resources obtained by the Active method; for example, to decommit the pin's allocators.

The filter graph manager's internal state is not updated until after this method returns, so do not test the state from this method.

CBasePin::IncrementTypeVersion

CBasePin Class

Increments the version number on the set of preferred media types.

Syntax

void IncrementTypeVersion(void);

Remarks

This method increments the m_TypeVersion member variable. If the pin dynamically changes the list of preferred media types, call this method whenever the list changes. For more information, see GetMediaTypeVersion.

CBasePin::IsConnected

CBasePin Class

Determines whether the pin is connected to another pin.

Syntax

BOOL IsConnected(void);

Return Value

Returns TRUE if the pin is connected. Otherwise, returns FALSE.

CBasePin::IsStopped

CBasePin Class

Determines whether the filter containing this pin is stopped.

Syntax

BOOL IsStopped(void);

Return Value

Returns TRUE if the filter is stopped. Otherwise, returns FALSE.

Remarks

Do not call this method from within in the CBasePin constructor method, because the filter might not be initialized yet.

CBasePin::Name

CBasePin Class

Retrieves the pin identifier.

Syntax

LPWSTR Name(void);

Return Value

Returns the value of the m_pName member variable.

CBasePin::NewSegment

CBasePin Class

Notifies the pin that media samples received after this call are grouped as a segment. Implements the IPin::NewSegment method.

Syntax

HRESULT NewSegment(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop,
    double dRate
);

Parameters

tStart
Starting media position of the segment, in 100-nanosecond units.
tStop
End media position of the segment, in 100-nanosecond units.
dRate
Rate at which this segment should be processed, as a percentage of the original rate.

Return Value

Returns S_OK.

Remarks

This method sets the m_tStart, m_tStop, and m_dRate member variables. In your derived class, override this method to pass the notification downstream.

CBasePin::Notify

CBasePin Class

Notifies the pin that a quality change is requested. Implements the IQualityControl::Notify method.

Syntax

HRESULT Notify(
    IBaseFilter *pSelf,
    Quality q
);

Parameters

pSelf
Pointer to the IBaseFilter interface of the filter that delivered the quality-control message.
q
Quality structure that contains the quality-control message.

Return Value

The base class returns E_NOTIMPL.

Remarks

Output pins should override this method to accept quality-control messages.

If an external quality manager was installed (see SetSink), pass the message to that quality manager. Otherwise, the filter should handle the message itself, or pass the message upstream. For more information, see Quality-Control Management.

CBasePin::QueryAccept

CBasePin Class

Determines whether the pin accepts a specified media type. Implements the IPin::QueryAccept method.

Syntax

HRESULT QueryAccept(
    const AM_MEDIA_TYPE *pmt
);

Parameters

pmt
Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns S_TRUE if the media type is acceptable. Otherwise, returns S_FALSE.

Remarks

In the base class, this method delegates to the CheckMediaType method. If CheckMediaType fails, QueryAccept returns S_FALSE.

This method does not hold the pin's critical section (m_pLock). If your derived class dynamically modifies the set of acceptable media types, you should override this method to hold the critical section.

CBasePin::QueryDirection

CBasePin Class

Retrieves the direction of the pin (input or output). Implements the IPin::QueryDirection method.

Syntax

HRESULT QueryDirection(
    PIN_DIRECTION *pPinDir
);

Parameters

pPinDir
Pointer to a variable that receives a member of the PIN_DIRECTION enumerated type.

Return Value

Returns S_OK or E_POINTER.

CBasePin::QueryId

CBasePin Class

Retrieves the pin identifier. Implements the IPin::QueryId method.

Syntax

HRESULT QueryId(
    LPWSTR *Id
);

Parameters

Id
Pointer to the pin identifier.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | Null pointer argument.

Remarks

This method returns a copy of the m_pName member variable.

CBasePin::QueryInternalConnections

CBasePin Class

Retrieves the pins that are connected internally to this pin (within the filter). Implements the IPin::QueryInternalConnections method.

Syntax

HRESULT QueryInternalConnections(
    IPin *apPin,
    ULONG *nPin
);

Parameters

apPin
Address of an array of IPin pointers.
nPin
On input, specifies the size of the array. When the method returns, the value is set to the number of pointers returned in the array.

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | Insufficient array size.
S_OK | Success.
E_FAIL | Failure.
E_NOTIMPL | Not implemented.

The base class returns E_NOTIMPL.

Remarks

On some filters, input pins correspond to particular output pins. For each pin, this method fills an array with pointers to the corresponding pins. If every input pin provides data for every output pin, return E_NOTIMPL.

CBasePin::QueryPinInfo

CBasePin Class

Retrieves information about the pin. Implements the IPin::QueryPinInfo method.

Syntax

HRESULT QueryPinInfo(
    PIN_INFO *pInfo
);

Parameters

pInfo
Pointer to a PIN_INFO structure that receives the pin information.

Return Value

Returns S_OK or E_POINTER.

Remarks

This method uses the m_pName member variable for the achName member of the PIN_INFO structure.

When the method returns, if the pFilter member of the PIN_INFO structure is non-NULL, it has an outstanding reference count. Be sure to release the interface when you are done.

CBasePin::ReceiveConnection

CBasePin Class

Accepts a connection from another pin. Implements the IPin::ReceiveConnection method.

Syntax

HRESULT ReceiveConnection(
    IPin *pConnector,
    AM_MEDIA_TYPE *pmt
);

Parameters

pConnector
Pointer to the connecting pin's IPin interface.
pmt
Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | Success.
E_POINTER | Null pointer argument.
VFW_E_ALREADY_CONNECTED | The pin is already connected.
VFW_E_NOT_STOPPED | The filter is active and the pin does not support dynamic reconnection.
VFW_E_TYPE_NOT_ACCEPTED | The specified media type is not acceptable.

Remarks

The pin that initiates the connection calls this method on the receiving pin. If the receiving pin returns an error code, the connection fails.

In the base class, this method performs the following steps:

  • Checks whether the pin is already connected.
  • Checks whether the filter is stopped.
  • Calls the CheckConnect method to test whether the connecting pin is suitable.
  • Calls the CheckMediaType method to test whether the media type is acceptable.

If all of these steps succeed, the method calls the CompleteConnect and SetMediaType methods to complete the connection. If CheckConnect or CheckMediaType fail, the method calls the BreakConnect method.

CBasePin::Run

CBasePin Class

Notifies the pin that the filter is now running.

Syntax

HRESULT Run(
    REFERENCE_TIME tStart
);

Parameters

tStart
Start time as passed to the filter's IMediaFilter::Run method.

Return Value

Returns S_OK.

Remarks

When the filter goes from paused to running, the CBaseFilter class calls this method on all of the filter's pins.

This method does nothing in the base class. Derived classes can override this method. For example, a pin might start a worker thread that delivers samples.

The filter graph manager's internal state is not updated until after this member function returns, so do not test the state from this method.

CBasePin::SetMediaType

CBasePin Class

Sets the media type for the connection.

Syntax

virtual HRESULT SetMediaType(
    const CMediaType *pmt
);

Parameters

pmt
Pointer to a CMediaType object that specifies the media type.

Return Value

Returns S_OK.

Remarks

This method establishes the format for a pin connection. Before calling this method, the pin calls the CBasePin::CheckMediaType method to determine whether the media type is acceptable. Therefore, the pmt parameter is assumed to be an acceptable media type.

In the base class, this method sets the m_mt member variable and returns S_OK. A derived class can override this method if it requires notification when the media type is set.

CBasePin::SetReconnectWhenActive

CBasePin Class

Specifies whether the pin supports dynamic reconnections.

Syntax

void SetReconnectWhenActive(
    bool bCanReconnect
);

Parameters

bCanReconnect
Boolean value that specifies whether the pin can dynamically reconnect. If TRUE, the pin can dynamically reconnect.

Remarks

By default, you must stop a filter before reconnecting any of its pins. If the pin can reconnect while the filter is active, call this method with a value of TRUE. For more information, see Dynamic Graph Building.

CBasePin::SetSink

CBasePin Class

Sets an external quality manager. Implements the IQualityControl::SetSink method.

Syntax

HRESULT SetSink(
    IQualityControl *piqc
);

Parameters

piqc
Pointer to the IQualityControl interface of the quality manager.

Return Value

Returns S_OK.

Remarks

Call this method to redirect quality-control messages to an external quality manager. For more information, see Quality-Control Management.

CBasePin::TryMediaTypes

CBasePin Class

Given a list of media types, tries to complete a connection using one of those types.

Syntax

virtual HRESULT TryMediaTypes(
    IPin *pReceivePin,
    const CMediaType *pmt,
    IEnumMediaTypes *pEnum
);

Parameters

pReceivePin
Pointer to the receiving pin's IPin interface.
pmt
Pointer to a CMediaType object that limits the possible media types, or NULL.
pEnum
Pointer to an IEnumMediaTypes interface, used to enumerate the list of media types.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | Success.
VFW_E_NO_ACCEPTABLE_TYPES | Did not find an acceptable media type.

Remarks

For each media type returned by the IEnumMediaTypes interface, this method attempts a connection by calling the AttemptConnection method.

If the pmt parameter is non-NULL, the pin skips media types that do not match this type. The pmt parameter can specify a partial media type. A partial media type has a value of GUID_NULL for either the major type, the subtype, or the format. The GUID_NULL value matches any type, similar to a "wildcard" value.


CBasePropertyPage Class

CBasePropertyPage class hierarchy

Property pages can be implemented on filters to provide access to custom properties on the filter. This can be useful for developing and debugging the filter, because GraphEdit displays these property pages. Also, the Microsoft® Windows Media™ Player control queries filters in its underlying filter graph for the property pages they support and exposes them to the user. A good example is the video renderer, which exposes quality management information (such as frame rate) through a property page.

This class provides the framework for a property page associated with a filter and implements the IPropertyPage interface. A property page is a Component Object Model (COM) object, which should be created with a resource ID for a dialog box that will be loaded when required. It should also be given a resource ID for a title string when created.

In addition to implementing the IPropertyPage interface methods, this class provides several virtual member functions that can be overridden and specialized by the derived class (they return NOERROR by default). These virtual member functions are called at specific events, such as when the property page is activated or deactivated, connected or disconnected, when the changes to properties are to be applied, or when messages to the dialog box are received.

A filter exposing custom property pages should also expose the same functionality to an application through a custom interface. Otherwise, an application has no way to control the filter without displaying the property page. For example, the video renderer supports the IQualProp interface to access the same quality management information. In fact, the renderer property page uses that interface to get the information for its property page. To make it easier for applications to access their custom interfaces, filters should also implement their custom interfaces in a plug-in distributor (PID), which is an object that is aggregated with the filter graph manager. Typically, the PID implements its associated filter's interface by simply passing calls through from the application to the filter interface.

Protected Data Members

m_bDirty | Flag to determine whether anything has changed.
m_DialogId | Resource identifier for the dialog box.
m_Dlg | Dialog box window handle for the property page.
m_hwnd | Window handle for the property page.
m_pPageSite | IPropertyPage interface pointer used to access the filter's property information.
m_TitleId | Resource identifier for the property page title.

Member Functions

CBasePropertyPage Constructs a CBasePropertyPage object.

Overridable Member Functions

OnActivate | Called when the property page is activated.
OnApplyChanges | Called when the user applies changes to the property page.
OnConnect | Called when the property page is connected to the filter.
OnDeactivate | Called when the property page is dismissed.
OnDisconnect | Called when the property page is disconnected from the owning filter.
OnReceiveMessage | Called when a message is sent to the property page dialog box window.

Implemented INonDelegatingUnknown Methods

NonDelegatingAddRef | Default implementation increments the owning filter's reference count.
NonDelegatingQueryInterface | Called to retrieve CBasePropertyPage interfaces. Override this member function to pass out pointers to any interfaces added by the derived class.
NonDelegatingRelease | Default implementation decrements the owning filter's reference count.

Implemented IPropertyPage Methods

Activate | Creates a dialog box window for the property page.
Apply | Applies current property page values to the underlying object.
Deactivate | Destroys the window created with CBasePropertyPage::Activate.
GetPageInfo | Retrieves information about the property page.
Help | Invokes Help in response to user request.
IsPageDirty | Indicates whether the property page has changed since activated or since the most recent call to CBasePropertyPage::Apply.
Move | Positions and resizes the property page dialog box within the frame.
SetObjects | Provides the property page with an array of IUnknown pointers for objects associated with this property page.
SetPageSite | Initializes a property page and provides the page with a pointer to the IPropertyPageSite interface through which the property page communicates with the property frame.
Show | Makes the property page dialog box visible or invisible.
TranslateAccelerator | Provides a pointer to an MSG structure that specifies a keystroke to process.

CBasePropertyPage::Activate

CBasePropertyPage Class

Creates the property page dialog box.

Syntax

HRESULT Activate(
    HWND hwndParent,
    LPCRECT prect,
    BOOL fModal
    );

Parameters

hwndParent
Handle to the parent window of the dialog box.
prect
Pointer to the RECT structure that contains the dialog box's screen position.
fModal
Value that specifies a modal dialog box if TRUE, or a modeless dialog box if FALSE.

Return Value

Returns E_OUTOFMEMORY if the dialog box creation fails, or E_UNEXPECTED if a property page already exists.

Remarks

This member function implements the COM IPropertyPage::Active method, which creates a dialog box for the property page (without a frame, caption, system menu, or controls) using hwndParent as the parent window and prect as the positioning rectangle.

The property page maintains the window handle created in this process, which it uses to destroy the dialog box within CBasePropertyPage::Deactivate.

CBasePropertyPage::Apply

CBasePropertyPage Class

Applies current property page values to the underlying object.

Syntax

HRESULT Apply(void);

Return Value

Returns E_UNEXPECTED if CBasePropertyPage::SetObjects has not been called or if the m_pPageSite data member has not been initialized with a pointer to the filter's property page.

Remarks

This member function implements the COM IPropertyPage::Apply method. The object to be changed is provided through a previous call to CBasePropertyPage::SetObjects. This should be the filter's IUnknown interface. Therefore, this member function should not fail because of nonexistent interfaces.

This member function sets the m_bDirty data member to FALSE and calls the virtual CBasePropertyPage::OnApplyChanges member function, which should be overridden in the derived class to apply the changes to the properties.

CBasePropertyPage::CBasePropertyPage

CBasePropertyPage Class

Constructs a CBasePropertyPage object.

Syntax

CBasePropertyPage(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    int DialogId,
    int TitleId
    );

Parameters

pName
Pointer to the name of the property page object for debugging purposes.
pUnk
Pointer to the COM delegating object.
DialogId
Resource ID for the dialog box.
TitleId
Resource ID for the dialog box title.

Remarks

This constructor sets the CBasePropertyPage data members as follows:

  • m_DialogId is set to DialogId.
  • m_TitleId is set to TitleId.
  • m_hwnd is set to NULL.
  • m_Dlg is set to NULL.
  • m_pPageSite is set to NULL.
  • m_bDirty is set to FALSE.

CBasePropertyPage::Deactivate

CBasePropertyPage Class

Destroys the window created with CBasePropertyPage::Activate.

Syntax

HRESULT Deactivate(void);

Return Value

Returns E_UNEXPECTED if the data member m_hwnd does not contain a window handle for the property page.

Remarks

This member function implements the COM IPropertyPage::Deactivate method. It calls the virtual CBasePropertyPage::OnDeactivate member function and then destroys the property page dialog box.

CBasePropertyPage::GetPageInfo

CBasePropertyPage Class

Retrieves information about the property page.

Syntax

HRESULT GetPageInfo(
    LPPROPPAGEINFO pPageInfo
    );

Parameters

pPageInfo
Pointer to the caller-allocated PROPPAGEINFO structure in which the property page stores its page information. All allocations stored in this structure become the caller's responsibility.

Return Value

Returns E_OUTOFMEMORY if the function cannot allocate memory for the property page title.

Remarks

This member function implements the COM IPropertyPage::GetPageInfo method. It calls the GetDialogSize function to obtain the dialog box size and sets it to a default value in case this call fails.

CBasePropertyPage::Help

CBasePropertyPage Class

Invokes Help in response to user request.

Syntax

HRESULT Help(
    LPCWSTR lpszHelpDir
    );

Parameters

lpszHelpDir
Pointer to the string under the HelpDir key in the property page's CLSID information in the registry. If HelpDir does not exist, this will be the path found in the InProcServer32 entry minus the server file name.

Return Value

Returns E_NOTIMPL by default.

Remarks

This member function implements the COM IPropertyPage::Help method, but only as a placeholder. The function does nothing but return E_NOTIMPL.

Calls to this member function must occur between calls to CBasePropertyPage::Activate and CBasePropertyPage::Deactivate.

If the page fails this member function (such as E_NOTIMPL), the frame will attempt to use the pszHelpFile and dwHelpContext fields of the PROPPAGEINFO structure obtained through CBasePropertyPage::GetPageInfo. Therefore, the derived class should either implement CBasePropertyPage::Help or return Help information through CBasePropertyPage::GetPageInfo.

CBasePropertyPage::IsPageDirty

CBasePropertyPage Class

Indicates whether the property page has changed since activated or since the most recent call to CBasePropertyPage::Apply.

Syntax

HRESULT IsPageDirty(void);

Return Value

Returns S_OK if the value state of the property page is dirty, that is, it has changed and is different from the state of the objects. Returns S_FALSE if the value state of the page has not changed and is current with that of the objects.

Remarks

This member function implements the COM IPropertyPage::IsPageDirty method. It returns the value of the m_bDirty data member.

CBasePropertyPage::Move

CBasePropertyPage Class

Positions and resizes the property page dialog box within the frame.

Syntax

HRESULT Move(
    LPCRECT prect
    );

Parameters

prect
Pointer to the RECT structure containing the positioning information for the property page dialog box.

Return Value

Returns E_UNEXPECTED if the m_hwnd data member does not contain a window handle for the property page.

Remarks

This member function implements the COM IPropertyPage::Move method by calling the Microsoft® Win32® MoveWindow function. This member function is called from the CBasePropertyPage::Activate member function to position the property page dialog box.

CBasePropertyPage::NonDelegatingAddRef

CBasePropertyPage Class

Increments the reference count for an interface.

Syntax

ULONG NonDelegatingAddRef(void);

Return Value

Returns the object's reference count.

Remarks

This member function implements the INonDelegatingUnknown::NonDelegatingAddRef method. It increments the owning filter's reference count.

CBasePropertyPage::NonDelegatingQueryInterface

CBasePropertyPage Class

Retrieves an interface and increments the reference count.

Syntax

HRESULT NonDelegatingQueryInterface(
    REFIID riid,
    void **ppv
    );

Parameters

riid
Reference identifier.
ppv
Address of a pointer to the interface.

Return Value

Returns E_POINTER if ppv is invalid. Returns NOERROR if the query is successful or E_NOINTERFACE if it is not.

Remarks

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method and passes out references to the IPropertyPage interface. It then calls the CUnknown::NonDelegatingQueryInterface base class member function. Override this class to return other interfaces on the object in the derived class.

CBasePropertyPage::NonDelegatingRelease

CBasePropertyPage Class

Decrements the reference count for an interface.

Syntax

ULONG NonDelegatingRelease(void);

Return Value

Returns the reference count.

Remarks

This member function implements the INonDelegatingUnknown::NonDelegatingRelease method. It releases a reference count to the owning filter.

CBasePropertyPage::OnActivate

CBasePropertyPage Class

Called when the property page is activated.

Syntax

virtual HRESULT OnActivate(void);

Return Value

Returns NOERROR by default. The overriding member function should return a valid HRESULT value.

Remarks

This member function is called from the CBasePropertyPage::Activate member function to notify the derived class when the property page is displayed. Override this member function to initialize values in the dialog box. This can be done by calling the Win32 SetDlgItemText function with data member values previously initialized when the property page was connected (in the overridden CBasePropertyPage::OnConnect member function).

For example:

// Set the text fields in the property page.

HRESULT CQualityProperties::OnActivate()
{
    SetEditFieldData();
    return NOERROR;
}

// Initialize the property page fields.

void CQualityProperties::SetEditFieldData()
{
    ASSERT(m_pQualProp);
    TCHAR buffer[50];

    wsprintf(buffer,"%d", m_iDropped);
    SendDlgItemMessage(m_Dlg, IDD_QDROPPED, WM_SETTEXT, 0, (DWORD) (LPSTR) buffer);
    wsprintf(buffer,"%d", m_iDrawn);
    SendDlgItemMessage(m_Dlg, IDD_QDRAWN, WM_SETTEXT, 0, (DWORD) (LPSTR) buffer);
    wsprintf(buffer,"%d.%02d", m_iFrameRate/100, m_iFrameRate%100);
    SendDlgItemMessage(m_Dlg, IDD_QAVGFRM, WM_SETTEXT, 0, (DWORD) (LPSTR) buffer);
    wsprintf(buffer,"%d", m_iFrameJitter);
    SendDlgItemMessage(m_Dlg, IDD_QJITTER, WM_SETTEXT, 0, (DWORD) (LPSTR) buffer);
    wsprintf(buffer,"%d", m_iSyncAvg);
    SendDlgItemMessage(m_Dlg, IDD_QSYNCAVG, WM_SETTEXT, 0, (DWORD) (LPSTR) buffer);
    wsprintf(buffer,"%d", m_iSyncDev);
    SendDlgItemMessage(m_Dlg, IDD_QSYNCDEV, WM_SETTEXT, 0, (DWORD) (LPSTR) buffer);
}

CBasePropertyPage::OnApplyChanges

CBasePropertyPage Class

Called when the user applies changes to the property page.

Syntax

virtual HRESULT OnApplyChanges(void);

Return Value

Returns NOERROR by default. The overriding member function should return a valid HRESULT value.

Remarks

Override this member function if your property page allows users to set property values. When this member function is called, process the changed properties. For example, set appropriate data members in the derived class to the new values, or call methods in the filter to set the properties. The overriding member function is responsible for calling CBasePropertyPage::IsPageDirty to set the m_bDirty data member to TRUE if the properties in the object do not reflect those in the property page when this member function exits.

CBasePropertyPage::OnConnect

CBasePropertyPage Class

Called when the property page is connected to the filter.

Syntax

virtual HRESULT OnConnect(
    IUnknown *pUnknown
    );

Parameters

pUnknown
Pointer to the IUnknown interface of the filter associated with the property page.

Return Value

Returns NOERROR by default. The overriding member function should return a valid HRESULT value.

Remarks

This member function is called from the CBasePropertyPage::SetObjects member function with the ppUnk parameter of that member function, which should be the filter's IUnknown interface. Override this member function to acquire property values to be sent to the property page dialog box later (in CBasePropertyPage::OnActivate).

The following example illustrates the use of this member function.

// Give us the filter to communicate with.

HRESULT CQualityProperties::OnConnect(IUnknown *pUnknown)
{
    ASSERT(m_pQualProp == NULL);

    // Ask the renderer for its IQualProp interface.

    HRESULT hr = pUnknown->QueryInterface(IID_IQualProp,(void **)&m_pQualProp);
    if (FAILED(hr)) {
        return E_NOINTERFACE;
    }

    ASSERT(m_pQualProp);

    // Get quality data for the page.

    m_pQualProp->get_FramesDroppedInRenderer(&m_iDropped);
    m_pQualProp->get_FramesDrawn(&m_iDrawn);
    m_pQualProp->get_AvgFrameRate(&m_iFrameRate);
    m_pQualProp->get_Jitter(&m_iFrameJitter);
    m_pQualProp->get_AvgSyncOffset(&m_iSyncAvg);
    m_pQualProp->get_DevSyncOffset(&m_iSyncDev);
    return NOERROR;
}

CBasePropertyPage::OnDeactivate

CBasePropertyPage Class

Called when the property page is dismissed.

Syntax

virtual HRESULT OnDeactivate(void);

Return Value

Returns NOERROR by default. The overriding member function should return a valid HRESULT value.

Remarks

This member function is called from the CBasePropertyPage::Deactivate member function when the user closes the property page. Override this member function to handle any special requirements at that time.

CBasePropertyPage::OnDisconnect

CBasePropertyPage Class

Called when the property page is disconnected from the owning filter.

Syntax

virtual HRESULT OnDisconnect(void);

Return Value

Returns NOERROR by default. The overriding member function should return a valid HRESULT value.

Remarks

This member function is called from the CBasePropertyPage::SetObjects member function when the property page is disconnected from the filter. Override this member function to handle any special requirements at that time, such as releasing reference counts on underlying property interfaces.

The following example demonstrates an implementation of this member function in a derived class.

// Release any IQualProp interface you have.

HRESULT CQualityProperties::OnDisconnect()
{
    // Release the interface.

    if (m_pQualProp == NULL) {
        return E_UNEXPECTED;
    }

    m_pQualProp->Release();
    m_pQualProp = NULL;
    return NOERROR;
}

CBasePropertyPage::OnReceiveMessage

CBasePropertyPage Class

Called when a message is sent to the property page dialog box.

Syntax

virtual BOOL OnReceiveMessage(
    HWND hwnd,
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam
    );

Parameters

hwnd
Window procedure that received the message.
uMsg
Message.
wParam
Additional message information. This parameter's content depends on the value of the uMsg parameter.
lParam
Additional message information. This parameter's content depends on the value of the uMsg parameter.

Return Value

By default, returns the value returned by the Win32 DefWindowProc function.

Remarks

The default implementation of this member function calls DefWindowProc with the supplied parameters. Override this member function for special handling of messages.

CBasePropertyPage::SetObjects

CBasePropertyPage Class

Provides the property page with an IUnknown pointer for objects associated with this property page.

Syntax

HRESULT SetObjects(
    ULONG cObjects,
    LPUNKNOWN *ppUnk
    );

Parameters

cObjects
Number of IUnknown pointers in the array pointed to by ppUnk. This number should be 1 or 0. If it is 0, the property page must release any pointers previously passed to this method.
ppUnk
Address of a pointer to a single IUnknown interface identifying a unique object affected by the property sheet in which this (and possibly other) property page is displayed. The property page must cache this pointer by calling IUnknown::AddRef.

Return Value

Returns E_POINTER if ppUnk is null, E_UNEXPECTED if cObjects is greater than 1, and otherwise returns the value returned by the CBasePropertyPage::OnConnect or CBasePropertyPage::OnDisconnect member function that it calls.

Remarks

This member function implements the COM IPropertyPage::SetObjects method. This member function calls the virtual CBasePropertyPage::OnConnect member function when the cObjects value is 1, or the virtual CBasePropertyPage::OnDisconnect member function when the cObjects value is 0. Override these virtual member functions to acquire (by calling IUnknown::AddRef) or release (by calling IUnknown::Release) interfaces to which the property page applies.

The caller must provide the property page with this object before calling CBasePropertyPage::Activate, and should call SetObjects with 0-v as the parameter when deactivating the page or when releasing the object entirely.

This member function allows only one object to be associated with the property page.

CBasePropertyPage::SetPageSite

CBasePropertyPage Class

Initializes a property page and provides the page with a pointer to the IPropertyPageSite interface through which the property page communicates with the property frame.

Syntax

HRESULT SetPageSite(
    LPPROPERTYPAGESITE pPageSite
    );

Parameters

pPageSite
Pointer to the IPropertyPageSite interface of the page site that manages and provides services to this property page within the entire property sheet.

Return Value

Returns E_UNEXPECTED if if the m_pPageSite data member has not been initialized with a pointer to the filter's property page.

Remarks

This member function implements the COM IPropertyPage::SetPageSite method. When passed an IPropertyPageSite interface, it reference counts the interface and assigns it to m_pPageSite. When passed a null value, it releases the reference count on the IPropertyPageSite interface.

CBasePropertyPage::Show

CBasePropertyPage Class

Makes the property page dialog box visible or invisible.

Syntax

HRESULT Show(
    UINT nCmdShow
    );

Parameters

nCmdShow
Command describing whether to become visible. Only SW_SHOWNORMAL, SW_SHOW, and SW_HIDE are accepted.

Return Value

Returns E_UNEXPECTED if the data member m_hwnd does not contain a window handle for the property page. Returns E_INVALIDARG if the nCmdShow parameter is not equal to SW_SHOW or SW_SHOWNORMAL (show) or SW_HIDE (hide).

Remarks

If the page is made visible, the page should set the focus to itself, specifically to the first property on the page. This member function implements the COM IPropertyPage::Show method. This is called just before exiting the CBasePropertyPage::Activate member function with the nCmdShow SHOW_NORMAL value.

CBasePropertyPage::TranslateAccelerator

CBasePropertyPage Class

Provides a pointer to an MSG structure that specifies a keystroke to process.

Syntax

HRESULT TranslateAccelerator(
    LPMSG lpMsg
    );

Parameters

lpMsg
Pointer to the MSG structure describing the keystroke to process.

Return Value

Returns E_NOTIMPL by default.

Remarks

This member function implements the COM IPropertyPage::TranslateAccelerator method. Calls to this member function must occur after a call to CBasePropertyPage::Activate and before the corresponding call to CBasePropertyPage::Deactivate. Override this member function to implement keyboard accelerators for the property page.


CBaseReferenceClock Class

CBaseReferenceClock class hierarchy

Implements a reference clock.

Declaration: Refclock.h.

This class implements a reference clock that supports the IReferenceClock interface. If a filter can provide a reference clock for the filter graph—for example, by accessing a hardware device—it can use this class to implement the clock.

The CBaseReferenceClock object maintains two distinct time values:

  • Internally, the GetPrivateTime method returns the actual time kept by the clock.
  • Externally, the GetTime method returns the reference time for the filter graph.

It is valid for the internal clock to run backward over brief periods. For example, if the clock drifts forward, the filter can adjust it backwards. (See SetTimeDelta.) The GetTime method uses the time values reported by GetPrivateTime. However, the reference time is monotonically increasing; in other words, it never runs backward. Therefore, if the internal clock runs backward, GetTime continues to report the old time until the internal clock catches up.

For example, the two methods might return the following sequences:

GetPrivateTime: 105, 106, 103, 104, 105, 106, 107, 108
GetTime:        105, 106, 106, 106, 106, 106, 107, 108

On the third clock tick, the internal clock jumps backward to 103. The GetTime method continues to report 106 until the internal clock catches up.

By default, GetPrivateTime returns the system time, through a call to the timeGetTime function. A filter that is providing a reference clock from an external device can do one of the following:

  • Override GetPrivateTime to return the time from the device.
  • Monitor the discrepancy between the device time and the system time, and call SetTimeDelta to make corrections.

This class uses a CAMSchedule object to handle scheduling of advise requests. For details, see the documentation for the CAMSchedule class.

Protected Member Variables
m_pSchedule | CAMSchedule object that handles scheduling tasks for the clock.
Protected Methods
~CBaseReferenceClock | Destructor method.
Public Methods
CBaseReferenceClock | Constructor method.
GetPrivateTime | Retrieves the real time from the clock.
SetTimeDelta | Adjusts the internal clock time.
GetSchedule | Retrieves a pointer to the clock's scheduling object.
TriggerThread | Wakes up the worker thread that handles scheduling.
IReferenceClock Methods
GetTime | Retrieves the current reference time.
AdviseTime | Creates a one-shot advise request.
AdvisePeriodic | Creates a periodic advise request.
Unadvise | Removes a pending advise request.
Helper Functions
ConvertToMilliseconds | Converts a reference time to milliseconds.

CBaseReferenceClock.m_pSchedule

CBaseReferenceClock Class

CAMSchedule object that handles scheduling tasks for the clock.

Syntax

CAMSchedule * const m_pSchedule;

CBaseReferenceClock::AdvisePeriodic

CBaseReferenceClock Class

Creates a periodic advise request. Implements the IReferenceClock::AdvisePeriodic method.

Syntax

HRESULT AdvisePeriodic(
    REFERENCE_TIME StartTime,
    REFERENCE_TIME PeriodTime,
    HSEMAPHORE hSemaphore,
    DWORD *pdwAdviseToken
);

Parameters

StartTime
Time of the first notification, in 100-nanosecond units. Must be greater than zero and less than MAX_TIME.
PeriodTime
Time between notifications, in 100-nanosecond units. Must be greater than zero.
hSemaphore
Handle to a semaphore, created by the caller.
pdwAdviseToken
Pointer to a variable that receives an identifier for the advise request.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success
E_INVALIDARG | Invalid time values
E_OUTOFMEMORY | Failure
E_POINTER | NULL pointer argument

Remarks

At each notification time, the clock releases the semaphore specified in the hSemaphore parameter. When no further notifications are required, call the Unadvise method and pass the pdwAdviseToken value returned from this call.

CBaseReferenceClock::AdviseTime

CBaseReferenceClock Class

Creates a one-shot advise request. Implements the IReferenceClock::AdviseTime method.

Syntax

HRESULT AdviseTime(
    REFERENCE_TIME baseTime,
    REFERENCE_TIME streamTime,
    HEVENT hEvent,
    DWORD *pdwAdviseToken
);

Parameters

baseTime
Base reference time, in 100-nanosecond units.
streamTime
Stream offset time, in 100-nanosecond units.
hEvent
Handle to an event, created by the caller.
pdwAdviseToken
Pointer to a variable that receives an identifier for the advise request.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success
E_INVALIDARG | Invalid time values
E_OUTOFMEMORY | Failure
E_POINTER | NULL pointer argument

Remarks

This method creates a one-shot advise request for the reference time baseTime + streamTime. The sum must be greater than zero and less than MAX_TIME, or the method returns E_INVALIDARG. At the requested time, the clock signals the event specified in the hEvent parameter.

To cancel the notification before the time is reached, call the Unadvise method and pass the pdwAdviseToken value returned from this call. After the notification has occurred, the clock automatically clears it, so it is not necessary to call Unadvise. However, it is not an error to do so.

CBaseReferenceClock::CBaseReferenceClock

CBaseReferenceClock Class

Constructor method.

Syntax

CBaseReferenceClock(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    CAMSchedule *pSched = NULL
);

Parameters

pName
Pointer to a string containing the name of the object. For more information, see CBaseObject.
pUnk
Pointer to the IUnknown interface of the delegating object.
phr
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
pSched
Pointer to a CAMSchedule object. If NULL, this method creates a new CAMSchedule object.

CBaseReferenceClock::~CBaseReferenceClock

CBaseReferenceClock Class

Destructor method.

Syntax

CBaseReferenceClock(void);

CBaseReferenceClock::GetPrivateTime

CBaseReferenceClock Class

Retrieves the real time from the clock.

Syntax

virtual REFERENCE_TIME GetPrivateTime(void);

Return Value

Returns the current clock time, in 100-nanosecond units.

Remarks

This method returns the real time reported by the clock. External callers use the GetTime method, which calls this method. Unlike the GetTime method, the internal clock is allowed to go backward. If that happens, the GetTime method continues to return the last time that it reported, until the GetPrivateTime method catches up.

CBaseReferenceClock::GetSchedule

CBaseReferenceClock Class

Retrieves a pointer to the clock's scheduling object.

Syntax

CAMSchedule* GetSchedule(void);

Return Value

Returns the m_pSchedule member variable.

CBaseReferenceClock::GetTime

CBaseReferenceClock Class

Retrieves the current reference time. Implements the IReferenceClock::GetTime method.

Syntax

HRESULT GetTime(
    REFERENCE_TIME *pTime
);

Parameters

pTime
Pointer to a variable that receives the current time, in 100-nanosecond units.

Return Value

Returns one of the HRESULT values shown in the following table.

E_POINTER | NULL pointer argument.
S_FALSE | Returned time is the same as the previous value.
S_OK | Success.

Remarks

This method calls the GetPrivateTime method to determine the real clock time. If the clock time is strictly greater than the previous value, GetTime uses the clock time and returns S_OK. Otherwise, GetTime uses the previous value and returns S_FALSE. Therefore, the internal clock can run backward for a short period, without causing the reference time to run backward. Instead, the reference time will "stall" at the same value until the internal clock catches up.

CBaseReferenceClock::SetTimeDelta

CBaseReferenceClock Class

Adjusts the internal clock time.

Syntax

HRESULT SetTimeDelta(
    const REFERENCE_TIME& TimeDelta
);

Parameters

TimeDelta
Amount to adjust the clock time, in 100-nanosecond units. A positive value moves the clock forward, and a negative value moves the clock backward.

Return Value

Returns S_OK.

Remarks

The derived class can use this method to adjust the internal clock, if it drifts from the device that is providing timing information.

The GetTime method never returns decreasing values. If you adjust the clock backwards, GetTime returns the previous value until the clock reaches that value again.

CBaseReferenceClock::TriggerThread

CBaseReferenceClock Class

Wakes up the worker thread that handles scheduling.

Syntax

void TriggerThread(void);

Return Value

No return value.

Remarks

The clock uses a worker thread that calls the CAMSchedule::Advise method at appropriate times. The derived class can call TriggerThread to wake up the thread.

CBaseReferenceClock::Unadvise

CBaseReferenceClock Class

Removes a pending advise request. Implements the IReferenceClock::Unadvise method.

Syntax

HRESULT Unadvise(
    DWORD dwAdviseToken
);

Parameters

dwAdviseToken
Identifier of the request to remove. Use the value returned by the AdviseTime or AdvisePeriodic methods in the pdwAdviseToken parameter.

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | Not found.
S_OK | Success.

ConvertToMilliseconds Function

CBaseReferenceClock Class

Converts a reference time to milliseconds.

Syntax

LONGLONG ConvertToMilliseconds(
    const REFERENCE_TIME& RT
);

Parameters

RT
Reference time, in 100-nanosecond units.

Return Value

Returns the reference time converted to milliseconds.


CBaseRenderer Class

CBaseRenderer class hierarchy

Base class for implementing renderer filters. It supports one input pin, implemented by the CRendererInputPin class.

Declaration: Renbase.h

To use this class, declare a derived class that inherits CBaseRenderer. At a minimum, the derived class must implement the following methods, which are declared as pure virtual in the base class:

  • CheckMediaType: Accepts or rejects proposed media types. The filter calls this method during the pin connection process.
  • DoRenderSample: Renders a sample. The filter calls this method for every sample that it receives while running.

The base class handles state changes and synchronization issues. It also schedules samples for rendering, although it does not implement any quality-control measures.

The base class also declares several "handler" methods. These are methods that the filter calls at specific points in the streaming process. They do nothing in the base class, but the derived class can override them. In the table that follows, they are listed under the heading Public Methods: Handlers.

The OnReceiveFirstSample handler deserves special mention. The filter calls this method if it receives a sample while the filter is paused. That can occur if the graph switches from stopped to paused, or if the graph is seeked while paused. Video renderers typically use the sample to display a still frame. When the filter switches from paused to running, it sends the same sample to the DoRenderSample method, as the first sample in the stream.

Scheduling

When the upstream filter calls the input pin's IMemInputPin::Receive method to deliver a sample, the pin passes this call to the filter's Receive method. The filter either drops the sample, renders it immediately, or schedules it for rendering.

If the sample has no time stamps, or if no reference clock is available, the filter renders the sample immediately. Otherwise, the filter calls the ShouldDrawSampleNow method to determine what to do. By default, the sample is scheduled based on its time stamps. The derived class can override ShouldDrawSampleNow to support quality control.

To schedule a sample, the filter calls the IReferenceClock::AdviseTime method, which creates an advise request. The Receive method then blocks until the scheduled time, or until the filter changes state. Blocking prevents the upstream filter from delivering more samples until the current sample is rendered.

When the upstream filter calls the IPin::EndOfStream method to signal the end of the stream, the filter sends an EC_COMPLETE event to the filter graph manager. The filter waits for the current sample's stop time before sending the event.

Protected Member Variables
m_bAbort | Flag that indicates whether to stop rendering and reject further samples.
m_bEOS | Flag that indicates whether end-of-stream was reached.
m_bEOSDelivered | Flag that indicates whether the filter has posted the EC_COMPLETE event.
m_bInReceive | Flag that indicates whether the filter is processing a Receive call.
m_bRepaintStatus | Flag that enables or disables repaint events.
m_bStreaming | Flag that indicates whether the filter is streaming data.
m_dwAdvise | Identifier of the timer event that schedules rendering.
m_EndOfStreamTimer | Timer-event identifier, for scheduling EC_COMPLETE notifications.
m_evComplete | Event that is signaled when a state transition is complete.
m_InterfaceLock | Filter-state lock.
m_pInputPin | Pointer to the filter's input pin.
m_pMediaSample | Pointer to the current media sample.
m_pPosition | Helper object to pass seek commands upstream.
m_pQSink | Pointer to the object that receives quality-control messages.
m_RendererLock | Streaming lock.
m_RenderEvent | Event used to schedule rendering.
m_SignalTime | Stop time on the current sample.
m_ThreadSignal | Event used to release the streaming thread.
Public Methods
CancelNotification | Cancels the timer event that schedules rendering. Virtual.
CBaseRenderer | Constructor method.
~CBaseRenderer | Destructor method.
GetMediaPositionInterface | Retrieves the filter's IMediaPosition and IMediaSeeking interface pointers. Virtual.
GetPin | Retrieves a pin. Virtual.
GetPinCount | Retrieves the number of pins. Virtual.
GetSampleTimes | Retrieves the time stamps from a sample. Virtual.
OnDisplayChange | Posts an EC_DISPLAY_CHANGED event to the filter graph manager.
PrepareReceive | Prepares to render a sample. Virtual.
Receive | Receives the next media sample in the stream. Virtual.
Render | Renders a sample. Virtual.
ScheduleSample | Schedules a sample for rendering. Virtual.
SendNotifyWindow | Notifies the upstream filter of the video window handle.
SendRepaint | Sends a repaint event to the filter graph manager.
SetMediaType | Called when the pin's media type is set. Virtual.
SignalTimerFired | Clears the timer identifier used to schedule rendering.
SourceThreadCanWait | Holds or releases the streaming thread. Virtual.
WaitForReceiveToComplete | Waits for the Receive method to complete.
WaitForRenderTime | Waits for the current sample's presentation time. Virtual.
Public Methods: Accessor Methods
ClearPendingSample | Releases the current sample. Virtual.
GetCurrentSample | Retrieves the current sample. Virtual.
GetRealState | Retrieves the filter state.
GetRenderEvent | Retrieves the event that schedules rendering.
HaveCurrentSample | Determines whether the filter has a sample. Virtual.
IsEndOfStream | Queries whether the end-of-stream notification was received.
IsEndOfStreamDelivered | Queries whether the EC_COMPLETE event has been delivered to the filter graph manager.
IsStreaming | Queries whether the filter is streaming data.
SetAbortSignal | Sets the abort flag, which indicates whether to stop rendering and reject further samples.
SetRepaintStatus | Enables or disables repaint events.
Public Methods: State-Change Methods
Active | Called when the state is switched to paused or running. Virtual.
BeginFlush | Begins a flush operation. Virtual.
BreakConnect | Releases the input pin from a connection. Virtual.
CheckReady | Queries whether a state transition is complete.
CompleteConnect | Completes the input pin's connection to another pin. Virtual.
CompleteStateChange | Determines whether a transition to the paused state is complete. Virtual.
EndFlush | Ends a flush operation. Virtual.
Inactive | Called when the state is switched to stopped. Virtual.
NotReady | Signals that a state transition is not yet complete.
Ready | Signals that a state transition is complete.
StartStreaming | Initiates streaming when the filter switches to a running state. Virtual.
StopStreaming | Halts streaming when the filter switches out of the running state. Virtual.
Public Methods: End-Of-Stream Methods
EndOfStream | Notifies the filter that the input pin received an end-of-stream notification. Virtual.
NotifyEndOfStream | Posts an EC_COMPLETE event to the filter graph manager.
ResetEndOfStream | Resets the end-of-stream flags.
ResetEndOfStreamTimer | Cancels the timer that schedules EC_COMPLETE notifications. Virtual.
SendEndOfStream | If end-of-stream was reached, schedules an EC_COMPLETE event for the filter graph manager. Virtual.
TimerCallback | Callback method for the end-of-stream timer event.
Public Methods: Handlers
OnReceiveFirstSample | Called when the filter receives a sample while paused. Virtual.
OnRenderEnd | Called after a sample is rendered. Virtual.
OnRenderStart | Called when rendering is about to start. Virtual.
OnStartStreaming | Called when the filter begins streaming. Virtual.
OnStopStreaming | Called when the filter stops streaming. Virtual.
OnWaitEnd | Called when the filter starts waiting for a sample's presentation time. Virtual.
OnWaitStart | Called when the filter is done waiting for a sample's presentation time. Virtual.
PrepareRender | Called before the filter renders a sample. Virtual.
ShouldDrawSampleNow | Determines how a sample is scheduled for rendering. Virtual.
Pure Virtual Methods
CheckMediaType | Determines if the filter accepts a specific media type.
DoRenderSample | Renders a sample.
IMediaFilter Methods
GetState | Retrieves the filter's state (running, stopped, or paused).
Pause | Pauses the filter.
Run | Runs the filter.
Stop | Stops the filter.
IBaseFilter Methods
FindPin | Retrieves the pin with the specified identifier.

CBaseRenderer.m_bAbort

CBaseRenderer Class

Flag that indicates whether to stop rendering and reject further samples.

Syntax

BOOL m_bAbort;

CBaseRenderer.m_bEOS

CBaseRenderer Class

Flag that indicates whether end-of-stream was reached.

Syntax

BOOL m_bEOS;

CBaseRenderer.m_bEOSDelivered

CBaseRenderer Class

Flag that indicates whether the filter has posted the EC_COMPLETE event.

Syntax

BOOL m_bEOSDelivered;

CBaseRenderer.m_bInReceive

CBaseRenderer Class

Flag that indicates whether the filter is processing a Receive call.

Syntax

BOOL m_bInReceive;

CBaseRenderer.m_bRepaintStatus

CBaseRenderer Class

Flag that enables or disables repaint events.

Syntax

BOOL m_bRepaintStatus;

CBaseRenderer.m_bStreaming

CBaseRenderer Class

Flag that indicates whether the filter is streaming data.

Syntax

BOOL m_bStreaming;

CBaseRenderer.m_dwAdvise

CBaseRenderer Class

Identifier of the timer event that schedules rendering.

Syntax

DWORD_PTR m_dwAdvise;

CBaseRenderer.m_EndOfStreamTimer

CBaseRenderer Class

Timer-event identifier, for scheduling EC_COMPLETE notifications.

Syntax

UINT m_EndOfStreamTimer;

CBaseRenderer.m_evComplete

CBaseRenderer Class

Event that is signaled when a state transition is complete.

Syntax

CAMEvent m_evComplete;

CBaseRenderer.m_InterfaceLock

CBaseRenderer Class

Filter-state lock.

Syntax

CCritSec m_InterfaceLock;

CBaseRenderer.m_pInputPin

CBaseRenderer Class

Pointer to the filter's input pin.

Syntax

CRendererInputPin *m_pInputPin;

CBaseRenderer.m_pMediaSample

CBaseRenderer Class

Pointer to the current media sample.

Syntax

IMediaSample *m_pMediaSample;

CBaseRenderer.m_pPosition

CBaseRenderer Class

Helper object to pass seek commands upstream.

Syntax

CRendererPosPassThru *m_pPosition;

CBaseRenderer.m_pQSink

CBaseRenderer Class

Pointer to the object that receives quality-control messages.

Syntax

IQualityControl *m_pQSink;

Remarks

The base class does not implement quality control. This member variable defaults to NULL.

CBaseRenderer.m_RendererLock

CBaseRenderer Class

Streaming lock.

Syntax

CCritSec m_RendererLock;

CBaseRenderer.m_RenderEvent

CBaseRenderer Class

Event used to schedule rendering.

Syntax

CAMEvent m_RenderEvent;

CBaseRenderer.m_SignalTime

CBaseRenderer Class

Stop time on the current sample.

Syntax

REFERENCE_TIME m_SignalTime;

CBaseRenderer.m_ThreadSignal

CBaseRenderer Class

Event used to release the streaming thread.

Syntax

CAMEvent m_ThreadSignal;

CBaseRenderer::Active

CBaseRenderer Class

Called when the state is switched to paused or running.

Syntax

virtual HRESULT Active(void);

Return Value

Returns S_OK.

Remarks

The input pin calls this method from its own CRendererInputPin::Active method. This method does nothing in the base class.

CBaseRenderer::BeginFlush

CBaseRenderer Class

Begins a flush operation.

Syntax

virtual HRESULT BeginFlush(void);

Return Value

Returns S_OK.

Remarks

The filter's input pin calls this method when it receives a call to the IPin::BeginFlush method. The filter releases the streaming thread, and releases any sample that it was holding for rendering.

CBaseRenderer::BreakConnect

CBaseRenderer Class

Releases the input pin from a connection.

Syntax

virtual HRESULT BreakConnect(void);

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | The pin was not connected.
S_OK | Success.
VFW_E_NOT_STOPPED | The filter is still active.

Remarks

The filter's input pin calls this method from inside its own BreakConnect method. (For more information, see CBasePin::BreakConnect.) The filter performs some internal bookkeeping, such as resetting the end-of-stream flag.

CBaseRenderer::CancelNotification

CBaseRenderer Class

Cancels the timer event that schedules rendering.

Syntax

virtual HRESULT CancelNotification(void);

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | There was no pending timer event.
S_OK | Success.

Remarks

The filter calls this method when streaming stops. The method cancels any scheduled rendering.

CBaseRenderer::CBaseRenderer

CBaseRenderer Class

Constructor method.

Syntax

CBaseRenderer(
    REFCLSID RenderClass,
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

RenderClass
Class identifier of the renderer.
pName
Pointer to a string containing the name of the filter, for debugging purposes.
pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
phr
Pointer to an HRESULT variable. (Ignored.)

CBaseRenderer::~CBaseRenderer

CBaseRenderer Class

Destructor method.

Syntax

~CBaseRenderer(void);

CBaseRenderer::CheckMediaType

CBaseRenderer Class

Determines if the filter accepts a specific media type.

Syntax

virtual HRESULT CheckMediaType(
    const CMediaType *pmt
) PURE;

Parameters

pmt
Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns S_OK if the proposed media type is acceptable. Otherwise, returns S_FALSE or an error code.

Remarks

The input pin calls this method from its own CBasePin::CheckMediaType method. The derived class must implement this method.

CBaseRenderer::CheckReady

CBaseRenderer Class

Queries whether a state transition is complete.

Syntax

BOOL CheckReady(void);

Return Value

Returns TRUE if the state transition is complete, or FALSE if the filter is still transitioning to a new state.

See Also

NotReady, Ready

CBaseRenderer::ClearPendingSample

CBaseRenderer Class

Releases the current sample.

Syntax

virtual HRESULT ClearPendingSample(void);

Return Value

Returns S_OK.

CBaseRenderer::CompleteConnect

CBaseRenderer Class

Completes the input pin's connection to another pin.

Syntax

virtual HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin
Pointer to the output pin's IPin interface.

Return Value

Returns S_OK.

Remarks

The filter's input pin calls this method from inside its own CompleteConnect method, which is called in order to complete a pin connection. (For more information, see CBasePin::CompleteConnect.) The filter calls the SetRepaintStatus method to enable EC_REPAINT events.

CBaseRenderer::CompleteStateChange

CBaseRenderer Class

Determines whether a transition to the paused state is complete.

Syntax

virtual HRESULT CompleteStateChange(
    FILTER_STATE OldState
);

Parameters

OldState
State prior to the transition.

Return Value

Returns S_OK if the transition is complete. Otherwise, returns S_FALSE.

Remarks

The Pause method calls this method to update the state-transition status. In general, the transition to paused does not finish until the filter receives a sample. However, in some situations the transition completes immediately: for example, if the filter is unconnected, or if the end of the stream was reached. This method checks the various criteria and then calls the Ready method or the NotReady method to update the transition status.

CBaseRenderer::DoRenderSample

CBaseRenderer Class

Renders a sample.

Syntax

virtual HRESULT DoRenderSample(
    IMediaSample *pMediaSample
) PURE;

Parameters

pMediaSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value.

Remarks

The derived class must implement this method. The behavior depends entirely on the type of filter being implemented. A video renderer, for example, would draw the video image contained in the sample.

CBaseRenderer::EndFlush

CBaseRenderer Class

Ends a flush operation.

Syntax

virtual HRESULT EndFlush(void);

Return Value

Returns S_OK.

Remarks

The filter's input pin calls this method when it receives a call to the IPin::EndFlush method.

CBaseRenderer::EndOfStream

CBaseRenderer Class

Notifies the filter that the input pin received an end-of-stream notification.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns S_OK.

Remarks

The filter's input pin calls this method when it receives an end-of-stream notification.

This method sets the m_bEOS flag to TRUE and calls the SendEndOfStream method to schedule an EC_COMPLETE event. If the filter is paused and waiting for a sample, this method completes the state transition.

CBaseRenderer::FindPin

CBaseRenderer Class

Retrieves the pin with the specified identifier.

Syntax

HRESULT FindPin(
    LPCWSTR Id,
    IPin **ppPin
);

Parameters

Id
Pointer to a constant, null-terminated Unicode string that identifies the pin. Must be L"In".
ppPin
Address of a variable that receives a pointer to the pin's IPin interface. If the method fails, *ppPin is set to NULL.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NOT_FOUND | Not found.

Remarks

This method overrides the CBaseFilter::FindPin method. The filter's only pin (the input pin) is named In.

CBaseRenderer::GetCurrentSample

CBaseRenderer Class

Retrieves the current sample.

Syntax

virtual IMediaSample *GetCurrentSample(void);

Return Value

Returns a pointer to the sample's IMediaSample interface, or NULL if no sample is available.

Remarks

If the return value is non-NULL, the IMediaSample pointer has an outstanding reference count. Be sure to release it.

CBaseRenderer::GetMediaPositionInterface

CBaseRenderer Class

Retrieves the filter's IMediaPosition and IMediaSeeking interface pointers.

Syntax

virtual HRESULT GetMediaPositionInterface(
    REFIID riid,
    void **ppv
);

Parameters

riid
Reference identifier of the interface.
ppv
Address of a variable that receives the interface pointer.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_NOINTERFACE | Interface not supported.

Remarks

The filter delegates all seeking commands to a CRendererPosPassThru object, which passes them upstream. This method creates the CRendererPosPassThru object, if it does not yet exist, and queries it for the requested interface.

The m_pPosition member variable stores a pointer to the CRendererPosPassThru object.

CBaseRenderer::GetPin

CBaseRenderer Class

Retrieves a pin.

Syntax

virtual CBasePin *GetPin(
    int n
);

Parameters

n
Number of the specified pin. Must be zero.

Return Value

Returns the m_pInputPin pointer.

Remarks

This method implements the CBaseFilter::GetPin method, which is pure virtual in the CBaseFilter class. The filter supports exactly one pin (the input pin). The first time this method is called, it creates the pin as a new CRendererInputPin object.

CBaseRenderer::GetPinCount

CBaseRenderer Class

Retrieves the number of pins.

Syntax

virtual int GetPinCount(void);

Return Value

Returns 1.

Remarks

This method implements the CBaseFilter::GetPinCount method, which is pure virtual in the CBaseFilter class.

CBaseRenderer::GetRealState

CBaseRenderer Class

Retrieves the filter state.

Syntax

FILTER_STATE GetRealState(void);

Return Value

Returns the value of CBaseFilter.m_State. The value is a member of the FILTER_STATE enumerated type.

Remarks

This method provides a simpler alternative to the GetState method, for internal use.

CBaseRenderer::GetRenderEvent

CBaseRenderer Class

Retrieves the event that schedules rendering.

Syntax

CAMEvent *GetRenderEvent(void);

Return Value

Returns a pointer to the m_RenderEvent event.

CBaseRenderer::GetSampleTimes

CBaseRenderer Class

Retrieves the time stamps from a sample.

Syntax

virtual HRESULT GetSampleTimes(
    IMediaSample *pMediaSample,
    REFERENCE_TIME *pStartTime,
    REFERENCE_TIME *pEndTime
);

Parameters

pMediaSample
Pointer to the sample's IMediaSample interface.
pStartTime
Pointer to a variable that receives the start time.
pEndTime
Pointer to a variable that receives the end time.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | The sample should be rendered immediately.
S_FALSE | The sample should be scheduled for rendering, based on the time stamps.
E_FAIL | Do not render this sample.
VFW_E_START_TIME_AFTER_END | Bad time stamp: The end time is earlier than the start time.

Remarks

The filter calls this method to determine how it should handle a sample. If the return value is S_OK, the filter renders the sample immediately. If the return value is S_FALSE, the filter schedules the sample for rendering, based on the time stamps. If the return value is an error code, the filter rejects the sample.

This method returns S_OK if the sample has no time stamps, or if the filter does not have a reference clock. Otherwise, it returns the value of the ShouldDrawSampleNow method. In the base class, ShouldDrawSampleNow always returns S_FALSE. The derived class can override this behavior. For example, if the derived class implements quality control management, it might return E_FAIL to drop a sample.

CBaseRenderer::GetState

CBaseRenderer Class

Retrieves the filters's state (running, stopped, or paused).

Syntax

HRESULT GetState(
    DWORD dwMilliSecsTimeout,
    FILTER_STATE *State
);

Parameters

dwMilliSecsTimeout
Time-out interval, in milliseconds.
State
Pointer to a variable that receives a member of the FILTER_STATE enumerated type, indicating the filter's state.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
VFW_S_STATE_INTERMEDIATE | The filter is transitioning to the indicated state.
E_POINTER | NULL pointer argument.

Remarks

This method overrides the CBaseFilter::GetState method. When the renderer is paused, it does not complete the state transition until it receives a sample to render. If the time-out expires before the state transition is complete, the method returns VFW_S_STATE_INTERMEDIATE.

CBaseRenderer::HaveCurrentSample

CBaseRenderer Class

Determines whether the filter has a sample.

Syntax

virtual BOOL HaveCurrentSample(void);

Return Value

Returns TRUE if the filter has a sample, or FALSE otherwise.

CBaseRenderer::Inactive

CBaseRenderer Class

Called when the state is switched to stopped.

Syntax

virtual HRESULT Inactive(void);

Return Value

Returns S_OK.

Remarks

The input pin calls this method from its own CRendererInputPin::Inactive method. The filter calls the ClearPendingSample method to release the most recent sample.

CBaseRenderer::IsEndOfStream

CBaseRenderer Class

Queries whether the end-of-stream notification was received.

Syntax

BOOL IsEndOfStream(void);

Return Value

Returns the m_bEOS flag.

CBaseRenderer::IsEndOfStreamDelivered

CBaseRenderer Class

Queries whether the EC_COMPLETE event has been delivered to the filter graph manager.

Syntax

BOOL IsEndOfStreamDelivered(void);

Return Value

Returns the m_bEOSDelivered flag.

CBaseRenderer::IsStreaming

CBaseRenderer Class

Queries whether the filter is streaming data.

Syntax

BOOL IsStreaming(void);

Return Value

Returns the m_bStreaming flag.

CBaseRenderer::NotReady

CBaseRenderer Class

Signals that a state transition is not yet complete.

Syntax

void NotReady(void);

Remarks

This method causes the GetState method to return VFW_S_STATE_INTERMEDIATE, which indicates that the filter is still transitioning to its current state. The filter calls this method whenever a state transition is pending. (This occurs when the filter pauses, until it receives a sample.)

See Also

CheckReady, Ready

CBaseRenderer::NotifyEndOfStream

CBaseRenderer Class

Posts an EC_COMPLETE event to the filter graph manager.

Syntax

void NotifyEndOfStream(void);

See Also

EndOfStream, SendEndOfStream

CBaseRenderer::OnDisplayChange

CBaseRenderer Class

Posts an EC_DISPLAY_CHANGED event to the filter graph manager.

Syntax

BOOL CBaseRenderer::OnDisplayChange(void);

Return Value

Returns TRUE if the event was posted, or FALSE otherwise.

Remarks

Video renderers should call this method in response to WM_DISPLAYCHANGE messages. If the input pin is connected, the method sends an EC_DISPLAY_CHANGED event to the filter graph manager.

CBaseRenderer::OnReceiveFirstSample

CBaseRenderer Class

Called when the filter receives a sample while paused.

Syntax

virtual void OnReceiveFirstSample(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample
Pointer to the sample's IMediaSample interface.

Remarks

The Receive method calls this method. It does nothing in the base class, but the derived class can override it. This method is intended primarily for video renderers. When a video renderer is paused, it typically displays the first sample as a still image.

Seeking the graph while paused also causes this method to be called.

CBaseRenderer::OnRenderEnd

CBaseRenderer Class

Called after a sample is rendered.

Syntax

virtual void OnRenderEnd(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample
Pointer to the sample's IMediaSample interface.

Remarks

The Render method calls this method. It does nothing in the base class, but the derived class can override it; for example, to collect quality-control data.

CBaseRenderer::OnRenderStart

CBaseRenderer Class

Called when rendering is about to start.

Syntax

virtual void OnRenderStart(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample
Pointer to the sample's IMediaSample interface.

Remarks

The Render method calls this method. It does nothing in the base class, but the derived class can override it; for example, to collect quality-control data.

CBaseRenderer::OnStartStreaming

CBaseRenderer Class

Called when the filter begins streaming.

Syntax

virtual HRESULT OnStartStreaming(void);

Return Value

Returns S_OK.

Remarks

The StartStreaming method calls this method. It does nothing in the base class, but the derived class can override it.

CBaseRenderer::OnStopStreaming

CBaseRenderer Class

Called when the filter stops streaming.

Syntax

virtual HRESULT OnStopStreaming(void);

Return Value

Returns S_OK.

Remarks

The StopStreaming method calls this method. It does nothing in the base class, but the derived class can override it.

CBaseRenderer::OnWaitEnd

CBaseRenderer Class

Called when the filter is done waiting for a sample's presentation time.

Syntax

virtual void OnWaitEnd(void);

Remarks

The WaitForRenderTime method calls this method when it has finished waiting for a sample's presentation time. This method does not do anything in the base class, but the derived class can override it.

If you are implementing quality control, you might override this method along with the OnWaitStart method. You can use these methods to track the filter's performance.

CBaseRenderer::OnWaitStart

CBaseRenderer Class

Called when the filter starts waiting for a sample's presentation time.

Syntax

virtual void OnWaitStart(void);

Remarks

The WaitForRenderTime method calls this method when it begins waiting for a sample's presentation time. This method does not do anything in the base class, but the derived class can override it.

If you are implementing quality control, you might override this method along with the OnEndStart method. You can use these methods to track the filter's performance.

CBaseRenderer::Pause

CBaseRenderer Class

Pauses the filter.

Syntax

HRESULT Pause(void);

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | The transition is complete.
S_FALSE | Transition is not complete.

Remarks

This method overrides the CBaseFilter::Pause method. It performs the following steps:

  • Calls the CBaseFilter::Pause method.
  • Commits the allocator. (See IMemAllocator::Commit.)
  • If the previous state was stopped, the filter releases any sample it is holding. (The sample is no longer valid.)
  • Calls the CompleteStateChange method and returns the value.

CBaseRenderer::PrepareReceive

CBaseRenderer Class

Prepares to render a sample.

Syntax

virtual HRESULT PrepareReceive(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_OK | Success.
E_FAIL | Failed.
E_UNEXPECTED | Unexpected error.
VFW_E_SAMPLE_REJECTED | Filter is dropping this sample.

Remarks

The filter calls this method from inside the Receive method, before it renders a sample. If the filter is running, this method schedules the sample for rendering.

If the filter already has a pending sample, or if the end-of-stream was already reached, the method returns E_UNEXPECTED. Possibly the upstream filter is not serializing its streaming calls correctly.

If the scheduling algorithm determines that the sample should be dropped (see ScheduleSample), the method returns VFW_E_SAMPLE_REJECTED. However, the input pin's IMemInputPin::Receive method does not pass this error code to the upstream filter, because dropping a sample is not an error.

CBaseRenderer::PrepareRender

CBaseRenderer Class

Called before the filter renders a sample.

Syntax

virtual void PrepareRender(void);

Remarks

The filter calls this method before it calls the OnReceiveFirstSample method or the Render method. PrepareRender does not do anything in the base class. The derived class can override it to perform any actions required before rendering. For example, a video renderer can override this method to realize its palette.

CBaseRenderer::Ready

CBaseRenderer Class

Signals that a state transition is complete.

Syntax

void Ready(void);

Remarks

This method causes the GetState method to return S_OK, which indicates that the filter has completed the transition to its current state. The filter calls this method whenever it completes a state transition.

See Also

CheckReady, NotReady

CBaseRenderer::Receive

CBaseRenderer Class

Receives the next media sample in the stream.

Syntax

virtual HRESULT Receive(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

The input pin calls this method when it receives a sample from the upstream filter.

If the filter is running, this method performs the following steps:

  1. Schedules the sample for rendering (PrepareReceive).
  2. Waits for the scheduled time (WaitForRenderTime).
  3. Renders the sample (Render).
  4. Releases the sample (ClearPendingSample).

If the filter is paused, the method performs the following steps:

  1. Notifies the derived class that a sample is available (OnReceiveFirstSample).
  2. Waits for the scheduled time.
  3. Renders the sample.
  4. Releases the sample.

While paused, the method waits in step 2 until the filter switches to a running state. At that point, the filter schedules the sample.

In the base class, the OnReceiveFirstSample method does nothing. The derived class can override it. For example, when a video renderer is paused, it displays the first sample as a still image.

CBaseRenderer::Render

CBaseRenderer Class

Renders a sample.

Syntax

virtual HRESULT Render(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_FALSE | The filter is stopped, or pMediaSample is NULL.
S_OK | Success.

Remarks

This method calls the pure virtual method DoRenderSample, which does the real work. The derived class must implement DoRenderSample.

Immediately before calling DoRenderSample, this method calls the OnRenderStart method. Immediately after, it calls the OnRenderEnd method. The derived class can override those two methods as needed.

CBaseRenderer::ResetEndOfStream

CBaseRenderer Class

Resets the end-of-stream flags.

Syntax

virtual HRESULT ResetEndOfStream(void);

Return Value

Returns S_OK.

Remarks

This method clears the previous end-of-stream condition. At that point, the filter can receive new data. The Stop and BeginFlush methods call this method.

CBaseRenderer::ResetEndOfStreamTimer

CBaseRenderer Class

Cancels the timer that schedules EC_COMPLETE notifications.

Syntax

void ResetEndOfStreamTimer(void);

See Also

SendEndOfStream, TimerCallback.

CBaseRenderer::Run

CBaseRenderer Class

Runs the filter.

Syntax

HRESULT Run(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the error.

Remarks

This method overrides the CBaseFilter::Run method. It performs the following actions:

  • Calls the CBaseFilter::Run method.
  • Commits the allocator. (See IMemAllocator::Commit.)
  • If the previous state was stopped, the filter releases any sample it is holding. (The sample is no longer valid.)
  • Calls the StartStreaming method and returns the result. If a sample is pending, the StartStreaming method schedules it for rendering.

If the filter is not connected, it posts an EC_COMPLETE event immediately.

CBaseRenderer::ScheduleSample

CBaseRenderer Class

Schedules a sample for rendering.

Syntax

virtual BOOL ScheduleSample(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns TRUE if the sample was scheduled, or FALSE if the sample was dropped.

Remarks

This method first determines whether the sample should be rendered immediately, rendered in the future, or dropped. (To do so, it calls the GetSampleTimes method.) If the sample should be rendered immediately, the method signals the m_RenderEvent event. If the sample should be rendered in the future, the method calls the IReferenceClock::AdviseTime method for scheduling.

CBaseRenderer::SendEndOfStream

CBaseRenderer Class

If end-of-stream was reached, schedules an EC_COMPLETE event for the filter graph manager.

Syntax

virtual HRESULT SendEndOfStream(void);

Return Value

Returns an HRESULT value. Possible values include those in the following table.

S_FALSE | The filter graph manager is not accepting event notifications.
S_OK | Success.

Remarks

The filter might receive an end-of-stream notification before the current sample's stop time. If so, the filter should wait before posting an EC_COMPLETE notification to the filter graph manager.

Therefore:

  • If the filter has received an early end-of-stream (EOS) notification, this method schedules a timer event. When the timer event is activated, the filter posts the EC_COMPLETE event.
  • If the filter has received an EOS notification that was not early, this method posts the EC_COMPLETE event immediately.
  • If the filter does not have any pending EOS notification, the method returns without doing anything.

The timer callback method is TimerCallback. To deliver the EC_COMPLETE event, the filter calls the NotifyEndOfStream method.

CBaseRenderer::SendNotifyWindow

CBaseRenderer Class

Notifies the upstream filter of the video window handle.

Syntax

void SendNotifyWindow(
    IPin *pPin,
    HWND hwnd
);

Parameters

pPin
Pointer to the IPin interface of the upstream filter's output pin.
hwnd
Handle to the video window, or NULL.

Return Value

No return value.

Remarks

If the output pin of the upstream filter supports the IMediaEventSink interface, this method sends it the EC_NOTIFY_WINDOW event code along with the window handle.

Video renderers can override their CompleteConnect methods to call this method. It provides a mechanism for informing the upstream filter of the window handle. If you do this, override the BreakConnect method as well, and call SendNotifyWindow with a NULL handle.

CBaseRenderer::SendRepaint

CBaseRenderer Class

Sends a repaint event to the filter graph manager.

Syntax

void SendRepaint(void);

Remarks

This method sends an EC_REPAINT event to the filter graph manager if the following conditions are true:

  • The input pin is connected.
  • The filter is not flushing data.
  • The end-of-stream was not reached.
  • The m_bAbort flag is FALSE.
  • The m_bRepaintStatus flag is TRUE.

Depending on the state of the graph, the EC_REPAINT event can cause the upstream filter to re-send a sample; the filter graph to seek to its current location; or the filter graph manager to pause momentarily. (See EC_REPAINT.) This event is potentially inefficient, so it should be used sparingly. However, video renderers sometimes need to refresh the display.

CBaseRenderer::SetAbortSignal

CBaseRenderer Class

Sets the abort flag, which indicates whether to stop rendering and reject further samples.

Syntax

void SetAbortSignal(
    BOOL bAbort
);

Parameters

bAbort
Boolean value indicating whether to stop rendering. If TRUE, the filter will not render any more samples.

Remarks

This method sets the m_bAbort flag.

CBaseRenderer::SetMediaType

CBaseRenderer Class

Called when the pin's media type is set.

Syntax

virtual HRESULT SetMediaType(
    const CMediaType *pmt
);

Parameters

pmt
Pointer to a CMediaType object that specifies the media type.

Return Value

Returns S_OK.

Remarks

The input pin calls this method from its own CRendererInputPin::SetMediaType method. This method does nothing in the base class.

CBaseRenderer::SetRepaintStatus

CBaseRenderer Class

Enables or disables repaint events.

Syntax

void SetRepaintStatus(
    BOOL bRepaint
);

Parameters

bRepaint
Boolean value indicating whether repaint events are enabled. If TRUE, the filter will sent EC_REPAINT events to the filter graph manager. Otherwise, it will not send EC_REPAINT events.

Remarks

This method ensures that the filter graph manager is not flooded with redundant EC_REPAINT events. After the filter sends an EC_REPAINT event, it calls this method with the value TRUE. The filter does not send more EC_REPAINT events until it receives more data.

CBaseRenderer::ShouldDrawSampleNow

CBaseRenderer Class

Determines how a sample is scheduled for rendering.

Syntax

virtual HRESULT ShouldDrawSampleNow(
    IMediaSample *pMediaSample,
    REFERENCE_TIME *pStartTime,
    REFERENCE_TIME *pEndTime
);

Parameters

pMediaSample
Pointer to the sample's IMediaSample interface.
pStartTime
Pointer to a variable that contains the sample's start time.
pEndTime
Pointer to a variable that contains the sample's end time.

Return Value

Returns S_FALSE. If the derived class overrides this method, return one of the values shown in the following table.

S_OK | The sample should be rendered immediately.
S_FALSE | The sample should be scheduled for rendering, based on the time stamps.
Error code | Do not render this sample.

Remarks

The GetSampleTimes method calls this method. By default, samples are always scheduled for rendering based on their time stamps. The derived class can override this method; for example, to implement quality control.

CBaseRenderer::SignalTimerFired

CBaseRenderer Class

Clears the timer identifier used to schedule rendering.

Syntax

virtual void SignalTimerFired(void);

Remarks

The filter calls this method when the rendering timer activates (see WaitForRenderTime) or when the timer is canceled (see CancelNotification). The method resets the m_dwAdvise member variable to zero.

CBaseRenderer::SourceThreadCanWait

CBaseRenderer Class

Holds or releases the streaming thread.

Syntax

virtual HRESULT SourceThreadCanWait(
    BOOL bCanWait
);

Parameters

bCanWait
Boolean value indicating whether to hold the streaming thread. If TRUE, the streaming thread is blocked while the filter waits to render the next samples. If FALSE, the streaming thread is released.

Return Value

Returns S_OK.

Remarks

Calling the SourceThreadCanWait method with the value FALSE forces the filter to return from a blocked IMemInputPin::Receive call. When the filter is running, it blocks Receive calls until the current sample's presentation time. When the filter is paused, it blocks Receive calls indefinitely. This behavior regulates the flow of data in the stream. When the filter is stopped or flushing, however, it should not block.

The blocking is controlled by the WaitForRenderTime method, which waits on two events: m_RenderEvent and m_ThreadSignal. The m_RenderEvent event is signaled when the presentation time arrives. The m_ThreadSignal event is signaled when SourceThreadCanWait is called with the value FALSE. Calling SourceThreadCanWait with the value TRUE resets the event.

The Stop and BeginFlush methods call SourceThreadCanWait with the value FALSE (releasing the streaming thread). The Pause, Run, and EndFlush methods call SourceThreadCanWait with the value TRUE.

CBaseRenderer::StartStreaming

CBaseRenderer Class

Initiates streaming when the filter switches to a running state.

Syntax

virtual HRESULT StartStreaming(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

If the filter has a sample, it schedules the sample for rendering. Otherwise, if there is a pending end-of-stream notification, the filter sends an EC_COMPLETE event to the filter graph manager.

This method calls the OnStartStreaming method. That method does nothing in the base class, but the derived class can override it.

CBaseRenderer::Stop

CBaseRenderer Class

Stops the filter.

Syntax

HRESULT Stop(void);

Return Value

Returns S_OK.

Remarks

This method overrides the CBaseFilter::Stop method. It performs the following actions:

  • Calls CBaseFilter::Stop.
  • Decommits the allocator. (See IMemAllocator::Decommit.)
  • Cancels any scheduled rendering and releases the streaming thread.
  • Waits for any pending Receive call to complete.

CBaseRenderer::StopStreaming

CBaseRenderer Class

Halts streaming when the filter switches out of the running state.

Syntax

virtual HRESULT StopStreaming(void);

Return Value

Returns S_OK.

Remarks

This method calls the OnStopStreaming method. That method does nothing in the base class, but the derived class can override it.

CBaseRenderer::TimerCallback

CBaseRenderer Class

Callback method for the end-of-stream timer event.

Syntax

void TimerCallback(void);

Remarks

The SendEndOfStream method uses a timer event to schedule EC_COMPLETE notifications. The TimerCallback method is the callback function for the timer event. The TimerCallback method calls SendEndOfStream again, and SendEndOfStream determines whether to send the EC_COMPLETE notification or set another timer.

The ResetEndOfStreamTimer method cancels the timer event.

CBaseRenderer::WaitForReceiveToComplete

CBaseRenderer Class

Waits for the Receive method to complete.

Syntax

void WaitForReceiveToComplete(void);

Remarks

The Stop and BeginFlush methods call this method to synchronize the state change with the Receive method.

Specifically, this method dispatches messages while it waits for the m_bInReceive flag to become FALSE. The flag becomes TRUE in the PrepareReceive method and switches back to FALSE after the Receive method calls the PrepareRender method. The derived class can use PrepareRender to set the palette. Waiting for PrepareRender to complete ensures that palette-change messages are dispatched before the state change occurs. This avoids a potential deadlock.

CBaseRenderer::WaitForRenderTime

CBaseRenderer Class

Waits for the current sample's presentation time.

Syntax

virtual HRESULT WaitForRenderTime(void);

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
VFW_E_STATE_CHANGED | The filter state changed before the presentation time arrived.

Remarks

This method waits until one of the following occurs:

  • The sample's presentation time arrives, at which point the sample can be rendered.
  • The filter stops or begins flushing data.

If the presentation time arrives, the m_RenderEvent event is signaled. If the state changes, the m_ThreadSignal event is signaled. This method waits on both events. The derived class can override this method to wait on additional events, if necessary.

This method calls the OnWaitStart method when the wait begins, and the OnWaitEnd method when the wait is done. Neither method does anything in the base class, but the derived class can override them.


CBaseStreamControl Class

CBaseStreamControl class hierarchy

This class implements the IAMStreamControl interface for both input and output pins. It provides control over starting and stopping an individual stream in the filter graph. (For more information, see IAMStreamControl.)

If you are implementing a pin that supports IAMStreamControl, you should inherit from this base class. The following is a typical declaration for an input pin:

class CMyInputPin : public CBaseInputPin, public CBaseStreamControl

Be sure to override NonDelegatingQueryInteface to expose IAMStreamControl. For more information, see How to Implement IUnknown.

Stream Control State

This class uses the StreamControlState enumeration to describe the current state of a stream:

  • STREAM_FLOWING: The stream is flowing through the pin.
  • STREAM_DISCARDING: The pin is discarding samples.

The class also provides a helper function, CheckStreamState, that retrieves the current state. A pin derived from this class should call this function in order to determine how to process a given sample.

It is also important that the pin be synchronized to a reference clock. Otherwise, it will discard every sample immediately, which could cause an entire file to get pushed through the filter as fast as possible, making it impossible to restart the stream at a later time. When the pin is synchronized correctly, it holds a sample until the scheduled time before discarding it. To specify the reference clock, call the SetSyncSource member function.

Using the CBaseStreamControl Class

In order to use this base class correctly, you must call certain member functions at particular times. The following describes what to do, and gives brief code examples. (In your own code, you will probably need to handle various other details that the examples omit.)

  • Reference clock: In the filter's IMediaFilter::SetSyncSource method, set the reference clock on the pin. Call the SetSyncSource member function with the IReferenceClock interface pointer:
    STDMETHODIMP CMyFilter::SetSyncSource(IReferenceClock *pClock)
{
   m_pMyPin->SetSyncSource(pClock);
   return CBaseFilter::SetSyncSource(pClock);
}
  • Event sink: In the filter's JoinFilterGraph method, after the filter retrieves a pointer to the IMediaEventSink interface (from the filter graph), pass that pointer to the pin by calling the SetFilterGraph member function:
    STDMETHODIMP CMyFilter::JoinFilterGraph(IFilterGraph * pGraph, LPCWSTR pName)
{
   HRESULT hr = CBaseFilter::JoinFilterGraph(pGraph, pName);
   if (hr == S_OK)
      m_pMyPin->SetFilterGraph(m_pSink);
   return hr;
}
  • Filter state: Whenever the filter changes state, call the NotifyFilterState member function on the pin. The following example shows a transition to the running state:
    STDMETHODIMP CMyFilter::Run(REFERENCE_TIME tStart)
{
   m_pMyPin->NotifyFilterState(State_Running, tStart);
   return CBaseFilter::Run(tStart);
}
  • Flushing: Whenever the pin begins flushing data (IPin::BeginFlush) or stops flushing data (IPin::EndFlush), call the Flushing member function with a value of TRUE of FALSE, respectively:
    HRESULT CMyPin::BeginFlush()
{
   Flushing(TRUE);
   return CBaseOutputPin::BeginFlush();    // Or CBaseInputPin, for input pins
}

HRESULT CMyPin::EndFlush()
{
   Flushing(FALSE);
   return CBaseOutputPin::EndFlush();   // Or CBaseInputPin, for input pins
}
  • Media samples: In the pin's IMemInputPin::Receive method, call the CheckStreamState function to determine whether to deliver the sample or discard it. Once an output pin has discarded samples, it must set the discontinuity property on the next sample that it delivers. In the following example, the derived class uses a member variable named m_fLastSampleDiscarded to keep track of discontinuities:
    CMyPin::Receive(IMediaSample *pSample)
{
    int iStreamState = CheckStreamState(pSample);
    if (iStreamState == STREAM_FLOWING) {
        if (m_fLastSampleDiscarded)
            pSample->SetDiscontinuity(TRUE);
        m_fLastSampleDiscarded = FALSE;
        // Deliver sample, or otherwise handle.
    }
    else {
    m_fLastSampleDiscarded = TRUE;     // Next one is discontinuity
    // Do NOT deliver this sample. Just throw it away.
    }
}

Member Functions

CBaseStreamControl | Constructs a CBaseStreamControl object.
CheckStreamState | Retrieves a stream's current state.
Flushing | Notifies the pin when the filter is flushing.
GetInfo | Retrieves information about the current streaming settings.
NotifyFilterState | Notifies the pin of what state your filter is in.
SetFilterGraph | Sets the event sink notification that your filter graph is using.
SetSyncSource | Identifies the reference clock being used by the graph your filter is in.
StartAt | Informs the pin when to start sending streaming data.
StopAt | Informs the pin when to stop processing data and discard any new samples.

CBaseStreamControl::CBaseStreamControl

CBaseStreamControl Class

Constructs a CBaseStreamControl object.

Syntax

CBaseStreamControl(void);

Return Value

No return value.

Remarks

This function initializes both the start time and stop time to MAX_TIME, which indicates starting from the beginning of the stream and not stopping until the end of the stream.

CBaseStreamControl::CheckStreamState

CBaseStreamControl Class

Retrieves a stream's current state.

Syntax

enum StreamControlState CheckStreamState(
    IMediaSample *pSample
    );

Parameters

pSample
Pointer to an IMediaSample interface.

Return Value

Returns a StreamControlState enumeration type.

Remarks

Your filter calls this member function when your pin receives a sample that it is about to forward. The first sample you forward after throwing one or more away should be marked as a discontinuity.

If your filter implements the IAMDroppedFrames interface and is counting how many frames are dropped, do not count a discarded frame as a dropped frame.

CBaseStreamControl::Flushing

CBaseStreamControl Class

Notifies the pin that the filter is flushing.

Syntax

void Flushing(
    BOOL bInProgress
    );

Parameters

bInProgress
Value indicating whether the filter is flushing. TRUE indicates flushing in progress; FALSE indicates not flushing.

Return Value

No return value.

Remarks

If you are implementing your own filter, your pin must call this member function on BeginFlush and EndFlush to say when it is flushing.

Note that capture filters that do not support seeking do not call this method.

CBaseStreamControl::GetInfo

CBaseStreamControl Class

Retrieves information about the current streaming settings.

Syntax

HRESULT GetInfo(
    AM_STREAM_INFO *pInfo
    );

Parameters

pInfo
Pointer to an AM_STREAM_INFO structure.

Return Value

Returns S_OK.

Remarks

This member function implements the IAMStreamControl interface and is called by the user to find out if a pin is streaming and to obtain the stream's attributes.

CBaseStreamControl::NotifyFilterState

CBaseStreamControl Class

Notifies the pin of your filter's state.

Syntax

void NotifyFilterState(
    FILTER_STATE new_state,
    REFERENCE_TIME tStart = 0
    );

Parameters

new_state
Filter's new state.
tStart
Time at which streaming starts (only valid when new_state is in State_Running).

Return Value

No return value.

Remarks

This member function notifies the pin of a filter's new state by setting a FILTER_STATE enumeration type variable.

If you are implementing your own filter, inform your pin's CBaseStreamControl::NotifyFilterState member function what state your filter is in every time your filter changes state, as shown in the following example.

STDMETHODIMP CMyFilter::Run(REFERENCE_TIME tStart)
{
   // Once error check is successful
   m_pMyPin->NotifyFilterState(State_Running, tStart);

   // Now continue with whatever should occur next, for example...
   return CBaseFilter::Run(tStart);
}

STDMETHODIMP CMyFilter::Pause()
{
   // Once error check is successful
   m_pMyPin->NotifyFilterState(State_Paused, 0);

   // Now continue with whatever should occur next, for example...
   return CBaseFilter::Pause();
}

STDMETHODIMP CMyFilter::Stop()
{
   // Once error check is successful
   m_pMyPin->NotifyFilterState(State_Stopped, 0);

   // Now continue with whatever should occur next, for example...
   return CBaseFilter::Stop(tStart);
}

CBaseStreamControl::SetFilterGraph

CBaseStreamControl Class

Sets the event sink your filter graph is using for event notification.

Syntax

void SetFilterGraph(
    IMediaEventSink *pSink
    );

Parameters

pSink
Pointer to an IMediaEventSink interface.

Return Value

No return value.

Remarks

A filter calls this member function in its JoinFilterGraph member function after it creates the IMediaEventSink.

CBaseStreamControl::SetSyncSource

CBaseStreamControl Class

Identifies the reference clock being used by the graph your filter is in.

Syntax

void SetSyncSource(
    IReferenceClock *pRefClock
    );

Parameters

pRefClock
Pointer to the IReferenceClock interface.

Return Value

No return value.

Remarks

Filters with pins that use this class should ensure that they pass sync source information to this member function

CBaseStreamControl::StartAt

CBaseStreamControl Class

Tells the pin when to start sending streaming data.

Syntax

HRESULT StartAt(
    const REFERENCE_TIME *ptStart = NULL,
    DWORD dwCookie = 0
    );

Parameters

ptStart
Pointer to the reference time at which to start streaming. If NULL, start immediately (no notification). If MAX_TIME, start canceled or will have no effect.
dwCookie
Value, other than 0, to be sent with the notification when the start occurs. (Only used if ptStart is non-NULL or MAX_TIME).

Return Value

Returns NOERROR.

Remarks

Streams are enabled by default, so this member function will have no effect unless you have previously called StopAt.

After the stream is in a STREAM_FLOWING state, the filter will send an EC_STREAM_CONTROL_STARTED event notification to the filter graph manager.

Note If start and stop are scheduled for a single point in time, the effect is as if the start occurred an infinitesimal time before the stop. You can use this effect to capture a single frame.

CBaseStreamControl::StopAt

CBaseStreamControl Class

Informs the pin when to stop processing data and to discard any new samples.

Syntax

HRESULT StopAt(
    const REFERENCE_TIME *ptStop = NULL,
    BOOL bSendExtra = FALSE,
    DWORD dwCookie = 0
    );

Parameters

ptStop
Pointer to the reference time at which to stop streaming. If NULL, stop immediately (no notification). If MAX_TIME, cancels stop.
bSendExtra
Flag that specifies whether the pin will send an extra sample after the scheduled ptStop time; TRUE means that it will. For more information, see Remarks.
dwCookie
Value to be sent with the notification when the stop occurs. (Only used if ptStart is not NULL or MAX_TIME).

Return Value

Returns NOERROR.

Remarks

This member function implements the IAMStreamControl::StopAt method and is used by pins and filters that must support the stopping of streams. It sets the StreamControlState enumeration type to STREAM_DISCARDING.

In a video capture scenario, specify StopAt on both the output pin of a capture filter and an input pin of a multiplexer and have the multiplexer send notification of completion. This ensures that the capture filter doesn't needlessly capture extra frames, while also guaranteeing that the multiplexer has written the last frame to disk.

In addition, the capture output pin should specify TRUE for the bSendExtra variable while all other pins specify FALSE. If an extra frame is not sent the multiplexer will end up waiting for the stop time indefinitely and not realize it already has received all the capture information.

If you are using ICaptureGraphBuilder, the ICaptureGraphBuilder::ControlStream method will accomplish all this for you automatically.

Note If a stop time is given in the middle of a packet, the filter will deliver the whole packet before going into a discarding state. Also, if start and stop are scheduled for a single point in time, the effect is as if the start occurred an infinitesimal time before the stop. You can use this effect to capture a single frame.


CBaseVideoRenderer Class

CBaseVideoRenderer class hierarchy

The CBaseVideoRenderer base class is used for building video renderer filters.

Protected Data Members

m_bDrawLateFrames | Flag to signal that no frames are to be dropped. Debug only. This destroys synchronization.
m_bSupplierHandlingQuality | TRUE indicates quality control messages are being handled. This lets the renderer know to wait until as late as possible to drop frames itself, and to display the next frame very early after the supplier has dropped a frame.
m_cFramesDrawn | Total number of frames that have been drawn since streaming started.
m_cFramesDropped | Cumulative frames that have been dropped in the renderer since streaming started. Frames can also be dropped upstream without the renderer recognizing them.
m_idDecision | MSR_id for the decision code of ShouldDrawSampleNow.
m_idDuration | MSR_id for the duration of a frame.
m_idFrameAccuracy | Performance log identifier for the time in milliseconds that the frame was late.
m_idFrameAvg | Performance log identifier for the average frame time that is used for synchronization and quality control.
m_idQualityRate | MSR_id for the quality rate requested.
m_idQualityTime | MSR_id for the quality time requested.
m_idRenderAvg | Performance log identifier for the average renderer time recorded.
m_idSchLateTime | MSR_id for how late the frame was when scheduled.
m_idSendQuality | MSR_id for timing the notifications (unused).
m_idTimeStamp | MSR_id for a frame time stamp.
m_idWait | Performance log identifier for the recorded wait time (unused).
m_idWaitReal | Performance log identifier for the true wait time.
m_iSumFrameTime | Sum of the interframe times; needed for the property page.
m_iSumSqAcc | Sum of the squares of the accuracies (in milliseconds) needed for the property page.
m_iSumSqFrameTime | Sum of the squares of interframe times; needed for the property page.
m_iTotAcc | Sum of the accuracies (in milliseconds) needed for the property page.
m_nNormal | Number of consecutive frames drawn at their scheduled time. A negative number indicates that a frame has just been dropped by the renderer.
m_trDuration | Duration of the last frame (difference between the start and end times).
m_trEarliness | How early a frame is allowed to be played when a frame has just been dropped.
m_trFrame | Most recently recorded time between frames. Used in statistical measurements.
m_trFrameAvg | Average interframe time in reference time units.
m_trLastDraw | Time of previous frame. Used for interframe time references.
m_trLate | Amount of time that the current frame was late. Used in statistical measurements.
m_trRenderAvg | Time that frames are taking to perform the bit-block transfer.
m_trRenderLast | Time for the last frame bit-block transfer.
m_trRenderStart | Time the bit-block transfer started. Used to get m_trRenderLast.
m_trThrottle | Period to insert after rendering each frame, typically used when audio quality has been increased and video performance must be decreased to allow this.
m_trWaitAvg | Average wait time in reference time units.
m_tStreamingStart | Used for property page statistics. Represents the start time of the current streaming process or the previous streaming process if not currently streaming.

Member Functions

CBaseVideoRenderer | Constructs a CBaseVideoRenderer object.
GetStdDev | Estimates the standard deviation in milliseconds between when each frame is due and when it is actually rendered, for per-frame statistics.
PreparePerformanceData | Sets the m_trLate and m_trFrame values of the current frame.
ThrottleWait | Inserts a wait period after each frame.

Overridable Member Functions

JoinFilterGraph | Sends EC_WINDOW_DESTROYED event notification when filter is removed from the filter graph.
OnDirectRender | Collects timing information that controls synchronization and quality control.
OnRenderEnd | Records information for quality control and synchronization.
OnRenderStart | Records information for quality control and synchronization.
OnStartStreaming | Resets all times that control streaming.
OnStopStreaming | Called at the end of streaming to fix times for the property page report.
OnWaitEnd | Called when a wait time ends. Performance logging only.
OnWaitStart | Updates times spent waiting and not waiting. Performance logging only.
RecordFrameLateness | Records how timely the rendering occurred and gathers statistics for the property page.
ResetStreamingTimes | Resets all times that control the streaming.
ScheduleSample | Sets up an advise link with the clock.
SendQuality | Sends a quality message to indicate what the supplier should do about quality.
ShouldDrawSampleNow | Determines if the video should be drawn when it is due, without setting a timer advise link with the clock.

Implemented IQualProp Methods

get_AvgFrameRate | Retrieves the average frame rate since streaming started in frames per 100 seconds.
get_AvgSyncOffset | Retrieves the average of the time in milliseconds between when each frame was due and when it was actually rendered. This applies to all frames since streaming started.
get_DevSyncOffset | Retrieves the standard deviation of the time in milliseconds between when each frame was due and when it was actually rendered for all frames since streaming started.
get_FramesDrawn | Retrieves the number of frames drawn since streaming started.
get_FramesDroppedInRenderer | Retrieves the number of frames dropped by the renderer. Frames can also be dropped upstream.
get_Jitter | Retrieves the standard deviation of the time in milliseconds between each frame and the next. This applies to all frames since streaming started.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface Provides access to other interfaces, particularly the property page.

Implemented IQualityControl Methods

Notify | Notifies the recipient that a quality change is requested.
SetSink | Sets the IQualityControl object that will receive quality messages.

CBaseVideoRenderer::CBaseVideoRenderer

CBaseVideoRenderer Class

Constructs a CBaseVideoRenderer object.

Syntax

CBaseVideoRenderer(
    REFCLSID RenderClass,
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr
    );

Parameters

RenderClass
Class identifier for this renderer.
pName
Pointer to a description used for debugging purposes.
pUnk
Pointer to the aggregated owner object.
phr
Pointer to an HRESULT value.

Return Value

No return value.

CBaseVideoRenderer::get_AvgFrameRate

CBaseVideoRenderer Class

Calculates and retrieves the average frame rate achieved.

Syntax

HRESULT get_AvgFrameRate(
    int *piAvgFrameRate
    );

Parameters

piAvgFrameRate
Pointer to the number of frames per second since streaming began.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_AvgFrameRate method.

CBaseVideoRenderer::get_AvgSyncOffset

CBaseVideoRenderer Class

Retrieves the average of the time in milliseconds between when each frame was due and when it was actually rendered for all frames since streaming started.

Syntax

HRESULT get_AvgSyncOffset(
    int *piAvg
    );

Parameters

piAvg
Pointer to the average of the time as previously described.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_AvgSyncOffset method.

CBaseVideoRenderer::get_DevSyncOffset

CBaseVideoRenderer Class

Retrieves the standard deviation of the time in milliseconds between when each frame was due and when it was actually rendered, for all frames since streaming started.

Syntax

HRESULT get_DevSyncOffset(
    int *piDev
    );

Parameters

piDev
Pointer to the standard deviation of the time as previously described.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_DevSyncOffset method.

CBaseVideoRenderer::get_FramesDrawn

CBaseVideoRenderer Class

Retrieves the m_cFramesDrawn member variable, giving the number of frames drawn since streaming started.

Syntax

HRESULT get_FramesDrawn(
    int *pcFramesDrawn
    );

Parameters

pcFramesDrawn
Pointer to the number of frames drawn.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_FramesDrawn method.

CBaseVideoRenderer::get_FramesDroppedInRenderer

CBaseVideoRenderer Class

Retrieves the number of frames dropped by the renderer.

Syntax

HRESULT get_FramesDroppedInRenderer(
    int *pcFramesDropped
    );

Parameters

pcFramesDropped
Pointer to the number of frames dropped.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_FramesDroppedInRenderer method. This is how the property page retrieves the data from the scheduler. Frames can also be dropped upstream without the renderer even seeing them.

CBaseVideoRenderer::get_Jitter

CBaseVideoRenderer Class

Retrieves the standard deviation of time in milliseconds between each frame and the next for all frames since streaming started.

Syntax

HRESULT get_Jitter(
    int *piJitter
    );

Parameters

piJitter
Pointer to the standard deviation of the interframe time, in milliseconds.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualProp::get_Jitter method.

CBaseVideoRenderer::GetStdDev

CBaseVideoRenderer Class

Estimates the standard deviation in milliseconds between when each frame is due and when it is actually rendered, for per-frame statistics.

Syntax

HRESULT GetStdDev(
    int nSamples,
    int *piResult,
    LONGLONG llSumSq,
    LONGLONG iTot
    );

Parameters

nSamples
Integer value that contains the number of video samples received by the video renderer.
piResult
Pointer to an integer value that will contain the standard deviation.
llSumSq
Value that represents the standard deviation, in milliseconds, of all rendered video samples. The lower the value, the more consistent the rendering.
iTot
Value that represents the mean value, in milliseconds, between the stamped time and rendered time for all rendered video samples.

Return Value

Returns NOERROR.

CBaseVideoRenderer::JoinFilterGraph

CBaseVideoRenderer Class

Sends EC_WINDOW_DESTROYED event notification when a filter is removed from the filter graph.

Syntax

HRESULT JoinFilterGraph(
    IBaseFilterGraph *pGraph,
    LPCWSTR pName
    );

Parameters

pGraph
Pointer to the filter graph to join.
pName
[in, string] Pointer to the name of the filter being added.

Return Value

No return value.

Remarks

This member function overrides the CBaseFilter::JoinFilterGraph member function. If this function determines that the filter is being notified that it is leaving the filter graph (pGraph is null, but m_pGraph is not), it sends an EC_WINDOW_DESTROYED event notification so that the resource manager does not hold on to the renderer as a focus object.

CBaseVideoRenderer::NonDelegatingQueryInterface

CBaseVideoRenderer Class

Returns an interface and increments the reference count.

Syntax

HRESULT NonDelegatingQueryInterface(
    REFIID riid,
    VOID **ppv
    );

Parameters

riid
Reference identifier.
ppv
Address of a pointer to the interface.

Return Value

Returns E_POINTER if ppv is invalid. Returns NOERROR if the query is successful or E_NOINTERFACE if it is not.

CBaseVideoRenderer::Notify

CBaseVideoRenderer Class

Receives a notification that a quality change is requested.

Syntax

HRESULT Notify(
    IBaseFilter *pSelf,
    Quality q
    );

Parameters

pSelf
[in] Pointer to the filter that is sending the quality notification.
q
[in] Quality notification structure.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualityControl::Notify method on the video renderer. This is called, typically by the filter graph manager, when the quality must be cut back. This might occur when the quality of audio playback has been increased to the point that the video playback quality must be decreased.

Notify sets the m_trThrottle data member to a delay value to be inserted between frames by ThrottleWait.

CBaseVideoRenderer::OnDirectRender

CBaseVideoRenderer Class

Collects timing information that controls synchronization and quality control.

Syntax

virtual void OnDirectRender(
    IMediaSample *pMediaSample
    );

Parameters

pMediaSample
Pointer to the media sample.

Return Value

Returns an HRESULT value.

Remarks

Call this member function instead of OnRenderStart and OnRenderEnd. This is used by the Microsoft® DirectDraw® video renderer.

CBaseVideoRenderer::OnRenderEnd

CBaseVideoRenderer Class

Performs smoothing for cases where the rendering time varies due to interruptions.

Syntax

void OnRenderEnd(
    IMediaSample *pMediaSample
    );

Parameters

pMediaSample
Pointer to the media sample.

Return Value

No return value.

Remarks

This member function should be called just after drawing an image.

This member function overrides CBaseRenderer::OnRenderEnd.

CBaseVideoRenderer::OnRenderStart

CBaseVideoRenderer Class

Sets information for rendering.

Syntax

void OnRenderStart(
    IMediaSample *pMediaSample
    );

Parameters

pMediaSample
Pointer to the media sample.

Return Value

No return value.

Remarks

This member function retrieves the current clock time from the system and stores it in a member variable to be used when the drawing is complete. The function also performs performance logging. This member function should be called just before drawing starts.

This member function overrides CBaseRenderer::OnRenderStart.

CBaseVideoRenderer::OnStartStreaming

CBaseVideoRenderer Class

Resets all times that control streaming.

Syntax

HRESULT OnStartStreaming(void);

Return Value

Returns an HRESULT value.

Remarks

This member function overrides CBaseRenderer::OnStartStreaming.

CBaseVideoRenderer::OnStopStreaming

CBaseVideoRenderer Class

Called at the end of streaming to fix times for the property page report.

Syntax

HRESULT OnStopStreaming(void);

Return Value

Returns an HRESULT value.

Remarks

This member function is called twice, once when pausing and again when the stream is actually stopped.

This member function overrides CBaseRenderer::OnStopStreaming.

CBaseVideoRenderer::OnWaitEnd

CBaseVideoRenderer Class

Called when a wait time ends.

Syntax

void OnWaitEnd(void);

Return Value

No return value.

Remarks

This member function does only performance logging. It is called when the thread is awoken from waiting in the window, or when the next sample is due to be rendered. It could eventually be used to gather information that controls synchronization.

CBaseVideoRenderer::OnWaitStart

CBaseVideoRenderer Class

Updates times spent waiting and not waiting.

Syntax

void OnWaitStart(void);

Return Value

No return value.

Remarks

This member function is called when starting to wait for a rendering event. It is used only for performance measurements.

CBaseVideoRenderer::PreparePerformanceData

CBaseVideoRenderer Class

Sets the m_trLate and m_trFrame values of the current frame.

Syntax

void PreparePerformanceData(
    int trLate,
    int trFrame
    );

Parameters

trLate
Value indicating how late the sample was beyond its due time, in reference time units.
trFrame
Interframe time, in reference time units.

Return Value

No return value.

Remarks

This member function sets m_trLate to the value of trLate and m_trFrame to the value of trFrame.

When the CBaseVideoRenderer::RecordFrameLateness member function is called from either CBaseVideoRenderer::OnRenderStart or CBaseVideoRenderer::OnDirectRender, it passes the values of m_trLate and m_trFrame for it to update the statistics. PreparePerformanceData is called from CBaseVideoRenderer::OnWaitEnd to set these data member values.

CBaseVideoRenderer::RecordFrameLateness

CBaseVideoRenderer Class

Records how timely the rendering occurred and gathers statistics for the property page.

Syntax

virtual void RecordFrameLateness(
    int trLate,
    int trFrame
    );

Parameters

trLate
Value indicating how late the sample was beyond its due time, in reference time units.
trFrame
Interframe time, in reference time units.

Return Value

No return value.

CBaseVideoRenderer::ResetStreamingTimes

CBaseVideoRenderer Class

Resets all times that control the streaming.

Syntax

virtual HRESULT ResetStreamingTimes(void);

Return Value

Returns an HRESULT value.

Remarks

The times are set so that frames will not be initially dropped and so that the first frame will be drawn.

CBaseVideoRenderer::ScheduleSample

CBaseVideoRenderer Class

Overrides the base class that does the main work to keep a count of samples drawn and dropped (which are used by the IQualProp implementation).

Syntax

BOOL ScheduleSample(
    IMediaSample *pMediaSample
    );

Parameters

pMediaSample
Pointer to the media sample.

Return Value

Returns TRUE if the sample is scheduled; otherwise, returns FALSE.

CBaseVideoRenderer::SendQuality

CBaseVideoRenderer Class

Sends a quality message to indicate what the supplier should do about quality.

Syntax

virtual HRESULT SendQuality(
    REFERENCE_TIME trLate,
    REFERENCE_TIME trRealStream
    );

Parameters

trLate
Amount of time by which the frame is late.
trRealStream
Current stream time.

Return Value

Returns an HRESULT value.

Remarks

This member function sends a quality control message upstream to control quality management. The nature of the quality message (that is, whether to reduce or increase the number of samples) is determined in the quality management implementation in this derived class (see CBaseVideoRenderer::ShouldDrawSampleNow).

CBaseVideoRenderer::SetSink

CBaseVideoRenderer Class

Sets the IQualityControl object that will receive quality messages.

Syntax

HRESULT SetSink(
    IQualityControl *piqc
    );

Parameters

piqc
Pointer to the IQualityControl object to which the notifications should be sent.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IQualityControl::SetSink method on the video renderer.

CBaseVideoRenderer::ShouldDrawSampleNow

CBaseVideoRenderer Class

Determines if the video should be drawn without setting a timer advise link with the clock.

Syntax

virtual HRESULT ShouldDrawSampleNow(
    IMediaSample *pMediaSample,
    REFERENCE_TIME *ptrStart,
    REFERENCE_TIME *ptrEnd
    );

Parameters

pMediaSample
Pointer to the IMediaSample interface for the sample.
ptrStart
Pointer to the time to begin rendering.
ptrEnd
Pointer to the time to stop rendering.

Return Value

Returns an HRESULT value. Returns S_OK to mean draw at once without waiting, S_FALSE to mean draw at time ptrStart, or an error to mean do not draw the sample; that is, skip it to save time.

Remarks

This member function overrides CBaseRenderer::ShouldDrawSampleNow.

CBaseVideoRenderer::ThrottleWait

CBaseVideoRenderer Class

Inserts a wait period after each frame.

Syntax

void ThrottleWait(void);

Return Value

No return value.

Remarks

This member function waits for a time period obtained from the m_trThrottle data member.


CBaseVideoWindow Class

CBaseVideoWindow class hierarchy

The CBaseVideoWindow class handles the IDispatch component of the IVideoWindow interface and leaves the IVideoWindow properties and methods pure virtual.

Member Functions

CBaseVideoWindow Constructs a CBaseVideoWindow object.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface Returns a specified reference-counted interface.

Implemented IDispatch Methods

GetIDsOfNames | Maps a single member and an optional set of parameters to a corresponding set of integer dispatch identifiers, which can be used during subsequent calls to the IDispatch::Invoke method.
GetTypeInfo | Retrieves a type-information object, which can retrieve the type information for an interface.
GetTypeInfoCount | Retrieves the number of type-information interfaces provided by an object.
Invoke | Provides access to properties and methods exposed by an object.

CBaseVideoWindow::CBaseVideoWindow

CBaseVideoWindow Class

Constructs a CBaseVideoWindow object.

Syntax

CBaseVideoWindow(
  const TCHAR *pName,
  LPUNKNOWN pUnk
  );

Parameters

pName
Pointer to the name of the object used in the CBaseVideoWindow constructor for debugging purposes.
pUnk
Pointer to the owner of this object.

Return Value

No return value.

Remarks

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of an object.

CBaseVideoWindow::GetIDsOfNames

CBaseVideoWindow Class

Maps a single member function and an optional set of parameters to a corresponding set of integer dispatch identifiers, which can be used upon subsequent calls to the CBaseVideoWindow::Invoke member function.

Syntax

HRESULT GetIDsOfNames(

  REFIID riid,

  OLECHAR **rgszNames,

  UINT cNames,

  LCID lcid,

  DISPID *rgdispid

  );

Parameters

riid
Reference identifier. Reserved for future use. Must be NULL.
rgszNames
Address of a pointer to a passed-in array of names to be mapped.
cNames
Count of the names to be mapped.
lcid
Locale context in which to interpret the names.
rgdispid
Pointer to a caller-allocated array, each element of which contains an ID corresponding to one of the names passed in the rgszNames array. The first element represents the member name; the subsequent elements represent each of the member's parameters.

Return Value

Returns one of the following values.
DISP_E_UNKNOWN_CLSID | The CLSID was not recognized.
DISP_E_UNKNOWNNAME | One or more of the names were not known. The returned DISPIDs contain DISPID_UNKNOWN for each entry that corresponds to an unknown name.
E_OUTOFMEMORY | Out of memory.
S_OK | Success.

CBaseVideoWindow::GetTypeInfo

CBaseVideoWindow Class

Retrieves a type-information object, which can retrieve the type information for an interface.

Syntax

HRESULT GetTypeInfo(

  UINT itinfo,

  LCID lcid,

  ITypeInfo **pptinfo

  );

Parameters

itinfo
Type information to return. Pass zero to retrieve type information for the IDispatch implementation.
lcid
Locale ID for the type information. For classes that support localized member names, an object might be able to return different type information for different languages. For classes that do not support localized member names, this parameter can be ignored.
pptinfo
Address of a pointer to the type-information object requested.

Return Value

Returns an E_POINTER if pptinfo is invalid. Returns TYPE_E_ELEMENTNOTFOUND if itinfo is not zero. Returns S_OK if successful. Otherwise, returns an HRESULT from one of the calls to retrieve the type. The HRESULT indicates the error and can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.

CBaseVideoWindow::GetTypeInfoCount

CBaseVideoWindow Class

Retrieves the number of type-information interfaces provided by an object.

Syntax

HRESULT GetTypeInfoCount(

  UINT *pctinfo

  );

Parameters

pctinfo
Pointer to the location that receives the number of type-information interfaces that the object provides. If the object provides type information, this number is 1; otherwise, the number is 0.

Return Value

Returns E_POINTER if pctinfo is invalid; otherwise, returns S_OK.

CBaseVideoWindow::Invoke

CBaseVideoWindow Class

Provides access to properties and methods exposed by an object.

Syntax

HRESULT Invoke(

  DISPID dispidMember,

  REFIID riid,

  LCID lcid,

  WORD wFlags,

  DISPPARAMS *pdispparams,

  VARIANT *pvarResult,

  EXCEPINFO *pexcepinfo,

  UINT *puArgErr

  );

Parameters

dispidMember
Identifier of the member. Use CBaseVideoWindow::GetIDsOfNames or the object's documentation to obtain the dispatch identifier.
riid
Reserved for future use. Must be IID_NULL.
lcid
Locale context in which to interpret arguments.
wFlags
Flags describing the context of the CBaseVideoWindow::Invoke call.
pdispparams
Pointer to a DISPPARAMS structure containing an array of arguments, an array of argument dispatch IDs for named arguments, and counts for number of elements in the arrays.
pvarResult
Pointer to where the result is to be stored, or NULL if the caller expects no result.
pexcepinfo
Pointer to a structure containing exception information.
puArgErr
Pointer to the index of the first argument, within the rgvarg array, that has an error. The rgvarg array is a member of the DISPPARAMS structure.

Return Value

Returns DISP_E_UNKNOWNINTERFACE if riid is not IID_NULL. Returns one of the error codes from CBaseVideoWindow::GetTypeInfo if the call fails. Otherwise, returns the HRESULT from the call to IDispatch::Invoke.

CBaseVideoWindow::NonDelegatingQueryInterface

CBaseVideoWindow Class

Returns a specified reference-counted interface.

Syntax

HRESULT NonDelegatingQueryInterface(
  REFIID riid,
  void **ppv
  );

Parameters

riid
Reference identifier.
ppv
Address of a pointer to the interface.

Return Value

Returns E_POINTER if ppv is invalid. Returns NOERROR if the query is successful or E_NOINTERFACE if it is not.

Remarks

Returns pointers to the IVideoWindow and IUnknown interfaces by default. Override this method to publish any additional interfaces implemented by the derived class.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.


CBaseWindow Class

CBaseWindow class hierarchy

Base class for managing windows. Video renderers can use this class to create video windows.

Declaration: Winutil.h

To use this class, create a derived class that inherits from CBaseWindow. In the derived class:

  • Implement the pure virtual method GetClassWindowStyles, which defines the window styles.
  • Override the OnReceiveMessage method, which handles window messages.
  • Implement a destructor that calls the DoneWithWindow method.

Before using an instance of the derived class, call the PrepareWindow method.

Protected Member Variables
m_hInstance | Handle to the module instance.
m_hwnd | Handle to the object's window.
m_hdc | Handle to the window's device context.
m_Width | Width of the client area, in pixels.
m_Height | Height of the client area, in pixels.
m_bActivated | Flag that specifies whether the window has been activated.
m_pClassName | Static string that contains the name of the window class.
m_ClassStyles | Class styles for the window.
m_WindowStyles | Window styles for the window.
m_WindowStylesEx | Extended window styles for the window.
m_ShowStageMessage | Private message that brings the window to the foreground.
m_ShowStageTop | Private message that sets the window style to WS_EX_TOPMOST.
m_RealizePalette | Private message that realizes the palette.
m_MemoryDC | Handle to the memory device context.
m_hPalette | Handle to the window's palette.
m_bNoRealize | Flag that specifies whether the window should realize its palette.
m_bBackground | Flag that specifies whether the palette should be a background palette.
m_bRealizing | Flag that specifies whether a new palette is being realized.
m_WindowLock | Critical section, to serialize access to the object.
m_bDoGetDC | Flag that specifies whether to retrieve the device context.
m_bDoPostToDestroy | Flag that specifies whether the window posts or sends its destruction message.
Protected Methods
OnPaletteChange | Handles palette-change messages. Virtual.
Public Methods
CBaseWindow | Constructor method.
DoneWithWindow | Destroys the window. Virtual.
PrepareWindow | Creates the window. Virtual.
InactivateWindow | Inactivates the window. Virtual.
ActivateWindow | Sizes the window according to the requirements of the derived class. Virtual.
OnSize | Handles WM_SIZE messages. Virtual.
OnClose | Handles WM_CLOSE messages. Virtual.
GetDefaultRect | Retrieves the default size of the client area. Virtual.
UninitialiseWindow | Releases the window's resources. Virtual.
InitialiseWindow | Initializes the window. Virtual.
CompleteConnect | Notifies the window that the renderer's input pin has been connected.
DoCreateWindow | Creates the window.
PerformanceAlignWindow | Aligns the window to a DWORD boundary, for maximum performance.
DoShowWindow | Sets the window's show state.
PaintWindow | Causes the window to be repainted.
DoSetWindowForeground | Brings the window to the foreground.
SetPalette | Installs a palette for the window. Virtual.
SetRealize | Specifies whether the window realizes palettes.
DoRealisePalette | Realizes the window's current palette. Virtual.
PossiblyEatMessage | Enables a derived class to forward messages to another window. Virtual.
GetWindowWidth | Retrieves the current width of the window.
GetWindowHeight | Retrieves the current height of the window.
GetWindowHWND | Retrieves a handle to the window.
GetMemoryHDC | Retrieves a handle to the memory device context.
GetWindowHDC | Retrieves a handle to the window's device context.
OnReceiveMessage | Handles window messages. Virtual.
Pure Virtual Methods
GetClassWindowStyles | Retrieves the window's class styles and window styles.

CBaseWindow.m_hInstance

CBaseWindow Class

Handle to the module instance.

Syntax

HINSTANCE m_hInstance;

Remarks

The DLL entry point function sets a global variable with a handle to the module instance. The CBaseWindow class stores this handle in its constructor method.

CBaseWindow.m_hwnd

CBaseWindow Class

Handle to the object's window.

Syntax

HWND m_hwnd;

CBaseWindow.m_hdc

CBaseWindow Class

Handle to the window's device context.

Syntax

HDC m_hdc;

CBaseWindow.m_Width

CBaseWindow Class

Width of the client area, in pixels.

Syntax

LONG m_Width;

CBaseWindow.m_Height

CBaseWindow Class

Height of the client area, in pixels.

Syntax

LONG m_Height;

CBaseWindow.m_bActivated

CBaseWindow Class

Flag that specifies whether the window has been activated. If TRUE, the window has been activated.

Syntax

BOOL m_bActivated;

CBaseWindow.m_pClassName

CBaseWindow Class

Static string that contains the name of the window class.

Syntax

LPTSTR m_pClassName;

CBaseWindow.m_ClassStyles

CBaseWindow Class

Class styles for the window.

Syntax

DWORD m_ClassStyles;

CBaseWindow.m_WindowStyles

CBaseWindow Class

Window styles for the window.

Syntax

DWORD m_WindowStyles;

CBaseWindow.m_WindowStylesEx

CBaseWindow Class

Extended window styles for the window.

Syntax

DWORD m_WindowStylesEx;

CBaseWindow.m_ShowStageMessage

CBaseWindow Class

Private message that brings the window to the foreground.

Syntax

UINT m_ShowStageMessage;

Remarks

The DoSetWindowForeground method sends this message.

CBaseWindow.m_ShowStageTop

CBaseWindow Class

Private message that sets the window style to WS_EX_TOPMOST.

Syntax

UINT m_ShowStageTop;

Remarks

Video renderers should send this message to the window if they switch to full-screen mode.

CBaseWindow.m_RealizePalette

CBaseWindow Class

Private message that realizes the palette.

Syntax

UINT m_RealizePalette;

Remarks

The SetPalette method sends this message.

CBaseWindow.m_MemoryDC

CBaseWindow Class

Handle to the memory device context.

Syntax

HDC m_MemoryDC;

CBaseWindow.m_hPalette

CBaseWindow Class

Handle to the window's palette.

Syntax

HPALETTE m_hPalette;

CBaseWindow.m_bNoRealize

CBaseWindow Class

Flag that specifies whether the window should realize its palette. If TRUE, the window does not realize its palette. The default value is FALSE.

Syntax

BYTE m_bNoRealize;

CBaseWindow.m_bBackground

CBaseWindow Class

Flag that specifies whether the palette should be a background palette. If TRUE, the palette is selected as a background palette.

Syntax

m_bBackground;

CBaseWindow.m_bRealizing

CBaseWindow Class

Flag that specifies whether a new palette is being realized. In debug builds, the value is TRUE while the palette is changing and FALSE otherwise. This variable is not used in retail builds.

Syntax

BYTE m_bRealizing;

CBaseWindow.m_WindowLock

CBaseWindow Class

Critical section, to serialize access to the object.

Syntax

CCritSec m_WindowLock;

CBaseWindow.m_bDoGetDC

CBaseWindow Class

Flag that specifies whether to retrieve the device context (DC). If TRUE, the object retrieves a handle to the window's DC and creates a compatible memory DC.

Syntax

BOOL m_bDoGetDC;

CBaseWindow.m_bDoPostToDestroy

CBaseWindow Class

Flag that specifies whether the window posts or sends its destruction message. If TRUE, the DoneWithWindow method uses the PostMessage function to send itself a private destruction message. If FALSE, DoneWithWindow uses the SendMessage function to send the message. By default, the value is FALSE.

Syntax

BOOL m_bDoPostToDestroy;

CBaseWindow::ActivateWindow

CBaseWindow Class

Sizes the window according to the requirements of the derived class.

Syntax

virtual HRESULT ActivateWindow(void);

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | Window was already activated.
S_OK | Success.

Remarks

This methods calls the CBaseWindow::GetDefaultRect method to determine the window size. The derived class should override GetDefaultRect to return the size of the images that will be displayed.

If the window is already active, calling ActivateWindow moves the window to the top of the Z order, but does not resize the window. The same is true if the window has a parent.

CBaseWindow::CBaseWindow

CBaseWindow Class

Constructor method.

Syntax

CBaseWindow(
    BOOL bDoGetDC = TRUE
    BOOL bPostToDestroy = FALSE
);

Parameters

bDoGetDC
Boolean value that specifies whether to retrieve the device context.
bPostToDestroy
Boolean value that specifies the m_bDoPostToDestroy member variable.

Remarks

After you create the object, call the PrepareWindow method to create the window. PrepareWindow is a virtual method. It calls InitialiseWindow, also a virtual method. These methods are separated from the constructor so that derived classes can override them, if necessary.

If the value of the bDoGetDC parameter is TRUE, the CBaseWindow object retrieves a handle to the window's device context (DC) and stores it in the m_hdc member variable. The object also creates a compatible memory DC, which it stores in the m_MemoryDC member variable. These actions occur in the InitialiseWindow method.

CBaseWindow::CompleteConnect

CBaseWindow Class

Notifies the window that the renderer's input pin has been connected.

Syntax

HRESULT CompleteConnect(void);

Return Value

Returns S_OK.

Remarks

This method resets the window activation flag (m_bActivated) to FALSE. When a video renderer completes a pin connection, it might call the ActivateWindow method to set the window's size and position. To force ActivateWindow to recalculate these attributes, first call the CompleteConnect method.

CBaseWindow::DoCreateWindow

CBaseWindow Class

Creates the window.

Syntax

HRESULT DoCreateWindow(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

The PrepareWindow method calls this method.

CBaseWindow::DoneWithWindow

CBaseWindow Class

Destroys the window.

Syntax

virtual HRESULT DoneWithWindow(void);

Return Value

Returns S_OK.

Remarks

Call this method from the derived object's destructor method.

If this method is called from the same thread that created the window, the method performs the following actions:

  • Calls the InactivateWindow method, which deactivates the window.
  • Calls the UninitialiseWindow method, which releases resources used by the window.
  • Destroys the window.

If the thread calling DoneWithWindow is not the thread that created the window, the method sends a private "destroy" message to the window. When the window receives this message, it calls DoneWithWindow on itself. (If m_bDoPostToDestroy is TRUE, the window posts the message.)

CBaseWindow::DoRealisePalette

CBaseWindow Class

Realizes the window's current palette.

Syntax

virtual HRESULT DoRealisePalette(
    BOOL bForceBackground
);

Parameters

bForceBackground
Boolean value that specifies whether the palette is forced to be a background palette. For more information, see SelectPalette in the Platform SDK.

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | An internal call to GdiFlush returned an error.
S_OK | Success.

Remarks

The CBaseWindow::OnPaletteChange method calls this method. To set a new palette, call the CBaseWindow::SetPalette method.

CBaseWindow::DoSetWindowForeground

CBaseWindow Class

Brings the window to the foreground.

Syntax

void DoSetWindowForeground(
    BOOL bFocus
);

Parameters

bFocus
Boolean value that specifies whether to give the window focus. If the value is TRUE, the window gains focus.

CBaseWindow::DoShowWindow

CBaseWindow Class

Sets the window's show state.

Syntax

HRESULT DoShowWindow(
    LONG ShowCmd
);

Parameters

ShowCmd
Flag that specifies how the window is to be shown. The value can be any constant defined for the nCmdShow parameter of the Microsoft® Windows® ShowWindow function. For more information, see the Platform SDK.

Return Value

Returns S_OK.

CBaseWindow::GetClassWindowStyles

CBaseWindow Class

Retrieves the window's class styles and window styles.

Syntax

virtual LPTSTR GetClassWindowStyles(
    DWORD *pClassStyles,
    DWORD *pWindowStyles,
    DWORD *pWindowStylesEx
) PURE;

Parameters

pClassStyles
Pointer to a variable that receives the class styles.
pWindowStyles
Pointer to a variable that receives the window styles.
pWindowStylesEx
Pointer to a variable that receives the extended window styles.

Return Value

Returns a static text string that contains the class name.

Remarks

The CBaseWindow::PrepareWindow method calls this method to retrieve the window's class styles and window styles.

This method is pure virtual; the derived class must implement it. The following example shows a possible implementation:

LPTSTR CMyWindowClass::GetClassWindowStyles(DWORD *pClassStyles,
                                            DWORD *pWindowStyles,
                                            DWORD *pWindowStylesEx)
{
    *pClassStyles = CS_HREDRAW | CS_VREDRAW;
    *pWindowStyles = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN;
    *pWindowStylesEx = WS_EX_WINDOWEDGE;
    return TEXT("MyWindowClass");
}

The object uses the class style for the lpszClassName member of a WNDCLASS structure, which it passes to the RegisterClass function. The object uses the window styles for the dwExStyle and dwStyle parameters of the CreateWindowEx function. For more information, see the Platform SDK.

CBaseWindow::GetDefaultRect

CBaseWindow Class

Retrieves the default size of the client area.

Syntax

virtual RECT GetDefaultRect(void);

Return Value

Returns the default rectangle.

Remarks

When the window is activated, the object calls this method to determine how large it should make the window's client area. In the base class, this method returns a rectangle whose height and width are the defined constants DEFHEIGHT and DEFWIDTH. A derived class should override this method. For a video renderer, the derived class will typically return the size of the native video image.

CBaseWindow::GetMemoryHDC

CBaseWindow Class

Retrieves a handle to the memory device context (DC).

Syntax

virtual HDC GetMemoryHDC(void);

Return Value

Returns a handle to the memory DC.

CBaseWindow::GetWindowHDC

CBaseWindow Class

Retrieves a handle to the window's device context (DC).

Syntax

HDC GetWindowHDC(void);

Return Value

Returns a handle to the DC.

CBaseWindow::GetWindowHeight

CBaseWindow Class

Retrieves the current height of the window.

Syntax

LONG GetWindowHeight(void);

Return Value

Returns the height of the window, in pixels.

CBaseWindow::GetWindowHWND

CBaseWindow Class

Retrieves a handle to the window.

Syntax

HWND GetWindowHWND(void);

Return Value

Returns a handle to the window.

CBaseWindow::GetWindowWidth

CBaseWindow Class

Retrieves the current width of the window.

Syntax

LONG GetWindowWidth(void);

Return Value

Returns the width of the window, in pixels.

CBaseWindow::InactivateWindow

CBaseWindow Class

Inactivates the window. In the base class, this method hides the window.

Syntax

virtual HRESULT InactivateWindow(void);

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
S_FALSE | Window is already inactive.

CBaseWindow::InitialiseWindow

CBaseWindow Class

Initializes the window.

Syntax

virtual InitialiseWindow(
    HWND hwnd
);

Parameters

hwnd
Handle to the window.

Return Value

Returns S_OK.

Remarks

By default, this method retrieves a handle to the window's device context (DC) and creates a compatible memory DC. If the value of the m_bDoGetDC flag is FALSE, however, this method does not retrieve the device contexts. The memory DC is useful for selecting bitmaps before blitting them to the window.

The DoCreateWindow method calls this method.

CBaseWindow::OnClose

CBaseWindow Class

Handles WM_CLOSE messages.

Syntax

virtual BOOL OnClose(void);

Return Value

Returns TRUE.

Remarks

In the base class, this method simply hides the window. Typically, a derived class will override this method so that it sends an EC_USERABORT event as well. Do not override the method to destroy the window. Instead, call the CBaseWindow::DoneWithWindow method when the owning filter is destroyed.

CBaseWindow::OnPaletteChange

CBaseWindow Class

Handles palette-change messages.

Syntax

virtual LRESULT OnPaletteChange(
    HWND hwnd,
    UINT Message
);

Parameters

hwnd
Handle to the window.
Message
Message identifier.

Return Value

Returns 0 if the message was processed, or 1 if the message was not processed.

Remarks

This method handles WM_PALETTECHANGED and WM_QUERYNEWPALETTE messages. It calls the DoRealisePalette method to realize the new palette.

CBaseWindow::OnReceiveMessage

CBaseWindow Class

Handles window messages.

Syntax

virtual LRESULT OnReceiveMessage(
    HWND hwnd,
    INT uMsg,
    WPARAM wParam,
    LPARAM lParam
);

Parameters

hwnd
Handle to the window.
uMsg
Message identifier.
wParam
First message parameter.
lParam
Second message parameter.

Return Value

Returns 0 if the message was processed, or 1 if the message was not processed.

Remarks

The base class handles the following messages:

  • WM_CLOSE
  • WM_MOVE
  • WM_PALETTECHANGED
  • WM_QUERYNEWPALETTE
  • WM_SIZE
  • WM_SYSCOLORCHANGE

A derived class can override this method to handle other messages. The derived class should call the base class method to handle any messages that the derived class ignores.

CBaseWindow::OnSize

CBaseWindow Class

Handles WM_SIZE messages.

Syntax

virtual BOOL OnSize(
    LONG Width,
    LONG Height
);

Parameters

Width
Width of the client area, in pixels.
Height
Height of the client area, in pixels.

Return Value

Returns TRUE.

Remarks

This method stores the new width and height. To retrieve these values, call the CBaseWindow::GetWindowHeight and CBaseWindow::GetWindowWidth methods.

CBaseWindow::PaintWindow

CBaseWindow Class

Causes the window to be repainted.

Syntax

void PaintWindow(
    BOOL bErase
);

Parameters

bErase
Boolean value that specifies whether the background is erased. If the value is TRUE, the background is erased.

Remarks

This method generates a WM_PAINT message by invalidating the window's entire client area.

CBaseWindow::PerformanceAlignWindow

CBaseWindow Class

Aligns the window to a DWORD boundary, for maximum performance.

Syntax

HRESULT PerformanceAlignWindow(void);

Return Value

Returns S_OK.

Remarks

This method aligns the left and top edges of the window to DWORD boundaries, which can improve performance. If the window has a parent, the method returns S_OK but does perform the alignment.

CBaseWindow::PossiblyEatMessage

CBaseWindow Class

Enables a derived class to forward messages to another window.

Syntax

virtual BOOL PossiblyEatMessage(
    UINT uMsg,
    WPARAM wParam,
    LPARAM lParam
);

Parameters

uMsg
Message identifier.
wParam
First message parameter.
lParam
Second message parameter.

Return Value

Returns TRUE if the message was forwarded, or FALSE otherwise. The base class returns FALSE.

Remarks

Before the CBaseWindow::OnReceiveMessage method handles a message, it calls PossiblyEatMessage. If PossiblyEatMessage returns TRUE, OnReceiveMessage ignores the message. A derived class can override PossiblyEatMessage so that it forwards some messages to an owner window. For example, the CBaseControlWindow class, which derives from CBaseWindow, forwards keyboard and mouse messages.

CBaseWindow::PrepareWindow

CBaseWindow Class

Creates the window.

Syntax

virtual HRESULT PrepareWindow(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_FAIL | Failure.

Remarks

Call this method after creating the object. This method performs some initial bookkeeping and then calls the DoCreateWindow method to create the window.

CBaseWindow::SetPalette

CBaseWindow Class

Installs a palette for the window.

Syntax

virtual HRESULT SetPalette(
    HPALETTE hPalette
);

HRESULT SetPalette(void);

Parameters

hPalette
Handle to the new palette. Cannot be NULL.

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | An internal call to GdiFlush returned an error.
S_OK | Success.

Remarks

The hPalette parameter specifies a new palette. If the method is called with no parameters, the palette given by the m_hPalette member variable is selected. The caller must ensure the validity of m_hPalette.

If the value of the m_bNoRealize member variable is FALSE (the default), this method selects the palette and realizes it. Otherwise, it selects the palette but does not realize it. The object does not delete any previous palette that it was using. The caller is responsible for deleting palettes.

Any thread can safely call this method, not just the thread that owns the window. The window sends a private message to itself, which triggers a call to the OnPaletteChange method.

CBaseWindow::SetRealize

CBaseWindow Class

Specifies whether the window realizes palettes.

Syntax

void SetRealize(
    BOOL bRealize
);

Parameters

bRealize
Boolean value that specifies whether to realize palettes. If TRUE, the SetPalette method realizes palettes.

Remarks

By default, the SetPalette method realizes the specified palette. Call this method to change the default behavior, so that palettes are selected but not realized. This method sets the m_bNoRealize member variable.

CBaseWindow::UninitialiseWindow

CBaseWindow Class

Releases the window's resources.

Syntax

virtual UninitialiseWindow(void);

Return Value

Returns S_OK.

Remarks

This method frees resources that were acquired by the InitialiseWindow method. The DoneWithWindow method calls this method.


CBasicAudio Class

CBasicAudio class hierarchy

The CBasicAudio class handles the IDispatch interface component of the IBasicAudio interface and leaves the properties and methods of IBasicAudio pure virtual to be implemented by a derived filter class.

The CBasicAudio::GetIDsOfNames, CBasicAudio::GetTypeInfo, CBasicAudio::GetTypeInfoCount, and CBasicAudio::Invoke member functions are standard implementations of the IDispatch interface using the CBaseDispatch class (and a type library) to parse the commands and pass them to the pure virtual IBasicAudio methods.

Microsoft® DirectShow® uses units of 100th of a decibel for the volume scale. A value of 0 indicates maximum volume supported by the device. A value of –10,000 is the minimum volume (usually silence). Balance is expressed in the range –10,000 to 10,000, with 0 being neutral. A negative balance value means that the right channel is attenuated by this decibel value (that is, it is quieter). Similarly, a positive balance value means that the right channel is louder than the left; that is, the left channel is attenuated by the corresponding negative decibel value.

Member Functions

CBasicAudio Constructs a CBasicAudio object.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface Retrieves a specified reference-counted interface.

Implemented IDispatch Methods

GetIDsOfNames | Maps a single member and an optional set of parameters to a corresponding set of integer dispatch identifiers, which can be used during subsequent calls to the CBasicAudio::Invoke member function.
GetTypeInfo | Retrieves a type-information object, which can retrieve the type information for an interface.
GetTypeInfoCount | Retrieves the number of type-information interfaces provided by an object.
Invoke | Provides access to properties and methods exposed by an object.

CBasicAudio::CBasicAudio

CBasicAudio Class

Constructs a CBasicAudio object.

Syntax

CBasicAudio(
  const TCHAR *pName,
  LPUNKNOWN pUnk
  );

Parameters

pName
Pointer to the name of the object used in the CBasicAudio constructor for debugging purposes.
pUnk
Pointer to the owner of this object.

Return Value

No return value.

Remarks

Allocate the pName parameter in static memory. This name appears on the debugging terminal when the object is created and deleted.

CBasicAudio::GetIDsOfNames

CBasicAudio Class

Maps a single member function and an optional set of parameters to a corresponding set of integer dispatch identifiers, which can be used upon subsequent calls to the CBasicAudio::Invoke member function.

Syntax

HRESULT GetIDsOfNames(

  REFIID riid,

  OLECHAR **rgszNames,

  UINT cNames,

  LCID lcid,

  DISPID *rgdispid

  );

Parameters

riid
Reference identifier. Reserved for future use. Must be NULL.
rgszNames
Address of a pointer to a passed-in array of names to be mapped.
cNames
Count of the names to be mapped.
lcid
Locale context in which to interpret the names.
rgdispid
Pointer to a caller-allocated array, each element of which contains an ID corresponding to one of the names passed in the rgszNames array. The first element represents the member name; the subsequent elements represent each of the member's parameters.

Return Value

Returns one of the following values.
DISP_E_UNKNOWN_CLSID | The CLSID was not recognized.
DISP_E_UNKNOWNNAME | One or more of the names were not known. The returned DISPIDs contain DISPID_UNKNOWN for each entry that corresponds to an unknown name.
E_OUTOFMEMORY | Out of memory.
S_OK | Success.

CBasicAudio::GetTypeInfo

CBasicAudio Class

Retrieves a type-information object, which can retrieve the type information for an interface.

Syntax

HRESULT GetTypeInfo(

  UINT itinfo,

  LCID lcid,

  ITypeInfo **pptinfo

  );

Parameters

itinfo
Type information to return. Pass zero to retrieve type information for the IDispatch implementation.
lcid
Locale ID for the type information. For classes that support localized member names, an object might be able to return different type information for different languages. This is important for classes that support localized member names. For classes that do not support localized member names, this parameter can be ignored.
pptinfo
Address of a pointer to the type-information object requested.

Return Value

Returns an E_POINTER if pptinfo is invalid. Returns TYPE_E_ELEMENTNOTFOUND if itinfo is not zero. Returns S_OK if is successful. Otherwise, returns an HRESULT from one of the calls to retrieve the type. The HRESULT indicates the error and can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.

CBasicAudio::GetTypeInfoCount

CBasicAudio Class

Retrieves the number of type-information interfaces provided by an object.

Syntax

HRESULT GetTypeInfoCount(

  UINT *pctinfo

  );

Parameters

pctinfo
Pointer to the location that receives the number of type-information interfaces that the object provides. If the object provides type information, this number is 1; otherwise, the number is 0.

Return Value

Returns E_POINTER if pctinfo is invalid; otherwise, returns S_OK.

CBasicAudio::Invoke

CBasicAudio Class

Provides access to properties and methods exposed by an object.

Syntax

HRESULT Invoke(

  DISPID dispidMember,

  REFIID riid,

  LCID lcid,

  WORD wFlags,

  DISPPARAMS *pdispparams,

  VARIANT *pvarResult,

  EXCEPINFO *pexcepinfo,

  UINT *puArgErr

  );

Parameters

dispidMember
Identifier of the member. Use CBasicAudio::GetIDsOfNames or the object's documentation to obtain the dispatch identifier.
riid
Reserved for future use. Must be IID_NULL.
lcid
Locale context in which to interpret arguments.
wFlags
Flags describing the context of the CBasicAudio::Invoke call.
pdispparams
Pointer to a DISPPARAMS structure containing an array of arguments, an array of argument dispatch IDs for named arguments, and counts for number of elements in the arrays.
pvarResult
Pointer to where the result is to be stored, or NULL if the caller expects no result.
pexcepinfo
Pointer to a structure containing exception information.
puArgErr
Pointer to the index of the first argument, within the rgvarg array, that has an error. The rgvarg array is a member of the DISPPARAMS structure.

Return Value

Returns DISP_E_UNKNOWNINTERFACE if riid is not IID_NULL. Returns one of the error codes from CBasicAudio::GetTypeInfo if the call fails. Otherwise, returns the HRESULT from the call to IDispatch::Invoke.

CBasicAudio::NonDelegatingQueryInterface

CBasicAudio Class

Returns a specified reference-counted interface.

Syntax

HRESULT NonDelegatingQueryInterface(
  REFIID riid,
  void **ppv
  );

Parameters

riid
Reference identifier.
ppv
Address of a pointer to the interface.

Return Value

Returns E_POINTER if ppv is invalid. Returns NOERROR if the query is successful or E_NOINTERFACE if it is not.

Remarks

Returns pointers to the IBasicAudio and IUnknown interfaces by default. Override this member function to publish any additional interfaces implemented by the derived class.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.


CCmdQueue Class

The CCmdQueue class is a base class that provides a queue of CDeferredCommand objects and member functions to add, remove, check status, and invoke the queued commands. A CCmdQueue object is a part of an object that implements IQueueCommand methods. The filter graph manager implements IQueueCommand methods so that applications can queue commands to the filter graph. Filters that implement the IQueueCommand interface directly use this class. If you want to use CDeferredCommand objects, your queue must be derived from this class.

There are two modes of synchronization: coarse and accurate. In coarse mode, the application waits until a specified time arrives and then executes the command. In accurate mode, the application waits until processing begins on the sample that appears at the time, and then executes the command. The filter determines which one it will implement. The filter graph manager always implements coarse mode for commands that are queued at the filter graph manager.

If you want coarse synchronization, you probably want to wait until there is a command due, and then execute it. You can do this by calling CCmdQueue::GetDueCommand. If you have several things to wait for, get the event handle from CCmdQueue::GetDueHandle and then call CCmdQueue::GetDueCommand when this is signaled. stream time will advance only between calls to the CCmdQueue::Run and CCmdQueue::EndRun member functions. There is no guarantee that if the handle is set, there will be a command ready. Each time the event is signaled, call the GetDueCommand member function (probably with a time-out of zero); this can return E_ABORT if no command is ready.

If you want accurate synchronization, call the CCmdQueue::GetCommandDueFor member function and pass the samples you are about to process as a parameter. This returns the following:

  • A stream-time command due at or before that stream time.
  • A presentation-time command due at or before the presentation of the stream time. Do this only between the CCmdQueue::Run and CCmdQueue::EndRun member functions, because outside of this, the mapping from stream time to presentation time is not known.
  • Any presentation-time command due now.

If you want accurate synchronization for samples that might be processed during paused mode, you must use stream-time commands.

In all cases, commands remain queued until called or canceled. The setting and resetting of the event handle is managed entirely by this queue object.

Protected Data Members

m_bRunning | Flag for running state; set TRUE when running.
m_dwAdvise | Advise identifier from the reference clock (zero if no outstanding advise).
m_evDue | Sets the time when any commands are due.
m_listPresentation | Stores commands queued in presentation time.
m_listStream | Stores commands queued in stream time.
m_Lock | Protects access to lists.
m_pClock | Current reference clock.
m_StreamTimeOffset | Contains the stream time offset when m_bRunning is true.
m_tCurrentAdvise | Advise time is for this presentation time.

Member Functions

CCmdQueue | Constructs a CCmdQueue object.
CheckTime | Determines if a given time is due.
GetDueHandle | Retrieves the event handle that will be signaled.

Overridable Member Functions

EndRun | Switches to stopped or paused mode.
GetCommandDueFor | Retrieves a deferred command that is scheduled at a specified time.
GetDueCommand | Retrieves a pointer to the next command that is due.
Insert | Adds the CDeferredCommand object to the queue.
New | Initializes a command to be run and returns a new CDeferredCommand object.
Remove | Removes the CDeferredCommand object from the queue.
Run | Switches to running mode.
SetSyncSource | Sets the clock used for timing.
SetTimeAdvise | Sets up a timer event with the reference clock.

CCmdQueue::CCmdQueue

CCmdQueue Class

Constructs a CCmdQueue object.

Syntax

CCmdQueue(void);

Return Value

No return value.

CCmdQueue::CheckTime

CCmdQueue Class

Determines if a specified time is due.

Syntax

BOOL CheckTime(
    CRefTime time,
    BOOL bStream
    );

Parameters

time
Time to check.
bStream
TRUE if the time parameter is a stream-time value; FALSE if time is a presentation-time value.

Return Value

Returns TRUE if the specified time has not yet passed.

CCmdQueue::EndRun

CCmdQueue Class

Switches to the stopped or paused mode.

Syntax

virtual HRESULT EndRun(void);

Return Value

Returns an HRESULT value that depends on the implementation. The HRESULT indicates the error and can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
S_OK or NOERROR | Success.

Remarks

Time mapping between stream time and presentation time is not known after this member function has been called. Call the CCmdQueue::Run member function to carry out this mapping.

CCmdQueue::GetCommandDueFor

CCmdQueue Class

Retrieves a deferred command that is scheduled at a specified time.

Syntax

virtual HRESULT GetCommandDueFor(
    REFERENCE_TIME tStream,
    CDeferredCommand **ppCmd
    );

Parameters

tStream
Time for which the command is scheduled.
ppCmd
Address of a pointer to the deferred command to be carried out at the time specified in the tStream parameter.

Return Value

Returns VFW_E_NOT_FOUND if no commands are due; otherwise, returns S_OK.

Remarks

This member function takes a stream time and returns the deferred command scheduled at that time. The actual stream-time offset is calculated when the command queue is run. Commands remain queued until run or canceled. This member function will not block.

CCmdQueue::GetDueCommand

CCmdQueue Class

Retrieves a pointer to the next command that is due.

Syntax

virtual HRESULT GetDueCommand(
    CDeferredCommand **ppCmd,
    long msTimeout
    );

Parameters

ppCmd
Address of a pointer to the deferred command.
msTimeout
Amount of time to wait before carrying out the time-out.

Return Value

Returns E_ABORT if a time-out occurs. Returns S_OK if successful; otherwise, returns an error. Returns an object that has been incremented using IUnknown::AddRef.

Remarks

This member function blocks until a pending command is due. The member function blocks for the amount of time, in milliseconds, specified in the msTimeout parameter. Stream-time commands become due only between the CCmdQueue::Run and CCmdQueue::EndRun member functions. The command remains queued until run or canceled.

CCmdQueue::GetDueHandle

CCmdQueue Class

Retrieves the event handle to be signaled.

Syntax

HANDLE GetDueHandle(void);

Return Value

Returns the event handle.

Remarks

Return the event handle whenever there are deferred commands that are due for execution (when CCmdQueue::GetDueCommand will not block).

CCmdQueue::Insert

CCmdQueue Class

Adds the CDeferredCommand object to the queue.

Syntax

virtual HRESULT Insert(
    CDeferredCommand *pCmd
    );

Parameters

pCmd
Pointer to the CDeferredCommand object to add to the queue.

Return Value

Returns S_OK in the default implementation.

CCmdQueue::New

CCmdQueue Class

Initializes a command to be run and returns a new CDeferredCommand object.

Syntax

virtual HRESULT New(
    CDeferredCommand **ppCmd,
    LPUNKNOWN pUnk,
    REFTIME time,
    GUID *iid,
    long dispidMethod,
    short wFlags,
    long cArgs,
    VARIANT *pDispParams,
    VARIANT *pvarResult,
    short *puArgErr,
    BOOL bStream
    );

Parameters

ppCmd
Address of a pointer to a CDeferredCommand object by which an application can cancel the command, set a new presentation time for it, or retrieve estimate information.
pUnk
Pointer to the object that will run the command.
time
Time at which to run the queued command or commands.
iid
Pointer to the globally unique identifier (GUID) of the interface to call.
dispidMethod
Method on the interface to be called.
wFlags
Flags describing the context of the call. This parameter supports the same flags as the IDispatch::Invoke method.
cArgs
Number of arguments passed.
pDispParams
Pointer to the list of variant types associated with the dispatch parameters.
pvarResult
Pointer to the list where results, if any, are to be returned.
puArgErr
Pointer to the index within the pDispParams parameter list where the last error occurred.
bStream
Value indicating whether the time parameter is a stream-time value (TRUE) or a presentation-time value (FALSE).

Return Value

Returns S_OK if successful. Returns E_OUTOFMEMORY if ppCmd returns from creating the new CDeferredCommand object with a value of NULL. Otherwise, returns an HRESULT that indicates an error from attempting to create a new CDeferredCommand object. If there is an error, no object has been queued.

Remarks

The new CDeferredCommand object will be initialized with the parameters and will be added to the queue during construction. This method is similar to the IDispatch::Invoke method.

Values for the wFlags parameter include the following:
DISPATCH_METHOD | The member is being run as a method. If a property has the same name, both this and the DISPATCH_PROPERTYGET flag can be set.
DISPATCH_PROPERTYGET | The member is being retrieved as a property or data member.
DISPATCH_PROPERTYPUT | The member is being changed as a property or data member.
DISPATCH_PROPERTYPUTREF | The member is being changed via a reference assignment, rather than a value assignment. This value is valid only when the property accepts a reference to an object.

CCmdQueue::Remove

CCmdQueue Class

Removes the CDeferredCommand object from the queue.

Syntax

virtual HRESULT Remove(
    CDeferredCommand *pCmd
    );

Parameters

pCmd
Pointer to the CDeferredCommand object to remove from the queue.

Return Value

Returns VFW_E_NOT_FOUND if the object is not found in the queue. Otherwise, returns S_OK.

CCmdQueue::Run

CCmdQueue Class

Switches to running mode so that commands that are deferred by the stream time can be run.

Syntax

virtual HRESULT Run(
    REFERENCE_TIME tStreamTimeOffset
    );

Parameters

tStreamTimeOffset
Offset time.

Return Value

Returns S_OK in the default implementation.

Remarks

During running mode, stream-time-to-presentation-time mapping is known.

CCmdQueue::SetSyncSource

CCmdQueue Class

Sets the clock used for timing.

Syntax

virtual HRESULT SetSyncSource(
    IReferenceClock *pIrc
    );

Parameters

pIrc
Pointer to the IReferenceClock interface.

Return Value

Returns S_OK in the default implementation.

CCmdQueue::SetTimeAdvise

CCmdQueue Class

Sets up a timer event with the reference clock.

Syntax

void SetTimeAdvise(void);

Return Value

No return value.

Remarks

This member function calls the IReferenceClock::AdviseTime method to set up a notification for the earliest time required in the queue. Presentation-time commands that are deferred are always checked. If the filter graph is in running mode, deferred commands using stream time are also checked.


CCritSec Class

CCritSec class hierarchy

Provides a thread lock.

Declaration: Wxutil.h

This class is a wrapper for a critical section. You can lock and unlock the thread by calling the Lock and Unlock methods. However, it is safer to use this class in conjunction with the CAutoLock class. When the CAutoLock class goes out of scope, it automatically unlocks the CCritSec object. Moreover, it compiles to efficient inline code.

Public Member Variables
m_currentOwner | Thread identifier of the owning thread.
m_lockCount | Number of outstanding locks on this object.
m_fTrace | Boolean value that specifies whether to trace this lock.
Public Methods
CCritSec | Constructor method.
~CCritSec | Destructor method.
Lock | Locks the critical section object.
Unlock | Unlocks the critical section object.

CCritSec.m_currentOwner

CCritSec Class

Thread identifier of the owning thread.

Syntax

DWORD m_currentOwner;

Remarks

This member variable is defined only in the debug version of the base class. The CCritSec debug functions use this member.

CCritSec.m_lockCount

CCritSec Class

Number of outstanding locks on this object.

Syntax

DWORD m_lockCount;

Remarks

This member variable is defined only in the debug version of the base class. The CCritSec debug functions use this member.

CCritSec.m_fTrace

CCritSec Class

Boolean value that specifies whether to trace this lock.

Syntax

BOOL m_fTrace;

Remarks

This member variable is defined only in the debug version of the base class. If the value is TRUE, a trace of the lock state is written to the debug log. (Debug logging for critical sections must be active.) For more information, see DbgLockTrace.

CCritSec::CCritSec

CCritSec Class

Constructor method.

Syntax

CCritSec(void);

Remarks

This method calls the Microsoft® Win32® InitializeCriticalSection function to initialize the critical section.

CCritSec::~CCritSec

CCritSec Class

Destructor method.

Syntax

~CCritSec(void);

Remarks

This method calls the Microsoft® Win32® DeleteCriticalSection function to delete the critical section.

CCritSec::Lock

CCritSec Class

Locks the critical section object.

Syntax

void Lock(void);

Return Value

No return value.

Remarks

This method calls the Microsoft® Win32® EnterCriticalSection method.

Call the CCritSec::Unlock member function to unlock the critical section. You can make multiple calls to the Lock method on the same thread; be sure to call Unlock a corresponding number of times.

If the object is already locked by another thread, the CCritSec::Lock method blocks until the object is released, or until a possible-deadlock exception occurs.

CCritSec::Unlock

CCritSec Class

Unlocks the critical section object.

Syntax

void Unlock(void);

Return Value

No return value.

Remarks

This method calls the Microsoft® Win32® LeaveCriticalSection method.

Call this method once for each call to the Lock method.


CCrossbar Class

CCrossbar is a helper class that you can you use in an application to control Analog Video Crossbar filters on devices such as analog TV tuner cards. These cards generally have multiple inputs (for composite video, S-video, TV Audio, and so on). The crossbar filter represents all the possible ways in which a signal coming into a given input can be routed on the hardware. Some devices may implement multiple crossbars connected in series and some devices may have no crossbars.

This class creates a single object that encapsulates all connected crossbars. CCrossbar enumerates all unique inputs that can be reached from a given starting pin and automatically routes audio when a video source is selected.

CCrossbar supports an arbitrarily complex graph of crossbar filters. These filters can be layered and can contain dead inputs and outputs. CCrossbar can enumerate all the possible inputs and select a single input for recording and viewing.

Given a starting input pin (typically the analog video input to the capture filter), this class recursively traces upstream searching for all viable inputs. An input is considered viable if it is a video pin and is either unconnected or is connected to a filter that does not support the IAMCrossbar interface. The use of this class is demonstrated in the AMCap sample application in the DirectX® 8 SDK.

Member Functions

CCrossbar | Constructs a CCrossbar object.
GetInputCount | Retrieves the number of unique video inputs that can be selected.
GetInputIndex | Retrieves the currently selected input.
GetInputName | Retrieves a human-readable string describing the type of each input.
GetInputType | Retrieves the computer-readable physical type of each input.
SetInputIndex | Selects a particular input.

CCrossbar::CCrossbar

CCrossbar Class

Constructs a CCrossbar object.

Syntax

CCrossbar(
    IPin *pPin);

Parameters

pPin
Pointer to starting input pin.

Return Value

No return value.

CCrossbar::GetInputCount

CCrossbar Class

Retrieves the number of unique video inputs that can be selected.

Syntax

HRESULT GetInputCount(
    LONG *pCount);

Parameters

pCount
Pointer to the number of video inputs.

Return Value

Returns S_OK.

CCrossbar::GetInputIndex

CCrossbar Class

Retrieves the currently selected input.

Syntax

HRESULT GetInputIndex(
    LONG *Index);

Parameters

Index
Pointer to current routing index.

Return Value

Returns S_OK.

CCrossbar::GetInputName

CCrossbar Class

Retrieves a human-readable string describing the type of each input.

Syntax

HRESULT GetInputName(
    LONG Index,
    TCHAR *pName,
    LONG NameSize);

Parameters

Index
Current routing index.
pName
Pointer to the buffer that will receive the text version of the current routing input. It cannot be equal to NULL before the method call or the operation will fail. For example, if the current routing input is of type PhysConn_Video_Tuner, the function will return the string "Video Tuner" in this parameter. For more information, see Remarks.
NameSize
Size of the buffer that will receive the text version of the current routing input. Note that the buffer pointed to by pName must be large enough to include a terminating null character.

Return Value

If the buffer is large enough to copy the string name, the method returns S_OK; otherwise, the method returns E_FAIL.

Remarks

The following table shows what the pName parameter returns, depending on the current routing type.

Physical type | pName
PhysConn_Video_Tuner | Video Tuner
PhysConn_Video_Composite | Video Composite
PhysConn_Video_SVideo | Video SVideo
PhysConn_Video_RGB | Video RGB
PhysConn_Video_YRYBY | Video YRYBY
PhysConn_Video_SerialDigital | Video SerialDigital
PhysConn_Video_ParallelDigital | Video ParallelDigital
PhysConn_Video_SCSI | Video SCSI
PhysConn_Video_AUX | Video AUX
PhysConn_Video_1394 | Video 1394
PhysConn_Video_USB | Video USB
PhysConn_Video_VideoDecoder | Video Decoder
PhysConn_Video_VideoEncoder | Video Encoder
PhysConn_Audio_Tuner | Audio Tuner
PhysConn_Audio_Line | Audio Line
PhysConn_Audio_Mic | Audio Mic
PhysConn_Audio_AESDigital | Audio AESDigital
PhysConn_Audio_SPDIFDigital | Audio SPDIFDigital
PhysConn_Audio_SCSI | Audio SCSI
PhysConn_Audio_AUX | Audio AUX
PhysConn_Audio_1394 | Audio 1394
PhysConn_Audio_USB | Audio USB
PhysConn_Audio_AudioDecoder | Audio Decoder

CCrossbar::GetInputType

CCrossbar Class

Retrieves the computer-readable physical type of each input.

Syntax

HRESULT GetInputType(
    LONG Index,
    LONG *PhysicalType);

Parameters

Index
Current routing index.
PhysicalType
Pointer to the physical type of pin (video). Returns a member of the PhysicalConnectorType enumerated data type.

Return Value

Returns E_FAIL if the Index parameter is out of bounds; otherwise, returns S_OK.

CCrossbar::SetInputIndex

CCrossbar Class

Selects a particular input.

Syntax

HRESULT SetInputIndex(
    LONG Index);

Parameters

Index
Routing index to be set.

Return Value

Returns S_OK if successful; otherwise, returns E_FAIL.


CDeferredCommand Class

CDeferredCommand class hierarchy

Deferred commands are queued by calls to methods on the IQueueCommand interface and are exposed by the filter graph manager and by some filters. A successful call to one of these methods returns an IDeferredCommand interface representing the queued command.

A CDeferredCommand object represents a single deferred command and exposes the IDeferredCommand interface as well as other methods that permit time checks and actual execution. A CDeferredCommand object contains a reference to the CCmdQueue object on which it is queued.

Reference counts control the lifetime of the CDeferredCommand class. When calling the CDeferredCommand::Invoke member function, the calling application gets an interface pointer that is reference-counted, and the CCmdQueue object also holds a reference count on the deferred command. Calling the IDeferredCommand::Cancel member function takes the deferred command off the command queue and thus reduces the reference count by one. Once taken off the queue, the command cannot be put back on the queue.

Protected Data Members

m_bStream | Flag for stream time or presentation time. to be passed to the invoked method.
m_Dispatch | Accesses the ITypeInfo interface.
m_dispidMethod | Method on the interface to run.
m_DispParams | CDispParams object containing the DISPPARAMS parameter list
m_hrResult | Stores the returned HRESULT value.
m_iid | Globally unique identifier (GUID) of the interface.
m_pQueue | Pointer to the CCmdQueue object that exposes the IQueueCommand interface.
m_pUnk | IUnknown pointer to the interface on which the command will be run.
m_pvarResult | Resulting information, if any, from the invoked method.
m_time | Time at which the command will be run.
m_wFlags | Flags specifying the context of the invocation.

Member Functions

CDeferredCommand | Constructs a CDeferredCommand object.
GetFlags | Retrieves the context flags associated with the deferred command.
GetIID | Retrieves the interface identifier (IID) of the interface on which the method will be run.
GetMethod | Retrieves the dispatch identifier of the method to be run.
GetParams | Retrieves the DISPPARAMS argument list to the method.
GetResult | Retrieves the resulting argument list, if one exists.
GetTime | Retrieves the time when the method will be run.
Invoke | Provides access to methods and properties exposed by an object.
IsStreamTime | Specifies whether the command is to be run at stream time or presentation time.

Implemented IDeferredCommand Methods

Cancel | Cancels a previously queued CDeferredCommand::Invoke request.
Confidence | Not currently implemented.
Postpone | Specifies a new presentation time for a previously queued command.
GetHResult | Retrieves the HRESULT value of the invoked method.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface Retrieves a specified reference-counted interface.

CDeferredCommand::Cancel

CDeferredCommand Class

Cancels a previously queued CDeferredCommand::Invoke request.

Syntax

HRESULT Cancel(void);

Return Value

Returns VFW_E_ALREADY_CANCELLED if m_pQueue is NULL. Returns an HRESULT from CCmdQueue::Remove if the call generates an error. Returns S_OK if successful.

Remarks

This member function implements the IDeferredCommand::Cancel method.

CDeferredCommand::CDeferredCommand

CDeferredCommand Class

Constructs a CDeferredCommand object.

Syntax

CDeferredCommand(
    CCmdQueue *pQ,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    LPUNKNOWN pUnkExecutor,
    REFTIME time,
    GUID *iid,
    long dispidMethod,
    short wFlags,
    long cArgs,
    VARIANT *pDispParams,
    VARIANT *pvarResult,
    short *puArgErr,
    BOOL bStream
    );

Parameters

pQ
Pointer to an object that exposes the IQueueCommand interface.
pUnk
Pointer to the outer IUnknown interface for aggregation.
phr
Pointer to a returned HRESULT value.
pUnkExecutor
Pointer to the object that will carry out this command.
time
Time at which the command will be run.
iid
Pointer to the globally unique identifier (GUID) of the interface that contains the method.
dispidMethod
Method on the interface to call.
wFlags
Context of the invocation.
cArgs
Number of arguments passed.
pDispParams
Pointer to a list of argument variant types.
pvarResult
Pointer to a returned variant type list, if any.
puArgErr
Pointer to the last argument in the pDispParams parameter list with an error.
bStream
Value indicating whether the deferred command time is in stream time (TRUE) or presentation time (FALSE).

Return Value

No return value.

CDeferredCommand::Confidence

CDeferredCommand Class

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT Confidence(
    LONG *pConfidence
    );

Parameters

pConfidence
Pointer to the confidence level.

Return Value

Returns E_NOTIMPL.

Remarks

For information about implementing this method, see IDeferredCommand::Confidence.

CDeferredCommand::GetFlags

CDeferredCommand Class

Retrieves the context flags associated with the deferred command.

Syntax

short GetFlags(void);

Return Value

The value retrieved will be one of the following:
DISPATCH_METHOD | Run the member as a method. If a property has the same name, both this and the DISPATCH_PROPERTYGET flag can be set.
DISPATCH_PROPERTYGET | The member is being retrieved as a property or data member.
DISPATCH_PROPERTYPUT | The member is being changed as a property or data member.
DISPATCH_PROPERTYPUTREF | The member is being changed via a reference assignment, rather than a value assignment. This flag is valid only when the property accepts a reference to an object.

CDeferredCommand::GetHResult

CDeferredCommand Class

Retrieves the HRESULT value from the invoked command.

Syntax

HRESULT GetHResult(
    HRESULT *phrResult
    );

Parameters

phrResult
Pointer to the HRESULT value.

Return Value

Returns E_ABORT if m_pQueue is NULL. Otherwise, returns S_OK.

Remarks

This member function implements the IDeferredCommand::GetHResult method.

CDeferredCommand::GetIID

CDeferredCommand Class

Retrieves the interface identifier (IID) of the interface on which the method will be run.

Syntax

REFIID GetIID(void);

Return Value

Returns the IID of the interface on which the method will be run.

CDeferredCommand::GetMethod

CDeferredCommand Class

Retrieves the dispatch identifier (DISPID) of the method to be run.

Syntax

long GetMethod(void);

Return Value

Returns the DISPID of the method to run.

CDeferredCommand::GetParams

CDeferredCommand Class

Retrieves the DISPPARAMS argument list to the method.

Syntax

DISPPARAMS* GetParams(void);

Return Value

Returns a DISPPARAMS argument list.

CDeferredCommand::GetResult

CDeferredCommand Class

Retrieves the resulting argument list, if one exists.

Syntax

VARIANT* GetResult(void);

Return Value

Returns a VARIANT containing the method's argument list, if it exists.

CDeferredCommand::GetTime

CDeferredCommand Class

Retrieves the time at which the method will be run.

Syntax

CRefTime GetTime(void);

Return Value

Returns a CRefTime object containing a reference time.

CDeferredCommand::Invoke

CDeferredCommand Class

Provides access to methods and properties exposed by an object.

Syntax

HRESULT Invoke(void);

Return Value

Returns VFW_E_ALREADY_CANCELLED if m_pQueue is NULL. Otherwise, returns the HRESULT resulting from a call to IDispatch::GetTypeInfo or IUnknown::QueryInterface.

CDeferredCommand::IsStreamTime

CDeferredCommand Class

Specifies whether the command is to be run at stream time or presentation time.

Syntax

BOOL IsStreamTime(void);

Return Value

Returns TRUE if set to stream time; otherwise, returns FALSE.

CDeferredCommand::NonDelegatingQueryInterface

CDeferredCommand Class

Retrieves a specified reference-counted interface.

Syntax

HRESULT NonDelegatingQueryInterface(
    REFIID riid,
    void **ppv
    );

Parameters

riid
Reference identifier.
ppv
Address of a pointer to the interface.

Return Value

Returns E_POINTER if ppv is invalid. Returns NOERROR if the query is successful or E_NOINTERFACE if it is not.

Remarks

Returns pointers to the IDeferredCommand and IUnknown interfaces by default. Override this method to publish any additional interfaces implemented by the derived class.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.

CDeferredCommand::Postpone

CDeferredCommand Class

Specifies a new presentation time for a previously queued command.

Syntax

HRESULT Postpone(
    REFTIME newtime
    );

Parameters

newtime
New presentation time.

Return Value

Returns VFW_E_TIME_ALREADY_PASSED if newtime is already passed. Otherwise, returns an HRESULT resulting from a call to CCmdQueue::Remove (when extracting from the list) or CCmdQueue::Insert (when reinserting with the changed time).

Remarks

This member function implements the IDeferredCommand::Postpone method.


CDispParams Class

CDispParams class hierarchy

The CDispParams class implements the DISPPARAMS structure used in Automation as a C++ base class. The IDispatch::Invoke method uses the OLE DISPPARAMS structure to contain the arguments passed to any method or property.

The DISPPARAMS structure is defined as follows:

typedef struct FARSTRUCT tagDISPPARAMS{
VARIANTARG FAR* rgvarg;               // Array of arguments
   DISPID FAR* rgdispidNamedArgs;     // Dispatch IDs of named arguments
   unsigned int cArgs;                // Number of arguments
   unsigned int cNamedArgs;           // Number of named arguments
} DISPPARAMS;

Member Functions

CDispParams Constructs a CDispParams object.

CDispParams::CDispParams

CDispParams Class

Constructs a CDispParams object.

Syntax

CDispParams(

  UINT nArgs,

  VARIANT *pArgs

  );

Parameters

nArgs
Number of arguments passed to the method or property.
pArgs
Pointer to the list of arguments. In the list, each argument is stored with its variant type.

Return Value

No return value.


CDrawImage Class

The CDrawImage class is a worker class for the owning CBaseWindow object. It handles the actual drawing operation from that class. To use this class, be sure to call CDrawImage::NotifyAllocator when the allocator has been agreed upon, and call CDrawImage::NotifyMediaType with a pointer to a CMediaType object (which must not be stack-based, because a pointer is maintained by this class rather than making a copy) when that is agreed.

When the palette changes, call CDrawImage::IncrementPaletteVersion, and before rendering call CDrawImage::SetDrawContext so that the class can obtain the handle to a device context (HDC) handles from the owning CBaseWindow object.

Protected Data Members

m_bStretch | Flag to stretch the images.
m_bUsingImageAllocator | Flag to determine if samples share DIBSECTION structures.
m_EndSample | End time for the current sample.
m_hdc | Main window device context (DC).
m_MemoryDC | Off-screen draw DC.
m_pBaseWindow | Owning video window object.
m_PaletteVersion | Current palette version token.
m_perfidRenderNow | Moment when returned from draw (for performance logging).
m_perfidRenderTime | Time taken to render an image (for performance logging).
m_pMediaType | Pointer to the current media type format.
m_SourceRect | Source image rectangle.
m_StartSample | Start time for the current sample.
m_TargetRect | Destination rectangle.

Member Functions

CDrawImage | Constructs a CDrawImage object.
DisplaySampleTimes | Displays a time stamp of a sample on top of its image.
DrawImage | Looks after drawing an image to a window.
FastRender | Draws an image using BitBlt and StretchBlt.
GetPaletteVersion | Retrieves the currently installed palette version.
GetSourceRect | Retrieves the current source rectangle.
GetTargetRect | Retrieves the current target rectangle.
IncrementPaletteVersion | Increments the current palette version.
NotifyAllocator | Notifies the draw object which allocator is being used.
NotifyEndDraw | Indicates the conclusion of image rendering.
NotifyMediaType | Passes the media type established during connection.
NotifyStartDraw | Indicates the beginning of image rendering.
ResetPaletteVersion | Resets the current palette version.
ScaleSourceRect | Retrieves a scaled version of a provided source rectangle.
SetDrawContext | Sets the window and off-screen device contexts to draw with.
SetSourceRect | Sets the source rectangle for the video.
SetStretchMode | Determines whether it is necessary to stretch.
SetTargetRect | Sets the target rectangle for the window.
SlowRender | Uses the Microsoft® Win32® SetDIBitsToDevice and StretchDIBits functions to draw an image.
UpdateColourTable | Updates the palette held in a DIBSECTION structure.
UsingImageAllocator | Retrieves the type of samples to be drawn.

CDrawImage::CDrawImage

CDrawImage Class

Constructs a CDrawImage object.

Syntax

CDrawImage(
    CBaseWindow *pBaseWindow
);

Parameters

pBaseWindow
Pointer to the window where drawing will occur.

Return Value

No return value.

Remarks

This class handles drawing of images through GDI. It works closely in conjunction with the CImageAllocator and CBaseWindow classes. It must know about the CImageAllocator class, because the draw code provides a faster drawing implementation if the buffers it is handed are created through the Microsoft® Win32® CreateDIBSection function. The image allocator creates this type of sample. It is told whether the buffers are allocated by a CImageAllocator object (or derived class) through the CDrawImage::NotifyAllocator member function.

If the buffers used to draw are not allocated by a compatible allocator, it will draw using the Win32 SetDIBitsToDevice family of APIs. The CBaseWindow class retrieves the window handle where the images are to be drawn. The device contexts that the drawing code should use are passed in through the CDrawImage::SetDrawContext member function.

The CImageAllocator, CImageSample, and CDrawImage classes are all tightly associated. The buffers that the image allocator creates are made using the Win32 CreateDIBSection function. The allocator then creates its own samples (based on the CImageSample class). The image samples are initialized with the buffer pointer and its length. The sample is also passed in a structure (a DIBDATA structure) that holds a number of pieces of information obtained from the CreateDIBSection function.

These samples can then be passed to the draw object. The draw object knows the private format of the samples, and how to get the DIBDATA structure back from them. After the draw object has obtained that information, it can pass a bitmap handle, stored in the DIBDATA structure, down into GDI when it draws the image that the sample contains. By using the bitmap handle from the sample in the drawing, rather than just the buffer pointer (which is the alternative if the sample is not a CImageSample), it gets a modest performance improvement.

CDrawImage::DisplaySampleTimes

CDrawImage Class

Displays time stamp of a sample on top of the image.

Syntax

void DisplaySampleTimes(
    IMediaSample *pSample
);

Parameters

pSample
Pointer to the sample containing time stamps.

Return Value

No return value.

Remarks

In debugging builds, it is often instructive to see the time stamps for images that the object is drawing. This member function gets the data pointer for the image the sample holds, along with its time stamps; then, using an off-screen device context, it draws the times approximately 80 percent of the way down the image (and centered horizontally).

This is a protected member function.

CDrawImage::DrawImage

CDrawImage Class

Draws an image.

Syntax

BOOL DrawImage(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample
Pointer to the sample to draw.

Return Value

No return value.

Remarks

If the samples have been allocated by a CImageAllocator object (or a derived class), the images that the samples contain will be drawn using the Microsoft Win32 BitBlt or StretchBlt function. If not, they will be drawn using SetDIBitsToDevice or StretchDIBits. The client must call CDrawImage::NotifyAllocator prior to calling this member function to inform the CDrawImage object how the image buffers have been allocated. The object is informed each time the source or destination changes (through its CDrawImage::SetSourceRect and CDrawImage::SetTargetRect member functions). It uses this information to determine if it needs to stretch the image during the draw.

CDrawImage::FastRender

CDrawImage Class

Draws the sample image using the Microsoft Win32 BitBlt and StretchBlt functions.

Syntax

void FastRender(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample
Pointer to the sample to draw.

Return Value

No return value.

Remarks

This protected member function is called by CDrawImage with a sample that contains an image buffer. The image buffer must have been allocated through the Win32 CreateDIBSection function and by a CImageAllocator object (or derived class). There are some performance benefits from drawing images created through this mechanism.

CDrawImage::GetPaletteVersion

CDrawImage Class

Retrieves the current palette version.

Syntax

LONG GetPaletteVersion(void);

Return Value

Returns the palette version.

Remarks

This member function is applicable only when using samples allocated through a CImageAllocator (or derived class) object. For more information about working with palettes, see the CDrawImage::UpdateColourTable member function.

CDrawImage::GetSourceRect

CDrawImage Class

Retrieves the current source rectangle the draw object is using.

Syntax

void GetSourceRect(
    RECT *pSourceRect
);

Parameters

pSourceRect
Pointer to the source rectangle.

Return Value

No return value.

CDrawImage::GetTargetRect

CDrawImage Class

Retrieves the current destination rectangle the draw object is using.

Syntax

void GetTargetRect(
    RECT *pTargetRect
);

Parameters

pTargetRect
Pointer to the target rectangle.

Return Value

No return value.

CDrawImage::IncrementPaletteVersion

CDrawImage Class

Increments the current palette version.

Syntax

void IncrementPaletteVersion(void);

Return Value

No return value.

Remarks

This member function is applicable only when using samples allocated through a CImageAllocator (or derived class) object. For more information about working with palettes, see the CDrawImage::UpdateColourTable member function.

CDrawImage::NotifyAllocator

CDrawImage Class

Notifies the draw object which allocator the output pin is actually going to use.

Syntax

void NotifyAllocator(
    BOOL bUsingImageAllocator
);

Parameters

bUsingImageAllocator
Flag that specifies whether to use a CImageAllocator object allocator. For more information, see Remarks.

Return Value

No return value.

Remarks

This member function tells the draw object whose allocator to use. This should be called with TRUE if the filter agrees to use an allocator based around the Microsoft® DirectShow® CImageAllocator base class. These image buffers are made through CreateDIBSection. Otherwise this should be called with FALSE, and the images will be drawn using SetDIBitsToDevice and StretchDIBits.

CDrawImage::NotifyEndDraw

CDrawImage Class

Indicates the conclusion of image rendering.

Syntax

void NotifyEndDraw(void);

Return Value

No return value.

Remarks

This member function is used for performance measurements and just calls the MSR_STOP macro.

CDrawImage::NotifyMediaType

CDrawImage Class

Provides the image format for the draw object.

Syntax

void NotifyMediaType(
    CMediaType *pMediaType
);

Parameters

pMediaType
Pointer to the media type.

Return Value

No return value.

Remarks

The draw object must know the format of the images it will be drawing. For the most part, this is so it can retrieve the palette when the images are 8-bit palettized. A filter using the draw class will usually call this just after completing a connection.

The function does not take a copy of the media type but just stores a pointer (for performance reasons). Therefore, the caller should ensure that the media type is not destroyed inadvertently.

CDrawImage::NotifyStartDraw

CDrawImage Class

Indicates the beginning of image rendering.

Syntax

void NotifyStartDraw(void);

Return Value

No return value.

Remarks

This member function is used for performance measurements and just calls the MSR_START macro.

CDrawImage::ResetPaletteVersion

CDrawImage Class

Resets the current palette version.

Syntax

void ResetPaletteVersion(void);

Return Value

No return value.

Remarks

This member function is applicable only when using samples allocated through a CImageAllocator (or derived class) object. For more information about working with palettes, see the CDrawImage::UpdateColourTable member function.

CDrawImage::ScaleSourceRect

CDrawImage Class

Retrieves a scaled version of a provided source rectangle.

Syntax

virtual RECT ScaleSourceRect(
    const RECT *pSource
);

Parameters

pSource
Pointer to an unscaled source rectangle.

Return Value

Returns the scaled source rectangle (returns unscaled pSource by default).

Remarks

The base class implementation does not scale the source rectangle. Derived classes can override this to implement scaling, if required.

CDrawImage::SetDrawContext

CDrawImage Class

Sets the device contexts used for drawing.

Syntax

void SetDrawContext(void);

Return Value

No return value.

Remarks

The draw object always needs a device context for the window to draw images in. It might also need an off-screen device context to select bitmaps into when using DIBSECTION buffers (for more details on these and CreateDIBSection, see the Microsoft Platform SDK documentation). This member function will typically be called by a filter using this class, after it has initialized a window.

CDrawImage::SetSourceRect

CDrawImage Class

Sets the source rectangle for the video.

Syntax

void SetSourceRect(
    RECT *pSourceRect
);

Parameters

pSourceRect
Pointer to the new source rectangle.

Return Value

No return value.

Remarks

The source rectangle should already have been validated before calling this member function so that the source rectangle specified will not extend over the edges of the available video.

CDrawImage::SetStretchMode

CDrawImage Class

Decides whether the video is to be stretched.

Syntax

void SetStretchMode(void);

Return Value

No return value.

Remarks

When the object is asked to draw an image, the object must know whether the video is being stretched, because it affects the function it calls (BitBlt or StretchBlt, for example). Rather than calculate this for every frame, it works it out just once when the source or destination rectangle is updated. This member function is called by SetSourceRect and SetTargetRect to manage this calculation.

This is a protected member function.

CDrawImage::SetTargetRect

CDrawImage Class

Sets the target rectangle for the video.

Syntax

void SetTargetRect(
    RECT *pTargetRect
);

Parameters

pTargetRect
Pointer to the new target area.

Return Value

No return value.

Remarks

The destination rectangle should already have been validated before calling this member function, so that the destination specified will not define an empty playback area.

CDrawImage::SlowRender

CDrawImage Class

Draws the sample image using SetDIBitsToDevice and StretchDIBits.

Syntax

void SlowRender(
    IMediaSample *pMediaSample
);

Parameters

pMediaSample
Pointer to the sample to draw.

Return Value

No return value.

Remarks

The sample provided should contain the image to draw and should match the format as specified to the draw object through NotifyMediaType.

This is a protected member function.

CDrawImage::UpdateColourTable

CDrawImage Class

Updates the palette associated with a sample.

Syntax

void UpdateColourTable(
    HDC hdc,
    BITMAPINFOHEADER *pbmi
);

Parameters

hdc
Device context containing the sample image.
pbmi
Pointer to the BITMAPINFO structure containing the new palette.

Return Value

No return value.

Remarks

This member function is applicable only when using samples allocated through a CImageAllocator (or derived class) object. CImageAllocator creates samples that are created with the Microsoft Win32 CreateDIBSection function. When a palettized buffer is allocated through CreateDIBSection, a palette is passed in that is associated with that buffer.

Should the palette be changed, the new palette must be associated with the buffer before drawing it (this is done through the Win32 SetDIBColorTable function and internally with the UpdateColourTable member function). The drawing code knows to update the palette because the palette version it stores in the sample will differ from the palette version it keeps internally.

In essence, the sample gets an initial palette version when created. When the palette is changed (probably by a filter), it tells the draw object to increment its palette version (through the IncrementPaletteVersion member function). When the draw object next comes to draw the sample, it will see that the sample has an old palette version and will know to call UpdateColourTable on it.

The draw object knows the type of buffer used for samples through the NotifyAllocator member function. If it is called with TRUE, the buffers passed to it must be allocated by a CImageAllocator (or derived class) object. If it is called with FALSE, the buffers should be allocated in standard system memory (or other memory accessible to GDI in the same manner).

When the allocator is decommitted, it will typically delete all the samples it holds on to. When it is subsequently committed, the samples will be created again with their initial palette versions. At this point, the allocator should also reset the palette version in the draw object so that they remain in sync. An allocator can do this by calling the ResetPaletteVersion member function.

This is a protected member function.

CDrawImage::UsingImageAllocator

CDrawImage Class

Retrieves the type of samples to be drawn.

Syntax

BOOL UsingImageAllocator(void);

Return Value

Returns one of the following values.
TRUE | Allocated through CreateDIBSection.
FALSE | Not allocated through CreateDIBSection.

Remarks

This member function is applicable only when using samples allocated through a CImageAllocator (or derived class) object. For more information about working with palettes and the image allocator, see the CDrawImage::UpdateColourTable member function.


CDynamicOutputPin Class

Implements an output pin that supports dynamic reconnections and format changes.

Declaration: Amfilter.h

This class derives from the CBaseOutputPin class and implements the IPinFlowControl interface. It supports several operations that are important for dynamic graph building:

  • Dynamic reconnection: The pin can disconnect and reconnect while the filter is still active (paused or running).
  • Dynamic format change: The pin can negotiate a new media type while the filter is still active, without reconnecting.
  • Flow control: The owning filter (or an application) can block data flow from the pin without stopping the filter.

The pin has three possible states: blocked, unblocked, and pending. In the pending state, the pin is waiting for some operation to complete on another thread, before the pin switches to the blocked state. While the pin is blocked, the filter cannot deliver data through the pin, or change the pin's connection.

To coordinate among multiple threads, the owning filter must follow certain rules. (For more information about threads in the filter graph, see Threads and Critical Sections.) First, the streaming thread must always call the StartUsingOutputPin method before it calls any of the following methods:

  • ChangeOutputFormat
  • ChangeMediaType
  • DynamicReconnect
  • CBaseOutputPin::Deliver
  • CBaseOutputPin::DeliverEndOfStream
  • CBaseOutputPin::DeliverNewSegment
  • IMemInputPin::Receive
  • IMemInputPin::ReceiveMultiple
  • IPin::EndOfStream
  • IPin::NewSegment

Afterward, it must call the StopUsingOutputPin method.

Second, the application thread must not call any of the methods in the previous list. Third, the streaming thread must not call the class methods that block or unblock the pin. These methods are: Block, SynchronousBlockOutputPin, AsynchronousBlockOutputPin, and UnblockOutputPin.

These rules ensure that the application thread cannot block the pin while the streaming thread is using it, and vice versa. After the streaming thread has called StartUsingOutputPin, the pin will not block until the streaming thread calls StopUsingOutputPin. Conversely, if the pin is blocked, StartUsingOutputPin waits until the pin is unblocked.

To avoid forgetting to call StopUsingOutputPin, you can use the CAutoUsingOutputPin class. It calls StopUsingOutputPin automatically when it goes out of scope.

When the owning filter joins or leaveds the filter graph (in its IBaseFilter::JoinFilterGraph method), it must call the pin's SetConfigInfo method.

Protected Member Variables
m_BlockStateLock | Critical section that protects the blocking state.
m_hUnblockOutputPinEvent | Event that is signaled when the pin is not blocked.
m_hNotifyCallerPinBlockedEvent | Event that is signaled when the pin successfully blocks, or the user cancels a pending block.
m_BlockState | Blocking state.
m_dwBlockCallerThreadID | The identifier of the thread that last called the IPinFlowControl::Block method on this pin.
m_dwNumOutstandingOutputPinUsers | Number of streaming threads using this pin.
m_hStopEvent | Event that is signaled when the filter stops or the pin flushes data.
m_pGraphConfig | Pointer to the IGraphConfig interface for performing dynamic reconnections.
m_bPinUsesReadOnlyAllocator | Flag that specifies whether samples from the pin's allocator are read-only.
Protected Methods
SynchronousBlockOutputPin | Blocks the pin; does not return until the pin is blocked.
AsynchronousBlockOutputPin | Blocks the pin; might return before the pin is blocked.
UnblockOutputPin | Unblocks the pin.
BlockOutputPin | Blocks the pin.
WaitEvent | Waits until the specified event is signaled.
Public Methods
CDynamicOutputPin | Constructor method.
~CDynamicOutputPin | Destructor method.
SetConfigInfo | Specifies the IGraphConfig pointer and the stop event.
DeliverBeginFlush | Requests the connected input pin to begin a flush operation.
DeliverEndFlush | Requests the connected input pin to end a flush operation.
Inactive | Notifies the pin that the filter has stopped.
Active | Notifies the pin that the filter is now active.
CompleteConnect | Completes a connection to an input pin. Virtual.
StartUsingOutputPin | Obtains access to the pin for a streaming operation. Virtual.
StopUsingOutputPin | Releases access to the pin after a streaming operation. Virtual.
StreamingThreadUsingOutputPin | Determines whether any thread is performing a streaming operation on the pin. Virtual.
ChangeOutputFormat | Dynamically changes the media type for the connection, and delivers new segment information.
ChangeMediaType | Dynamically changes the media type for the connection.
DynamicReconnect | Performs a dynamic reconnection with a new media type.
IPin Methods
Disconnect | Breaks the current pin connection.
IPinFlowControl Methods
Block | Blocks or unblocks the flow of data from the pin.

CDynamicOutputPin.m_BlockStateLock

CDynamicOutputPin Class

Critical section that protects the blocking state.

Syntax

CCritSec m_BlockStateLock;

Remarks

Hold this critical section before using any of the following member variables:

  • m_BlockState
  • m_dwBlockCallerThreadID
  • m_dwNumOutstandingOutputPinUsers
  • m_hNotifyCallerPinBlockedEvent

CDynamicOutputPin.m_hUnblockOutputPinEvent

CDynamicOutputPin Class

Event that is signaled when the pin is not blocked.

Syntax

HANDLE m_hUnblockOutputPinEvent;

CDynamicOutputPin.m_hNotifyCallerPinBlockedEvent

CDynamicOutputPin Class

Event that is signaled when the pin successfully blocks, or the user cancels a pending block.

Syntax

HANDLE m_hNotifyCallerPinBlockedEvent;

Remarks

Before accessing this variable, hold the m_BlockStateLock critical section.

CDynamicOutputPin.m_BlockState

CDynamicOutputPin Class

Blocking state.

Syntax

BLOCK_STATE m_BlockState;

Remarks

The following states are defined:

  • NOT_BLOCKED
  • PENDING
  • BLOCKED

Before accessing this variable, hold the m_BlockStateLock critical section.

CDynamicOutputPin.m_dwBlockCallerThreadID

CDynamicOutputPin Class

The identifier of the thread that last called the IPinFlowControl::Block method on this pin. This member variable is only valid while the pin is blocked.

Syntax

DWORD m_dwBlockCallerThreadID;

Remarks

Before accessing this variable, hold the m_BlockStateLock critical section.

CDynamicOutputPin.m_dwNumOutstandingOutputPinUsers

CDynamicOutputPin Class

Number of streaming threads using this pin.

Syntax

DWORD m_dwNumOutstandingOutputPinUsers;

Remarks

The StartUsingOutputPin method increments this variable, and the StopUsingOutputPin method decrements it. When the value is greater than zero, some thread is using this pin to stream data or to change the connection type. The pin cannot be blocked while this is the case.

Before accessing this variable, hold the m_BlockStateLock critical section.

See Also

StreamingThreadUsingOutputPin

CDynamicOutputPin.m_hStopEvent

CDynamicOutputPin Class

Event that is signaled when the filter stops or the pin flushes data.

Syntax

HANDLE m_hStopEvent;

CDynamicOutputPin.m_pGraphConfig

CDynamicOutputPin Class

Pointer to the IGraphConfig interface for performing dynamic reconnections.

Syntax

IGraphConfig* m_pGraphConfig;

CDynamicOutputPin.m_bPinUsesReadOnlyAllocator

CDynamicOutputPin Class

Flag that specifies whether samples from the pin's allocator are read-only. If the value is TRUE, the sample are read-only. The default value is FALSE.

Syntax

BOOL m_bPinUsesReadOnlyAllocator;

CDynamicOutputPin::Active

CDynamicOutputPin Class

Notifies the pin that the filter is now active.

Syntax

HRESULT Active(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_FAIL | Failure. SetConfigInfo was not called.

Remarks

This method overrides the CBaseOutputPin::Active method. It resets the m_hStopEvent event. If the owning filter has not called SetConfigInfo, this method returns E_FAIL.

CDynamicOutputPin::AsynchronousBlockOutputPin

CDynamicOutputPin Class

Blocks the pin; might return before the pin is blocked.

Syntax

HRESULT AsynchronousBlockOutputPin(
    HANDLE hNotifyCallerPinBlockedEvent
);

Parameters

hNotifyCallerPinBlockedEvent
Handle to an event. The event is signaled when the output pin is blocked, or if the caller cancels the block operation.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_PIN_ALREADY_BLOCKED | Pin is already blocked on another thread.
VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD | Pin is already blocked on the calling thread.

Remarks

Do not call this method from the streaming thread.

If no streaming thread is using the pin, this method immediately blocks the pin. Otherwise, it sets the pin status to "pending" and returns. When the streaming operation completes, the streaming thread calls the StopUsingOutputPin method, which blocks the pin and signals the hNotifyCallerPinBlockedEvent event. To cancel a pending block, call the UnblockOutputPin method.

CDynamicOutputPin::Block

CDynamicOutputPin Class

Blocks or unblocks the flow of data from the pin. Implements the IPinFlowControl::Block method.

Syntax

HRESULT Block(
    DWORD dwBlockFlags,
    HANDLE hEvent
);

Parameters

dwBlockFlags
Flag that indicates whether to block or unblock the pin. Must be one of the following values:
  • Zero: Unblock data flow from the pin.
  • AM_PIN_FLOW_CONTROL_BLOCK: Block data flow from the pin.
hEvent
Handle to an event object, or NULL.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | Pin is already unblocked.
S_OK | Success.
E_INVALIDARG | Invalid argument.
VFW_E_PIN_ALREADY_BLOCKED | Pin is already blocked on another thread.
VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD | Pin is already blocked on the calling thread.

Remarks

For more information about this method, see IPinFlowControl::Block. Internally, this method calls one of the following protected methods:

  • Block (asynchronous): AsynchronousBlockOutputPin
  • Block (synchronous): SynchronousBlockOutputPin
  • Unblock: UnblockOutputPin

Unblocking is always performed synchronously.

CDynamicOutputPin::BlockOutputPin

CDynamicOutputPin Class

Blocks the pin. While the pin is blocked, the StartUsingOutputPin method waits for the pin to become unblocked. The blocked state prevents the output pin from delivering samples, changing its output format, or reconnecting itself.

Syntax

void BlockOutputPin(void);

Remarks

Before calling this method, hold the m_BlockStateLock critical section. Do not call this method if a streaming thread is using the pin, either to deliver data or to change the connection. To check whether a streaming thread is using the pin, call the StreamingThreadUsingOutputPin method.

CDynamicOutputPin::CDynamicOutputPin

CDynamicOutputPin Class

Constructor method.

Syntax

CDynamicOutputPin(
    TCHAR *pObjectName,
    CBaseFilter *pFilter,
    CCritSec *pLock,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName
Pointer to a string containing the name of the object. For more information, see CBaseObject.
pFilter
Pointer to the filter that created this pin.
pLock
Pointer to a CCritSec lock, used to serialize state changes. Use the same critical section as the filter lock, CBaseFilter.m_pLock
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.
pName
Pointer to a Unicode™ string containing the pin identifier. For more information, see IPin::QueryId.

CDynamicOutputPin::~CDynamicOutputPin

CDynamicOutputPin Class

Destructor method.

Syntax

~CDynamicOutputPin(void);

CDynamicOutputPin::ChangeMediaType

CDynamicOutputPin Class

Dynamically changes the media type for the connection. The change can occur while the filter graph is running. Once this method is called, samples with the old media type cannot be delivered. The caller must ensure that no old samples are pending.

Syntax

HRESULT ChangeMediaType(
    const CMediaType *pmt
);

Parameters

pmt
Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_FAIL | Failure. Possibly the owning filter did not call SetConfigInfo.
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

Call the StartUsingOutputPin method before calling this method.

This method first checks whether the downstream input pin can accept the new format without reconnecting. It queries the input pin for the IPinConnection interface. If the input pin supports IPinConnection, the method calls the IPinConnection::DynamicQueryAccept method with the proposed media type. If the input pin accepts the new media type, the method calls the IPin::ReceiveConnection method and renegotiates the allocator requirements.

On the other hand, if the downstream pin does not support IPinConnection, or if it rejects the new media type, the method calls the DynamicReconnect method to perform a dynamic reconnection.

CDynamicOutputPin::ChangeOutputFormat

CDynamicOutputPin Class

Dynamically changes the media type for the connection, and delivers new segment information. The change can occur while the filter graph is running. Once this method is called, samples with the old media type cannot be delivered. The caller must ensure that no old samples are pending.

Syntax

HRESULT ChangeOutputFormat(
    const AM_MEDIA_TYPE *pmt,
    REFERENCE_TIME tSegmentStart,
    REFERENCE_TIME tSegmentStop,
    double dSegmentRate
);

Parameters

pmt
Pointer to an AM_MEDIA_TYPE structure that specifies the media type.
tSegmentStart
Start time of the segment.
tSegmentStop
Stop time of the segment.
dSegmentRate
Segment rate.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_FAIL | Failure. Possibly the owning filter did not call SetConfigInfo.
VFW_E_NOT_CONNECTED | The pin is not connected.

Remarks

This method changes the format type while the filter is running. If the downstream pin accepts the new format, no reconnection is necessary. Otherwise, the method attempts to reconnect the pin. If the method successfully changes the format, it delivers the new segment information. This method calls the ChangeMediaType method to perform the format change.

You must call the StartUsingOutputPin method before calling this method.

CDynamicOutputPin::CompleteConnect

CDynamicOutputPin Class

Completes a connection to an input pin.

Syntax

virtual HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin
Pointer to the input pin's IPin interface.

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

This method overrides the CBaseOutputPin::CompleteConnect method. To support dynamic reconnections, this method commits the allocator if the filter is active. In the base class, connections can occur only when the filter is stopped, so the allocator is always committed in the CBaseOutputPin::Active method.

CDynamicOutputPin::DeliverBeginFlush

CDynamicOutputPin Class

Requests the connected input pin to begin a flush operation.

Syntax

HRESULT DeliverBeginFlush(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

This method overrides the CBaseOutputPin::DeliverBeginFlush method. It sets the m_hStopEvent event.

CDynamicOutputPin::DeliverEndFlush

CDynamicOutputPin Class

Requests the connected input pin to end a flush operation.

Syntax

HRESULT DeliverEndFlush(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

This method overrides the CBaseOutputPin::DeliverEndFlush method. It resets the m_hStopEvent event.

CDynamicOutputPin::Disconnect

CDynamicOutputPin Class

Breaks the current pin connection. Implements the IPin::Disconnect method.

Syntax

HRESULT Disconnect(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | The pin was not connected.
S_OK | Success.

Remarks

This method overrides the CBasePin::Disconnect method to enable disconnecting while the filter is active.

CDynamicOutputPin::DynamicReconnect

CDynamicOutputPin Class

Performs a dynamic reconnection with a new media type. The reconnection can occur while the filter graph is running.

Syntax

HRESULT DynamicReconnect(
    const CMediaType *pmt
);

Parameters

pmt
Pointer to an AM_MEDIA_TYPE structure that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_FAIL | Failure. Possibly the owning filter did not call the SetConfigInfo method.

Remarks

This method must be called from the same thread that delivers data to the pin. Once this method is called, samples with the old media type cannot be delivered. The caller must ensure that no old samples are pending.

Call StartUsingOutputPin before calling this method.

CDynamicOutputPin::Inactive

CDynamicOutputPin Class

Notifies the pin that the filter has stopped.

Syntax

HRESULT Inactive(void);

Return Value

Returns S_OK if successful, or an HRESULT value indicating the cause of the failure.

Remarks

This method overrides the CBaseOutputPin::Inactive method. It sets the m_hStopEvent event.

CDynamicOutputPin::SetConfigInfo

CDynamicOutputPin Class

Specifies the IGraphConfig pointer and the stop event.

Syntax

void SetConfigInfo(
    IGraphConfig *pGraphConfig,
    HANDLE hStopEvent
);

Parameters

pGraphConfig
Pointer to the IGraphConfig interface, or NULL.
hStopEvent
Handle to an event that is signaled when the filter stops, or NULL.

Remarks

The filter must call this method when it joins the filter graph. The filter graph manager supports IGraphConfig. For the hStopEvent parameter, create a manual-reset event. When the filter leaves the filter graph, call this method again with NULL for both parameters.

CDynamicOutputPin::StartUsingOutputPin

CDynamicOutputPin Class

Obtains access to the pin for a streaming operation.

Syntax

virtual HRESULT StartUsingOutputPin(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_UNEXPECTED | Unexpected error.
VFW_E_STATE_CHANGED | The filter was stopped, or the pin has begun flushing.

Remarks

Call this method before calling any methods that deliver data to the connected input pin or that change the connection's media type. For example, this rule applies to the following methods:

  • ChangeOutputFormat
  • ChangeMediaType
  • DynamicReconnect
  • CBaseOutputPin::Deliver
  • CBaseOutputPin::DeliverEndOfStream
  • CBaseOutputPin::DeliverNewSegment
  • IMemInputPin::Receive
  • IMemInputPin::ReceiveMultiple
  • IPin::EndOfStream
  • IPin::NewSegment

Afterward, call the StopUsingOutputPin method to release the access to the pin.

If the pin is blocked, StartUsingOutputPin waits for the pin to become unblocked. If the filter stops while the method is waiting, the method immediately returns VFW_E_STATE_CHANGED. The pin maintains a count of how many times StartUsingOutputPin has been called without a corresponding call to StopUsingOutputPin. If another thread tries to block the pin while this count is non-zero, the pin sets its blocking status to "pending." The pin becomes blocked once all of the streaming operations have completed, in the final call to StopUsingOutputPin.

Do not hold the m_BlockStateLock critical section when you call this method. Otherwise, if the pin is blocked, it can never become unblocked, causing a deadlock.

CDynamicOutputPin::StopUsingOutputPin

CDynamicOutputPin Class

Releases access to the pin after a streaming operation.

Syntax

virtual void StopUsingOutputPin(void);

See Also

StartUsingOutputPin

CDynamicOutputPin::StreamingThreadUsingOutputPin

CDynamicOutputPin Class

Determines whether any thread is performing a streaming operation on the pin.

Syntax

virtual bool StreamingThreadUsingOutputPin(void);

Return Value

Returns TRUE if a thread is performing a streaming operation on the pin. Otherwise, returns FALSE.

Remarks

If any threads have successfully returned from the StartUsingOutputPin method and have not made a corresponding call to the StopUsingOutputPin method, this method returns TRUE.

CDynamicOutputPin::SynchronousBlockOutputPin

CDynamicOutputPin Class

Blocks the pin; does not return until the pin is blocked.

Syntax

HRESULT SynchronousBlockOutputPin(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_PIN_ALREADY_BLOCKED | Pin is already blocked on another thread.
VFW_E_PIN_ALREADY_BLOCKED_ON_THIS_THREAD | Pin is already blocked on the calling thread.

Remarks

Do not call this method from the streaming thread.

CDynamicOutputPin::UnblockOutputPin

CDynamicOutputPin Class

Unblocks the pin. When the pin is unblocked, it can deliver samples, change its output format, and reconnect itself.

Syntax

HRESULT UnblockOutputPin(void);

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | Pin was already unblocked.
S_OK | Success.

CDynamicOutputPin::WaitEvent

CDynamicOutputPin Class

Waits until the specified event is signaled.

Syntax

static HRESULT WaitEvent(
    HANDLE hEvent
);

Parameters

hEvent
Handle to an event.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_UNEXPECTED | Unexpected error.


CEnumMediaTypes Class

CEnumMediaTypes class hierarchy

Enumerator for preferred media types.

Declaration: Amfilter.h

This class implements the IEnumMediaTypes interface. It calls the following CBasePin methods:

  • GetMediaType: Retrieves a media type, referenced by a zero-based index.
  • GetMediaTypeVersion: Determines whether the set of preferred types has changed.

Whenever a pin alters its list of preferred media types, the pin increments the media-type version number. When this happens, the enumerator object is no longer synchronized with the pin, and the class methods return VFW_E_ENUM_OUT_OF_SYNC. Call the Reset method to resynchronize the enumerator.

Public Methods
CEnumMediaTypes | Constructor method.
~CEnumMediaTypes | Destructor method. Virtual.
IEnumMediaTypes Methods
Clone | Makes a copy of the enumerator with the same enumeration state.
Next | Retrieves a specified number of media types.
Reset | Resets the enumeration sequence to the beginning.
Skip | Skips over a specified number of media types.

CEnumMediaTypes::CEnumMediaTypes

CEnumMediaTypes Class

Constructor method.

Syntax

CEnumMediaTypes(
    CBasePin *pPin,
    CEnumMediaTypes *pEnumMediaTypes
);

Parameters

pPin
Pointer to the pin on which the enumeration is to be performed.
pEnumMediaTypes
Pointer to the IEnumMediaTypes interface of an enumerator to clone, or NULL.

Remarks

If pEnumMediaTypes is NULL, this method initializes the enumerator to the beginning of the enumeration sequence. Otherwise, it duplicates the internal state of the enumerator specified by pEnumMediaTypes.

CEnumMediaTypes::~CEnumMediaTypes

CEnumMediaTypes Class

Destructor method.

Syntax

virtual ~CEnumMediaTypes(void);

CEnumMediaTypes::Clone

CEnumMediaTypes Class

Makes a copy of the enumerator with the same enumeration state. Implements the IEnumMediaTypes::Clone method.

Syntax

HRESULT Clone(
    IEnumMediaTypes **ppEnum
);

Parameters

ppEnum
Address of a variable that receives a pointer to the IEnumMediaTypes interface of the new enumerator.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.

CEnumMediaTypes::Next

CEnumMediaTypes Class

Retrieves a specified number of media types. Implements the IEnumMediaTypes::Next method.

Syntax

HRESULT Next(
    ULONG cMediaTypes,
    AM_MEDIA_TYPE **ppMediaTypes,
    ULONG *pcFetched
);

Parameters

cMediaTypes
Number of media types to retrieve.
ppMediaTypes
Array of pointers to AM_MEDIA_TYPE structures, of size cPins.
pcFetched
Pointer to a variable that receives the number of media types the method returned. Can be NULL if cMediaTypes is 1.

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | Did not retrieve as many media types as requested.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.

Remarks

If the method succeeds, the array specified by ppMediaTypes contains pointers to AM_MEDIA_TYPE structures. The number of structures is equal to *pcFetched. Free each media type by calling the DeleteMediaType function.

This method calls the pin's CBasePin::GetMediaType method to retrieve the media types.

CEnumMediaTypes::Reset

CEnumMediaTypes Class

Resets the enumeration sequence to the beginning. Implements the IEnumMediaTypes::Reset method.

Syntax

HRESULT Reset(void);

Return Value

Returns S_OK.

CEnumMediaTypes::Skip

CEnumMediaTypes Class

Skips over a specified number of media types. Implements the IEnumMediaTypes::Skip method.

Syntax

HRESULT Skip(
    ULONG cMediaTypes
);

Parameters

cMediaTypes
Number of media types to skip.

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | Skipped past the end of the sequence.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The pin's state has changed and is now inconsistent with the enumerator.


CEnumPins Class

CEnumPins class hierarchy

Enumerator for pins.

Declaration: Amfilter.h

This class implements the IEnumPins interface. It calls the following CBaseFilter methods:

  • GetPin: Retrieves a pin on the filter, referenced by a zero-based index.
  • GetPinCount: Retrieves the total number of pins on the filter.
  • GetPinVersion: Determines whether the pins have changed.

If the filter dynamically creates or destroys pins, it increments the pin version whenever the pins change. If the version number changes, the enumerator object is no longer synchronized with the filter. Once the enumerator is out of sync, the methods in CEnumPins return VFW_E_ENUM_OUT_OF_SYNC. Call the Reset method to resynchronize the enumerator.

Public Methods
CEnumPins | Constructor method.
~CEnumPins | Destructor method. Virtual.
IEnumPins Methods
Clone | Makes a copy of the enumerator with the same enumeration state.
Next | Retrieves a specified number of pins.
Reset | Resets the enumeration sequence to the beginning.
Skip | Skips over a specified number of pins.

CEnumPins::CEnumPins

CEnumPins Class

Constructor method.

Syntax

CEnumPins(
    CBaseFilter *pFilter,
    CEnumPins *pEnumPins
);

Parameters

pFilter
Pointer to the filter on which to enumerate the pins.
pEnumPins
Pointer to the IEnumPins interface of an enumerator to clone, or NULL.

Remarks

If pEnumPins is NULL, this method initializes the enumerator to the beginning of the enumeration sequence. Otherwise, it duplicates the internal state of the enumerator specified by pEnumPins.

CEnumPins::~CEnumPins

CEnumPins Class

Destructor method.

Syntax

virtual ~CEnumPins(void);

CEnumPins::Clone

CEnumPins Class

Makes a copy of the enumerator with the same enumeration state. Implements the IEnumPins::Clone method.

Syntax

HRESULT Clone(
    IEnumPins **ppEnum
);

Parameters

ppEnum
Address of a variable that receives a pointer to the IEnumPins interface of the new enumerator.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.

CEnumPins::Next

CEnumPins Class

Retrieves a specified number of pins in the enumeration sequence. Implements the IEnumPins::Next method.

Syntax

HRESULT Next(
    ULONG cPins,
    IPin **ppPins,
    ULONG *pcFetched
);

Parameters

cPins
Number of pins to retrieve.
ppPins
Array of size cPins that is filled with IPin pointers.
pcFetched
Pointer to a variable that receives the number of pins retrieved. Can be NULL if cPins is 1.

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | Did not retrieve as many pins as requested.
S_OK | Success.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.

Remarks

This method retrieves pointers to the specified number of pins, starting at the current position in the enumeration, and places them in the specified array.

This method calls the filter's CBaseFilter::GetPin method to retrieve the pins.

If the method succeeds, the IPin pointers all have outstanding reference counts. Be sure to release them when you are done.

CEnumPins::Reset

CEnumPins Class

Resets the enumeration sequence to the beginning. Implements the IEnumPins::Reset method.

Syntax

HRESULT Reset(void);

Return Value

Returns S_OK.

CEnumPins::Skip

CEnumPins Class

Skips over a specified number of pins in the enumeration sequence. Implements the IEnumPins::Skip method.

Syntax

HRESULT Skip(
    ULONG cPins
);

Parameters

cPins
Number of pins to skip.

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | Skipped past the end of the sequence.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The filter's state has changed and is now inconsistent with the enumerator.


CFactoryTemplate Class

Provides a template for creating class factories.

Declaration: Combase.h

In Microsoft® DirectShow®, class factories are specialized using the CFactoryTemplate class, also called the factory template. Each class factory holds a pointer to a factory template. The factory template contains information about a COM object, including the object's class identifier (CLSID) and a pointer to a function that creates the object.

In your DLL, declare a global array of factory templates named g_Templates. Include one factory template for each object in the DLL. When the DllGetClassObject function makes a new class factory, it searches the array for a template with a matching CLSID. Assuming it finds one, it creates a class factory that holds a pointer to the matching template. When the client calls IClassFactory::CreateInstance, the class factory calls the instantiation function defined in the template.

For more information, see How to Create a DLL.

Public Member Variables
m_Name | Name of the filter.
m_ClsID | Pointer to the CLSID of the object.
m_lpfnNew | Pointer to a function that creates an instance of the object.
m_lpfnInit | Pointer to a function that gets called from the DLL entry point.
m_pAMovieSetup_Filter | Pointer to an AMOVIESETUP_FILTER structure.
Public Methods
IsClassID | Determines whether a CLSID matches this class template.
CreateInstance | Calls the object-creation function for the class.

CFactoryTemplate.m_Name

CFactoryTemplate Class

Wide-character string containing the name of the filter.

Syntax

const WCHAR *m_Name;

CFactoryTemplate.m_ClsID

CFactoryTemplate Class

Pointer to the CLSID of the object.

Syntax

const CLSID *m_ClsID;

CFactoryTemplate.m_lpfnNew

CFactoryTemplate Class

Pointer to a function that creates an instance of the object.

Syntax

typedef CUnknown *(CALLBACK *LPFNNewCOMObject)(LPUNKNOWN pUnkOuter, HRESULT *phr);

LPFNNewCOMObject m_lpfnNew;

Remarks

In your DLL, declare a static function that returns a pointer to a new instance of the object. In the factory template, set the m_lpfnNew member variable to the address of this static function.

The following example shows a typical function for m_lpfnNew:

CUnknown * WINAPI CMyComponent::CreateInstance(LPUNKNOWN pUnk, HRESULT *pHr)
{
    CMyComponent *pNewObject = new CMyComponent(NAME("My Component"), pUnk, pHr );
    if (pNewObject == NULL)
{
        *phr = E_OUTOFMEMORY;
    }
    return pNewObject;
}

CFactoryTemplate.m_lpfnInit

CFactoryTemplate Class

Pointer to a function that gets called from the DLL entry point. Can be NULL.

Syntax

typedef void (CALLBACK *LPFNInitRoutine)(BOOL bLoading, const CLSID *rclsid);

LPFNInitRoutine m_lpfnInit;

Remarks

If you provide this function in your DLL, the DLL entry-point function calls it with following parameters:

  • bLoading: TRUE when the DLL is loaded, FALSE when the DLL is unloaded.
  • rclsid: Pointer to the object's CLISD, specified in the m_ClsID member variable.

CFactoryTemplate.m_pAMovieSetup_Filter

CFactoryTemplate Class

Pointer to an AMOVIESETUP_FILTER structure.

Syntax

const AMOVIESETUP_FILTER *m_pAMovieSetup_Filter;

Remarks

Use this structure to make a filter self-registering. If your component is not a filter, this member variable can be NULL. For more information, see How to Register DirectShow Filters.

CFactoryTemplate::CreateInstance

CFactoryTemplate Class

Calls the object-creation function for the class.

Syntax

CUnknown *CreateInstance(
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pUnk
Pointer to the aggregating IUnknown interface.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.

Return Value

Returns an instance of the class object.

Remarks

The IClassFactory::CreateInstance method calls this class method. This method calls the function pointed to by the m_lpfnNew member variable.

CFactoryTemplate::IsClassID

CFactoryTemplate Class

Determines whether a CLSID matches this class template.

Syntax

BOOL IsClassID(
    REFCLSID rclsid
);

Parameters

rclsid
Reference to a CLSID.

Return Value

Returns TRUE if the rclsid parameter is the same CLSID as the m_ClsID member variable, or else returns FALSE.


CGenericList Class

CGenericList class hierarchy

Class template that implements a type-specific list. For more information, see CBaseList.

Declaration: Wxlist.h

To use this template, declare a variable of type CGenericList, with a template argument that defines the type of object in the list. For example, the following statement declares a list of CBaseFilter objects:

CGenericList<CBaseFilter> myFilterList("Filters");

For convenience, the following list types are defined:

typedef CGenericList<CBaseObject> CBaseObjectList;
typedef CGenericList<IUnknown> CBaseInterfaceList;

Public Methods
CGenericList | Constructor method.
~CGenericList | Destructor method.
GetHeadPosition | Retrieves the position of the first item in the list.
GetTailPosition | Retrieves the position of the last item of the list.
GetCount | Retrieves the number of items in the list.
GetNext | Retrieves the item at the specified position, and advances the position.
Get | Retrieves the item at the specified position.
GetHead | Retrieves the item at the head of the list.
RemoveHead | Removes the first item in the list.
RemoveTail | Removes the last item in the list.
Remove | Removes the item at the specified position.
AddBefore | Inserts an item or list before the specified position.
AddAfter | Inserts an item or list after the specified position.
AddHead | Adds an item or list to the front of the list.
AddTail | Appends an item or list to the end of the list.
Find | Retrieves the first position that holds the specified item.

CGenericList::AddAfter

CGenericList Class

Inserts an item or list after the specified position.

Syntax

POSITION AddAfter(
    POSITION p,
    OBJECT *pObj
);

Parameters

p
Position after which to add the item. If p is NULL, the method adds the item to the head of the list.
pObj
Pointer to an object of type OBJECT (the template type).

Return Value

Returns the position indicator of the inserted item.

Syntax

BOOL AddAfter(
    POSITION pos,
    CGenericList<OBJECT> *pList
);

Parameters

pos
Position after which to insert the list.
pList
Pointer to the list to insert.

Return Value

Returns TRUE if successful, or FALSE otherwise.

CGenericList::AddBefore

CGenericList Class

Inserts an item or list before the specified position.

Syntax

POSITION AddBefore(
    POSITION p,
    OBJECT *pObj
);

Parameters

p
Position before which to insert the list. If p is NULL, this method adds the item to the tail of the list.
pObj
Pointer to an object of type OBJECT (the template type).

Return Value

Returns the position indicator for the inserted item.

Syntax

BOOL AddBefore(
    POSITION pos,
    CGenericList<OBJECT> *pList
);

Parameters

pos
Position before which to insert the list.
pList
Pointer to the list to insert.

Return Value

Returns TRUE if successful. Otherwise, returns FALSE.

CGenericList::AddHead

CGenericList Class

Adds an item or list to the front of the list.

Syntax

POSITION AddHead(
    OBJECT *pObj
);

Parameters

pObj
Pointer to an object of type OBJECT (the template type).

Return Value

Returns a POSITION value indicating the new head position. If the method fails, the return value is NULL.

Syntax

BOOL AddHead(
    CGenericList<OBJECT> *pList
);

Parameters

pList
Pointer to the list of items to add.

Return Value

Returns TRUE if successful, or FALSE otherwise.

CGenericList::AddTail

CGenericList Class

Appends an item or list to the end of the list.

Syntax

POSITION AddTail(
    OBJECT *pObj
);

Parameters

pObj
Pointer to an object of type OBJECT (the template type).

Return Value

Returns a POSITION value for the new tail position. If the method fails, it returns NULL.

Syntax

BOOL AddTail(
    CGenericList<OBJECT> *pList
);

Parameters

pList
Pointer to the list to append.

Return Value

Returns TRUE if successful, or FALSE otherwise.

CGenericList::CGenericList

CGenericList Class

Constructor method.

Syntax

CGenericList(
    TCHAR *pName,
    INT iItems,
    BOOL bLock,
    BOOL bAlert
);

CGenericList(
    TCHAR *pName
);

Parameters

pName
Pointer to the name of the list.
iItems
Size of the node cache.
bLock
Not used.
bAlert
Not used.

Remarks

For efficiency, the CGenericList class maintains a cache of list nodes. If you know approximately how many items the list will hold, use the first version of the constructor. The second version uses a default cache size.

CGenericList::~CGenericList

CGenericList Class

Destructor method.

Syntax

CGenericList(void);

CGenericList::Find

CGenericList Class

Retrieves the first position that holds the specified item.

Syntax

POSITION Find(
    OBJECT *pObj
);

Parameters

pObj
Pointer to an object of type OBJECT (the template type).

Return Value

Returns a POSITION value, or NULL if the item is not in the list.

CGenericList::Get

CGenericList Class

Retrieves the item at the specified position.

Syntax

OBJECT *Get(
    POSITION pos
);

Parameters

pos
Position indicator for the item to retrieve.

Return Value

Returns a pointer to an object of type OBJECT (the template type).

Remarks

If pos is NULL, the method returns NULL.

CGenericList::GetCount

CGenericList Class

Retrieves the number of items in the list.

Syntax

int GetCount(void);

Return Value

Returns the number of items in the list.

CGenericList::GetHead

CGenericList Class

Retrieves the item at the head of the list.

Syntax

OBJECT GetHead(void);

Return Value

Returns a pointer to an object of type OBJECT (the template type).

CGenericList::GetHeadPosition

CGenericList Class

Retrieves the position of the first item in the list.

Syntax

POSITION GetHeadPosition(void);

Return Value

Returns a POSITION value, or NULL if the list is empty.

CGenericList::GetNext

CGenericList Class

Retrieves the item at the specified position, and advances the position.

Syntax

OBJECT *GetNext(
    POSITION& rp
);

Parameters

rp
Reference to a POSITION value.

Return Value

Returns a pointer to an object of type OBJECT (the template type).

Remarks

This method advances the position indicator to the next position. If the position indicator moves past the end of the list, the method sets it to NULL.

If rp is NULL, the method returns NULL.

CGenericList::GetTailPosition

CGenericList Class

Retrieves the position of the last item of the list.

Syntax

POSITION GetTailPosition(void);

Return Value

Returns a POSITION value, or NULL if the list is empty.

CGenericList::Remove

CGenericList Class

Removes the item at the specified position.

Syntax

OBJECT *Remove(
    POSITION pos
    );

Parameters

pos
POSITION value indicating the item to remove.

Return Value

Returns a pointer to an object of type OBJECT (the template type).

Remarks

This method deletes the node from the list, but does not delete the item contained in that node.

If pos is NULL, the method returns NULL.

CGenericList::RemoveHead

CGenericList Class

Removes the first item in the list.

Syntax

OBJECT *RemoveHead(void);

Return Value

Returns a pointer to an object of type OBJECT (the template type), or NULL if the list is empty.

Remarks

This method deletes the list node, but not the item that the node contains.

CGenericList::RemoveTail

CGenericList Class

Removes the last item in the list.

Syntax

OBJECT *RemoveTail(void);

Return Value

Returns a pointer to an object of type OBJECT (the template type), or NULL if the list is empty.

Remarks

This method deletes the list node, but not the item that is contained in the node.


CImageAllocator Class

CImageAllocator class hierarchy

The CImageAllocator class is inherited from the CBaseAllocator class, which allocates sample buffers in shared memory. The number, size, and alignment of blocks are determined when the connected output pin calls CImageAllocator::SetProperties (which implements IMemAllocator::SetProperties). The shared memory blocks are used in subsequent calls to the Microsoft® Win32® CreateDIBSection function. The output pin can then fill these buffers with data, and the buffers will be handed to GDI using BitBlt.

Protected Data Members

m_pFilter | Owning filter of this object.
m_pMediaType | Current media type format.

Member Functions

Alloc | Allocates the samples through CreateDIBSection.
CheckSizes | Checks the allocator requirements.
CImageAllocator | Constructs a CImageAllocator object.
CreateDIB | Creates a device-independent bitmap (DIB).
Free | Releases and deletes the resources for any samples allocated.
NotifyMediaType | Notifies the allocator of the agreed media type.

Overridable Member Functions

CreateImageSample Creates a sample.

Implemented INonDelegatingUnknown Methods

NonDelegatingAddRef | Increments the reference count for an interface.
NonDelegatingRelease | Decrements the reference count for an interface.

Implemented IMemAllocator Methods

SetProperties Specifies the buffering requirements for the allocator.

CImageAllocator::Alloc

CImageAllocator Class

Creates image samples based around CreateDIBSection.

Syntax

HRESULT Alloc(void);

Return Value

Returns an HRESULT value.

Remarks

A filter defines the size and number of buffers required through the CImageAllocator::SetProperties member function. The base allocator class that this allocator derives from calls this internal virtual member function when it wants the memory actually committed. For each sample it wants to create, this allocator will create a DIBSECTION object for it (through the Microsoft Win32 CreateDIBSection function). With the information it gets from that call, it will call the virtual CreateImageSample member function, passing in the buffer pointer and length. After successfully creating an image sample, it will then initialize it with the DIBSECTION structure, among other information.

This is a protected member function.

CImageAllocator::CheckSizes

CImageAllocator Class

Internal member function that checks the required buffering properties.

Syntax

HRESULT CheckSizes(
  ALLOCATOR_PROPERTIES *pRequest
  );

Parameters

pRequest
Pointer to requested allocator properties.

Return Value

Returns an HRESULT value.

Remarks

The image allocator uses the Microsoft Win32 CreateDIBSection function to allocate its samples. That function accepts as input a pointer to a BITMAPINFO structure that describes the bitmap required. Because the size of the bitmap is therefore fixed according to the BITMAPINFO structure for the video, requests to the allocator for a buffer larger than that will not be granted. This member function, therefore, adjusts the requested size so that it is no larger than the size of the bitmap. If the requested size is smaller than the bitmap size, it returns E_INVALIDARG.

This is a protected member function.

CImageAllocator::CImageAllocator

CImageAllocator Class

Constructs a CImageAllocator object.

Syntax

CImageAllocator(
  CBaseFilter *pFilter,
  TCHAR *pName,
  HRESULT *phr
  );

Parameters

pFilter
Pointer to the owning filter object.
pName
Pointer to a debug-only string description.
phr
Pointer to a COM return code.

Return Value

No return value.

Remarks

The CImageAllocator, CImageSample, and CDrawImage classes are all tightly associated. The buffers that the image allocator creates are made using the Microsoft Win32 CreateDIBSection function. The allocator then creates its own samples (based on the CImageSample class). The image samples are initialized with the buffer pointer and its length. The sample is also passed in a structure (a DIBDATA structure) that holds a number of pieces of information obtained from the CreateDIBSection call.

These samples can then be passed to the draw object. The draw object knows the private format of the samples and how to get back the DIBDATA structure from them. Once it has obtained that information, it can pass a bitmap handle that is stored in the DIBDATA structure down into GDI when it draws the image that the sample contains. By using the bitmap handle from the sample in the drawing, rather than just the buffer pointer (which is the alternative if the sample is not a CImageSample), it gets a modest performance improvement.

This is a protected member function.

CImageAllocator::CreateDIB

CImageAllocator Class

Calls the Win32 CreateDIBSection function to create a device-independent bitmap (DIB).

Syntax

HRESULT CreateDIB(
  LONG InSize,
  DIBDATA &DibData
  );

Parameters

InSize
Size of the bitmap required.
DibData
Structure to fill out with details.

Return Value

Returns an HRESULT value.

Remarks

This is a protected member function.

CImageAllocator::CreateImageSample

CImageAllocator Class

Creates a CImageSample object.

Syntax

virtual CImageSample *CreateImageSample(
  LPBYTE pData,
  LONG Length
  );

Parameters

pData
Pointer to the data buffer the sample looks after.
Length
Associated length of the buffer.

Return Value

Returns a new CImageSample sample object.

Remarks

This virtual member function creates the actual sample for the allocator. It is passed the data buffer and its length to store. When the sample is subsequently asked for the buffer (through IMediaSample::GetPointer), this is the pointer it will return. The primary reason for having this split out into a separate virtual member function is so that derived classes from CImageAllocator can also derive classes from CImageSample and have a place to create them.

This is a protected member function.

CImageAllocator::Free

CImageAllocator Class

Deletes the samples and frees their resources.

Syntax

void Free(void);

Return Value

No return value.

Remarks

The base allocator calls this internal virtual member function when it wants to decommit the allocator.

This is a protected member function.

CImageAllocator::NonDelegatingAddRef

CImageAllocator Class

Increments the reference count for the owning filter.

Syntax

HRESULT NonDelegatingAddRef(void);

Return Value

Returns an HRESULT value.

Remarks

An allocator is conceptually a separate object from the filter that creates it. However, the image allocator is dependent on the filter that created it to supply it with additional information (such as the media type that it connected with). Therefore, although the allocator looks after its own NonDelegatingQueryInterface function, it delegates all reference counting to the owning filter. So, when the allocator is subject to its NonDelegatingAddRef function, for example, it is the filter that owns the allocator that will actually be reference counted.

CImageAllocator::NonDelegatingRelease

CImageAllocator Class

Decrements the reference count for the owning filter.

Syntax

HRESULT NonDelegatingRelease(void);

Return Value

Returns an HRESULT value.

Remarks

An allocator is conceptually a separate object from the filter that creates it. However, the image allocator is dependent on the filter that created it to supply it with additional information (such as the media type that it connected with). Therefore, although the allocator looks after its own NonDelegatingQueryInterface function, it delegates all reference counting to the owning filter. So when the allocator is released, for example, it is the filter that owns the allocator that will actually be released by the NonDelegatingRelease function.

CImageAllocator::NotifyMediaType

CImageAllocator Class

Passes the media type from a filter to the allocator.

Syntax

void NotifyMediaType(
  CMediaType *pMediaType
  );

Parameters

pMediaType
Pointer to the media type the filter established.

Return Value

No return value.

Remarks

The buffers that the image allocator creates are based around CreateDIBSection, which must be told what sort of bitmap the filter requires it to create. The filter does this by calling this member function on the allocator. A filter will usually call this member function after agreeing on a media type during a pin connection. The media type passed to this member function is a pointer; the allocator stores this pointer (not a copy) of the media type it points to (for performance reasons, copying media types is relatively slow). Therefore, the filter that calls this member function should ensure that the media type is always valid until the media type is next set on the allocator (or is called with a NULL type).

CImageAllocator::SetProperties

CImageAllocator Class

Determines the size, number, and alignment of blocks.

Syntax

HRESULT SetProperties(

  ALLOCATOR_PROPERTIES *pRequest,

  ALLOCATOR_PROPERTIES *pActual

  );

Parameters

pRequest
Pointer to requested allocator properties.
pActual
Pointer to allocator properties actually set.

Return Value

Returns an HRESULT value.

Remarks

The pRequest parameter is filled in by the caller with the requested values for the count, number, and alignment as specified by the ALLOCATOR_PROPERTIES structure. The pActual parameter is filled in by the allocator with the closest values that it can provide for the request. This member function cannot be called unless the allocator has been decommitted by using the IMemAllocator::Decommit method.


CImageDisplay Class

CImageDisplay class hierarchy

The CImageDisplay class initializes itself with a display format so that other objects can query or reset the display type. It also provides member functions to check display formats and accept only those video formats that can be efficiently rendered by using GDI calls.

Protected Data Members

m_Display VIDEOINFO structure corresponding to the current device display type.

Member Functions

CheckBitFields | Checks that the bit fields on a VIDEOINFO structure are correct.
CheckHeaderValidity | Determines if a BITMAPINFOHEADER structure is valid.
CheckMediaType | Determines if the filter can support the media type proposed by the output pin.
CheckPaletteHeader | Determines if the palette on a VIDEOINFO structure is correct.
CheckVideoType | Compares a video type to determine if it is compatible with the current display mode.
CImageDisplay | Constructs a CImageDisplay object.
CountPrefixBits | Counts the number of prefix bits.
CountSetBits | Counts the total number of bits set in a field.
GetBitMasks | Retrieves a set of color element bitmasks for the supplied VIDEOINFO structure.
GetColourMask | Retrieves a set of individual color element masks.
GetDisplayDepth | Retrieves the bit depth of the current display mode.
GetDisplayFormat | Retrieves a VIDEOINFO structure representing the current display mode.
IsPalettized | Determines if the display uses a palette.
RefreshDisplayType | Updates the CImageDisplay object with the current display type.
UpdateFormat | Updates the VIDEOINFO structure to remove implicit assumptions.

CImageDisplay::CheckBitFields

CImageDisplay Class

Checks that the bit fields in the VIDEOINFO structure are correct.

Syntax

BOOL CheckBitFields(
    const VIDEOINFO *pInput
    );

Parameters

pInput
Pointer to the VIDEOINFO structure to check.

Return Value

Returns one of the following values.
TRUE | Bit fields are correct.
FALSE | Bit fields contain an error.

Remarks

The assumption throughout the object is that any bitmasks are allowed no more than 8 bits to store a color component. This member function checks that the bit count assumption is enforced, and also ensures that all the bits set are contiguous.

This is a protected member function.

CImageDisplay::CheckHeaderValidity

CImageDisplay Class

Determines if a BITMAPINFOHEADER structure is valid.

Syntax

BOOL CheckHeaderValidity(
    const VIDEOINFO *pInput
    );

Parameters

pInput
Pointer to the VIDEOINFO structure that contains the bitmap details.

Return Value

Returns one of the following values.
TRUE | Format is valid.
FALSE | Format contains an error.

Remarks

The BITMAPINFOHEADER structure might be rejected for a number of reasons. These might include a number-of-planes entry greater or less than one, the size of the structure not being equal to the size of BITMAPINFOHEADER, or, perhaps, being asked to validate a YUV format (this member function only validates RGB formats; it will always return FALSE for YUV types).

CImageDisplay::CheckMediaType

CImageDisplay Class

Determines if the filter can support the media type proposed by the output pin.

Syntax

HRESULT CheckMediaType(
    const CMediaType *pmtIn
    );

Parameters

pmtIn
Pointer to the media type to check.

Return Value

Returns an HRESULT value.

Remarks

This helper member function can be used to validate a video media type. It examines the major type and subtype GUIDs and verifies that the format GUID defines a VIDEOINFO structure.

CImageDisplay::CheckPaletteHeader

CImageDisplay Class

Determines if the palette on a VIDEOINFO structure is correct.

Syntax

BOOL CheckPaletteHeader(
    const VIDEOINFO *pInput
    );

Parameters

pInput
Pointer to the VIDEOINFO structure to validate.

Return Value

Returns one of the following values.
TRUE | Palette is correct.
FALSE | No valid palette.

Remarks

This member function returns FALSE if the format specifies that no palette is available (it might be a true-color format). It also returns FALSE if the number of palette colors used (or those that are important) exceeds the number specified for the video format.

CImageDisplay::CheckVideoType

CImageDisplay Class

Compares a video type to determine if it is compatible with the current display mode.

Syntax

HRESULT CheckVideoType(
    const VIDEOINFO *pInput
    );

Parameters

pInput
Pointer to the VIDEOINFO structure to validate.

Return Value

Returns NOERROR if successful or E_INVALIDARG if unsuccessful.

Remarks

Many video rendering filters want a function to determine if proposed formats are okay. This member function checks the VIDEOINFO structure passed as a media type and returns NOERROR if the media type is valid; otherwise, it returns E_INVALIDARG434. Note, however, that only formats that can be easily displayed on the current display device are accepted; so, for example, a 16-bit device will not accept 24-bit images. Because most displays draw 8-bit palettized images efficiently, this format is always accepted unless the display is 16-color VGA.

CImageDisplay::CImageDisplay

CImageDisplay Class

Constructs a CImageDisplay object.

Syntax

CImageDisplay(void);

Return Value

No return value.

Remarks

The CImageDisplay class helps renderers that want to determine the format of the current display mode. This member function retrieves the display mode and creates a VIDEOINFO structure that represents its format. The class supplies that format for clients through member functions such as IsPalettized and GetDisplayFormat. If a client detects the display format has changed (perhaps it receives a WM_DISPLAYCHANGED message), it should call RefreshDisplayType.

CImageDisplay::CountPrefixBits

CImageDisplay Class

Counts the number of prefix bits.

Syntax

DWORD CountPrefixBits(
    const DWORD Field
    );

Parameters

Field
Input bitmask field.

Return Value

No return value.

Remarks

Given a bitmask, this helper member function counts the number of zero bits up to the least significant set bit. So, for a binary number 00000100, the member function returns 2 (decimal). The member function does, however, work on DWORD values, so it counts from the least significant bit up through the DWORD to the last bit (0x80000000). If no bits are found, this will return the (impossible) value 32 (decimal).

This is a protected member function.

CImageDisplay::CountSetBits

CImageDisplay Class

Counts the total number of bits set in a field.

Syntax

DWORD CountSetBits(
    const DWORD Field
    );

Parameters

Field
Field in which to count bit sets.

Return Value

Returns the number of bit sets.

Remarks

This is a protected member function.

CImageDisplay::GetBitMasks

CImageDisplay Class

Retrieves a set of color element bitmasks for the supplied VIDEOINFO structure.

Syntax

const DWORD *GetBitMasks(
    const VIDEOINFO *pVideoInfo
    );

Parameters

pVideoInfo
Pointer to the input VIDEOINFO structure format.

Return Value

No return value.

Remarks

This member function should be called only with RGB formats. If the RGB format has a bit depth of 16/32 bits per pixel, it will return the bitmasks for the individual red, green, and blue color elements (for example, RGB565 is 0xF800, 0x07E0, and 0x001F). For RGB24, this will return 0xFF0000, 0xFF00, and 0xFF. For palettized formats, this will return all zeros.

CImageDisplay::GetColourMask

CImageDisplay Class

Retrieves a set of individual color element masks.

Syntax

BOOL GetColourMask(
    DWORD *pMaskRed,
    DWORD *pMaskGreen,
    DWORD *pMaskBlue
    );

Parameters

pMaskRed
Pointer to the red mask.
pMaskGreen
Pointer to the green mask.
pMaskBlue
Pointer to the blue mask.

Return Value

Returns one of the following values.
TRUE | Masks were filled out correctly.
FALSE | No masks were available for the display.

Remarks

Given a video format described by a VIDEOINFO structure, this member function returns the mask that is used to obtain the range of acceptable colors for this type (for example, the mask for a 24-bit true color format is 0xFF in all cases). A 16-bit 5:6:5 display format uses 0xF8, 0xFC, and 0xF8. Therefore, given any RGB triplets, this member function can find one that is compatible with the display format by using a bitwise-AND operation.

CImageDisplay::GetDisplayDepth

CImageDisplay Class

Retrieves the bit depth of the current display mode.

Syntax

WORD GetDisplayDepth(void);

Return Value

Returns the number of bits per pixel used on the display.

CImageDisplay::GetDisplayFormat

CImageDisplay Class

Retrieves a VIDEOINFO structure representing the current display mode.

Syntax

const VIDEOINFO *GetDisplayFormat(void);

Return Value

Returns a VIDEOINFO structure representing the display format.

CImageDisplay::IsPalettized

CImageDisplay Class

Determines if the display uses a palette.

Syntax

BOOL IsPalettized(void);

Return Value

Returns TRUE if the display uses a palette; otherwise, returns FALSE.

CImageDisplay::RefreshDisplayType

CImageDisplay Class

Updates the CImageDisplay object with the current display type.

Syntax

HRESULT RefreshDisplayType(
    LPSTR szDeviceName
    );

Parameters

szDeviceName
Name of the device to update. If omitted, this parameter defaults to the main device.

Return Value

Returns NOERROR if successful; E_FAIL if unsuccessful.

Remarks

This member function should be called when a WM_DISPLAYCHANGED message is received.

CImageDisplay::UpdateFormat

CImageDisplay Class

Updates the VIDEOINFO structure to remove implicit assumptions.

Syntax

HRESULT UpdateFormat(
    VIDEOINFO *pVideoInfo
    );

Parameters

pVideoInfo
Pointer to the VIDEOINFO structure to update.

Return Value

Returns an HRESULT value. Current implementation returns NOERROR.

Remarks

This member function is probably suitable only for specific filters to use. The BITMAPINFO structure has certain fields that are not well specified. In particular, the number of colors specified for a palette can be zero, in which case it is defined to be the maximum for that format type. This member function updates these fields so that their contents are explicit.


CImagePalette Class

The CImagePalette class is a specialized class for image renderers that must create and manage palettes. It can be used to create palette handles from a media format containing a VIDEOINFO structure in the format block. To maximize performance, the class attempts to create a palette that is an identity palette (that is, one that exactly matches the current system palette), and compares palettes before updating to ensure that palettes are changed only when actually required.

Protected Data Members

m_hPalette | Palette handle owned by this object.
m_pBaseWindow | Window in which to realize the palette.
m_pDrawImage | Object that will perform the drawing.
m_pMediaFilter | Media filter to send events to.

Member Functions

CImagePalette | Constructs a CImagePalette object.
CopyPalette | Copies the palette out of any YUV or true-color VIDEOINFOHEADER structure into a palettized VIDEOINFOHEADER structure.
MakeIdentityPalette | Ensures the palette entries will become an identity palette.
MakePalette | Retrieves the color palette from the specified video image.
PreparePalette | Specifies an entry point for updating and creating palettes.
RemovePalette | Releases any palette resources allocated.
ShouldUpdate | Specifies an internal helper member function for updating palettes dynamically.

CImagePalette::CImagePalette

CImagePalette Class

Constructs a CImagePalette object.

Syntax

CImagePalette(
    CBaseFilter *pBaseFilter,
    CBaseWindow *pBaseWindow,
    CDrawImage *pDrawImage
);

Parameters

pBaseFilter
Pointer to the filter that owns this class.
pBaseWindow
Pointer to the window to realize palette in.
pDrawImage
Pointer to the object that draws using this palette.

Return Value

No return value.

Remarks

This class looks after the creation, management, and deletion of a window palette. It is passed in a number of other objects that might be interested in palettes. The class is optimized so that requested palette changes will be acted on only if the new set of colors differs from the current set. This is a performance optimization, because changing palettes is an expensive process.

This constructor is passed in the owning filter (pBaseFilter), which must be a valid pointer. When the class actually creates a palette, it tells the owning filter to send an EC_PALETTE_CHANGED message to the filter graph manager. The constructor might also be passed two further object pointers. If pBaseWindow is not null, when the renderer creates a new palette the class automatically installs it in this window. When told to remove a palette, the class also removes the palette from the base window and installs a standard VGA palette instead.

The constructor can also be passed a drawing object derived from the CDrawImage class. If this is non-NULL, when creating a new palette the class will inform the drawing object that the palette has changed (this is usually used in conjunction with a window object). This ensures that the drawing object is notified when the palette changes so that it can update any samples it has that were created using CreateDIBSection (because they might need their internal color tables updated).

CImagePalette::CopyPalette

CImagePalette Class

Copies the palette out of any YUV or true-color VIDEOINFOHEADER structure into a palettized VIDEOINFOHEADER structure.

Syntax

HRESULT CopyPalette(
    const CMediaType *pSrc,
    const CMediaType *pDest
);

Parameters

pSrc
Pointer to the source media type.
pDest
Pointer to the destination media type.

Return Value

Returns NOERROR if successful or S_FALSE if no palette is available.

Remarks

This member function is used when changing palettes on DirectDraw® samples. A filter acting as a source to the renderer can attach a palette to any buffer and pass it to the renderer as a new VIDEOINFOHEADER format. The renderer can then call CopyPalette to make a new palette from that format, and copy the palette colors into the new connection type.

CImagePalette::MakeIdentityPalette

CImagePalette Class

Modifies the PALETTEENTRY structure to create an identity palette.

Syntax

HRESULT MakeIdentityPalette(
    PALETTEENTRY *pEntry,
    INT iColours,
    LPSTR szDevice
);

Parameters

pEntry
Pointer to an array of prospective palette colors.
iColours
Number of colors in the array.
szDevice
Pointer to string that contains the name of the destination device. If omitted, this parameter defaults to the main device.

Return Value

Returns NOERROR if successful or S_FALSE if unsuccessful.

Remarks

When a palette is installed in a window, GDI does a fair job of compressing the requested colors where possible. So, for example, if the array contains five entries of black, they will be compressed into one palette entry. This is useful for most applications; however, when drawing video it will force GDI to map the pixels in the supplied image to the compressed palette (which results in serious performance penalties).

Therefore, the PALETTEENTRY fields supplied must be adjusted so that they will never have colors compressed. This means that when the window displaying the image has the foreground focus, the palette created by this object will map directly to the palette selected in the display device: a so-called identity palette.

CImagePalette::MakePalette

CImagePalette Class

Retrieves the color palette from the specified video image.

Syntax

HPALETTE MakePalette(
    const VIDEOINFOHEADER *pVideoInfo,
    LPSTR szDevice
);

Parameters

pVideoInfo
Pointer to the container for the palette colors required.
szDevice
Pointer to a string that contains the name of the destination device. If omitted, this parameter defaults to the main device.

Return Value

Returns a handle to the new palette (NULL if it fails).

CImagePalette::PreparePalette

CImagePalette Class

Specifies an entry point for creating and installing palettes.

Syntax

HRESULT PreparePalette(
    const CMediaType *pmtNew,
    const CMediaType *pmtOld,
    LPSTR szDevice
);

Parameters

pmtNew
Pointer to the media type holding new palette information.
pmtOld
Pointer to the media type holding old palette information.
szDevice
Pointer to an string that contains the name of the destination device. If omitted, this parameter defaults to the main device.

Return Value

Returns an HRESULT value.

Remarks

This is the main entry point for creating new palettes. It tries to detect situations where the palette colors requested have not changed (in which case it does not need to create a new palette). It uses the old media type to determine if the colors have changed. It also handles optionally installing the palette in a window (if supplied) and notifying the filter graph manager of a change in palettes (it uses the filter passed in to the constructor for this). Finally, it handles notifying the draw object of palette changes (also optional, depending on whether a draw object was passed in to the constructor).

CImagePalette::RemovePalette

CImagePalette Class

Removes and deletes any palette previously created.

Syntax

HRESULT RemovePalette(void);

Return Value

Returns an HRESULT value. Current implementation returns NOERROR.

CImagePalette::ShouldUpdate

CImagePalette Class

Determines whether it is necessary to create a new palette.

Syntax

BOOL ShouldUpdate(
    const VIDEOINFOHEADER *pNewInfo,
    const VIDEOINFOHEADER *pOldInfo
);

Parameters

pNewInfo
Pointer to a VIDEOINFOHEADER structure containing the new set of colors.
pOldInfo
Pointer to a VIDEOINFOHEADER structure containing the old set of colors.

Return Value

Returns one of the following values.
TRUE | A new palette is required.
FALSE | The existing palette suffices.

Remarks

Use this function to test whether it is necessary to create a new palette. If the original type does not use a palette and the new one does (or vice versa), this method returns TRUE. If neither formats use a palette, this method returns FALSE. If both formats use a palette, the colors are compared, and if they match, the method returns FALSE.


CImageSample Class

CImageSample class hierarchy

The CImageSample class inherits from CMediaSample and overrides the constructor to initialize itself with the DIBDATA structure. When the renderer is using its own allocator, it will use this class for its samples. It can therefore obtain the DIBSECTION structure information it requires to obtain the HBITMAP data it renders.

Protected Data Members

m_bInit | Flag to determine if the DIBSECTION structure information is initialized.
m_DibData | Information about the sample's DIBSECTION structure.

Member Functions

CImageSample | Constructs a CImageSample object.
GetDIBData | Retrieves the DIBSECTION structure information stored for the sample.
SetDIBData | Sets the DIBSECTION information stored for the sample.

CImageSample::CImageSample

CImageSample Class

Constructs a CImageSample object.

Syntax

CImageSample(
  CBaseAllocator *pAllocator,
  TCHAR *pName,
  HRESULT *phr,
  LPBYTE pBuffer,
  LONG length
  );

Parameters

pAllocator
Pointer to the base allocator to which the sample belongs.
pName
Pointer to the debug-only string description.
phr
Pointer to the COM return code.
pBuffer
Pointer to the image buffer.
length
Length of the image buffer.

Return Value

No return value.

Remarks

The CImageAllocator, CImageSample, and CDrawImage classes are all tightly associated. The buffers that the image allocator creates are made by using the Microsoft® Win32® CreateDIBSection function. The allocator then creates its own samples (based on the CImageSample class). The image samples are initialized with the buffer pointer and its length. The sample is also passed in a structure (a DIBDATA structure) that holds a number of pieces of information obtained from the CreateDIBSection call.

These samples can then be passed to the draw object. The draw object knows the private format of the samples and how to get back the DIBDATA structure from them. Once it has obtained that information, it can pass a bitmap handle, which is stored in the DIBDATA structure, down into GDI when it draws the image that the sample contains. By using the bitmap handle from the sample in the drawing, rather than just the buffer pointer (which is the alternative if the sample is not a CImageSample), it achieves a modest performance improvement.

CImageSample::GetDIBData

CImageSample Class

Retrieves the DIBDATA structure held by the sample.

Syntax

DIBDATA *GetDIBData(void);

Return Value

Returns a DIBDATA structure.

CImageSample::SetDIBData

CImageSample Class

Sets the DIBDATA structure that the sample should hold.

Syntax

void SetDIBData(
  DIBDATA *pDibData
  );

Parameters

pDibData
Pointer to the new DIBDATA structure.

Return Value

No return value.


CLoadDirectDraw Class

Microsoft® DirectShow® must work on multiple platforms; in particular, it also runs on Microsoft Windows NT® 3.51, which does not have DirectDraw® capabilities. The filters therefore cannot link statically to the DirectDraw library. To make the platform dependencies easier to handle, this class manages loading and unloading the library and creating the initial IDirectDraw interface.

Member Functions

CLoadDirectDraw | Constructs a CLoadDirectDraw object.
GetDirectDraw | Retrieves a pointer to the IDirectDraw interface.
IsDirectDrawLoaded | Verifies that DirectDraw is loaded.
IsDirectDrawVersion1 | Checks the version of DirectDraw installed on the current system.
LoadDirectDraw | Loads and initializes the DirectDraw library.
ReleaseDirectDraw | Releases the IDirectDraw interface.

CLoadDirectDraw::CLoadDirectDraw

CLoadDirectDraw Class

Constructs a CLoadDirectDraw object.

Syntax

CLoadDirectDraw(void);

Return Value

No return value.

CLoadDirectDraw::GetDirectDraw

CLoadDirectDraw Class

Retrieves the DirectDraw interface.

Syntax

LPDIRECTDRAW GetDirectDraw(void);

Return Value

Returns a pointer to the IDirectDraw interface.

Remarks

Call CLoadDirectDraw::LoadDirectDraw before calling this member function and call the CLoadDirectDraw::ReleaseDirectDraw member function to release the interface when you are done.

CLoadDirectDraw::IsDirectDrawLoaded

CLoadDirectDraw Class

Verifies that this object loaded DirectDraw.

Syntax

HRESULT IsDirectDrawLoaded(void);

Return Value

Returns S_OK if loaded; otherwise, returns S_FALSE.

CLoadDirectDraw::IsDirectDrawVersion1

CLoadDirectDraw Class

Checks the version of DirectDraw installed on the current system.

Syntax

BOOL IsDirectDrawVersion1(void);

Return Value

Returns TRUE if the installed version of DirectDraw doesn't support the IDirectDraw2 interface, or FALSE if the m_pDirectDraw data member is NULL or the installed version of DirectDraw supports IDirectDraw2.

Remarks

The video renderer must know what the installed version of DirectDraw is to perform certain tasks, such as full-screen playback, which the IDirectDraw2 interface supports.

CLoadDirectDraw::LoadDirectDraw

CLoadDirectDraw Class

Loads and initializes the DirectDraw library in the specified area.

Syntax

HRESULT LoadDirectDraw(
  LPSTR szDevice
  );

Parameters

szDevice
This parameter is optional; if omitted, this method loads DirectDraw to the base drawing area.

Return Value

Returns S_OK if DirectDraw loaded correctly or E_NOINTERFACE otherwise.

Remarks

DirectDraw is not always available, so applications can't statically link to the library. Therefore, this member function loads the library, gets the function entry point addresses, and calls them to create the driver objects. Call this member function before calling CLoadDirectDraw::GetDirectDraw to retrieve the IDirectDraw interface.

CLoadDirectDraw::ReleaseDirectDraw

CLoadDirectDraw Class

Releases the IDirectDraw interface.

Syntax

void ReleaseDirectDraw(void);

Return Value

No return value.

Remarks

This member function is called to release any IDirectDraw interface previously loaded. Call this only when all reference counts have been released.


CMediaControl Class

CMediaControl class hierarchy

The CMediaControl class provides base class handling of the IDispatch methods of the dual-interface IMediaControl. It leaves as pure virtual the properties and methods of the IMediaControl interface.

Typically, the filter graph manager is the only object that implements the IMediaControl interface. (filters implement the IMediaFilter interface, inherited by IBaseFilter, to receive control commands from the filter graph manager.) Therefore, this class library is of limited use to filter developers.

The CMediaControl::GetIDsOfNames, CMediaControl::GetTypeInfo, CMediaControl::GetTypeInfoCount, and CMediaControl::Invoke member functions are standard implementations of the IDispatch methods using the CBaseDispatch class (and a type library) to parse the commands and pass them to the pure virtual methods of the IMediaControl interface.

The IMediaControl methods, defined in control.odl, are left as pure virtual.

Member Functions

CMediaControl Constructs a CMediaControl object.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface Returns a specified reference-counted interface.

Implemented IDispatch Methods

GetIDsOfNames | Maps a single member and an optional set of parameters to a corresponding set of integer dispatch identifiers (DISPIDs), which can be used during subsequent calls to the CMediaControl::Invoke method.
GetTypeInfo | Retrieves a type-information object, which can retrieve the type information for an interface.
GetTypeInfoCount | Retrieves the number of type-information interfaces provided by an object.
Invoke | Provides access to properties and methods exposed by an object.

CMediaControl::CMediaControl

CMediaControl Class

Constructs a CMediaControl object.

Syntax

CMediaControl(
    const TCHAR *pName,
    LPUNKNOWN pUnk
    );

Parameters

pName
Pointer to the name of the object for debugging purposes.
pUnk
Pointer to the owner of this object.

Return Value

No return value.

Remarks

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.

CMediaControl::GetIDsOfNames

CMediaControl Class

Maps a single member function and an optional set of parameters to a corresponding set of integer dispatch identifiers (DISPIDs), which can be used upon subsequent calls to the CMediaControl::Invoke member function.

Syntax

HRESULT GetIDsOfNames(
    REFIID riid,
    OLECHAR **rgszNames,
    UINT cNames,
    LCID lcid,
    DISPID *rgdispid
    );

Parameters

riid
Reference identifier. Reserved for future use. Must be NULL.
rgszNames
Address of a pointer to a passed-in array of names to be mapped.
cNames
Count of the names to be mapped.
lcid
Locale context in which to interpret the names.
rgdispid
Pointer to a caller-allocated array, each element of which contains an ID corresponding to one of the names passed in the rgszNames array. The first element represents the member name; the subsequent elements represent each of the member's parameters.

Return Value

Returns one of the following values.
DISP_E_UNKNOWN_CLSID | The CLSID was not recognized.
DISP_E_UNKNOWNNAME | One or more of the names were not known. The returned DISPIDs contain DISPID_UNKNOWN for each entry that corresponds to an unknown name.
E_OUTOFMEMORY | Out of memory.
S_OK | Success.

CMediaControl::GetTypeInfo

CMediaControl Class

Retrieves a type-information object, which can retrieve the type information for an interface.

Syntax

HRESULT GetTypeInfo(
    UINT itinfo,
    LCID lcid,
    ITypeInfo **pptinfo
    );

Parameters

itinfo
Type information to return. Pass zero to retrieve type information for the IDispatch implementation.
lcid
Locale ID for the type information. For classes that support localized member names, an object might be able to return different type information for different languages. For classes that do not support localized member names, this parameter can be ignored.
pptinfo
Address of a pointer to the type-information object requested.

Return Value

Returns an E_POINTER if pptinfo is invalid. Returns TYPE_E_ELEMENTNOTFOUND if itinfo is not zero. Returns S_OK if is successful. Otherwise, returns an HRESULT from one of the calls to retrieve the type. The HRESULT indicates the error and can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
S_OK or NOERROR | Success.

CMediaControl::GetTypeInfoCount

CMediaControl Class

Retrieves the number of type-information interfaces provided by an object.

Syntax

HRESULT GetTypeInfoCount(
    UINT *pctinfo
    );

Parameters

pctinfo
Pointer to the number of type-information interfaces that the object provides. If the object provides type information, this number is 1; otherwise, the number is 0.

Return Value

Returns E_POINTER if pctinfo is invalid; otherwise, returns S_OK.

CMediaControl::Invoke

CMediaControl Class

Provides access to properties and methods exposed by an object.

Syntax

HRESULT Invoke(
    DISPID dispidMember,
    REFIID riid,
    LCID lcid,
    WORD wFlags,
    DISPPARAMS *pdispparams,
    VARIANT *pvarResult,
    EXCEPINFO *pexcepinfo,
    UINT *puArgErr
    );

Parameters

dispidMember
Identifier of the member. Use CMediaControl::GetIDsOfNames or the object's documentation to obtain the dispatch identifier.
riid
Reserved for future use. Must be IID_NULL.
lcid
Locale context in which to interpret arguments.
wFlags
Flags describing the context of the CMediaControl::Invoke call.
pdispparams
Pointer to a structure containing an array of arguments, an array of argument dispatch IDs for named arguments, and counts for number of elements in the arrays.
pvarResult
Pointer to where the result is to be stored, or NULL if the caller expects no result.
pexcepinfo
Pointer to a structure containing exception information.
puArgErr
Pointer to the index of the first argument, within the DISPPARAMS structure's rgvarg array, that has an error. For more information on DISPPARAMS, see the Platform SDK.

Return Value

Returns DISP_E_UNKNOWNINTERFACE if riid is not IID_NULL. Returns one of the error codes from CMediaControl::GetTypeInfo if the call fails. Otherwise, returns the HRESULT from the call to IDispatch::Invoke.

CMediaControl::NonDelegatingQueryInterface

CMediaControl Class

Retrieves a specified reference-counted interface.

Syntax

HRESULT NonDelegatingQueryInterface(
    REFIID riid,
    void **ppv
    );

Parameters

riid
Reference identifier.
ppv
Address of a pointer to the interface.

Return Value

Returns E_POINTER if ppv is invalid. Returns NOERROR if the query is successful or E_NOINTERFACE if it is not.

Remarks

Returns pointers to the IMediaControl and IUnknown interfaces by default. Override this member function to publish any additional interfaces implemented by the derived class.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.


CMediaEvent Class

CMediaEvent class hierarchy

The CMediaEvent class provides base class implementation of the IDispatch methods of the dual-interface IMediaEvent. It leaves as pure virtual the properties and methods of the IMediaEvent interface.

The CMediaEvent class also provides base class implementation of the IMediaEventEx interface which derives from IMediaEvent.

The CMediaEvent::GetIDsOfNames, CMediaEvent::GetTypeInfo, CMediaEvent::GetTypeInfoCount, and CMediaEvent::Invoke member functions are standard implementations of the IDispatch interface using the CBaseDispatch class (and a type library) to parse the commands and pass them to the pure virtual methods of the IMediaEvent interface.

Member Functions

CMediaEvent Constructs a CMediaEvent object.

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface Returns a specified reference-counted interface.

Implemented IDispatch Methods

GetIDsOfNames | Maps a single member and an optional set of parameters to a corresponding set of integer dispatch identifiers, which can be used during subsequent calls to the IDispatch::Invoke method.
GetTypeInfo | Retrieves a type-information object, which retrieves the type information for an interface.
GetTypeInfoCount | Retrieves the number of type-information interfaces provided by an object.
Invoke | Provides access to properties and methods exposed by an object.

CMediaEvent::CMediaEvent

CMediaEvent Class

Constructs a CMediaEvent object.

Syntax

CMediaEvent(
    const TCHAR *pName,
    LPUNKNOWN pUnk
    );

Parameters

pName
Pointer to the name of the object for debugging purposes.
pUnk
Pointer to the owner of this object.

Return Value

No return value.

Remarks

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.

CMediaEvent::GetIDsOfNames

CMediaEvent Class

Maps a single member function and an optional set of parameters to a corresponding set of integer dispatch identifiers, which can be used upon subsequent calls to the CMediaEvent::Invoke member function.

Syntax

HRESULT GetIDsOfNames(
    REFIID riid,
    OLECHAR **rgszNames,
    UINT cNames,
    LCID lcid,
    DISPID *rgdispid
    );

Parameters

riid
Reference identifier. Reserved for future use. Must be NULL.
rgszNames
Address of a pointer to a passed-in array of names to be mapped.
cNames
Count of the names to be mapped.
lcid
Locale context in which to interpret the names.
rgdispid
Pointer to a caller-allocated array, each element of which contains an ID corresponding to one of the names passed in the rgszNames array. The first element represents the member name; the subsequent elements represent each of the member's parameters.

Return Value

Returns one of the following values.
DISP_E_UNKNOWN_CLSID | The CLSID was not recognized.
DISP_E_UNKNOWNNAME | One or more of the names were not known. The returned DISPIDs contain DISPID_UNKNOWN for each entry that corresponds to an unknown name.
E_OUTOFMEMORY | Out of memory.
S_OK | Success.

CMediaEvent::GetTypeInfo

CMediaEvent Class

Retrieves a type-information object, which can retrieve the type information for an interface.

Syntax

HRESULT GetTypeInfo(
    UINT itinfo,
    LCID lcid,
    ITypeInfo **pptinfo
    );

Parameters

itinfo
Type information to return. Pass zero to retrieve type information for the IDispatch implementation.
lcid
Locale ID for the type information. For classes that support localized member names, an object might be able to return different type information for different languages. For classes that do not support localized member names, this parameter can be ignored.
pptinfo
Address of a pointer to the type-information object requested.

Return Value

Returns an E_POINTER if pptinfo is invalid. Returns TYPE_E_ELEMENTNOTFOUND if itinfo is not zero. Returns S_OK if is successful. Otherwise, returns an HRESULT from one of the calls to retrieve the type. The HRESULT indicates the error and can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
S_OK or NOERROR | Success.

CMediaEvent::GetTypeInfoCount

CMediaEvent Class

Retrieves the number of type-information interfaces provided by an object.

Syntax

HRESULT GetTypeInfoCount(
    UINT *pctinfo
    );

Parameters

pctinfo
Pointer to number of type-information interfaces that the object provides. If the object provides type information, this number is 1; otherwise, the number is 0.

Return Value

Returns E_POINTER if pctinfo is invalid; otherwise, returns S_OK.

CMediaEvent::Invoke

CMediaEvent Class

Provides access to properties and methods exposed by an object.

Syntax

HRESULT Invoke(
    DISPID dispidMember,
    REFIID riid,
    LCID lcid,
    WORD wFlags,
    DISPPARAMS *pdispparams,
    VARIANT *pvarResult,
    EXCEPINFO *pexcepinfo,
    UINT *puArgErr
    );

Parameters

dispidMember
Identifier of the member. Use CMediaEvent::GetIDsOfNames or the object's documentation to obtain the dispatch identifier.
riid
Reserved for future use. Must be IID_NULL.
lcid
Locale context in which to interpret arguments.
wFlags
Flags describing the context of the CMediaEvent::Invoke call.
pdispparams
Pointer to a structure containing an array of arguments, an array of argument dispatch IDs for named arguments, and counts for the number of elements in the arrays.
pvarResult
Pointer to where the result is to be stored, or NULL if the caller expects no result.
pexcepinfo
Pointer to a structure containing exception information.
puArgErr
Pointer to the index of the first argument, within the DISPPARAMS structure's rgvarg array, that has an error. For more information on DISPPARAMS, see the Platform SDK.

Return Value

Returns DISP_E_UNKNOWNINTERFACE if riid is not IID_NULL. Returns one of the error codes from CMediaEvent::GetTypeInfo if the call fails. Otherwise, returns the HRESULT from the call to IDispatch::Invoke.

CMediaEvent::NonDelegatingQueryInterface

CMediaEvent Class

Returns a specified reference-counted interface.

Syntax

HRESULT NonDelegatingQueryInterface(
    REFIID riid,
    void **ppv
    );

Parameters

riid
Reference identifier.
ppv
Address of a pointer to the interface.

Return Value

Returns E_POINTER if ppv is invalid. Returns NOERROR if the query is successful or E_NOINTERFACE if it is not.

Remarks

Returns a pointer to the IMediaEvent and IUnknown interfaces by default. Override this member function to publish any additional interfaces added by the derived class.

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.


CMediaPosition Class

CMediaPosition class hierarchy

Handles the IDispatch methods of the IMediaPosition dual interface.

This class inherits the IMediaPosition interface but does not implement it. It implements IDispatch through the CBaseDispatch class and the Microsoft® DirectShow® type library. Do not use this class directly. Instead, use one of the following classes:

  • Source filters: Use the CSourceSeeking base class to implement seeking.
  • Transform filters: Use the CPosPassThru class to pass seeking commands upstream.
  • Renderers: Use the CRendererPosPassThru class to pass seeking commands upstream.
Public Methods
CMediaPosition | Constructor method.
IDispatch Methods
GetIDsOfNames | Maps a set of names to a corresponding set of DISPIDs.
GetTypeInfo | Retrieves the type information for the object, which can then be used to get the type information for an interface.
GetTypeInfoCount | Retrieves the number of type information interfaces the object provides.
Invoke | Provides access to properties and methods exposed by the object.

CMediaPosition::CMediaPosition

CMediaPosition Class

Constructor method.

Syntax

CMediaPosition(
    const TCHAR *pName,
    LPUNKNOWN pUnk
);

CMediaPosition(
    const TCHAR *pName,
    LPUNKNOWN pUnk
    HRESULT *phr
);

Parameters

pName
Pointer to the name of the object, for debugging purposes. Allocate this parameter in static memory.
pUnk
Pointer to the owner of this object, or NULL if the object is not aggregated.
phr
Ignored.

CMediaPosition::GetIDsOfNames

CMediaPosition Class

Maps a set of names to a corresponding set of DISPIDs.

Syntax

HRESULT GetIDsOfNames(
    REFIID riid,
    OLECHAR **rgszNames,
    UINT cNames,
    LCID lcid,
    DISPID *rgdispid
);

Parameters

riid
Reserved. Use IID_NULL.
rgszNames
Address of an array of wide-character strings that contain the names to be mapped.
cNames
Size of the array given by the rgszNames parameter.
lcid
Locale context in which to interpret the names. Can be NULL.
rgdispid
Pointer to an array that receives the DISPIDs. Each element of receives an identifier that corresponds to one of the names passed in the rgszNames parameter.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
DISP_E_UNKNOWNNAME | One or more of the names were not known.

CMediaPosition::GetTypeInfo

CMediaPosition Class

Retrieves the type information for the object, which can then be used to get the type information for an interface.

Syntax

HRESULT GetTypeInfo(
    UINT itinfo,
    LCID lcid,
    ITypeInfo **pptinfo
);

Parameters

itinfo
Type information to return. Must be zero.
lcid
Locale identifier.
pptinfo
Address of a variable that receives an ITypeInfo pointer.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_POINTER | Null pointer argument.
TYPE_E_ELEMENTNOTFOUND | The itinfo parameter is not zero.

CMediaPosition::GetTypeInfoCount

CMediaPosition Class

Retrieves the number of type information interfaces the object provides.

Syntax

HRESULT GetTypeInfoCount(
    UINT *pctinfo
);

Parameters

pctinfo
Pointer to a variable that receives the number of type-information interfaces provided by the object. When the method returns, the value is 1.

Return Value

Returns one of the following values.

S_OK | Success.
E_POINTER | Null pointer argument.

CMediaPosition::Invoke

CMediaPosition Class

Provides access to properties and methods exposed by the object.

Syntax

HRESULT Invoke(
    DISPID dispidMember,
    REFIID riid,
    LCID lcid,
    WORD wFlags,
    DISPPARAMS *pdispparams,
    VARIANT *pvarResult,
    EXCEPINFO *pexcepinfo,
    UINT *puArgErr
);

Parameters

dispidMember
Identifier of the member. Use CMediaPosition::GetIDsOfNames to obtain the dispatch identifier.
riid
Reserved for future use. Must be IID_NULL.
lcid
Locale context in which to interpret arguments.
wFlags
Flags describing the context of the call.
pdispparams
Pointer to a DIPPARAMS structure that contains the arguments.
pvarResult
Pointer to a VARIANT that receives the result, or NULL if the caller expects no result.
pexcepinfo
Pointer to a structure that receives exception information.
puArgErr
Pointer to a variable that receives the index of the first argument that causes an error.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
DISP_E_UNKNOWNINTERFACE | The riid parameter is not IID_NULL


CMediaSample Class

CMediaSample class hierarchy

Defines a media sample that supports the IMediaSample2 interface. The media sample contains a pointer to a memory buffer, and various properties stored as protected member variables.

Declaration: Amfilter.h

Media samples are created by allocators, which are derived from the CBaseAllocator class. The CMediaSample constructor receives a pointer to an allocated buffer, along with the size of the buffer. Other properties are typically set and retrieved through IMediaSample interface methods.

The life cycle of a media sample differs from that of most COM objects:

  • The allocator holds a list of free samples. When a filter needs a new sample, it calls the allocator's IMemAllocator::GetBuffer method. The allocator retrieves a sample from its free list, increments the sample's reference count, and returns a pointer to the sample.
  • After the filter is done with the sample, it calls the IUnknown::Release method on the sample. Unlike most objects, the sample does not delete itself when its reference count reaches zero. Instead, it calls the IMemAllocator::ReleaseBuffer method on the allocator, and the allocator returns the sample to its free list.
  • The allocator does not destroy samples until the IMemAllocator::Decommit method is called.
Protected Member Variables
m_dwFlags | Sample property flags.
m_dwTypeSpecificFlags | Type-specific flags.
m_pBuffer | Pointer to the memory buffer that contains the media data.
m_lActual | Length of the valid data in the buffer, in bytes.
m_cbBuffer | Size of the buffer, in bytes.
m_pAllocator | Pointer to the allocator that created this sample.
m_pNext | Pointer to the next sample in the allocator's list of samples.
m_Start | Sample start time.
m_End | Sample end time.
m_MediaStart | Media start time.
m_MediaEnd | Media stop time.
m_pMediaType | Pointer to the media type, if the type has changed from the previous sample in the data stream.
m_dwStreamId | Stream identifier.
Public Member Variables
m_cRef | Reference count.
Public Methods
CMediaSample | Constructor method.
~CMediaSample | Destructor method. Virtual.
SetPointer | Sets the pointer to the memory buffer.
IMediaSample Methods
GetPointer | Retrieves a read/write pointer to the buffer.
GetSize | Retrieves the size of the buffer.
GetTime | Retrieves the stream times at which this sample should begin and finish.
SetTime | Sets the stream times at which this sample should start and finish.
IsSyncPoint | Determines if the beginning of the sample is a synchronization point.
SetSyncPoint | Specifies whether the beginning of this sample is a synchronization point.
IsPreroll | Determines if this sample is a preroll sample.
SetPreroll | Specifies whether this sample is a preroll sample.
GetActualDataLength | Retrieves the length of the valid data in the buffer.
SetActualDataLength | Sets the length of the valid data in the buffer.
GetMediaType | Retrieves the media type, if the media type differs from the previous sample.
SetMediaType | Sets the media type for the sample.
IsDiscontinuity | Determines if this sample represents a break in the data stream.
SetDiscontinuity | Specifies whether this sample represents a break in the data stream.
GetMediaTime | Retrieves the media times for this sample.
SetMediaTime | Sets the media times for this sample.
IMediaSample2 Methods
GetProperties | Retrieves the properties of the sample.
SetProperties | Sets the properties of the sample.

CMediaSample.m_dwFlags

CMediaSample Class

Sample property flags. Bitwise combination of flags from the AM_SAMPLE_PROPERTY_FLAGS enumerated type.

Syntax

DWORD m_dwFlags;

CMediaSample.m_dwTypeSpecificFlags

CMediaSample Class

Type-specific flags. The meaning of this member variable depends on the media type of the sample.

Syntax

DWORD m_dwTypeSpecificFlags;

CMediaSample.m_pBuffer

CMediaSample Class

Pointer to the memory buffer that contains the media data.

Syntax

LPBYTE m_pBuffer;

CMediaSample.m_lActual

CMediaSample Class

Length of the valid data in the buffer, in bytes. The value must be equal to or less than the size of the buffer (m_cbBuffer).

Syntax

LONG m_lActual;

CMediaSample.m_cbBuffer

CMediaSample Class

Size of the buffer, in bytes.

Syntax

LONG m_cbBuffer;

CMediaSample.m_pAllocator

CMediaSample Class

Pointer to the allocator that created this sample.

Syntax

CBaseAllocator *m_pAllocator;

Remarks

Although the sample keeps a pointer to the allocator, it does not hold a reference count. Instead, the allocator increments its own reference count in the IMemAllocator::GetBuffer method, and releases itself in the IMemAllocator::ReleaseBuffer method. This guarantees that the allocator will be available as long as another object is using the sample.

CMediaSample.m_pNext

CMediaSample Class

Pointer to the next sample in the allocator's list of samples.

Syntax

CMediaSample *m_pNext;

CMediaSample.m_Start

CMediaSample Class

Sample start time. This value is valid only if the m_dwFlags member variable contains the AM_SAMPLE_TIMEVALID flag.

Syntax

REFERENCE_TIME m_Start;

CMediaSample.m_End

CMediaSample Class

Sample end time. This value is valid only if the m_dwFlags member variable contains the AM_SAMPLE_STOPVALID flag.

Syntax

REFERENCE_TIME m_End;

CMediaSample.m_MediaStart

CMediaSample Class

Media start time.

Syntax

LONGLONG m_MediaStart;

CMediaSample.m_MediaEnd

CMediaSample Class

Media stop time. This value is calculated as an offset from the media start time (m_MediaStart).

Syntax

LONG m_MediaEnd;

CMediaSample.m_pMediaType

CMediaSample Class

Pointer to the media type, if the type has changed from the previous sample in the data stream. Otherwise, this member variable is NULL.

Syntax

AM_MEDIA_TYPE *m_pMediaType;

CMediaSample.m_dwStreamId

CMediaSample Class

Stream identifier. For more information, see AM_SAMPLE2_PROPERTIES.

Syntax

DWORD m_dwStreamId;

CMediaSample.m_cRef

CMediaSample Class

Reference count.

Syntax

LONG m_cRef;

CMediaSample::CMediaSample

CMediaSample Class

Constructor method.

Syntax

CMediaSample(
    TCHAR *pName,
    CBaseAllocator *pAllocator,
    HRESULT *phr,
    LPBYTE pBuffer = NULL,
    LONG length = 0
);

Parameters

pName
Pointer to a string containing the name of the media sample.
pAllocator
Pointer to the CBaseAllocator object that created this sample.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.
pBuffer
Pointer to a memory buffer allocated by the caller, of size length.
length
Length of the memory buffer.

Remarks

The base class does not modify the HRESULT value passed in the phr parameter.

CMediaSample::~CMediaSample

CMediaSample Class

Destructor method.

Syntax

~CMediaSample(void);

CMediaSample::GetActualDataLength

CMediaSample Class

Retrieves the length of the valid data in the buffer. Implements the IMediaSample::GetActualDataLength method.

Syntax

LONG GetActualDataLength(void);

Return Value

Returns the length of the valid data, in bytes.

Remarks

The m_lActual member variable specifies this property.

CMediaSample::GetMediaTime

CMediaSample Class

Retrieves the media times for this sample. Implements the IMediaSample::GetMediaTime method.

Syntax

HRESULT GetMediaTime(
    LONGLONG *pStart,
    LONGLONG *pEnd
);

Parameters

pStart
Pointer to a variable that receives the media start time.
pEnd
Pointer to a variable that receives the media stop time.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
VFW_E_MEDIA_TIME_NOT_SET | No media times were set for this sample.

Remarks

The m_MediaEnd member variable specifies an offset from m_MediaStart, but the value received by the pEnd parameter is an absolute media time, calculated as m_MediaStart + m_MediaEnd.

For information about media times, see Time and Clocks in DirectShow.

CMediaSample::GetMediaType

CMediaSample Class

Retrieves the media type, if the media type differs from the previous sample. Implements the IMediaSample::GetMediaType method.

Syntax

HRESULT GetMediaType(
    AM_MEDIA_TYPE **ppMediaType
);

Parameters

ppMediaType
Address of a variable that receives a pointer to an AM_MEDIA_TYPE structure. If the media type has not changed from the previous sample, *ppMediaType is set to NULL.

Return Value

Returns one of the HRESULT values shown in the following table.

S_FALSE | The media type has not changed from the previous sample.
S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.

Remarks

When you are done with the media type, free the memory block by calling the DeleteMediaType utility function.

The m_pMediaType member variable specifies the media type. The m_dwFlags member variable specifies whether the media type has changed.

CMediaSample::GetPointer

CMediaSample Class

Retrieves a read/write pointer to the buffer. Implements the IMediaSample::GetPointer method.

Syntax

HRESULT GetPointer(
    BYTE **ppBuffer
);

Parameters

ppBuffer
Address of a variable that receives a pointer to the buffer.

Return Value

Returns S_OK.

CMediaSample::GetProperties

CMediaSample Class

Retrieves the properties of the sample. Implements the IMediaSample2::GetProperties method.

Syntax

HRESULT GetProperties(
    DWORD cbProperties,
    BYTE *pbProperties
);

Parameters

cbProperties
Length of property data to retrieve, in bytes.
pbProperties
Pointer to a buffer of size cbProperties.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
E_POINTER | NULL pointer argument.

CMediaSample::GetSize

CMediaSample Class

Retrieves the size of the buffer. Implements the IMediaSample::GetSize method.

Syntax

LONG GetSize(void);

Return Value

Returns the size of the buffer, in bytes.

CMediaSample::GetTime

CMediaSample Class

Retrieves the stream times at which this sample should begin and finish. Implements the IMediaSample::GetTime method.

Syntax

HRESULT GetTime(
    REFERENCE_TIME *pTimeStart,
    REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart
Pointer to a variable that receives the beginning stream time, in 100-nanosecond units.
pTimeEnd
Pointer to a variable that receives the ending stream time, in 100-nanosecond units. If the sample has no stop time, the value is set to the start time plus one.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
VFW_S_NO_STOP_TIME | Sample has a valid start time, but no stop time.
VFW_E_SAMPLE_TIME_NOT_SET | Sample does not have valid time stamps.

Remarks

The m_Start and m_End member variables specify the time stamps. The m_dwFlags member variable specifies whether the time stamps are valid.

For information about time stamps, see Time and Clocks in DirectShow.

CMediaSample::IsDiscontinuity

CMediaSample Class

Determines if this sample represents a break in the data stream. Implements the IMediaSample::IsDiscontinuity method.

Syntax

HRESULT IsDiscontinuity(void);

Return Value

Returns S_OK if the sample is a break in the data stream, and S_FALSE otherwise.

Remarks

The m_dwFlags member variable specifies this property.

CMediaSample::IsPreroll

CMediaSample Class

Determines if this sample is a preroll sample. A preroll sample should not be displayed. Implements the IMediaSample::IsPreroll method.

Syntax

HRESULT IsPreroll(void);

Return Value

Returns S_OK if the sample is a preroll sample, and S_FALSE otherwise.

Remarks

The m_dwFlags member variable specifies this property.

CMediaSample::IsSyncPoint

CMediaSample Class

Determines if the beginning of the sample is a synchronization point. Implements the IMediaSample::IsSyncPoint method.

Syntax

HRESULT IsSyncPoint(void);

Return Value

Returns S_OK if the sample is a synchronization point, or S_FALSE otherwise.

Remarks

The m_dwFlags member variable specifies this property.

CMediaSample::SetActualDataLength

CMediaSample Class

Sets the length of the valid data in the buffer. Implements the IMediaSample::SetActualDataLength method.

Syntax

HRESULT SetActualDataLength(
    long lLen
);

Parameters

lLen
Length of the valid data, in bytes.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
VFW_E_BUFFER_OVERFLOW | lLen is larger than the allocated buffer size.

Remarks

This method sets the m_lActual member variable.

CMediaSample::SetDiscontinuity

CMediaSample Class

Specifies whether this sample represents a break in the data stream. Implements the IMediaSample::SetDiscontinuity method.

Syntax

HRESULT SetDiscontinuity(
    BOOL bDiscont
);

Parameters

bDiscont
Boolean value that specifies whether this sample is a discontinuity. If TRUE, the media sample is discontinuous with the previous sample.

Return Value

Returns S_OK.

Remarks

This method updates the m_dwFlags member variable, which specifies the discontinuity property.

CMediaSample::SetMediaTime

CMediaSample Class

Sets the media times for this sample. Implements the IMediaSample::SetMediaTime method.

Syntax

HRESULT SetMediaTime(
    LONGLONG *pStart,
    LONGLONG *pEnd
);

Parameters

pStart
Pointer to the media start time, or NULL.
pEnd
Pointer to the media stop time, or NULL.

Return Value

Returns S_OK.

Remarks

The media stop time must be greater than the media start time. Use NULL to invalidate the media times.

The pEnd parameter specifies an absolute media time, but the m_MediaEnd member variable is calculated as an offset from pStart. In other words, m_MediaEnd = *pTimeEnd – *pTimeStart.

For information about media times, see Time and Clocks in DirectShow.

CMediaSample::SetMediaType

CMediaSample Class

Sets the media type for the sample. Implements the IMediaSample::SetMediaType method.

Syntax

HRESULT SetMediaType(
    AM_MEDIA_TYPE *pMediaType
);

Parameters

pMediaType
Pointer to an AM_MEDIA_TYPE structure.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success
E_OUTOFMEMORY | Insufficient memory

Remarks

This method sets the m_pMediaType member variable, which specifies the media type, and the m_dwFlags member variable, which specifies whether the media type has changed.

This method makes a copy of the AM_MEDIA_TYPE structure.

CMediaSample::SetPointer

CMediaSample Class

Sets the pointer to the memory buffer.

Syntax

HRESULT SetPointer(
    BYTE *ptr,
    LONG cBytes
);

Parameters

ptr
Pointer to a memory buffer allocated by the caller, of size cBytes.
cBytes
Length of the buffer, in bytes.

Return Value

Returns S_OK.

Remarks

This method enables the allocator to set a new pointer for the sample.

This method is not available through the IMediaSample interface. The object that creates the sample can access this method (through CMediaSample), but other objects cannot.

CMediaSample::SetPreroll

CMediaSample Class

Specifies whether this sample is a preroll sample. A preroll sample should not be displayed. Implements the IMediaSample::SetPreroll method.

Syntax

HRESULT SetPreroll(
    BOOL bIsPreroll
);

Parameters

bIsPreroll
Boolean value that specifies whether this is a preroll sample. If TRUE, this is a preroll sample.

Return Value

Returns S_OK.

Remarks

This method updates the m_dwFlags member variable, which specifies the preroll property.

CMediaSample::SetProperties

CMediaSample Class

Sets the properties of the sample. This method implements the IMediaSample2::SetProperties method.

Syntax

HRESULT SetProperties(
    DWORD cbProperties,
    const BYTE *pbProperties
);

Parameters

cbProperties
Length of property data to set, in bytes.
pbProperties
Pointer to a buffer of size cbProperties.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success
E_INVALIDARG | Invalid argument
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

CMediaSample::SetSyncPoint

CMediaSample Class

Specifies whether the beginning of this sample is a synchronization point. This method implements the IMediaSample::SetSyncPoint method.

Syntax

HRESULT SetSyncPoint(
    BOOL bIsSyncPoint
);

Parameters

bIsSyncPoint
Boolean value that specifies whether this is a synchronization point. If TRUE, this is a synchronization point.

Return Value

Returns S_OK.

Remarks

This method updates the m_dwFlags member variable, which specifies the synchronization-point property.

CMediaSample::SetTime

CMediaSample Class

Sets the stream times when this sample should begin and finish. Implements the IMediaSample::SetTime method.

Syntax

HRESULT SetTime(
    REFERENCE_TIME *pTimeStart,
    REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart
Pointer to the stream time at which the sample begins, in 100-nanosecond units, or NULL.
pTimeEnd
Pointer to the stream time at which the sample ends, in 100-nanosecond units, or NULL.

Return Value

Returns S_OK.

Remarks

This method sets the m_Start and m_End member variables, which specify the time stamps. It also updates the m_dwFlags member variable, which specifies whether the time stamps are valid.

For information about time stamps, see Time and Clocks in DirectShow.


CMediaType Class

CMediaType class hierarchy

Class for managing media types. This class inherits the AM_MEDIA_TYPE structure. It can be cast to a variable of type AM_MEDIA_TYPE.

Declaration: Mtype.h

Public Methods
CMediaType | Constructor method.
~CMediaType | Destructor method.
IsValid | Determines whether a major type has been assigned to this object.
Type | Retrieves the major type.
SetType | Specifies the major type.
Subtype | Retrieves the subtype.
SetSubtype | Specifies the subtype.
IsFixedSize | Determines if the samples have a fixed size or a variable size.
IsTemporalCompressed | Determines if the stream uses temporal compression.
GetSampleSize | Retrieves the sample size.
SetSampleSize | Specifies a fixed sample size, or specifies that samples have a variable size.
SetVariableSize | Specifies that samples do not have a fixed size.
SetTemporalCompression | Specifies whether samples are compressed using temporal compression.
Format | Retrieves a pointer to the format block.
FormatLength | Retrieves the length of the format block.
SetFormatType | Specifies the format type.
FormatType | Retrieves the format type.
SetFormat | Specifies the format block.
ResetFormatBuffer | Deletes the format block.
AllocFormatBuffer | Allocates memory for the format block.
ReallocFormatBuffer | Reallocates the format block to a new size.
InitMediaType | Initializes the media type.
MatchesPartial | Determines if this media type matches a partially specified media type.
IsPartiallySpecified | Determines if the media type is partially defined.
Operators
operator = | Overloads the assignment operator to copy a media type.
operator == | Tests for equality between CMediaType objects.
operator != | Tests for inequality between CMediaType objects.

CMediaType::AllocFormatBuffer

CMediaType Class

Allocates memory for the format block.

Syntax

BYTE* AllocFormatBuffer(
    ULONG length
);

Parameters

length
Size required for the format block, in bytes.

Return Value

Returns a pointer to the new block if successful. Otherwise, returns NULL.

Remarks

If the method successfully allocates a new format block, it frees the existing format block. If the allocation fails, the method leaves the existing format block.

CMediaType::CMediaType

CMediaType Class

Constructor method.

Syntax

CMediaType(void);

CMediaType(
    const GUID *majortype
);

CMediaType(
    const AM_MEDIA_TYPE& mtype
);

CMediaType(
    const CMediaType& cmtype
);

Parameters

majortype
Pointer to a major type GUID.
mtype
Reference to an AM_MEDIA_TYPE structure.
cmtype
Reference to a CMediaType object.

Remarks

The constructor calls the InitMediaType function to initialize the media type. If the majortype parameter is specified, the constructor initializes the major type GUID. If the mtype or cmtype parameter is specified, the constructor copies the media type information (including the format block) into the new object.

CMediaType::~CMediaType

CMediaType Class

Destructor method.

Syntax

~CMediaType(void);

Remarks

The destructor calls the FreeMediaType function on itself.

CMediaType::Format

CMediaType Class

Retrieves a pointer to the format block.

Syntax

BYTE* Format(void) const;

Return Value

Returns the pbFormat member.

CMediaType::FormatLength

CMediaType Class

Retrieves the length of the format block.

Syntax

ULONG FormatLength(void) const;

Return Value

Returns the cbFormat member.

CMediaType::FormatType

CMediaType Class

Retrieves the format type.

Syntax

const GUID *FormatType(void) const;

Return Value

Returns a pointer to the formattype member.

CMediaType::GetSampleSize

CMediaType Class

Retrieves the sample size.

Syntax

ULONG GetSampleSize(void) const;

Return Value

If the sample size is fixed, returns the sample size in bytes. Otherwise, returns zero.

CMediaType::InitMediaType

CMediaType Class

Initializes the media type.

Syntax

void InitMediaType(void);

Remarks

This method zeroes the object's memory, sets the fixed-sample-size property to TRUE, and sets the sample size to 1.

CMediaType::IsFixedSize

CMediaType Class

Determines if the samples have a fixed size or a variable size.

Syntax

BOOL IsFixedSize(void) const;

Return Value

Returns the value of the bFixedSizeSamples member.

CMediaType::IsPartiallySpecified

CMediaType Class

Determines if the media type is partially defined. A media type is partial if the major type, subtype, or format type is GUID_NULL.

Syntax

BOOL IsPartiallySpecified(void) const;

Return Value

Returns TRUE if the media type is partially specified. Otherwise, returns FALSE.

Remarks

The IPin::Connect method can accept partial media types.

The implementation does not actually test the subtype. If there is a specified format type, the media type is not considered partial, even if the subtype is GUID_NULL.

CMediaType::IsTemporalCompressed

CMediaType Class

Determines if the stream uses temporal compression.

Syntax

BOOL IsTemporalCompressed(void) const;

Return Value

Returns the value of the bTemporalCompression member.

CMediaType::IsValid

CMediaType Class

Determines whether a major type has been assigned to this object.

Syntax

BOOL IsValid(void) const;

Return Value

Returns TRUE if a major type has been assigned to this object. Otherwise, returns FALSE.

Remarks

By default, CMediaType objects are initialized with a major type of GUID_NULL. Call this method to determine whether the object has been correctly initialized.

CMediaType::MatchesPartial

CMediaType Class

Determines if this media type matches a partially specified media type.

Syntax

BOOL MatchesPartial(
    const CMediaType *ppartial
    ) const;

Parameters

ppartial
Pointer to the media type to match.

Return Value

Returns TRUE if the media types match. Otherwise, returns FALSE.

Remarks

The media type specified by ppartial can have a value of GUID_NULL for the major type, subtype, or format type. Any members with GUID_NULL values are not tested. (In effect, GUID_NULL acts as a wildcard.) Members with values other than GUID_NULL must match for the media type to match.

CMediaType::ReallocFormatBuffer

CMediaType Class

Reallocates the format block to a new size.

Syntax

BYTE* ReallocFormatBuffer(
    ULONG length
);

Parameters

length
New size required for the format block, in bytes. Must be greater than zero.

Return Value

Returns a pointer to the new block if successful. Otherwise, returns either a pointer to the old format block, or NULL.

Remarks

This method allocates a new format block. It copies as much of the existing format block as possible into the new format block. If the new block is smaller than the existing block, the existing format block is truncated. If the new block is larger, the contents of the additional space are undefined. They are not explicitly set to zero.

CMediaType::ResetFormatBuffer

CMediaType Class

Deletes the format block.

Syntax

void ResetFormatBuffer(void);

CMediaType::SetFormat

CMediaType Class

Specifies the format block.

Syntax

BOOL SetFormat(
    BYTE *pFormat,
    ULONG length
);

Parameters

pFormat
Pointer to a block of memory that contains the format block.
length
Length of the format block, in bytes.

Return Value

Returns TRUE if successful, or FALSE if an error occurred.

Remarks

This method copies the format block specified by pFormat. To set the format type, call the SetFormatType method.

CMediaType::SetFormatType

CMediaType Class

Specifies the format type.

Syntax

void SetFormatType(
    const GUID *pformattype
);

Parameters

pformattype
Pointer to a GUID that specifies the format type.

Remarks

This method sets the formattype member. The format type defines the layout of the format block. For example, if the format type is FORMAT_VideoInfo, the format block should contain a VIDEOINFOHEADER structure. To set the format block, call the SetFormat method. The caller is responsible for making sure that the format block matches the format type.

CMediaType::SetSampleSize

CMediaType Class

Specifies a fixed sample size, or specifies that samples have a variable size.

Syntax

void SetSampleSize(
    ULONG sz
);

Parameters

sz
Sample size, in bytes, or zero.

Remarks

If value of sz is zero, the media type uses variable sample sizes. Otherwise, the sample size is fixed at sz bytes.

CMediaType::SetSubtype

CMediaType Class

Specifies the subtype.

Syntax

void SetSubtype(
    const GUID *psubtype
);

Parameters

psubtype
Pointer to a GUID that specifies the subtype.

CMediaType::SetTemporalCompression

CMediaType Class

Specifies whether samples are compressed using temporal (interframe) compression.

Syntax

void SetTemporalCompression(
    BOOL bCompressed
);

Parameters

bCompressed
Boolean value that specifies whether the stream uses temporal compression. If the stream uses temporal compression, set the value to TRUE.

Remarks

This method sets the bTemporalCompression member.

CMediaType::SetType

CMediaType Class

Specifies the major type.

Syntax

void SetType(
    const GUID *ptype
);

Parameters

ptype
Pointer to a GUID that specifies the major type.

CMediaType::SetVariableSize

CMediaType Class

Specifies that samples do not have a fixed size.

Syntax

void SetVariableSize(void);

Remarks

This method sets the bFixedSizeSamples member to FALSE. Subsequent calls to the CMediaType::GetSampleSize method return zero.

CMediaType::Subtype

CMediaType Class

Retrieves the subtype.

Syntax

const GUID *Type(void) const;

Return Value

Returns a pointer to the subtype member.

CMediaType::Type

CMediaType Class

Retrieves the major type.

Syntax

const GUID *Type(void) const;

Return Value

Returns a pointer to the majortype member.

CMediaType::operator =

CMediaType Class

Overloads the assignment operator to copy a media type.

Syntax

CMediaType& operator=(
    const CMediaType& cmtype
);

CMediaType& operator=(
    const AM_MEDIA_TYPE& mtype
);

Parameters

cmtype
Reference to a CMediaType object.
mtype
Reference to an AM_MEDIA_TYPE structure.

Return Value

Returns a reference to the object.

CMediaType::operator ==

CMediaType Class

Tests for equality between CMediaType objects.

Syntax

inline BOOL operator==(
    const CMediaType& rt
) const;

Parameters

rt
Reference to the CMediaType object to compare.

Return Value

Returns TRUE if rt is equal to this object. Otherwise, returns FALSE.

CMediaType::operator !=

CMediaType Class

Tests for inequality between CMediaType objects.

Syntax

BOOL operator!=(
    const CMediaType& rt
) const;

Parameters

rt
Reference to the CMediaType object to compare.

Return Value

Returns TRUE if rt is not equal to this object. Otherwise, returns FALSE.


CMemAllocator Class

CMemAllocator class hierarchy

Implements an allocator that supports the IMemAllocator interface.

Declaration: Amfilter.h

This class derives from CBaseAllocator. For more information about allocators, refer to the documentation for CBaseAllocator.

Protected Member Variables
m_pBuffer | Pointer to the memory block that contains the buffers.
Protected Methods
Free | Called during a decommit operation.
ReallyFree | Releases the memory for the buffers.
Alloc | Allocates memory for the buffers.
Public Methods
CMemAllocator | Constructor method.
~CMemAllocator | Destructor method.
CreateInstance | Creates a new instance of the CMemAllocator class.
IMemAllocator Methods
SetProperties | Specifies the number of buffers to allocate and the size of each buffer.

CMemAllocator.m_pBuffer

CMemAllocator Class

Pointer to the memory block that contains the buffers.

Syntax

LPBYTE m_pBuffer;

Remarks

Sample buffers are calculated as offsets from this pointer.

CMemAllocator::Alloc

CMemAllocator Class

Allocates memory for the buffers.

Syntax

HRESULT Alloc(void);

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_SIZENOTSET | Buffer requirements were not set.

Remarks

This method is called by the CBaseAllocator::Commit method. It allocates a contiguous block of memory sufficient for the buffer requirements given in the SetProperties method.

CMemAllocator::CMemAllocator

CMemAllocator Class

Constructor method.

Syntax

CMemAllocator(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
);

Parameters

pName
Pointer to a string containing the name of the allocator.
pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.

CMemAllocator::~CMemAllocator

CMemAllocator Class

Destructor method.

Syntax

~CMemAllocator(void);

Syntax

This method overrides the base-class destructor to call Decommit and ReallyFree.

CMemAllocator::CreateInstance

CMemAllocator Class

Creates a new instance of the CMemAllocator class.

Syntax

static CUnknown *CreateInstance(
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method.

Return Value

Returns a pointer to a new CMemAllocator object, typed as a CUnknown object.

CMemAllocator::Free

CMemAllocator Class

Called during a decommit operation.

Syntax

void Free(void);

Remarks

This method overrides the pure virtual method CBaseAllocator::Free, which is called during a decommit operation. In the CMemAllocator class, this method does not do anything. Memory is freed in the destructor method, by calling the ReallyFree method.

CMemAllocator::ReallyFree

CMemAllocator Class

Releases the memory for the buffers.

Syntax

void ReallyFree (void);

Remarks

The CMemAllocator class holds memory until the object is deleted.

CMemAllocator::SetProperties

CMemAllocator Class

Specifies the number of buffers to allocate and the size of each buffer.

Syntax

HRESULT SetProperties(
    ALLOCATOR_PROPERTIES *pRequest,
    ALLOCATOR_PROPERTIES *pActual
);

Parameters

pRequest
Pointer to an ALLOCATOR_PROPERTIES structure that contains the buffer requirements.
pActual
Pointer to an ALLOCATOR_PROPERTIES structure that receives the actual buffer properties.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_ALREADY_COMMITTED | Cannot change allocated memory while the filter is active.
VFW_E_BADALIGN | An invalid alignment was specified.
VFW_E_BUFFERS_OUTSTANDING | One or more buffers are still active.

Remarks

This method overrides the CBaseAllocator::SetProperties method.

The buffer alignment, specified by the cbAlign member of the ALLOCATOR_PROPERTIES structure, must be an even power of two.


CMsg Class

The CMsgThread class provides support for a worker thread to which requests can be posted asynchronously instead of sent directly. The CAMThread class provides a worker thread to which single requests can be sent. Only one client can make a request at a time, and the client blocks until the worker thread has completed the request. By contrast, the CMsgThread class provides a worker thread to which any number of requests can be posted. The requests (in the form of a CMsg object) are queued and executed in order, asynchronously. No reply or return value is received.

Data Members

dwFlags | Flag parameter to the request code.
lpParam | Data required by the worker thread as parameter or return values. This data should not be stack-based, as it will be referenced some time after completing the queuing operation.
pEvent | Event object that a worker thread can signal to indicate the completion of the operation.
uMsg | Request code that is defined by the client of the thread class and understood by the overridden worker thread function.

Member Functions

CMsg Constructs a CMsg object.

CMsg::CMsg

CMsg Class

Constructs a CMsg object.

Syntax

CMsg(

  UINT u,

  DWORD dw,

  LPVOID lp,

  CAMEvent *pEvent

  );

Parameters

u
Request code, defined by the client of the thread class and understood by the overridden worker thread function.
dw
Flag parameter to the request code.
lp
Pointer to data required by the worker thread as parameter or return values. This data should not be stack-based, as it will be referenced some time after completing the queuing operation.
pEvent
Pointer to the event object that a worker thread can signal to indicate the completion of the operation.

Return Value

No return value.

Remarks

This member function contains a request for a CMsgThread worker thread to act on. All the parameters are passed to the worker thread function as parameters when this message gets processed. The meanings of the parameters are defined by the client function that calls the worker thread and the derived class that supplies the worker thread's execution function.


CMsgThread Class

The CMsgThread class is a worker thread class that queues requests to the queuing thread for completion asynchronously. To use this class, derive your class from it and override the CMsgThread::ThreadMessageProc member function. The ThreadMessageProc member function carries out each request. Your client functions and the ThreadMessageProc member function must share a common definition of the parameters in the CMsg object.

A negotiated mechanism tells the worker thread to exit. Typically, this will be one value of the CMsg class's uMsg message code.

It is a good idea to send this message from the destructor of your derived class, and call the CMsgThread::WaitForThreadExit member function before completing the destruction of the derived class.

Protected Data Members

m_hSem | Indicates a handle used for signaling.
m_Lock | Protects access to lists.
m_lWaiting | Indicates waiting for a free thread.
m_ThreadQueue | Overrides the CMsgThread::GetThreadMsg member function and blocks on things other than this queue.

Member Functions

CMsgThread | Constructs a CMsgThread object.
CreateThread | Creates a thread.
GetThreadHandle | Retrieves the thread handle.
GetThreadID | Retrieves the identifier of the thread.
GetThreadPriority | Retrieves the current thread priority.
PutThreadMsg | Queues a request for execution by the worker thread.
ResumeThread | Continues the operation of the worker thread.
SetThreadPriority | Sets the priority of the thread to a new value.
SuspendThread | Suspends the operation of a running thread.
WaitForThreadExit | Blocks until the thread has exited after a call to the CMsgThread::SuspendThread member function.

Overridable Member Functions

GetThreadMsg | Retrieves a queued CMsg object containing a request.
OnThreadInit | Provides initialization on a thread.
ThreadMessageProc | Processes requests. This is a pure virtual member function.

CMsgThread::CMsgThread

CMsgThread Class

Constructs a CMsgThread object.

Syntax

CMsgThread(void);

Return Value

No return value.

Remarks

Constructing a message thread object does not automatically create the thread. You must call the CMsgThread::CreateThread member function to create the thread.

CMsgThread::CreateThread

CMsgThread Class

Creates a thread.

Syntax

BOOL CreateThread(void);

Return Value

Returns one of the following values.
TRUE | Thread was successfully created.
FALSE | Thread was not successfully created.

Remarks

The thread will loop, blocking until a request is queued (through the CMsgThread::PutThreadMsg member function) and then calling the CMsgThread::ThreadMessageProc member function with each message.

CMsgThread::GetThreadHandle

CMsgThread Class

Retrieves the handle to the thread in the CMsgThread object.

Syntax

HANDLE GetThreadHandle(void);

Return Value

Returns the thread handle.

Remarks

The thread handle can be passed to Microsoft® Win32® application programming interface (API) functions, such as WaitForMultipleObjects. The thread handle is signaled when the thread has exited.

CMsgThread::GetThreadID

CMsgThread Class

Retrieves the thread's identifier.

Syntax

DWORD GetThreadID(void);

Return Value

Returns the m_ThreadId private data member.

Remarks

This function returns the Microsoft Win32 identifier for the worker thread. You can call this member function on either the worker thread or a client thread.

CMsgThread::GetThreadMsg

CMsgThread Class

Retrieves a queued CMsg object containing a request.

Syntax

void virtual GetThreadMsg(
    CMsg *msg
    );

Parameters

msg
Pointer to an allocated CMsg object.

Remarks

This member function is called from the worker thread's private ThreadProc function to retrieve the next member function. The msg parameter should point to an allocated CMsg object that will be filled with the parameters to the next request in the queue. If there are no queued requests, this member function blocks until the next request is queued (by a call to the CMsgThread::PutThreadMsg member function).

CMsgThread::GetThreadPriority

CMsgThread Class

Uses the Microsoft Win32 GetThreadPriority function to retrieve the priority of the current worker thread.

Syntax

int GetThreadPriority(void);

Return Value

Returns the thread priority as an integer.

CMsgThread::OnThreadInit

CMsgThread Class

Provides initialization on a thread.

Syntax

virtual void OnThreadInit(void);

Return Value

No return value.

Remarks

Override this function if you want to do your own specific initialization on thread startup.

CMsgThread::PutThreadMsg

CMsgThread Class

Queues a request for execution by the worker thread.

Syntax

void PutThreadMsg(
    UINT uMsg,
    DWORD dwMsgFlags,
    LPVOID lpMsgParam,
    CAMEvent *pEvent = NULL
    );

Parameters

uMsg
Request code.
dwMsgFlags
Optional flags parameter.
lpMsgParam
Optional pointer to a data block containing additional parameters or return values. Must be statically or heap-allocated and not automatic.
pEvent
Optional pointer to an event object to be signaled upon completion.

Return Value

No return value.

Remarks

This member function queues a request for execution by the worker thread. The parameters of this member function will be queued (in a CMsg object) and passed to the CMsgThread::ThreadMessageProc member function of the worker thread. This member function returns immediately after queuing the request and does not wait for the thread to fulfill the request. The CMsgThread::ThreadMessageProc member function of the derived class defines the four parameters.

This member function uses a multithread safe list, so multiple calls to this member function from different threads can be made safely.

CMsgThread::ResumeThread

CMsgThread Class

Uses the Microsoft Win32 ResumeThread function to continue the operation of the worker thread after a previous call to the CMsgThread::SuspendThread member function.

Syntax

DWORD ResumeThread(void);

Return Value

If the member function succeeds, the return value is the previous suspend count of the thread. If the member function fails, the return value is 0xFFFFFFFF. To obtain extended error information, call the Microsoft Win32 GetLastError function.

CMsgThread::SetThreadPriority

CMsgThread Class

Uses the Microsoft Win32 SetThreadPriority function to set the priority of the thread to a new value.

Syntax

BOOL SetThreadPriority(
    int nPriority
    );

Parameters

nPriority
Priority of the thread.

Return Value

Returns one of the following values.
TRUE | Priority was successfully set.
FALSE | Priority was not set.

Remarks

The client and the worker thread can call this member function.

CMsgThread::SuspendThread

CMsgThread Class

Uses the Microsoft Win32 SuspendThread function to suspend the operation of a running thread.

Syntax

DWORD SuspendThread(void);

Return Value

If the member function succeeds, the return value is the previous suspend count of the thread. If the member function fails, the return value is 0xFFFFFFFF. To obtain extended error information, call the Microsoft Win32 GetLastError function.

Remarks

The client thread calls this member function to suspend the operation of the worker thread. The worker thread remains suspended and will not execute until an additional call to the CMsgThread::ResumeThread member function is made.

CMsgThread::ThreadMessageProc

CMsgThread Class

Processes requests. This is a pure virtual member function.

Syntax

virtual LRESULT ThreadMessageProc(
    UINT uMsg,
    DWORD dwFlags,
    LPVOID lpParam,
    CAMEvent *pEvent
    );

Parameters

uMsg
Request code.
dwFlags
Optional flag parameter to request.
lpParam
Optional pointer to extra data or a return data block.
pEvent
Optional pointer to an event object.

Return Value

Any nonzero return causes the thread to exit. Returns zero unless an exit request has been processed recently.

Remarks

This pure virtual function must be overridden in your derived class. It will be called once for each request queued by a call to the CMsgThread::PutThreadMsg member function.

The member function defines the four parameters. Typically, use the uMsg parameter to indicate the request, and the other three parameters will be optional additional parameters. The calling application can supply a pointer to a CAMEvent object in the pEvent parameter if your application requires it. You must set this event after processing the event by using an expression such as:

pEvent->SetEvent

One request code must be set aside to tell the worker thread to exit. Upon receiving this request, return 1 from this member function. Return 0 if you do not want the worker thread to exit.

CMsgThread::WaitForThreadExit

CMsgThread Class

Blocks until the thread exits.

Syntax

BOOL WaitForThreadExit(
    LPDWORD lpdwExitCode
    );

Parameters

lpdwExitCode
Pointer to the exit code returned by the thread.

Return Value

Returns either TRUE or FALSE, the meaning of which is determined by the class supplying the overridden CMsgThread::ThreadMessageProc member function and the calling member function.

Remarks

Ensure that the worker thread has exited completely before completing the destruction of your derived class; otherwise, the thread might still execute after your dynamic-link library (DLL) has been unloaded from the address space of the process. Even if the only instruction left to exit is a single-return instruction, this would cause an exception. The only reliable way to ensure that the thread has exited is to signal the thread to exit (using a privately negotiated CMsg object sent to the CMsgThread::PutThreadMsg member function) and then call this member function. You should do this in the destructor for your derived class.


COARefTime Class

COARefTime class hierarchy

Converts reference times between seconds and 100-nanosecond units.

Declaration: Ctlutil.h

This class converts between reference times that are compatible with Automation and reference times that are compatible with C/C++. Automation-compatible interfaces use double values to represent time in seconds. Other interfaces use 64-bit LONGLONG values to represent time in 100-nanosecond units. The following types are defined for these values:

typedef LONGLONG  REFERENCE_TIME;
typedef double    REFTIME;

Filters can use the COARefTime class to convert between the two formats. This class is derived from the CRefTime class.

Member Functions

Public Methods
COARefTime | Constructor method.
Operators
double | Converts the reference time to a double value.
REFERENCE_TIME | Retrieves the reference time as a REFERENCE_TIME value.
Operator = | Assigns a new reference time.
Operator == | Tests for equality between two reference times.
Operator != | Tests for inequality between two reference times.
Operator < | Tests if one reference time is less than another.
Operator > | Tests if one reference time is greater than another.
Operator <= | Tests if one reference time is less than or equal to another.
Operator >= | Tests if one reference time is greater than or equal to another.
Operator + | Adds two reference times.
Operator – | Subtracts one reference time from another.
Operator += | Adds two reference times, and sets this object to the result.
Operator –= | Subtracts one reference time from another, and sets this object to the result.
Operator * | Multiplies a reference time.
Operator / | Divides a reference time.

COARefTime::COARefTime

COARefTime Class

Constructor method.

Syntax

COARefTime(void);

COARefTime(
    CRefTime crt
);

COARefTime(
    REFERENCE_TIME t
);

COARefTime(
    double d
);

Parameters

crt
CRefTime object that specifies the reference time.
t
REFERENCE_TIME value that specifies the reference time in 100-nanosecond units.
d
double value that specifies the reference time in seconds.

Remarks

The reference time defaults to zero.

COARefTime::double

COARefTime Class

Converts the reference time to a double value.

Syntax

operator double();

Return Value

Returns the reference time in seconds.

COARefTime::REFERENCE_TIME

COARefTime Class

Retrieves the reference time as a REFERENCE_TIME value.

Syntax

operator REFERENCE_TIME();

Return Value

Returns the reference time in 100-nanosecond units.

COARefTime::Operator =

COARefTime Class

Assigns a new reference time.

Syntax

COARefTime& operator=(
    const double& rd
);

COARefTime& operator=(
    const REFERENCE_TIME& rt
);

Parameters

rd
Reference to a double value that specifies the new reference time in seconds.
rt
Reference to a REFERENCE_TIME value that specifies the new reference time in 100-nanosecond units.

Return Value

Returns a reference to the object.

COARefTime::Operator ==

COARefTime Class

Tests for equality between two reference times.

Syntax

BOOL operator==(
    const COARefTime& rt
);

Parameters

rt
Reference to the COARefTime object to compare.

Return Value

Returns TRUE if the two objects are equal. Otherwise, returns FALSE.

COARefTime::Operator !=

COARefTime Class

Tests for inequality between two reference times.

Syntax

BOOL operator!=(
    const COARefTime& rt
);

Parameters

rt
Reference to the COARefTime object to compare.

Return Value

Returns TRUE if the two objects are not equal. Otherwise, returns FALSE.

COARefTime::Operator <

COARefTime Class

Tests if one reference time is less than another.

Syntax

BOOL operator < (
    const COARefTime& rt
);

Parameters

rt
Reference to the COARefTime object to compare.

Return Value

Returns TRUE if this object is strictly less than rt. Otherwise, returns FALSE.

COARefTime::Operator >

COARefTime Class

Tests if one reference time is greater than another.

Syntax

BOOL operator > (
    const COARefTime& rt
);

Parameters

rt
Reference to the COARefTime object to compare.

Return Value

Returns TRUE if this object is strictly greater than rt. Otherwise, returns FALSE.

COARefTime::Operator >=

COARefTime Class

Tests if one reference time is less than or equal to another.

Syntax

BOOL operator >= (
    const COARefTime& rt
);

Parameters

rt
Reference to the COARefTime object to compare.

Return Value

Returns TRUE if this object is less than or equal to rt. Otherwise, returns FALSE.

COARefTime::Operator <=

COARefTime Class

Tests if one reference time is greater than or equal to another.

Syntax

BOOL operator <= (
    const COARefTime& rt
);

Parameters

rt
Reference to the COARefTime object to compare.

Return Value

Returns TRUE if this object is greater than or equal to rt. Otherwise, returns FALSE.

COARefTime::Operator +

COARefTime Class

Adds two reference times.

Syntax

COARefTime operator+(
    const COARefTime& rt
);

Parameters

rt
Reference to the COARefTime object to add.

Return Value

Returns a new COARefTime object equal to the sum of the reference times.

COARefTime::Operator –

COARefTime Class

Subtracts one reference time from another.

Syntax

COARefTime operator-(
    const COARefTime& rt
);

Parameters

rt
Reference to the COARefTime object to subtract.

Return Value

Returns a new COARefTime object equal to the difference of the reference times.

COARefTime::Operator +=

COARefTime Class

Adds two reference times, and sets this object to the result.

Syntax

COARefTime& operator+=(
    const COARefTime& rt
);

Parameters

rt
Reference to the COARefTime object to add.

Return Value

Returns a reference to the object.

COARefTime::Operator –=

COARefTime Class

Subtracts one reference time from another, and sets this object to the result.

Syntax

COARefTime& operator-=(
    const COARefTime& rt
);

Parameters

rt
Reference to the COARefTime object to subtract.

Return Value

Returns a reference to the object.

COARefTime::Operator *

COARefTime Class

Multiplies a reference time.

Syntax

COARefTime operator*(
    LONG l
);

Parameters

l
Multiplier.

Return Value

Returns a new COARefTime object equal to the product of this object and l.

COARefTime::Operator /

COARefTime Class

Divides a reference time.

Syntax

COARefTime operator/(
    LONG l
    );

Parameters

l
Divisor.

Return Value

Returns a new COARefTime object equal to the quotient of this object and l.


COutputQueue Class

COutputQueue class hierarchy

Implements a queue to deliver media samples.

Declaration: Outputq.h

This class enables an output pin to deliver samples asynchronously. Samples are placed on a queue, and a worker thread delivers them to the input pin. The queue can also hold control messages that indicate a new segment, an end-of-stream notification, or a flush operation.

To use this class, create a COutputQueue object for every output pin on the filter. In the constructor method, specify the input pin connected to that output pin. Using this class, the output pin does not call methods directly on the input pin. Instead, it calls corresponding methods in COutputQueue, as shown in the following table.

Pin Method | COutputQueue Method
IPin::BeginFlush | BeginFlush
IPin::EndFlush | EndFlush
IPin::EndOfStream | EOS
IPin::NewSegment | NewSegment
MemInputPin::Receive | Receive
MemInputPin::ReceiveMultiple | ReceiveMultiple

Optionally, you can configure the COutputQueue object to deliver samples synchronously, without a worker thread. The object can also decide at run time whether to use a worker thread, based on the characteristics of the input pin. For more information, see COutputQueue::COutputQueue.

Protected Member Variables
m_pPin | Pointer to the input pin's IPin interface.
m_pInputPin | Pointer to the input pin's IMemInputPin interface.
m_bBatchExact | Flag that specifies whether the object delivers samples in exact batches.
m_lBatchSize | Batch size.
m_List | Media sample queue.
m_hSem | Handle to a semaphore, used by the thread to wait for samples.
m_evFlushComplete | Event that signals when a flush operation has finished.
m_hThread | Handle to the worker thread.
m_ppSamples | Array of samples of size m_lBatchSize.
m_nBatched | Number of samples currently batched and awaiting processing.
m_lWaiting | Flag that has a nonzero value when the thread is waiting for a sample.
m_bFlushing | Flag that specifies whether the object is performing a flush operation.
m_bTerminate | Flag that specifies whether the thread should terminate.
m_bSendAnyway | Flag to override batch processing.
m_hr | HRESULT value that indicates whether the object will accept samples.
m_hEventPop | Event that is signalled whenever the object removes a sample from the queue.
Protected Methods
InitialThreadProc | Calls the ThreadProc method when the thread is created.
ThreadProc | Retrieves samples from the queue and delivers them to the input pin.
IsQueued | Determines whether the object is using a worker thread to deliver samples.
QueueSample | Queues a media sample or control message.
IsSpecialSample | Determines whether queued data is a control message.
FreeSamples | Frees all pending samples.
NotifyThread | Notifies the thread that the queue contains data.
Public Methods
COutputQueue | Constructor method.
~COutputQueue | Destructor method.
BeginFlush | Begins a flush operation.
EndFlush | Ends a flush operation.
EOS | Delivers an end-of-stream call to the input pin.
SendAnyway | Delivers any pending samples.
NewSegment | Delivers a new segment to the input pin.
Receive | Delivers a media sample to the input pin.
ReceiveMultiple | Delivers a batch of media samples to the input pin.
Reset | Resets the object so that it can receive more data.
IsIdle | Determines whether the object is waiting for data.
SetPopEvent | Specifies an event that is signalled whenever the object removes a sample from the queue.

COutputQueue.m_pPin

COutputQueue Class

Pointer to the input pin's IPin interface.

Syntax

IPin * const m_pPin;

COutputQueue.m_pInputPin

COutputQueue Class

Pointer to the input pin's IMemInputPin interface.

Syntax

IMemInputPin *m_pInputPin;

COutputQueue.m_bBatchExact

COutputQueue Class

Flag that specifies whether the object delivers samples in exact batches.

Syntax

BOOL const m_bBatchExact;

Remarks

If the value is TRUE, the object waits until it has a complete batch of media samples before delivering any. Otherwise, it delivers samples as they arrive. The m_lBatchSize member variable defines the batch size.

COutputQueue.m_lBatchSize

COutputQueue Class

Batch size.

Syntax

LONG const m_lBatchSize;

COutputQueue.m_List

COutputQueue Class

Media sample queue.

Syntax

typedef CGenericList<IMediaSample> CSampleList;
CSampleList *m_List;

Remarks

Pointer to a CGenericList class template, specialized to hold IMediaSample pointers.

COutputQueue.m_hSem

COutputQueue Class

Handle to a semaphore, used by the thread to wait for samples.

Syntax

HANDLE m_hSem;

COutputQueue.m_evFlushComplete

COutputQueue Class

Event that signals when a flush operation has finished.

Syntax

CAMEvent m_evFlushComplete;

COutputQueue.m_hThread

COutputQueue Class

Handle to the worker thread.

Syntax

HANDLE m_hThread;

COutputQueue.m_ppSamples

COutputQueue Class

Array of samples of size m_lBatchSize.

Syntax

IMediaSample  **m_ppSamples;

Remarks

The worker thread pulls samples from the queue (m_List) and places them in this array. It passes the array to the IMemInputPin::ReceiveMultiple method. If the object is not using a worker thread, the object places samples directly into this array.

COutputQueue.m_nBatched

COutputQueue Class

Number of samples currently batched and awaiting processing.

Syntax

LONG m_nBatched;

COutputQueue.m_lWaiting

COutputQueue Class

Flag that has a nonzero value when the thread is waiting for a sample.

Syntax

LONG m_lWaiting;

COutputQueue.m_bFlushing

COutputQueue Class

Flag that specifies whether the object is performing a flush operation. If TRUE, the object has started flushing.

Syntax

BOOL m_bFlushing;

COutputQueue.m_bTerminate

COutputQueue Class

Flag that specifies whether the thread should terminate. If TRUE, the thread terminates.

Syntax

BOOL m_bTerminate;

COutputQueue.m_bSendAnyway

COutputQueue Class

Flag to override batch processing. Setting this flag to TRUE overrides the m_bBatchExact flag and delivers all pending samples.

Syntax

BOOL m_bSendAnyway;

COutputQueue.m_hr

COutputQueue Class

HRESULT value that indicates whether the object will accept samples. If the value is S_OK, the object will accept samples. Otherwise, it rejects samples.

Syntax

BOOL volatile m_hr;

Remarks

This member variable is used to coordinate activities across threads. If the downstream input pin rejects a sample, or if the object begins flushing, the value is set to S_FALSE or an error code. The object will not deliver any more samples until flushing is complete, or until the Reset method is called.

COutputQueue.m_hEventPop

COutputQueue Class

Optional event that is signaled whenever the object removes a sample from the queue. The value is initially NULL. Call the SetPopEvent method to specify an event handle.

Syntax

HANDLE m_hEventPop;

COutputQueue::BeginFlush

COutputQueue Class

Begins a flush operation.

Syntax

void BeginFlush(void);

Remarks

This method sets the m_bFlushing member variable to TRUE. If the object is using a thread, the thread calls the FreeSamples method to free any pending samples. Otherwise, the object calls FreeSamples during the COutputQueue::EndFlush method. This method also sets the m_hr member variable to S_FALSE, which causes the object to discard all new samples.

The object passes the flush notification downstream by calling the IPin::BeginFlush method on the input pin.

COutputQueue::COutputQueue

COutputQueue Class

Constructor method.

Syntax

COutputQueue(
    IPin *pInputPin,
    HRESULT *phr,
    BOOL bAuto = TRUE,
    BOOL bQueue = TRUE,
    LONG lBatchSize = 1,
    BOOL bBatchExact = FALSE,
    LONG lListSize = DEFAULTCACHE,
    DWORD dwPriority = THREAD_PRIORITY_NORMAL
);

Parameters

pInputPin
Pointer to the IPin interface of the input pin. The object will deliver samples to this pin.
phr
Pointer to an HRESULT return code. Set the value to S_OK before calling this method. On return, phr receives a value that indicates the success or failure of the method.
bAuto
Flag that specifies whether the object decides when to create a queue. If TRUE, the object creates a queue only if the input pin might block. If FALSE, the bQueue parameter specifies whether to create a queue.
bQueue
If bAuto is TRUE, this parameter is ignored. If bAuto is FALSE, this flag specifies whether to create a queue.
lBatchSize
Maximum number of samples to deliver in one batch.
bBatchExact
Flag that specifies whether to use exact batch sizes. If TRUE, the object waits for lBatchSize samples before delivering them to the input pin. If FALSE, the object delivers samples as it receives them.
lListSize
Cache size for the queue. The default value, DEFAULTCACHE, is a constant defined for the CBaseList class.
dwPriority
Priority of the thread that delivers samples.

Remarks

If bAuto is TRUE, the object calls the IMemInputPin::ReceiveCanBlock method on the downstream pin. If ReceiveCanBlock returns S_OK (meaning the pin might block on Receive calls), the object creates a thread for delivering samples. Otherwise, it does not create a thread.

If bAuto is FALSE, the value of bQueue determines whether to create a thread.

If the object creates a thread, it assigns the thread handle to the m_hThread member variable. The thread procedure is InitialThreadProc, and the thread parameter is a pointer to this. The object also creates a queue for holding samples, which is given by the m_List member variable.

COutputQueue::~COutputQueue

COutputQueue Class

Destructor method.

Syntax

~COutputQueue(void);

COutputQueue::EndFlush

COutputQueue Class

Ends a flush operation.

Syntax

void EndFlush(void);

Remarks

If the object is using a thread, this method waits for the m_evFlushComplete event. The thread signals this event after it frees any pending samples. If the object is not using a thread, this method calls the FreeSamples method. Then the EndFlush method calls the IPin::EndFlush method on the input pin.

COutputQueue::EOS

COutputQueue Class

Delivers an end-of-stream call to the input pin.

Syntax

void EOS(void);

Remarks

If the object is using a thread, it queues an EOS_PACKET control message. The thread delivers any pending samples and calls the IPin::EndOfStream method on the input pin.

If the object is not using a thread, it calls the SendAnyway method to deliver any pending samples. Then it calls IPin::EndOfStream on the input pin.

COutputQueue::FreeSamples

COutputQueue Class

Frees all pending samples.

Syntax

void FreeSamples(void);

Remarks

This method removes any pending samples from the queue and from the sample array (m_ppSamples).

COutputQueue::InitialThreadProc

COutputQueue Class

Calls the ThreadProc method when the thread is created.

Syntax

static DWORD WINAPI InitialThreadProc(
    LPVOID pv
);

Parameters

pv
this pointer.

Return Value

Returns the value returned by the ThreadProc method.

Remarks

This method is the thread procedure for the object's worker thread. The object's this pointer is the thread parameter. The method dereferences this to call ThreadProc.

COutputQueue::IsIdle

COutputQueue Class

Determines whether the object is waiting for data.

Syntax

BOOL IsIdle(void);

Return Value

Returns TRUE if the thread is waiting and the sample array is empty. Otherwise, returns FALSE.

COutputQueue::IsQueued

COutputQueue Class

Determines whether the object is using a worker thread to deliver samples.

Syntax

BOOL IsQueued(void);

Return Value

Returns TRUE if the object is using a worker thread, or FALSE otherwise.

COutputQueue::IsSpecialSample

COutputQueue Class

Determines whether queued data is a control message.

Syntax

BOOL IsSpecialSample(
    IMediaSample *pSample
);

Parameters

pSample
Pointer to an item in the queue.

Return Value

Returns TRUE if pSample is a control message, or FALSE otherwise.

Remarks

The QueueSample method can receive control messages in addition to media samples. A control message is a defined constant (cast to a LONG_PTR type) that instructs the thread to perform an action. Control messages do not contain media data. For more information, see QueueSample.

COutputQueue::NewSegment

COutputQueue Class

Delivers a new segment to the input pin.

Syntax

HRESULT NewSegment(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop,
    double dRate
);

Parameters

tStart
[in] Starting media position of the segment, in 100-nanosecond units.
tStop
[in] End media position of the segment, in 100-nanosecond units.
dRate
[in] Rate at which this segment should be processed, as a percentage of the original rate.

Return Value

Returns an HRESULT value.

Remarks

If the object is using a thread, it queues the following items, in order:

  • A NEW_SEGMENT control message.
  • The segment data.

The NEW_SEGMENT message notifies the thread that the next item on the queue will contain segment data. The segment data is bundled in a structure, declared as follows:

struct NewSegmentPacket {
    REFERENCE_TIME tStart;
    REFERENCE_TIME tStop;
    double dRate;
};

The thread calls the IPin::NewSegment method on the input pin, using the data given in the structure.

If the object is not using a thread, it calls the SendAnyway method to deliver any pending samples. Then it calls IPin::NewSegment on the input pin.

COutputQueue::NotifyThread

COutputQueue Class

Notifies the thread that the queue contains data.

Syntax

void NotifyThread(void);

Remarks

Hold the critical section before calling this method.

COutputQueue::QueueSample

COutputQueue Class

Queues a sample.

Syntax

void QueueSample(
    IMediaSample *pSample
);

Parameters

pSample
Pointer to the sample's IMediaSample interface.

Remarks

This method adds a sample to the tail of the queue (m_List). Hold the critical section before calling this method, and call it only when the object is using a thread to deliver samples. To determine if the object is using a thread, call the IsQueued method.

This method can also be used to put control messages onto the queue. A control message is a defined constant (cast to a LONG_PTR type) that instructs the thread to perform some action. The COutputQueue class defines the control messages shown in the following table.

Message | Action
EOS_PACKET | Deliver an end-of-stream notification.
NEW_SEGMENT | Deliver a new segment.
RESET_PACKET | Reset the state of the queue.
SEND_PACKET | Send a partial batch of samples.

This is a protected method, which the COutputQueue class uses internally.

COutputQueue::Receive

COutputQueue Class

Delivers a media sample to the input pin.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | End-of-stream notification received before processing this sample.
S_OK | Success.

Remarks

This method calls the COutputQueue::ReceiveMultiple method.

COutputQueue::ReceiveMultiple

COutputQueue Class

Delivers a batch of media samples to the input pin.

Syntax

HRESULT ReceiveMultiple (
    IMediaSample **ppSamples,
    long nSamples,
    long *nSamplesProcessed
);

Parameters

ppSamples
Address of a pointer to an array of samples.
nSamples
Number of samples in the array.
nSamplesProcessed
Pointer to a variable that receives the number of samples delivered successfully.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | End-of-stream notification received before processing this sample.
S_OK | Success.

Remarks

If the object is using a thread, this method queues all of the samples passed in the array. Otherwise, the method calls the IMemInputPin::ReceiveMultiple method on the input pin.

COutputQueue::Reset

COutputQueue Class

Resets the object so that it can receive more data.

Syntax

void Reset(void);

Return Value

No return value.

Remarks

This method resets the m_hr member variable to S_OK. The object can receive media samples again; for example, after a flush operation.

COutputQueue::SendAnyway

COutputQueue Class

Delivers any pending samples.

Syntax

void SendAnyway(void);

Remarks

If the m_bBatchExact member variable is TRUE, the object fills the m_ppSamples array before it delivers a batch of samples. Call this method to deliver a partial batch. For example, the EOS method calls SendAnyway to serialize end-of-stream messages.

COutputQueue::SetPopEvent

COutputQueue Class

Specifies an event that is signalled whenever the object removes a sample from the queue.

Syntax

void COutputQueue::SetPopEvent(
    HANDLE hEvent
);

Syntax

hEvent
Handle to an event created by the caller.

COutputQueue::ThreadProc

COutputQueue Class

Retrieves samples from the queue and delivers them to the input pin.

Syntax

DWORD ThreadProc(void);

Return Value

Returns zero.

Remarks

The InitialThreadProc method calls this method, which implements the main thread loop. Within the loop, the method performs the following steps:

  1. Retrieves a sample for the queue (m_List).
  2. If the sample is a control message, the thread executes the control action. Otherwise, it places the sample into the m_ppSamples array.
  3. When the array is full (or if m_bBatchExact is FALSE), the thread calls the IMemInputPin::ReceiveMultiple method to deliver the samples.
  4. If no samples are queued, the thread waits on the m_hSem semaphore.

The thread terminates when the m_bTerminate member variable becomes TRUE.


CPersistStream Class

CPersistStream class hierarchy

CPersistStream is the base class for persistent properties of filters (that is, filter properties in saved graphs).

The simplest way to use CPersistStream is to:

  1. Arrange for your filter to inherit this class.
  2. Implement WriteToStream and ReadFromStream in your class. These will override the functions here, which do nothing but act as placeholders.
  3. Change your NonDelegatingQueryInterface to handle IPersistStream.
  4. Implement SizeMax to return an upper bound on the number of bytes of data you save.

    If you save Unicode™ data, remember that a WCHAR is 2 bytes.

  5. When your data changes, call SetDirty.

Version Numbers

At some point you might decide to alter or extend the format of your data. You will then wish you had a version number in all the old saved streams so you can tell, when you read them, whether they represent the old or new form. To assist you, this class writes and reads a version number. When it writes, it calls GetSoftwareVersion to inquire as to the version of the software being used at the moment. (In effect, this is a version number of the data layout in the file.) It writes this as the first thing in the data. If you want to change the version, implement (override) GetSoftwareVersion. It reads the version number from the file into mPS_dwFileVersion before calling ReadFromStream, so in ReadFromStream you can check mPS_dwFileVersion to see if you are reading an old version file. Usually you should accept files whose version is no newer than the software version that is reading them.

Protected Data Members

mPS_dwFileVersion | Version number of the file.
mPS_fDirty | Data for this stream must be saved.

Member Functions

CPersistStream | Constructs a CPersistStream object.
SetDirty | Indicates that the object must be saved to the stream.

Overridable Member Functions

GetClassID | Retrieves the class identifier of this stream.
GetSoftwareVersion | Retrieves the version number for this file format.
ReadFromStream | Reads the filter's data from the stream.
SizeMax | Retrieves the number of bytes needed for data (not including version number).
WriteToStream | Writes the filter's data to the stream.

CPersistStream implements IPersistStream. For more implementation information, see the COM Reference in the Microsoft Platform SDK.

Implemented IPersistStream Methods

GetSizeMax | Retrieves the number of bytes needed for data (including version number).
IsDirty | Checks if the object must be saved.
Load | Loads the data from the stream into memory.
Save | Saves the data from memory to the stream.

CPersistStream::CPersistStream

CPersistStream Class

Constructs a CPersistStream object.

Syntax

CPersistStream(
    IUnknown *pUnk,
    HRESULT *phr
);

Parameters

pUnk
Pointer to the IUnknown interface of the delegating object.
phr
Pointer to the general COM return value. This value is changed only if this function fails.

Return Value

No return value.

CPersistStream::GetClassID

CPersistStream Class

Retrieves the class identifier for this filter.

Syntax

HRESULT GetClassID(
    CLSID *pClsID
);

Parameters

pClsID
Pointer to a CLSID structure. Copy your class ID to here.

Return Value

Returns an HRESULT value.

CPersistStream::GetSizeMax

CPersistStream Class

Retrieves the maximum byte size needed for the current stream, including the version number.

Syntax

HRESULT GetSizeMax(
    ULARGE_INTEGER *pcbSize
);

Parameters

pcbSize
Pointer to the size in bytes needed to save this stream, including the version number.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IPersistStream::GetSizeMax method.

CPersistStream::GetSoftwareVersion

CPersistStream Class

Retrieves the software version for this stream.

Syntax

virtual DWORD GetSoftwareVersion(void);

Return Value

Returns a DWORD containing the version number. Each time the format of the stream is changed, this function should be altered to return a larger number than before.

Remarks

For an explanation as to why file format version numbers are useful, see Version Numbers.

CPersistStream::IsDirty

CPersistStream Class

Indicates whether the object has changed since it was last saved to its current stream.

Syntax

HRESULT IsDirty(void);

Return Value

Returns S_OK if the filter needs saving and S_FALSE if it does not need saving.

Remarks

This member function implements the IPersistStream::IsDirty method.

CPersistStream::Load

CPersistStream Class

Loads the filter's data from a given stream.

Syntax

HRESULT Load(
    LPSTREAM pStm
);

Parameters

pStm
Pointer to the stream from which to be loaded.

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IPersistStream::Load method.

CPersistStream::ReadFromStream

CPersistStream Class

Reads the filter's data from the given stream.

Syntax

virtual HRESULT ReadFromStream(
    IStream *pStream
);

Parameters

pStream
Pointer to an IStream interface from which data is to be read.

Return Value

Returns NOERROR by default; the overriding member function should return a valid HRESULT value.

Remarks

The default version reads nothing; it can be overridden to read data specific to your class.

CPersistStream::Save

CPersistStream Class

Saves the filter's data to the given stream.

Syntax

HRESULT Save(
    LPSTREAM pStm,
    BOOL fClearDirty
);

Parameters

pStm
Pointer to the stream to which data is to be saved.
fClearDirty
Flag that indicates whether to reset the current stream's dirty flag; TRUE means to reset it. (When the method is called as part of a Save operation, the value is typically TRUE; when called as part of a Save As operation, the value is typically FALSE.)

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IPersistStream::Save method. It calls WriteInt with the software version, calls CPersistStream::WriteToStream with the stream in pStm, and resets mPS_fDirty.

CPersistStream::SetDirty

CPersistStream Class

Changes the dirty flag for the current stream.

Syntax

HRESULT SetDirty(
    BOOL fDirty
);

Parameters

fDirty
New dirty flag for this stream. TRUE means that the data has not been saved.

Return Value

Returns an HRESULT value.

CPersistStream::SizeMax

CPersistStream Class

Retrieves the maximum byte size needed for the current stream, not including the version number.

Syntax

virtual int SizeMax(void);

Return Value

Returns the number of bytes needed for data, not including the version number.

Remarks

The default version returns zero; it should be overridden to provide some other appropriate value.

CPersistStream::WriteToStream

CPersistStream Class

Writes the filter's data to the given stream.

Syntax

virtual HRESULT WriteToStream(
    IStream *pStream
);

Parameters

pStream
Pointer to an IStream interface that specifies the filter data's destination stream.

Return Value

Returns NOERROR by default; the overriding member function should return a valid HRESULT value.

Remarks

The default version writes nothing; it can be overridden to write data specific to your class.


CPosPassThru Class

CPosPassThru class hierarchy

Handles seek commands for filters with one input pin that do not perform seeking on their own.

Declaration: Ctlutil.h

This helper class implements the IMediaPosition and IMediaSeeking interfaces for filters that pass seek commands upstream. When the filter graph manager receives a seek command from an application, it delivers the command to the renderer filters in the graph. The command is then passed upstream through each filter's output pin, until it reaches a filter that can execute the command (if any). Typically, seeking is implemented on source filters or parser filters.

The CPosPassThru class holds a pointer to the filter's input pin. It passes seek commands to the connected output pin on the upstream filter, as shown in the following diagram.

Use the CPosPassThru class for transform filters, and the derived CRendererPosPassThru class for renderer filters.

To use this class in your filter, create an instance of the class and specify the filter's input pin in the CPosPassThru constructor method. Then delegate all IMediaPosition and IMediaSeeking calls to the CPosPassThru object.

The simplest way to delegate seeking commands is to expose the CPosPassThru object's IMediaPosition and IMediaSeeking interfaces. When your filter or pin is queried for one of these interfaces, return a pointer to the CPosPassThru implementation of the interface. The following code shows how do this. It is adapted from the CTransformOutputPin class. The CreatePosPassThru function is a helper function that creates the CPosPassThru object:

// The following member variables are assumed:
// CPosPassThru *m_pPos;
// IPin *m_pPin;

if (riid == IID_IMediaPosition || riid == IID_IMediaSeeking)
{
    if (m_pPos == NULL)
    {
        HRESULT hr;
        hr = CreatePosPassThru(GetOwner(), FALSE, m_pPin, &m_pPos);
        if (FAILED(hr))
            return hr;
    }
    return m_pPosition->QueryInterface(riid, ppv);
}
else
{
    // Return pointers to the other interfaces on this pin.
}

Except where noted, all IMediaPosition and IMediaSeeking methods in this class call the corresponding method on the connected pin and return the result.

Public Methods
CPosPassThru | Constructor method.
ForceRefresh | Obsolete.
GetMediaTime | Retrieves the time stamps on the current sample. Virtual.
IMediaPosition Methods
get_Duration | Retrieves the duration of the stream.
put_CurrentPosition | Sets the current position, relative to the total duration of the stream.
get_StopTime | Retrieves the time at which the playback will stop, relative to the duration of the stream.
put_StopTime | Sets the time at which the playback will stop, relative to the duration of the stream.
get_PrerollTime | Retrieves the amount of data that will be queued before the start position.
put_PrerollTime | Sets the amount of data that will be queued before the start position.
get_Rate | Retrieves the playback rate.
put_Rate | Sets the playback rate.
get_CurrentPosition | Retrieves the current position, relative to the total duration of the stream.
CanSeekForward | Determines whether the stream can be seeked backward.
CanSeekBackward | Determines whether the stream can be seeked forward.
IMediaSeeking Methods
CheckCapabilities | Queries whether a stream has specified seeking capabilities.
ConvertTimeFormat | Converts from one time format to another.
GetAvailable | Retrieves the range of times in which seeking is efficient.
GetCapabilities | Retrieves all the seeking capabilities of the stream.
GetCurrentPosition | Retrieves the current position, relative to the total duration of the stream.
GetDuration | Retrieves the duration of the stream.
GetPositions | Retrieves the current position and the stop position, relative to the total duration of the stream.
GetPreroll | Retrieves the amount of data that will be queued before the start position.
GetRate | Retrieves the playback rate.
GetStopPosition | Retrieves the time at which the playback will stop, relative to the duration of the stream.
GetTimeFormat | Retrieves the current time format.
IsFormatSupported | Determines whether a specified time format is supported.
IsUsingTimeFormat | Determines whether a specified time format is the format currently in use.
QueryPreferredFormat | Retrieves the preferred time format for the stream.
SetPositions | Sets the current position and the stop position.
SetRate | Sets the playback rate.
SetTimeFormat | Sets the time format.
Helper Functions
CreatePosPassThru | Creates a CPosPassThru or CRendererPosPassThru object.

CPosPassThru::CanSeekBackward

CPosPassThru Class

Determines whether the stream can be seeked backward. Implements the IMediaPosition::CanSeekBackward method.

Syntax

HRESULT CanSeekBackward(
    LONG *pCanSeekBackward
);

Parameters

pCanSeekBackward
Pointer to a variable that receives the value OATRUE if the filter can seek backward, or OAFALSE otherwise.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::CanSeekForward

CPosPassThru Class

Determines whether the stream can be seeked forward. Implements the IMediaPosition::CanSeekForward method.

Syntax

HRESULT CanSeekForward(
    LONG *pCanSeekForward
);

Parameters

pCanSeekForward
Pointer to a variable that receives the value OATRUE if the filter can seek forward, or OAFALSE otherwise.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::CheckCapabilities

CPosPassThru Class

Queries whether a stream has specified seeking capabilities. Implements the IMediaSeeking::CheckCapabilities method.

Syntax

HRESULT CheckCapabilities(
    DWORD *pCapabilities
);

Parameters

pCapabilities
Pointer to a bitwise combination of one or more AM_SEEKING_SEEKING_CAPABILITIES attributes. When the method returns, the value indicates which of those attributes are available.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::ConvertTimeFormat

CPosPassThru Class

Converts from one time format to another. Implements the IMediaSeeking::ConvertTimeFormat method.

Syntax

HRESULT ConvertTimeFormat(
    LONGLONG *pTarget,
    const GUID *pTargetFormat,
    LONGLONG Source,
    const GUID *pSourceFormat
);

Parameters

pTarget
Pointer to a variable that receives the converted time.
pTargetFormat
Pointer to the time format GUID of the target format. If NULL, the current format is used.
Source
Time value to be converted.
pSourceFormat
Pointer to the time format GUID of the format to convert. If NULL, the current format is used.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::CPosPassThru

CPosPassThru Class

Constructor method.

Syntax

CPosPassThru(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    IPin *pPin
);

Parameters

pName
Pointer to the name of the object, for debugging purposes. Allocate this parameter in static memory.
pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
phr
Pointer to an HRESULT value. Ignored.
pPin
Pointer to the IPin interface of the filter's input pin.

CPosPassThru::ForceRefresh

CPosPassThru Class

Obsolete.

Syntax

HRESULT ForceRefresh(void);

Return Value

Returns S_OK.

Remarks

Originally this class was designed to cache pointers to the connected pin's IMediaPosition and IMediaSeeking interfaces. The ForceRefresh method released those interfaces.

As currently implemented, this class does not cache those interfaces. For compatibility, the ForceRefresh method is still included, but it returns S_OK without doing anything.

CPosPassThru::GetAvailable

CPosPassThru Class

Retrieves the range of times in which seeking is efficient. Implements the IMediaSeeking::GetAvailable method.

Syntax

HRESULT GetAvailable(
    LONGLONG *pEarliest,
    LONGLONG *pLatest
);

Parameters

pEarliest
Pointer to a variable that receives the earliest time for efficient seeking.
pLatest
Pointer to a variable that receives the latest time for efficient seeking.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::GetCapabilities

CPosPassThru Class

Retrieves all the seeking capabilities of the stream. Implements the IMediaSeeking::GetCapabilities method.

Syntax

HRESULT GetCapabilities(
    DWORD *pCapabilities
);

Parameters

pCapabilities
Pointer to a variable that receives a bitwise combination of AM_SEEKING_SEEKING_CAPABILITIES flags.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::GetCurrentPosition

CPosPassThru Class

Retrieves the current position, relative to the total duration of the stream. Implements the IMediaSeeking::GetCurrentPosition method.

Syntax

HRESULT GetCurrentPosition(
    LONGLONG *pCurrent
);

Parameters

pCurrent
Pointer to a variable that receives the current position, in units of the current time format.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.

Remarks

This method calls the CPosPassThru::GetMediaTime method to retrieve the most recent position. If GetMediaTime fails, the method calls IMediaSeeking::GetCurrentPosition on the connected pin.

The GetMediaTime method fails by default in the base class. If your filter caches the current position, override GetMediaTime to return the cached value.

CPosPassThru::get_CurrentPosition

CPosPassThru Class

Retrieves the current position, relative to the total duration of the stream. Implements the IMediaPosition::get_CurrentPosition method.

Syntax

HRESULT get_CurrentPosition(
    REFTIME *pllTime
);

Parameters

pllTime
Pointer to a variable that receives the current position, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::GetDuration

CPosPassThru Class

Retrieves the duration of the stream. Implements the IMediaSeeking::GetDuration method.

Syntax

HRESULT GetDuration(
    LONGLONG *pDuration
);

Parameters

pDuration
Pointer to a variable that receives the duration, in units of the current time format.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::get_Duration

CPosPassThru Class

Retrieves the duration of the stream. Implements the IMediaPosition::get_Duration method.

Syntax

HRESULT get_Duration(
    REFTIME *plength
);

Parameters

plength
Pointer to a variable that receives the total stream length, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::GetMediaTime

CPosPassThru Class

Retrieves the time stamps on the current sample.

Syntax

virtual HRESULT GetMediaTime(
    LONGLONG *pStartTime,
    LONGLONG *pEndTime
);

Parameters

pStartTime
Pointer to a variable that receives the start time, in units of the current time format.
pEndTime
Pointer to a variable that receives the end time, in units of the current time format.

Return Value

Returns E_FAIL.

Remarks

Override this method if your filter caches the time stamps on the samples it receives.

CPosPassThru::GetPositions

CPosPassThru Class

Retrieves the current position and the stop position, relative to the total duration of the stream. Implements the IMediaSeeking::GetPositions method.

Syntax

HRESULT GetPositions(
    LONGLONG *pCurrent,
    LONGLONG *pStop
);

Parameters

pCurrent
Pointer to a variable that receives the current position, in units of the current time format.
pStop
Pointer to a variable that receives the stop position, in units of the current time format.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::GetPreroll

CPosPassThru Class

Retrieves the amount of data that will be queued before the start position. Implements the IMediaSeeking::GetPreroll method.

Syntax

HRESULT GetPreroll(
    LONGLONG *pllPreroll
);

Parameters

pllPreroll
Pointer to a variable that receives the preroll time, in units of the current time format.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::get_PrerollTime

CPosPassThru Class

Retrieves the amount of data that will be queued before the start position. Implements the IMediaPosition::get_PrerollTime method.

Syntax

HRESULT get_PrerollTime(
    REFTIME *pllTime
);

Parameters

pllTime
Pointer to a variable that receives the preroll time, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::GetRate

CPosPassThru Class

Retrieves the playback rate. Implements the IMediaSeeking::GetRate method.

Syntax

HRESULT GetRate(
    double *pdRate
);

Parameters

pdRate
Pointer to a variable that receives the playback rate.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::get_Rate

CPosPassThru Class

Retrieves the playback rate. Implements the IMediaPosition::get_Rate method.

Syntax

HRESULT get_Rate(
    double *pdRate
);

Parameters

pdRate
Pointer to a variable that receives the playback rate.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::GetStopPosition

CPosPassThru Class

Retrieves the time at which the playback will stop, relative to the duration of the stream. Implements the IMediaSeeking::GetStopPosition method.

Syntax

HRESULT GetStopPosition(
    LONGLONG *pStop
);

Parameters

pStop
Pointer to a variable that receives the stop time, in units of the current time format.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::get_StopTime

CPosPassThru Class

Retrieves the time at which the playback will stop, relative to the duration of the stream. Implements the IMediaPosition::get_StopTime method.

Syntax

HRESULT get_StopTime(
    REFTIME *pllTime
);

Parameters

pllTime
Pointer to a variable that receives the stop time, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::GetTimeFormat

CPosPassThru Class

Retrieves the current time format. Implements the IMediaSeeking::GetTimeFormat method.

Syntax

HRESULT GetTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat
Pointer to a variable that receives a time format GUID.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::IsFormatSupported

CPosPassThru Class

Determines whether a specified time format is supported. Implements the IMediaSeeking::IsFormatSupported method.

Syntax

HRESULT IsFormatSupported(
    const GUID *pFormat
);

Parameters

pFormat
Pointer to a time format GUID.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::IsUsingTimeFormat

CPosPassThru Class

Determines whether a specified time format is the format currently in use. Implements the IMediaSeeking::IsUsingTimeFormat method.

Syntax

HRESULT IsUsingTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat
Pointer to a time format GUID.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::put_CurrentPosition

CPosPassThru Class

Sets the current position, relative to the total duration of the stream. Implements the IMediaPosition::put_CurrentPosition method.

Syntax

HRESULT put_CurrentPosition(
    REFTIME llTime
);

Parameters

llTime
New position, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::put_PrerollTime

CPosPassThru Class

Sets the amount of data that will be queued before the start position. Implements the IMediaPosition::put_PrerollTime method.

Syntax

HRESULT put_PrerollTime(
    REFTIME llTime
);

Parameters

llTime
Preroll time, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

Remarks

Although this member function passes the call upstream, the IMediaPosition::put_PrerollTime method is not implemented on any DirectShow source filters.

CPosPassThru::put_Rate

CPosPassThru Class

Sets the playback rate. Implements the IMediaPosition::put_Rate method.

Syntax

HRESULT put_Rate(
    double dRate
);

Parameters

dRate
Playback rate. Must not be zero.

Return Value

Returns E_INVALIDARG if dRate is zero. Otherwise, returns the HRESULT value from the connected pin.

Remarks

Negative rates indicate reverse play. Not all media will support reverse play.

CPosPassThru::put_StopTime

CPosPassThru Class

Sets the time at which the playback will stop, relative to the duration of the stream. Implements the IMediaPosition::put_StopTime method.

Syntax

HRESULT put_StopTime(
    REFTIME llTime
);

Parameters

llTime
Stop time as a double value, in seconds.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::QueryPreferredFormat

CPosPassThru Class

Retrieves the preferred time format for the stream. Implements the IMediaSeeking::QueryPreferredFormat method.

Syntax

HRESULT QueryPreferredFormat(
    GUID *pFormat
);

Parameters

pFormat
Pointer to a variable that receives a time format GUID.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::SetPositions

CPosPassThru Class

Sets the current position and the stop position. Implements the IMediaSeeking::SetPositions method.

Syntax

HRESULT SetPositions(
    LONGLONG *pCurrent,
    DWORD dwCurrentFlags,
    LONGLONG *pStop,
    DWORD dwStopFlags
);

Parameters

pCurrent
Pointer to a variable that specifies the current position, in units of the current time format.
dwCurrentFlags
Bitwise combination of flags. See IMediaSeeking::SetPositions for more information.
pStop
Pointer to a variable that specifies the stop time, in units of the current time format.
dwStopFlags
Bitwise combination of flags. See IMediaSeeking::SetPositions for more information.

Return Value

Returns the HRESULT value from the connected pin.

CPosPassThru::SetRate

CPosPassThru Class

Sets the playback rate. Implements the IMediaSeeking::SetRate method.

Syntax

HRESULT SetRate(
    double dRate
);

Parameters

dRate
Playback rate. Must not be zero.

Return Value

Returns E_INVALIDARG if dRate is zero. Otherwise, returns the HRESULT value from the connected pin.

CPosPassThru::SetTimeFormat

CPosPassThru Class

Sets the time format. Implements the IMediaSeeking::SetTimeFormat method.

Syntax

HRESULT SetTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat
Pointer to a time format GUID.

Return Value

Returns the HRESULT value from the connected pin.

CreatePosPassThru Function

CPosPassThru Class

Creates a CPosPassThru or CRendererPosPassThru object.

Syntax

STDAPI CreatePosPassThru(
    LPUNKNOWN pAgg,
    BOOL bRenderer,
    IPin *pPin,
    IUnknown **ppPassThru
);

Parameters

pAgg
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
bRenderer
Boolean value that specifies whether the filter is a renderer. Use the value TRUE if the filter is a renderer, or FALSE otherwise.
pPin
Pointer to the IPin interface on the filter's input pin.
ppPassThru
Address of a variable that receives a pointer to the object's IUnknown interface.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

If the value of bSupportRendering is TRUE, this method creates an instance of the CRendererPosPassThru class. Otherwise, it creates an instance of the CPosPassThru class. For more information, see CSeekingPassThru.


CPullPin Class

CPullPin class hierarchy

The CPullPin class is provided to allow a filter downstream from the source to create a thread and pull a media stream from an asynchronous source filter that supports the IAsyncReader interface. Typically this class is implemented on the input pin of a parser filter, since the Microsoft® DirectShow® asynchronous reader filter just reads a media stream from a file and provides no parsing.

Protected Data Members

m_pAlloc Pointer to the IMemAllocator interface used by the connection.

Member Functions

Active | Instructs the pin to start pulling data from the asynchronous reader.
AlignDown | Aligns a LONGLONG value down to the next LONG boundary.
AlignUp | Aligns a LONGLONG value up to the next LONG boundary.
Connect | Initiates a connection from this pin to the asynchronous reader.
CPullPin | Constructs a CPullPin object.
Disconnect | Breaks a connection to the asynchronous reader.
Duration | Retrieves the total duration of the media stream.
GetReader | Retrieves the asynchronous reader interface.
Inactive | Instructs the pin to stop pulling data from the asynchronous reader.
Seek | Sets the start and stop times of the media stream.

Overridable Member Functions

BeginFlush | Flushes this pin and all downstream pins.
DecideAllocator | Proposes an allocator for use by the asynchronous reader.
EndFlush | Signals end of flushing operation.
EndOfStream | Sends end-of-stream notification downstream.
OnError | Handles run-time errors that caused pulling to stop.
Receive | Handles the arrival of data from the asynchronous reader.

CPullPin::Active

CPullPin Class

Instructs the pin to start pulling data from the asynchronous reader.

Syntax

HRESULT Active(void);

Return Value

Returns an HRESULT value.

Remarks

The reader interface must be retrieved and the allocator decided before calling this member function. This is handled by the CPullPin::Connect member function.

CPullPin::AlignDown

CPullPin Class

Aligns a LONGLONG value down to the next LONG boundary.

Syntax

LONGLONG AlignDown(
    LONGLONG ll,
    LONG lAlign
    );

Parameters

ll
Element to be aligned.
lAlign
Alignment boundary.

Return Value

Returns the ll value aligned to lAlign.

Remarks

Aligning downward is a truncation operation.

CPullPin::AlignUp

CPullPin Class

Aligns a LONGLONG value up to the next LONG boundary.

Syntax

LONGLONG AlignUp(
    LONGLONG ll,
    LONG lAlign
    );

Parameters

ll
Element to be aligned.
lAlign
Alignment boundary.

Return Value

Returns an HRESULT value.

CPullPin::BeginFlush

CPullPin Class

Override to flush this pin and all downstream pins.

Syntax

virtual HRESULT BeginFlush(void);

Return Value

Returns an HRESULT value.

Remarks

This member function is called by the CPullPin::Seek member function before pausing the thread prior to a seeking operation. You must implement this member function to call the IPin::BeginFlush method on the connected downstream pin.

CPullPin::Connect

CPullPin Class

Initiates a connection from this pin to the asynchronous reader.

Syntax

HRESULT Connect(
    IUnknown *pUnk,
    IMemAllocator *pAlloc,
    BOOL bSync
    );

Parameters

pUnk
Pointer to the object to query for existence of asynchronous reader (IAsyncReader).
pAlloc
Pointer to the optional allocator to propose as preferred allocator if necessary.
bSync
Set to TRUE if the reader uses synchronous rather than asynchronous reads.

Return Value

Returns S_OK if successfully connected to the IAsyncReader interface from the object specified by pUnk.

CPullPin::CPullPin

CPullPin Class

Constructs a CPullPin object.

Syntax

CPullPin(void);

Return Value

No return value.

CPullPin::DecideAllocator

CPullPin Class

Negotiates an allocator to use with the asynchronous reader.

Syntax

virtual HRESULT DecideAllocator(
    IMemAllocator *pAlloc,
    ALLOCATOR_PROPERTIES *pProps
    );

Parameters

pAlloc
Pointer to the allocator to propose as the preferred allocator (optional). Pass NULL if you aren't proposing an allocator.
pProps
Pointer to the size, count, and alignment of the allocator (optional). Pass zero if not requesting the allocator properties.

Return Value

Returns S_OK if successful, VFW_E_BADALIGN if eProps contains an invalid alignment property, E_OUTOFMEMORY if there is not enough memory available to create an allocator, and E_NOINTERFACE if the created IMemAllocator interface is invalid.

Remarks

This member function calls the IAsyncReader::RequestAllocator method to negotiate an allocator.

CPullPin::Disconnect

CPullPin Class

Breaks a connection to the asynchronous reader.

Syntax

HRESULT Disconnect(void);

Return Value

Returns NOERROR if there is no connection.

Remarks

This member function disconnects any connection to an asynchronous file reader made in the CPullPin::Connect method.

CPullPin::Duration

CPullPin Class

Retrieves the total duration of the media stream.

Syntax

HRESULT Duration(
    REFERENCE_TIME *ptDuration
    );

Parameters

ptDuration
Pointer to the duration measured in bytes multiplied by UNIT (10,000,000).

Return Value

Returns an HRESULT value.

CPullPin::EndFlush

CPullPin Class

Override to signal the end of a flushing operation.

Syntax

virtual HRESULT EndFlush(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

This member function is called by the CPullPin::Seek member function after pausing the thread prior to a seeking operation. You must implement this member function to call the IPin::EndFlush method on the connected downstream pin.

CPullPin::EndOfStream

CPullPin Class

Override to send an end-of-stream notification downstream.

Syntax

virtual HRESULT EndOfStream(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

This member function is called during processing of received samples when the end of the stream is reached. You must implement this member function to call the IPin::EndOfStream method on the connected downstream pin.

CPullPin::GetReader

CPullPin Class

Retrieves the asynchronous reader.

Syntax

IAsyncReader* GetReader(void);

Return Value

Returns a reference-counted IAsyncReader interface.

CPullPin::Inactive

CPullPin Class

Instructs the pin to stop pulling data from the asynchronous reader.

Syntax

HRESULT Inactive(void);

Return Value

Returns an HRESULT value.

Remarks

This member function calls the IAsyncReader::BeginFlush method, ends the thread, calls the IAsyncReader::EndFlush method and then decommits the allocator.

CPullPin::OnError

CPullPin Class

Override to handle run-time errors that caused pulling to stop.

Syntax

virtual void OnError(
    HRESULT hr
    ) PURE;

Parameters

hr
HRESULT value of the trapped error.

Return Value

No return value.

Remarks

These errors are returned from the upstream filter (the asynchronous reader), which will have already reported errors to the filter graph manager. This member function must be implemented since it is called by several CPullPin member functions when trapping errors.

CPullPin::Receive

CPullPin Class

Override this member function to handle the arrival of data from the asynchronous reader.

Syntax

virtual HRESULT Receive(
    IMediaSample *pSample
    ) PURE;

Parameters

pSample
[in] Pointer to a media sample.

Return Value

Returns an HRESULT value. Returning a value other than S_OK will stop the data.

Remarks

You must implement this member function in your derived class. This member function is called whenever a new sample arrives while processing the sample stream. It should be written in the same manner as the IMemInputPin::Receive method on an input pin.

CPullPin::Seek

CPullPin Class

Sets the start and stop times of the media stream.

Syntax

HRESULT Seek(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop
    );

Parameters

tStart
Start time (defaults to zero).
tStop
Stop time (defaults to the value of CPullPin::Duration).

Return Value

Returns an HRESULT value.

Remarks

If the filter graph is running (active), the media rendering will start immediately at the new position defined by tStart.


CQueue Class

Class template that implements a simple, statically sized queue.

Declaration: Wxutil.h

The class constructor specifies the size of the queue. The PutQueueObject method queues an object, and the GetQueueObject method dequeues an object. The PutQueueObject method blocks until there is space in the queue for a new object. The GetQueueObject method blocks until there is something in the queue.

This class template uses two semaphores to control queuing operations, a "get" semaphore and a "put" semaphore. The GetQueueObject method waits on the "get" semaphore (using the WaitForSingleObject function) and releases the "put" semaphore (using the ReleaseSemaphore function). The PutQueueObject method waits on the "put" semaphore and releases the "get" semaphore. The class also use a critical section to serialize queuing operations among multiple threads.

Public Methods
CQueue | Constructor method.
~CQueue | Destructor method.
GetQueueObject | Retrieves the next object from the queue.
PutQueueObject | Puts an object onto the queue.

CQueue::CQueue

CQueue Class

Constructor method.

Syntax

CQueue(
    int n
);

CQueue(void);

Parameters

n
Size of the queue to create.

Remarks

If created with no parameters, the size of the queue is set to DEFAULT_QUEUESIZE.

CQueue::~CQueue

CQueue Class

Destructor method.

Syntax

~CQueue(void);

CQueue::GetQueueObject

CQueue Class

Retrieves the next object from the queue.

Syntax

T GetQueueObject(void);

Return Value

Returns an object of type T (the template type).

Remarks

This method blocks until an object is available on the queue.

CQueue::PutQueueObject

CQueue Class

Puts an object onto the queue.

Syntax

void PutQueueObject(
    T object
);

Parameters

object
Object of type T (the template type).

Remarks

This method blocks until there is space in the queue for the object.


CRefTime Class

CRefTime class hierarchy

Helper class to manage reference times.

Declaration: Reftime.h

A reference time is a unit of time represented in 100-nanosecond units. This class shares the same data layout as the REFERENCE_TIME data type, but adds some methods and operators that provide comparison, conversion, and arithmetic functions. For more information about reference times, see Time and Clocks in DirectShow.

Public Member Variables
m_time | REFERENCE_TIME value.
Public Methods
CRefTime | Constructor method.
GetUnits | Retrieves the reference time in 100-nanosecond units.
Millisecs | Converts the reference time to milliseconds.
Operators
operator REFERENCE_TIME() | Casts the object to a REFERENCE_TIME data type.
operator = | Assigns a new reference time.
operator += | Adds two reference times.
operator –= | Subtracts one reference time from another.

CRefTime.m_time

CRefTime Class

REFERENCE_TIME value.

Syntax

REFERENCE_TIME m_time;

CRefTime::CRefTime

CRefTime Class

Constructor method.

Syntax

CRefTime(void);

CRefTime(
    LONG msecs
);

CRefTime(
    REFERENCE_TIME rt
);

Parameters

msecs
Time in milliseconds.

rt
Time in 100-nanosecond units.

Remarks

The reference time defaults to zero.

CRefTime::GetUnits

CRefTime Class

Retrieves the reference time in 100-nanosecond units.

Syntax

LONGLONG GetUnits(void);

Return Value

Returns the value of m_time.

CRefTime::Millisecs

CRefTime Class

Converts the reference time to milliseconds.

Syntax

LONG Millisecs(void);

Return Value

Returns the reference time in milliseconds.

CRefTime::operator (REFERENCE_TIME)

CRefTime Class

Casts the object to a REFERENCE_TIME data type.

Syntax

operator REFERENCE_TIME() const;

Return Value

Returns the value of m_time.

Remarks

The following example shows how to use this cast operator:

CRefTime cRT(1000);
REFERENCE_TIME rt = (REFERENCE_TIME)cRT;

CRefTime::operator =

CRefTime Class

Assigns a new reference time.

Syntax

CRefTime& operator=(
    const CRefTime& rt
);

CRefTime& operator=(
    const LONGLONG ll
);

Parameters

rt
Reference to a CRefTime object that specifies the new reference time.
ll
New reference time, in 100-nanosecond units.

Return Value

Returns a reference to the object.

CRefTime::operator +=

CRefTime Class

Adds two reference times.

Syntax

CRefTime& operator+=(
    const CRefTime& rt
);

Parameters

rt
Reference to a CRefTime object.

Return Value

Returns a reference to the object.

CRefTime::operator –=

CRefTime Class

Subtracts one reference time from another.

Syntax

CRefTime& operator-=(
    const CRefTime& rt
);

Parameters

rt
Reference to a CRefTime object.

Return Value

Returns a reference to the object.


CRenderedInputPin Class

CRenderedInputPin class hierarchy

The CRenderedInputPin class is provided for renderer filters that render the stream delivered from an input pin (that is, that do not have an output pin to pass the data on). It overrides CBaseInputPin to handle the end-of-stream notification and is implemented specifically so that more than one stream can be handled using this renderer (since each pin must handle the end-of-stream independently).

Protected Data Members

m_bAtEndOfStream | Set to TRUE when the end-of-stream notification has been received.
m_bCompleteNotified | Set to TRUE when the EC_COMPLETE notification has been sent to the filter graph manager.

Member Functions

CRenderedInputPin Constructs a CRenderedInputPin object.

Overridable Member Functions

Active | Notifies the pin that the filter has changed state from stopped to paused.
EndFlush | Informs the pin to end a flush operation.
EndOfStream | Informs the pin that no additional data is expected until a new run command is issued.
Run | Notifies the pin that the filter has changed state from paused to running.

CRenderedInputPin::Active

CRenderedInputPin Class

Notifies the pin that the filter has changed state from stopped to paused or running.

Syntax

HRESULT Active(void);

Return Value

Returns an HRESULT value.

Remarks

This member function overrides CBasePin::Active. It sets both m_bAtEndOfStream and m_bCompleteNotified to FALSE before calling the base class implementation.

CRenderedInputPin::CRenderedInputPin

CRenderedInputPin Class

Constructs a CRenderedInputPin object.

Syntax

CRenderedInputPin(
    TCHAR *pObjectName,
    CBaseFilter *pFilter,
    CCritSec *pLock,
    HRESULT *phr,
    LPCWSTR pName
    );

Parameters

pObjectName
Pointer to the name of the object for debugging purposes.
pFilter
Pointer to the pin's owning filter.
pLock
Pointer to the critical section for the pin.
phr
Pointer to an HRESULT value.
pName
Pointer to the pin name.

Return Value

No return value.

CRenderedInputPin::EndFlush

CRenderedInputPin Class

Informs the pin to end a flush operation.

Syntax

HRESULT EndFlush(void);

Return Value

Returns an HRESULT value.

Remarks

This member function overrides CBaseInputPin::EndFlush. It sets both m_bAtEndOfStream and m_bCompleteNotified to FALSE before calling the base class implementation.

CRenderedInputPin::EndOfStream

CRenderedInputPin Class

Informs the pin that no additional data is expected until a new run command is issued.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns an HRESULT value.

Remarks

This member function implements the IPin::EndOfStream method. It calls CheckStreaming to see that the filter is in a streaming state, sets m_bAtEndOfStream to TRUE, and then sends the EC_COMPLETE notification to the filter graph manager.

The EC_COMPLETE filter graph notification should be issued only after all the data delivered to the pin prior to calling this member function has been processed. If the filter performs processing asynchronously, override CRenderedInputPin::EndOfStream to postpone sending the EC_COMPLETE notification until processing of all input data has completed.

CRenderedInputPin::Run

CRenderedInputPin Class

Notifies the pin that the filter has changed state from stopped to paused.

Syntax

HRESULT Run(
    REFERENCE_TIME tStart
    );

Parameters

tStart
Start time. Unreferenced by this class; for possible use by the derived class.

Return Value

Returns an HRESULT value (S_OK by default).

Remarks

This member function overrides the CBasePin::Run member function. It sends the EC_COMPLETE notification to the filter graph manager if m_bAtEndOfStream is TRUE.


CRendererInputPin Class

CRendererInputPin class hierarchy

Input pin for the CBaseRenderer class. Except where noted, the methods in this class delegate to corresponding methods on the CBaseRenderer class.

Declaration: Renbase.h

Protected Member Variables
m_pRenderer | Pointer to the filter.
Public Methods
CRendererInputPin | Constructor method.
BreakConnect | Adds customized code upon breaking a connection.
CompleteConnect | Completes the connection.
CheckMediaType | Determines if the pin can support a specific media type.
Active | Switches the pin to the active (paused or running) mode.
Inactive | Switches the pin to an inactive state and releases the memory of the allocator.
SetMediaType | Sets the media type of the pin.
Allocator | Retrieves a pointer to the default memory allocator.
IPin Methods
QueryId | Retrieves an identifier for the pin.
EndOfStream | Informs the pin that no additional data is expected until a new run command is issued.
BeginFlush | Informs the pin to begin a flush operation.
EndFlush | Informs the pin to end a flush operation.
IMemInputPin Methods
Receive | Retrieves the next block of data from the stream.

CRendererInputPin.m_pRenderer

CRendererInputPin Class

Pointer to the filter.

Syntax

CBaseRenderer *m_pRenderer;

CRendererInputPin::Active

CRendererInputPin Class

Notifies the pin that the filter is now active. Overrides the CBasePin::Active method.

Syntax

HRESULT Active(void);

Return Value

Returns an HRESULT value.

CRendererInputPin::Allocator

CRendererInputPin Class

Retrieves a pointer to the memory allocator.

Syntax

IMemAllocator* Allocator(void) const;

Return Value

Returns a pointer to the allocator's IMemAllocator interface, or NULL.

Remarks

This method returns the CBaseInputPin::m_pAllocator member variable. The method does not increment the reference count on the interface. This method is strictly an accessor method.

CRendererInputPin::BeginFlush

CRendererInputPin Class

Begins a flush operation. Overrides the CBaseInputPin::BeginFlush method.

Syntax

HRESULT BeginFlush(void);

Return Value

Returns an HRESULT value.

CRendererInputPin::BreakConnect

CRendererInputPin Class

Releases the pin from a connection. Overrides the CBaseInputPin::BreakConnect method.

Syntax

HRESULT BreakConnect(void);

Return Value

Returns an HRESULT value.

CRendererInputPin::CheckMediaType

CRendererInputPin Class

Determines if the pin accepts a specific media type. Overrides the CBasePin::CheckMediaType method.

Syntax

HRESULT CheckMediaType(
    const CMediaType *pmt
);

Parameters

pmt
Pointer to a media type object that contains the proposed media type.

Return Value

Returns an HRESULT value.

CRendererInputPin::CompleteConnect

CRendererInputPin Class

Completes a connection to an output pin. Overrides the CBasePin::CompleteConnect method.

Syntax

HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin
Pointer to the output pin's IPin interface

Return Value

Returns an HRESULT value.

CRendererInputPin::CRendererInputPin

CRendererInputPin Class

Constructor method.

Syntax

CRendererInputPin(
    CBaseRenderer *pRenderer,
    HRESULT *phr,
    LPCWSTR Name
    );

Parameters

pRenderer
Pointer to the CBaseRenderer object that implements the filter.
phr
Pointer to a variable that receives an HRESULT value.
Name
Pointer to a Unicode™ string containing the pin identifier.

CRendererInputPin::EndFlush

CRendererInputPin Class

Ends a flush operation. Overrides the CBaseInputPin::EndFlush method.

Syntax

HRESULT EndFlush(void);

Return Value

Returns an HRESULT value.

CRendererInputPin::EndOfStream

CRendererInputPin Class

Notifies the pin that no additional data is expected. Overrides the CBasePin::EndOfStream method.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns an HRESULT value.

CRendererInputPin::Inactive

CRendererInputPin Class

Notifies the pin that the filter is no longer active. Overrides the CBaseInputPin::Inactive method.

Syntax

HRESULT Inactive(void);

Return Value

Returns an HRESULT value.

CRendererInputPin::QueryId

CRendererInputPin Class

Retrieves the pin identifier. Overrides the CBasePin::QueryId method.

Syntax

HRESULT QueryId(
    LPWSTR *Id
    );

Parameters

Id
Address of a variable that receives a string containing the pin identifier.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

This method allocates the wide-character string "In" and assigns it to the Id parameter. The caller must free the allocated memory, using the CoTaskMemFree function.

CRendererInputPin::Receive

CRendererInputPin Class

Receives the next media sample in the stream. Overrides the CBaseInputPin::Receive method.

Syntax

HRESULT Receive(
    IMediaSample *pMediaSample
    );

Parameters

pMediaSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value.

CRendererInputPin::SetMediaType

CRendererInputPin Class

Sets the media type for the connection. Overrides the CBasePin::SetMediaType method.

Syntax

HRESULT SetMediaType(
    const CMediaType *pmt
);

Parameters

pmt
Pointer to a CMediaType object that specifies the media type.

Return Value

Returns an HRESULT value.


CRendererPosPassThru Class

CRendererPosPassThru class hierarchy

Handles seek commands for renderer filters.

Declaration: Ctlutil.h

This class derives from the CPosPassThru class. It adds support for caching the time stamps from samples as they arrive.

Use this class in the same way as the CPosPassThru class. (Refer to the CPosPassThru documentation for details.) In addition, however, the renderer filter must update the object's cached time stamps:

  • For each sample the filter receives, call the RegisterMediaTime method.
  • When the filter is stopped or receives an EndFlush call, call the ResetMediaTime method.
  • When the filter receives an end-of-stream notification, call the EOS method.

For an example of how to use this class, refer to the CBaseRenderer source code.

Public Methods
CRendererPosPassThru | Constructor method.
GetMediaTime | Retrieves the time stamps on the current sample.
RegisterMediaTime | Caches the time stamps from the current sample.
ResetMediaTime | Resets the cached time stamps to zero.
EOS | Updates the cached time stamps after an end-of-stream notification.

CRendererPosPassThru::CRendererPosPassThru

CRendererPosPassThru Class

Constructor method.

Syntax

CRendererPosPassThru(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    IPin *pPin
);

Parameters

pName
Pointer to the name of the object, for debugging purposes. Allocate this parameter in static memory.
pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
phr
Pointer to an HRESULT value. Ignored.
pPin
Pointer to the IPin interface of the filter's input pin.

CRendererPosPassThru::EOS

CRendererPosPassThru Class

Updates the cached time stamps after an end-of-stream notification.

Syntax

HRESULT EOS(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
E_FAIL | Failure. Possibly the filter is not streaming.

Remarks

The filter should call this method when it receives an end-of-stream notification (IPin::EndOfStream). The method sets both cached time stamps equal to the stop position, ensuring that the IMediaStream::GetCurrentPosition method returns the correct values at the end of the stream.

CRendererPosPassThru::GetMediaTime

CRendererPosPassThru Class

Retrieves the time stamps on the current sample.

Syntax

HRESULT GetMediaTime(
    LONGLONG *pStartTime,
    LONGLONG *pEndTime
);

Parameters

pStartTime
Pointer to a variable that receives the start time, in units of the current time format.
pEndTime
Pointer to a variable that receives the end time, in units of the current time format. Can be NULL.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
E_INVALIDARG | Conversion to this format is not supported.
E_POINTER | NULL pointer argument.

Remarks

This method overrides the CPosPassThru::GetMediaTime method. The time-stamp values are converted to the current time format by calling the CPosPassThru::ConvertTimeFormat method.

CRendererPosPassThru::RegisterMediaTime

CRendererPosPassThru Class

Caches the time stamps from the current sample.

Syntax

HRESULT RegisterMediaTime(
    IMediaSample *pMediaSample
);

HRESULT RegisterMediaTime(
    LONGLONG StartTime,
    LONGLONG EndTime
);

Parameters

pMediaSample
Pointer to the IMediaSample interface of the sample.
StartTime
Sample start time, in 100-nanosecond units.
EndTime
Sample end time, in 100-nanosecond units.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success.
VFW_E_MEDIA_TIME_NOT_SET | The sample is not time-stamped.

Remarks

This method stores the time stamps from the current sample. The GetMediaTime method retrieves the same values.

The filter should call this method for each sample that it receives. The method is overloaded to accept either a pointer to the sample, or the time stamp values themselves.

CRendererPosPassThru::ResetMediaTime

CRendererPosPassThru Class

Resets the cached time stamps to zero.

Syntax

HRESULT ResetMediaTime(void);

Return Value

Returns S_OK.

Remarks

The filter should call this method whenever the time stamps cached by the RegisterMediaTime method become invalid. Specifically, it should call this method in response to the IPin::EndFlush and IMediaFilter::Stop methods.

After this method is called, the GetMediaTime method returns zero for the start and end times.


CSeekingPassThru Class

Helper object that creates CPosPassThru and CRendererPosPassThru objects.

Declaration: Seekpt.h

The CPosPassThru and CRendererPosPassThru classes are helper objects that pass seeking commands upstream. The CSeekingPassThru class is a helper object for creating these helper objects. DirectShow adds further support by packaging this class as a COM component. (See SeekingPassThru.)

This class exposes the ISeekingPassThru interface. The ISeekingPassThru::Init method initializes the object. After the object is initialized, the filter can query it for the IMediaSeeking and IMediaPosition interfaces.

Filters can call the CreatePosPassThru helper function to create and initialize an instance of this object. The following code example is taken from a filter's QueryInterface method. It creates the helper object and queries it for a seeking interface:

if (riid == IID_IMediaPosition || riid == IID_IMediaSeeking) {
    if (m_pPosition == NULL)
    {
        HRESULT hr = CreatePosPassThru(GetOwner(), FALSE,
                        m_pFilter->m_pPin, &m_pPosition);
        if (FAILED(hr))
            return hr;
    }
    return m_pPosition->QueryInterface(riid, ppv);
}

Public Methods
CSeekingPassThru | Constructor method.
~CSeekingPassThru | Destructor method.
CreateInstance | Creates an instance of the object.
ISeekingPassThru Methods
Init | Initializes the object.

CSeekingPassThru::CSeekingPassThru

CSeekingPassThru Class

Constructor method.

Syntax

CPosPassThru(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
);

Parameters

pName
String containing the name of the object. See CBaseObject for more information.
pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
phr
Pointer to an HRESULT value. Ignored.

CSeekingPassThru::~CSeekingPassThru

CSeekingPassThru Class

Destructor method.

Syntax

~CPosPassThru(void);

CSeekingPassThru::CreateInstance

CSeekingPassThru Class

Creates an instance of the object. This method supports creation of the object through a class factory. For more information, see CFactoryTemplate.

Syntax

static CUnknown *CreateInstance(
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
phr
Pointer to an HRESULT value. Ignored.

Return Value

Returns a pointer to a new CSeekingPassThru object.

CSeekingPassThru::Init

CSeekingPassThru Class

Initializes the object.

Syntax

HRESULT Init(
    BOOL bSupportRendering,
    IPin *pPin
);

Parameters

bSupportRendering
[in] Boolean value that specifies whether the filter is a renderer. Use the value TRUE if the filter is a renderer, or FALSE otherwise.
pPin
Pointer to the IPin interface on the filter's input pin.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
E_FAIL | Object was already initialized.
E_OUTOFMEMORY | Not enough memory to create the object.

Remarks

If the value of bSupportRendering is TRUE, this method creates an instance of the CRendererPosPassThru class. Otherwise, it creates an instance of the CPosPassThru class.


CSource Class

CSource class hierarchy

Base class for implementing source filters.

Declaration: Source.h

A filter derived from CSource contains one or more output pins derived from the CSourceStream class. Each output pin creates a worker thread that pushes media samples downstream.

To implement an output pin:

  • Derive a class from CSourceStream.
  • Override the CSourceStream::GetMediaType method and possibly the CSourceStream::CheckMediaType method, which validate media types for the pin.
  • Implement the CBaseOutputPin::DecideBufferSize method, which returns the pin's buffer requirements.
  • Implement the CSourceStream::FillBuffer method, which fills a media sample buffer with data.

To implement the filter:

  • Derive a class from CSource.
  • In the constructor, create one or more output pins derived from CSourceStream. The pins automatically add themselves to the filter in their constructor methods, and remove themselves in their destructor methods.

To synchronize the filter state among multiple threads, call the CSource::pStateLock method. This method returns a pointer to the filter-state critical section. Use the CAutoLock class to hold the critical section. From a pin, you can access pStateLock from the pin's CBasePin.m_pFilter member variable, as follows:

CAutoLock lock(m_pFilter->pStateLock());

Note The CSource class is designed to support the push model for data flow. This class is not recommended for creating file-reader filters. File readers should support the pull model, through the IAsyncReader interface. For more information, see Data Flow for Filter Developers.

Protected Member Variables
m_iPins | Number of pins on the filter.
m_paStreams | Array of pins.
m_cStateLock | Critical section object that protects the filter state.
Public Methods
CSource | Constructor method.
~CSource | Destructor method.
GetPinCount | Retrieves the number of pins on the filter.
GetPin | Retrieves a pin.
pStateLock | Retrieves a pointer to the filter's critical section object.
AddPin | Adds a new output pin to the filter.
RemovePin | Removes a specified pin from the filter.
FindPinNumber | Retrieves the number of a specified pin on the filter.
IBaseFilter Methods
FindPin | Retrieves the pin with the specified identifier.

CSource.m_iPins

CSource Class

Number of pins on the filter.

Syntax

int m_iPins;

CSource.m_paStreams

CSource Class

Array of pins.

Syntax

CSourceStream **m_paStreams;

CSource.m_cStateLock

CSource Class

Critical section object that protects the filter state. The pStateLock helper method returns a pointer to this member variable.

Syntax

CCritSec m_cStateLock;

CSource::AddPin

CSource Class

Adds a new output pin to the filter.

Syntax

HRESULT AddPin(
    CSourceStream *pStream
);

Parameters

pStream
Pointer to the CSourceStream object that implements the pin.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success
E_OUTOFMEMORY | Insufficient memory

Remarks

The CSourceStream constructor calls this method, to add the output pin to the filter.

CSource::CSource

CSource Class

Constructor method.

Syntax

CSource(
    TCHAR *pName,
    LPUNKNOWN lpunk,
    CLSID clsid
);

Parameters

pName
Pointer to a string containing the name of the object. For more information, see CBaseObject.
lpunk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
clsid
Class identifier of the filter.

CSource::~CSource

CSource Class

Destructor method.

Syntax

~CSource(void);

CSource::FindPin

CSource Class

Retrieves the pin with the specified identifier. Implements the IBaseFilter::FindPin method.

Syntax

HRESULT FindPin(
    LPCWSTR Id,
    IPin **ppPin
);

Parameters

Id
Pointer to a null-terminated string that identifies the pin.
ppPin
Address of a variable that receives a pointer to the pin's IPin interface. If the method fails, *ppPin is set to NULL

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
E_POINTER | NULL pointer argument.
VFW_E_NOT_FOUND | Could not find a pin with this identifier.

Remarks

The first pin is "1"; the second pin is "2"; and so forth. For more information, see CSourceStream::QueryId.

CSource::FindPinNumber

CSource Class

Retrieves the number of a specified pin on the filter.

Syntax

int FindPinNumber(
    IPin *iPin
);

Parameters

iPin
Pointer to the pin's IPin interface.

Return Value

Returns the pin number, or –1 if the pin is not found on this filter. The first pin is numbered zero.

CSource::GetPin

CSource Class

Retrieves a pin. Implements the pure virtual CBaseFilter::GetPin method.

Syntax

CBasePin *GetPin(
    int n
);

Parameters

n
Number of the specified pin.

Return Value

Returns the pointer to the CBasePin object that implements the pin, or NULL if the index is out of range.

CSource::GetPinCount

CSource Class

Retrieves the number of pins on the filter. Implements the pure virtual CBaseFilter::GetPinCount method.

Syntax

int GetPinCount(void);

Return Value

Returns the number of pins on this filter.

CSource::pStateLock

CSource Class

Retrieves a pointer to the filter's critical section object.

Syntax

CCritSec* pStateLock(void);

Return Value

Returns a pointer to the m_cStateLock member variable.

CSource::RemovePin

CSource Class

Removes a specified pin from the filter. The method does not delete the pin.

Syntax

HRESULT RemovePin(
    CSourceStream *pStream
);

Parameters

pStream
Pointer to the CSourceStream object that implements the pin.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
S_FALSE | The filter does not contain this pin.

Remarks

The CSourceStream destructor calls this method, to remove the output pin from the filter.


CSourcePosition Class

CSourcePosition class hierarchy

CSourcePosition is an abstract class for implementing the IMediaPosition interface on a source filter.

This class is obsolete. If your source filter is seekable, it should expose the IMediaSeeking interface instead of IMediaPosition. You can use the CSourceSeeking base class for this purpose.

When CSourcePosition::put_CurrentPosition, CSourcePosition::put_StopTime, or CSourcePosition::put_Rate is called, CSourcePosition calls the pure virtual member function CSourcePosition::ChangeStart, CSourcePosition::ChangeStop, or CSourcePosition::ChangeRate, respectively. Override these functions in your derived class.

Protected Data Members

m_Duration | Duration of the stream.
m_pLock | Pointer to a CCritSec object for locking.
m_Rate | Sample rate.
m_Start | Start time.
m_Stop | Stop time.

Member Functions

CSourcePosition Constructs a CSourcePosition object.

Overridable Member Functions

ChangeRate | Override this pure virtual to handle notification that the rate property has changed.
ChangeStart | Override this pure virtual to handle notification that the start position property has changed.
ChangeStop | Override this pure virtual to handle notification that the stop position property has changed.

Implemented IMediaPosition Methods

get_CurrentPosition | Not currently implemented.
get_Duration | Retrieves the total duration of the media.
get_PrerollTime | Not currently implemented.
get_Rate | Retrieves the playback rate, relative to normal playback of the media.
get_StopTime | Retrieves the position within the media at which playback should stop.
put_CurrentPosition | Sets the position within the media at which playback should start.
put_PrerollTime | Not currently implemented.
put_Rate | Sets the playback rate, relative to normal playback of the media.
put_StopTime | Sets the position within the media at which playback should stop.

CSourcePosition::ChangeRate

CSourcePosition Class

Override this member function to handle notification of a change of sample rate.

Syntax

virtual HRESULT ChangeRate(void) PURE;

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This member function is called when a change to the rate has been made by a call to IMediaPosition::put_Rate. Override this and change the rate of data sent; typically, this will be by a call to CBaseInputPin::BeginFlush and CBaseInputPin::EndFlush, and then sending samples marked with new time stamps.

CSourcePosition::ChangeStart

CSourcePosition Class

Override this member function to handle notification of a change of start time.

Syntax

virtual HRESULT ChangeStart(void) PURE;

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This member function is called when a new start position has been requested by a call to IMediaPosition::put_CurrentPosition. Override this and change the data sent; typically, this will be by a call to CBaseInputPin::BeginFlush and CBaseInputPin::EndFlush, and then sending samples marked with new time stamps.

CSourcePosition::ChangeStop

CSourcePosition Class

Override this member function to handle notification of a change in stop time.

Syntax

virtual HRESULT ChangeStop(void) PURE;

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This member function is called when a change to the stop position has been made by a call to IMediaPosition::put_StopTime. Override this and ensure that the correct stop time is being observed; typically, this will be a call to CBaseInputPin::BeginFlush and CBaseInputPin::EndFlush, and then resending data.

CSourcePosition::CSourcePosition

CSourcePosition Class

Constructs a CSourcePosition object.

Syntax

CSourcePosition(

  const TCHAR *pName,

  LPUNKNOWN pUnk,

  HRESULT *phr,

  CCritSec *pLock

  );

Parameters

pName
Pointer to the name of the object used in the CSourcePosition constructor for debugging purposes.
pUnk
Pointer to the owner of this object.
phr
Pointer to an HRESULT value for resulting information.
pLock
Pointer to a CCritSec object used for locking.

Return Value

No return value.

Remarks

Allocate the pName parameter in static memory. This name appears on the debugging terminal upon creation and deletion of the object.

CSourcePosition::get_CurrentPosition

CSourcePosition Class

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT get_CurrentPosition(
  REFTIME *pllTime
);

Parameters

pllTime
Pointer to the returned start time as a double value in seconds.

Return Value

Returns E_NOTIMPL.

Remarks

Override this method if you can return the data you are actually working on. The start position is applied before the rate and therefore is the position at typical playback speed.

CSourcePosition::get_Duration

CSourcePosition Class

Retrieves the total duration of the media stream.

Syntax

HRESULT get_Duration(

  REFTIME *plength

  );

Parameters

plength
Pointer to the returned length of the media stream.

Return Value

Returns E_POINTER if pLength is invalid. Otherwise, returns S_OK.

Remarks

The duration assumes normal playback speed; it is therefore unaffected by the rate.

CSourcePosition::get_PrerollTime

CSourcePosition Class

Validates the pointer, but the preroll retrieval is not currently implemented.

Syntax

HRESULT get_PrerollTime(

  REFTIME *pllTime

  );

Parameters

pllTime
Pointer to the returned preroll time as a double value in seconds.

Return Value

Returns E_POINTER if pllTime is invalid. Otherwise, returns E_NOTIMPL.

Remarks

Preroll time is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.

CSourcePosition::get_Rate

CSourcePosition Class

Retrieves the rate of playback relative to normal playback speed.

Syntax

HRESULT get_Rate(

  double *pdRate

  );

Parameters

pdRate
Pointer to the returned rate.

Return Value

Returns E_POINTER if pdRate is invalid. Otherwise, returns S_OK.

Remarks

A rate of 1.0 indicates normal playback speed. A rate of 0.5 indicates half speed. A rate of –1.0 indicates normal speed in reverse.

CSourcePosition::get_StopTime

CSourcePosition Class

Retrieves the time at which the media stream stops.

Syntax

HRESULT get_StopTime(

  REFTIME *pllTime

  );

Parameters

pllTime
Pointer to the returned stop time as a double value in seconds.

Return Value

Returns E_POINTER if pllTime is invalid. Otherwise, returns S_OK.

Remarks

The stop time is a position between zero and the duration of the media at which playback should stop.

The stop position is applied before the rate and therefore is the position at typical playback speed.

CSourcePosition::put_CurrentPosition

CSourcePosition Class

Sets the time within the media stream that playback should begin.

Syntax

HRESULT put_CurrentPosition(
  REFTIME llTime
  );

Parameters

llTime
Start time expressed as a double value in seconds.

Return Value

Returns an HRESULT value from the call to CSourcePosition::ChangeStart.

Remarks

The start time is a position between zero and the duration of the media at which playback should begin when the next run command is issued.

Setting the start position when paused causes playback to resume from the new start position when the run command is issued.

The start position is applied before the rate and therefore is the position at typical playback speed.

CSourcePosition::put_PrerollTime

CSourcePosition Class

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT put_PrerollTime(
   REFTIME llTime
);

Parameters

llTime
Preroll time to be set.

Return Value

Returns E_NOTIMPL.

Remarks

Preroll time is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.

CSourcePosition::put_Rate

CSourcePosition Class

Sets the rate of playback relative to normal speed.

Syntax

HRESULT put_Rate(
  double dRate
  );

Parameters

dRate
Rate to set.

Return Value

Returns an HRESULT value from the call to CSourcePosition::ChangeRate.

Remarks

This property allows an application to speed up or slow down playback relative to the normal default playback speed. A rate of 1.0 indicates normal playback speed. Specifying 2.0 causes playback at twice the normal rate: a video created for 10 frames per second (fps) will be played back at 20 fps, if resources permit. Audio streams played back at above-normal speed increase the pitch rather than drop frames.

Negative rates indicate reverse play. Not all media will support reverse play.

CSourcePosition::put_StopTime

CSourcePosition Class

Sets the time at which the media stream will stop.

Syntax

HRESULT put_StopTime(
  REFTIME llTime
  );

Parameters

llTime
Stop time as a double value in seconds.

Return Value

Returns an HRESULT value from the call to CSourcePosition::ChangeStop.

Remarks

The stop time is a position between zero and the duration of the media at which playback should stop.

The stop position is applied before the rate and therefore is the position at typical playback speed.


CSourceSeeking Class

CSourceSeeking class hierarchy

Abstract class for implementing seeking in source filters with one output pin.

Declaration: Ctlutil.h.

This class supports the IMediaSeeking interface. It provides default implementations for all of the IMediaSeeking methods. Protected member variables store the start time, stop time, and current rate. By default, the only time format supported by the class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units).

Whenever the start position, stop position, or playback rate changes, the CSourceSeeking object calls a corresponding pure virtual method:

  • Start position: ChangeStart
  • Stop position: ChangeStop
  • Playback rate: ChangeRate

The derived class must implement these methods. After any seek operation, a filter must do the following:

  1. Call the IPin::BeginFlush method on the downstream input pin.
  2. Halt the worker thread that is delivering data.
  3. Call the IPin::EndFlush method on the input pin.
  4. Restart the worker thread.
  5. Call the IPin::NewSegment method on the input pin.
  6. Set the discontinuity property on the first sample. Call the IMediaSample::SetDiscontinuity method.

The call to BeginFlush frees the worker thread, if the thread is blocked waiting to deliver a sample.

In step 2, make sure that the thread has stopped sending data. Depending on the implementation, you might need to wait for the thread to exit, or for the thread to signal a response of some kind. If your filter uses the CSourceStream class, the CSourceStream::Stop method blocks until the worker thread replies.

Ideally, the new segment (step 5) should be delivered from the worker thread. It can also be done by the CSourceSeeking object, as long as the filter serializes it with the samples.

The following example shows a possible implementation. It assumes that the source filter's output pin is derived from CSourceSeeking and CSourceStream. This example defines a helper method, UpdateFromSeek, that performs steps 1–4. The CSourceStream::OnThreadStartPlay method is overridden to send the new segment, and to set a flag indicating the discontinuity. The worker thread picks up this flag and calls the IMediaSample::SetDiscontinuity method:

void CMyStream::UpdateFromSeek()
{
    if (ThreadExists())
    {
        DeliverBeginFlush();
        Stop();
        DeliverEndFlush();
        Run();
    }
}

HRESULT CMyStream::OnThreadStartPlay()
{
    m_bDiscontinuity = TRUE;
    return DeliverNewSegment(m_rtStart, m_rtStop, m_dRateSeeking);
}

Protected Member Variables
m_rtDuration | Duration of the stream.
m_rtStart | Start time.
m_rtStop | Stop time.
m_dRateSeeking | Playback rate.
m_dwSeekingCaps | Seeking capabilities.
m_pLock | Pointer to a critical section object for locking.
Protected Methods
CSourceSeeking | Constructor method.
Pure Virtual Methods
ChangeRate | Called when the playback rate changes.
ChangeStart | Called when the start position changes.
ChangeStop | Called when the stop position changes.
IMediaSeeking Methods
IsFormatSupported | Determines whether a specified time format is supported.
QueryPreferredFormat | Retrieves the object's preferred time format.
SetTimeFormat | Sets the time format.
IsUsingTimeFormat | Determines whether a specified time format is the format currently in use.
GetTimeFormat | Retrieves the current time format.
GetDuration | Retrieves the duration of the stream.
GetStopPosition | Retrieves the time at which the playback will stop, relative to the duration of the stream.
GetCurrentPosition | Retrieves the current position, relative to the total duration of the stream.
GetCapabilities | Retrieves all the seeking capabilities of the stream.
CheckCapabilities | Queries whether the stream has specified seeking capabilities.
ConvertTimeFormat | Converts from one time format to another.
SetPositions | Sets the current position and the stop position.
GetPositions | Retrieves the current position and the stop position.
GetAvailable | Retrieves the range of times in which seeking is efficient.
SetRate | Sets the playback rate.
GetRate | Retrieves the playback rate.
GetPreroll | Retrieves the preroll time.

CSourceSeeking.m_rtDuration

CSourceSeeking Class

Duration of the stream. By default, the value is set to the value of the m_rtStop member variable.

Syntax

CRefTime m_rtDuration;

CSourceSeeking.m_rtStart

CSourceSeeking Class

Start time. By default, the value is set to zero.

Syntax

CRefTime m_rtStart;

CSourceSeeking.m_rtStop

CSourceSeeking Class

Stop time. By default, the value is set to a very large number. The derived class can reset the value in its constructor, or when the filter is initialized.

Syntax

CRefTime m_rtStop;

CSourceSeeking.m_dRateSeeking

CSourceSeeking Class

Playback rate. By default, the value is set to 1.0.

Syntax

double m_dRateSeeking;

CSourceSeeking.m_dwSeekingCaps

CSourceSeeking Class

Seeking capabilities.

Syntax

DWORD m_dwSeekingCaps;

Remarks

By default, the value is set to the bitwise combination of the following flags:

  • AM_SEEKING_CanSeekForwards
  • AM_SEEKING_CanSeekBackwards
  • AM_SEEKING_CanSeekAbsolute
  • AM_SEEKING_CanGetStopPos
  • AM_SEEKING_CanGetDuration

If the filter supports a different set of capabilities, it should override this value.

CSourceSeeking.m_pLock

CSourceSeeking Class

Pointer to a critical section object for locking.

Syntax

CCritSec *m_pLock;

CSourceSeeking::ChangeRate

CSourceSeeking Class

Called when the playback rate changes.

Syntax

virtual HRESULT ChangeRate(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

The SetRate method calls this method, which the derived class must implement. The SetRate method updates the m_dRateSeeking member variable, but does not validate the new value. A rate of zero should always be rejected. Rates less than zero indicate negative playback. Most filters do not support negative rates.

The following example shows a possible implementation:

HRESULT CMyStream::ChangeRate( )
{
    {
        CAutoLock cAutoLockSeeking(CSourceSeeking::m_pLock);
        if( m_dRateSeeking <= 0 ) {
            m_dRateSeeking = 1.0;  // Reset to a reasonable value.
            return E_FAIL;
        }
    }
    UpdateFromSeek();
    return S_OK;
}

CSourceSeeking::ChangeStart

CSourceSeeking Class

Called when the start position changes.

Syntax

virtual HRESULT ChangeStart(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

The SetPositions method calls this method if the start position changes. This method is pure virtual; the derived class must implement it. After a seek operation, time stamps should restart from zero. Media times should reflect the new start time. The following example shows a possible implementation:

HRESULT CMyStream::ChangeStart( )
{
    m_rtSampleTime = 0;          // Reset the time stamps.
    m_rtMediaTime = m_rtStart;   // Reset the media times.
    UpdateFromSeek();
    return S_OK;
}

CSourceSeeking::ChangeStop

CSourceSeeking Class

Called when the stop position changes.

Syntax

virtual HRESULT ChangeStop(void) PURE;

Return Value

Returns an HRESULT value.

Remarks

The SetPositions method calls this method if the stop position changes. This method is pure virtual; the derived class must implement it. The following example shows a possible implementation:

HRESULT CMyStream::ChangeStop( )
{
    UpdateFromSeek();
    return S_OK;
}

CSourceSeeking::CheckCapabilities

CSourceSeeking Class

Queries whether the stream has specified seeking capabilities. Implements the IMediaSeeking::CheckCapabilities method.

Syntax

HRESULT CheckCapabilities(
    DWORD *pCapabilities
);

Parameters

pCapabilities
Pointer to a bitwise combination of one or more AM_SEEKING_SEEKING_CAPABILITIES attributes.

Return Value

Returns one of the HRESULT values listed in the following table.

S_FALSE | Not all of the capabilities in pCapabilities are present.
S_OK | All capabilities in pCapabilities are present.
E_POINTER | NULL pointer argument.

Remarks

As implemented, this method checks the value of *pCapabilities against the m_dwSeekingCaps member variable. However, it does not set *pCapabilities equal to m_dwSeekingCaps, as described for the IMediaSeeking::CheckCapabilities method. Also, in the case where none of the specified capabilities are available, the method does not return E_FAIL. A more complete implementation would be as follows:

DWORD dwCaps;
HRESULT hr = GetCapabilities(&dwCaps);
if (SUCCEEDED(hr))
{
    dwCaps &= *pCapabilities;
    hr =  dwCaps ? ( dwCaps == *pCapabilities ? S_OK : S_FALSE ) : E_FAIL;
    *pCapabilities = dwCaps;
}
else *pCapabilities = 0;
return hr;

CSourceSeeking::ConvertTimeFormat

CSourceSeeking Class

Converts from one time format to another. Implements the IMediaSeeking::ConvertTimeFormat method.

Syntax

HRESULT ConvertTimeFormat(
    LONGLONG *pTarget,
    const GUID *pTargetFormat,
    LONGLONG Source,
    const GUID *pSourceFormat
);

Parameters

pTarget
Pointer to a variable that receives the converted time.
pTargetFormat
Pointer to the time format GUID of the target format. If NULL, the current format is used.
Source
Time value to be converted.
pSourceFormat
Pointer to the time format GUID of the format to convert. If NULL, the current format is used.

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success
E_INVALIDARG | Invalid argument
E_POINTER | NULL pointer argument

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units). This method returns E_INVALIDARG, except in the trivial case where pTargetFormat and pSourceFormat both specify TIME_FORMAT_MEDIA_TIME.

CSourceSeeking::CSourceSeeking

CSourceSeeking Class

Constructor method.

Syntax

CSourceSeeking(
    const TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr,
    CCritSec *pLock
);

Parameters

pName
Pointer to a string containing the name of the object. For more information, see CBaseObject.
pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
phr
Pointer to an HRESULT value. Ignored.
pLock
Pointer to a CCritSec object that protects shared data used by this class.

CSourceSeeking::GetAvailable

CSourceSeeking Class

Retrieves the range of times in which seeking is efficient. Implements the IMediaSeeking::GetAvailable method.

Syntax

HRESULT GetAvailable(
    LONGLONG *pEarliest,
    LONGLONG *pLatest
);

Parameters

pEarliest
Pointer to a variable that receives the earliest time for efficient seeking. The variable is set to zero.
pLatest
Pointer to a variable that receives the latest time for efficient seeking. The variable is set to the value of the m_rtDuration member variable.

Return Value

Returns S_OK.

CSourceSeeking::GetCapabilities

CSourceSeeking Class

Retrieves all the seeking capabilities of the stream. Implements the IMediaSeeking::GetCapabilities method.

Syntax

HRESULT GetCapabilities(
    DWORD *pCapabilities
);

Parameters

pCapabilities
Pointer to a variable that receives a bitwise combination of AM_SEEKING_SEEKING_CAPABILITIES flags.

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success
E_POINTER | NULL pointer value

Remarks

The seeking capabilities are specified by the m_dwSeekingCaps member variable.

CSourceSeeking::GetCurrentPosition

CSourceSeeking Class

Retrieves the current position, relative to the total duration of the stream. Not implemented.

Syntax

HRESULT GetCurrentPosition(
  LONGLONG *pCurrent
);

Parameters

pCurrent
Pointer to a variable that receives the current position, in units of the current time format.

Return Value

Returns E_NOTIMPL.

Remarks

Source filters typically do not support this method. Instead, renderer filters report the current position through the CRendererPosPassThru class.

CSourceSeeking::GetDuration

CSourceSeeking Class

Retrieves the duration of the stream. Implements the IMediaSeeking::GetDuration method.

Syntax

HRESULT GetDuration(
    LONGLONG *pDuration
);

Parameters

pDuration
Pointer to a variable that receives the duration, in units of the current time format.

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success
E_POINTER | NULL pointer value

Remarks

The duration is specified by the m_rtDuration member variable.

CSourceSeeking::GetPositions

CSourceSeeking Class

Retrieves the current position and the stop position. Implements the IMediaSeeking::GetPositions method.

Syntax

HRESULT GetPositions(
    LONGLONG *pCurrent,
    LONGLONG *pStop
);

Parameters

pCurrent
Pointer to a variable that receives the start position.
pStop
Pointer to a variable that receives the stop position.

Return Value

Returns S_OK.

Remarks

For the pCurrent parameter, this method returns the value of the m_rtStart member variable, which represents the latest seek time, not the current streaming position. However, when an application calls IMediaSeeking::GetPositions through the filter graph manager, the values typically come from a renderer filter, not a source filter.

CSourceSeeking::GetPreroll

CSourceSeeking Class

Retrieves the preroll time. Implements the IMediaSeeking::GetPreroll method.

Syntax

HRESULT GetPreroll(
    LONGLONG *pPreroll
);

Parameters

pPreroll
Pointer to a variable that receives the preroll time. The value is set to zero.

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success
E_POINTER | NULL pointer value

CSourceSeeking::GetRate

CSourceSeeking Class

Retrieves the playback rate. Implements the IMediaSeeking::GetRate method.

Syntax

HRESULT GetRate(
    double *pdRate
);

Parameters

pdRate
Pointer to a variable that receives the playback rate.

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success
E_POINTER | NULL pointer value

Remarks

The playback rate is specified by the m_dRateSeeking member variable.

CSourceSeeking::GetStopPosition

CSourceSeeking Class

Retrieves the time at which the playback will stop, relative to the duration of the stream. Implements the IMediaSeeking::GetStopPosition method.

Syntax

HRESULT GetStopPosition(
    LONGLONG *pStop
);

Parameters

pStop
Pointer to a variable that receives the stop time, in units of the current time format.

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success
E_POINTER | NULL pointer value

Remarks

The stop time is specified by the m_rtStop member variable.

CSourceSeeking::GetTimeFormat

CSourceSeeking Class

Retrieves the current time format. Implements the IMediaSeeking::GetTimeFormat method.

Syntax

HRESULT GetTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat
Pointer to a variable that receives a time format GUID.

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success
E_POINTER | NULL pointer value

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units).

CSourceSeeking::IsFormatSupported

CSourceSeeking Class

Determines whether a specified time format is supported. Implements the IMediaSeeking::IsFormatSupported method.

Syntax

HRESULT IsFormatSupported(
    const GUID *pFormat
);

Parameters

pFormat
Pointer to a time format GUID.

Return Value

Returns one of the HRESULT values listed in the following table.

S_FALSE | The format is not supported.
S_OK | The format is supported.
E_POINTER | NULL pointer argument.

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units).

CSourceSeeking::IsUsingTimeFormat

CSourceSeeking Class

Determines whether a specified time format is the format currently in use.

Syntax

HRESULT IsUsingTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat
Pointer to a time format GUID.

Return Value

Returns one of the HRESULT values listed in the following table.

S_FALSE | The specified format is not the current format.
S_OK | The specified format is the current format.
E_POINTER | NULL pointer argument.

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units).

CSourceSeeking::QueryPreferredFormat

CSourceSeeking Class

Retrieves the object's preferred time format. Implements the IMediaSeeking::QueryPreferredFormat method.

Syntax

HRESULT QueryPreferredFormat(
    GUID *pFormat
);

Parameters

pFormat
Pointer to a variable that receives a time format GUID.

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success
E_POINTER | NULL pointer value

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units).

CSourceSeeking::SetPositions

CSourceSeeking Class

Sets the current position and the stop position. Implements the IMediaSeeking::SetPositions method.

Syntax

HRESULT SetPositions(
    LONGLONG *pCurrent,
    DWORD CurrentFlags,
    LONGLONG *pStop,
    DWORD StopFlags
);

Parameters

pCurrent
Pointer to a variable that specifies the current position.
CurrentFlags
Bitwise combination of flags. See Remarks.
pStop
Pointer to a variable that specifies the stop time, in units of the current time format.
StopFlags
Bitwise combination of flags. See Remarks.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_OK | Success
E_INVALIDARG | Invalid flags
E_POINTER | NULL pointer argument

Remarks

The following flags are supported:

  • AM_SEEKING_NoPositioning
  • AM_SEEKING_AbsolutePositioning
  • AM_SEEKING_RelativePositioning
  • AM_SEEKING_IncrementalPositioning (pStop only)

For more information, see IMediaSeeking::SetPositions.

This method updates the values of the m_rtStart and m_rtStop member variables, and then calls the pure virtual methods ChangeStart and ChangeStop.

CSourceSeeking::SetRate

CSourceSeeking Class

Sets the playback rate. Implements the IMediaSeeking::SetRate method.

Syntax

HRESULT SetRate(
    double dRate
);

Parameters

dRate
Playback rate.

Return Value

Returns an HRESULT value.

Remarks

This method updates the value of the m_dRateSeeking member variable, and then calls the pure virtual method ChangeRate. The method does not validate the dRate parameter.

CSourceSeeking::SetTimeFormat

CSourceSeeking Class

Sets the time format. Implements the IMediaSeeking::SetTimeFormat method.

Syntax

HRESULT SetTimeFormat(
    const GUID *pFormat
);

Parameters

pFormat
Pointer to a time format GUID.

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success.
E_INVALIDARG | Specified format is not supported.
E_POINTER | NULL pointer argument.

Remarks

The only time format supported by the base class is TIME_FORMAT_MEDIA_TIME (100-nanosecond units).


CSourceStream Class

CSourceStream class hierarchy

Output pin for the CSource filter class.

Declaration: Source.h

For information on using this class, see CSource. This class inherits the CAMThread class, which provides a worker thread for streaming data from the pin. The CSourceStream class implements the following helper methods to send requests to the thread:

  • Exit
  • Init
  • Pause
  • Run
  • Stop

The first request to the thread must be Init. The Exit request terminates the thread. In practice, it is not necessary to call any of these methods directly, because the pin's Active and Inactive methods call them as needed.

The class also provides several "handler" methods:

  • OnThreadCreate
  • OnThreadDestroy
  • OnThreadStartPlay

These do nothing in the base class, but the derived class can override them.

Protected Member Variables
m_pFilter | Pointer to the filter that contains this pin.
Protected Methods
OnThreadCreate | Called when the streaming thread is initialized. Virtual.
OnThreadDestroy | Called when the streaming thread is about to exit. Virtual.
OnThreadStartPlay | Called at the start of the DoBufferProcessingLoop method. Virtual.
Active | Notifies the pin that the filter is now active.
Inactive | Notifies the pin that the filter is no longer active.
GetRequest | Waits for the next thread request.
CheckRequest | Checks if there is a thread request, without blocking.
ThreadProc | Thread procedure. Virtual.
DoBufferProcessingLoop | Generates media data and delivers it to the downstream input pin. Virtual.
CheckMediaType | Determines if the pin accepts a specific media type. Virtual.
GetMediaType | Retrieves a preferred media type. Virtual.
Public Methods
CSourceStream | Constructor method.
~CSourceStream | Destructor method. Virtual.
Init | Initializes the streaming thread.
Exit | Signals the streaming thread to exit.
Run | Signals the streaming thread to run.
Pause | Signals the streaming thread to become active.
Stop | Signals the streaming thread to stop.
Pure Virtual Methods
FillBuffer | Fills a media sample with data.
IPin Methods
QueryId | Retrieves an identifier for the pin.

CSourceStream.m_pFilter

CSourceStream Class

Pointer to the filter that contains this pin.

Syntax

CSource *m_pFilter;

CSourceStream::Active

CSourceStream Class

Notifies the pin that the filter is now active. Overrides the CBasePin::Active method. If the pin is connected, this method starts the streaming thread.

Syntax

HRESULT Active(void);

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_FALSE | Pin is already active.
S_OK | Success.
E_FAIL | Could not start the thread.

CSourceStream::CheckMediaType

CSourceStream Class

Determines if the pin accepts a specific media type. Implements the pure virtual CBasePin::CheckMediaType method.

Syntax

virtual HRESULT CheckMediaType(
    CMediaType *pMediaType
);

Parameters

pMediaType
Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | This pin supports this media type.
E_FAIL | The pin does not support this media type.

Remarks

By default, the pin supports a single media type. This method retrieves the supported type by calling the single-parameter version of the GetMediaType method, and compares it to the proposed type. If your pin supports more than one media type, override this method.

CSourceStream::CheckRequest

CSourceStream Class

Checks if there is a thread request, without blocking.

Syntax

BOOL CheckRequest(
    Command *pCom
);

Parameters

pCom
Pointer to a variable that receives the value passed in the last call to the CAMThread::CallWorker method.

Return Value

Returns TRUE if there is a pending request, or FALSE otherwise.

Remarks

This method overrides the CAMThread::CheckRequest method to perform type-checking. The CSourceStream class defines the following enumerated type for the pCom parameter:

enum Command {CMD_INIT, CMD_PAUSE, CMD_RUN, CMD_STOP, CMD_EXIT};

CSourceStream::CSourceStream

CSourceStream Class

Constructor method.

Syntax

CSourceStream(
    TCHAR *pObjectName,
    HRESULT *phr,
    CSource *pms,
    LPCWSTR pName
);

Parameters

pObjectName
Pointer to a string containing the debug name of the pin.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.
pms
Pointer to the CSource filter that created this pin.
pName
Pointer to a string that contains the name of the pin.

Remarks

The string given in the pObjectName parameter is used strictly for debugging purposes. For more information, see CBaseObject.

The string given in the pName parameter is the name returned by the IPin::QueryPinInfo method. This name is not used for the pin identifier that the QueryId method returns. Instead, QueryId calculates a pin identifier based on the pin number. (Pin identifiers support graph persistence. For more information, see IPin::QueryId.)

CSourceStream::~CSourceStream

CSourceStream Class

Destructor method.

Syntax

~CSourceStream(void);

CSourceStream::DoBufferProcessingLoop

CSourceStream Class

Generates media data and delivers it to the downstream input pin.

Syntax

virtual HRESULT DoBufferProcessingLoop(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | Thread received a stop request.
S_OK | Stream ended, or downstream filter is not accepting samples.

Remarks

This method implements the main loop that processes data and delivers it downstream. Each time through the loop, the method retrieves an empty media sample from the allocator. It passes the sample to the FillBuffer method. The FillBuffer method—which the derived class must implement—then generates media data and moves it into the sample buffer.

The loop ends when any of the following occurs:

  • The input pin's IMemInputPin::Receive method rejects a sample.
  • The FillBuffer method returns S_FALSE, indicating the end of the stream, or returns an error code.
  • The thread receives a Stop request.

The DoBufferProcessingLoop method handles the end-of-stream notification. If an error occurs, it sends an EC_ERRORABORT event to the filter graph manager.

CSourceStream::Exit

CSourceStream Class

Signals the streaming thread to exit.

Syntax

HRESULT Exit(void);

Return Value

Returns S_OK or E_UNEXPECTED.

Remarks

The Inactive method calls this method.

CSourceStream::FillBuffer

CSourceStream Class

Fills a media sample with data.

Syntax

virtual HRESULT FillBuffer(
    IMediaSample *pSample
) PURE;

Parameters

pSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | End of stream
S_OK | Success

Remarks

The derived class must implement this method.

The media sample given to this method has no time stamps. The derived class should call the IMediaSample::SetTime method to set the time stamps. If appropriate for the media type, the derived class should also set the media times, by calling the IMediaSample::SetMediaTime method. For more information, see Time and Clocks in DirectShow.

CSourceStream::GetMediaType

CSourceStream Class

Retrieves a preferred media type.

Syntax

virtual HRESULT GetMediaType(
    int iPosition,
    CMediaType *pMediaType
);

virtual HRESULT GetMediaType(
    CMediaType *pMediaType
);

Parameters

iPosition
Zero-based index value.
pMediaType
Pointer to a CMediaType object that receives the media type.

Return Value

Returns one of the HRESULT values shown in the following table.
S_OK | Success.
VFW_S_NO_MORE_ITEMS | Index out of range.
E_INVALIDARG | Index less than zero.
E_UNEXPECTED | Unexpected error.

Remarks

There are two versions of this method. One version overrides the CBasePin::GetMediaType method and takes an index value as a parameter. The other version is designed to retrieve a single media type, so it lacks the index parameter.

The single-parameter method returns E_UNEXPECTED. The two-parameter method checks that the iPosition parameter is 1, and then calls the single-parameter version. Depending on the number of media types the pin supports, you must override one of these methods:

  • If the pin supports exactly one media type, override the single-parameter version. Fill in the media type that the pin supports.
  • If the pin supports more than one media type, override the two-parameter version. Also override the CheckMediaType method.

CSourceStream::GetRequest

CSourceStream Class

Waits for the next thread request.

Syntax

Command GetRequest(void);

Return Value

Returns the next thread request.

Remarks

This method overrides the CAMThread::GetRequest method. The return value is cast to the following enumerated type:

enum Command {CMD_INIT, CMD_PAUSE, CMD_RUN, CMD_STOP, CMD_EXIT};

CSourceStream::Inactive

CSourceStream Class

Notifies the pin that the filter is no longer active. Overrides the CBasePin::Inactive method. If the streaming thread is active, this method stops it and waits for the thread to exit.

Syntax

HRESULT Inactive(void);

Return Value

Returns S_OK or another HRESULT value.

CSourceStream::Init

CSourceStream Class

Initializes the streaming thread.

Syntax

HRESULT Init(void);

Return Value

Returns S_OK, or another HRESULT value.

Remarks

This method must be the first thread request sent to the ThreadProc method. The Active method calls this method.

CSourceStream::OnThreadCreate

CSourceStream Class

Called when the streaming thread is initialized.

Syntax

virtual HRESULT OnThreadCreate(void);

Return Value

Returns S_OK.

Remarks

The thread procedure, ThreadProc, calls this method when it first receives an Init request. The method does nothing in the base class. The derived class can override this method to perform thread initializations. If the derived class returns an error code, the thread exits with an error.

CSourceStream::OnThreadDestroy

CSourceStream Class

Called when the streaming thread is about to exit.

Syntax

virtual HRESULT OnThreadDestroy(void);

Return Value

Returns S_OK.

Remarks

The thread procedure, ThreadProc, calls this method before it exits. The method does nothing in the base class; it is available for the derived class to override. If the derived class returns an error code, the thread exits with an error.

CSourceStream::OnThreadStartPlay

CSourceStream Class

Called at the start of the DoBufferProcessingLoop method.

Syntax

virtual HRESULT OnThreadStartPlay(void);

Return Value

Returns S_OK.

Remarks

This method does nothing in the base class; it is available for the derived class to override.

CSourceStream::Pause

CSourceStream Class

Signals the streaming thread to become active.

Syntax

HRESULT Pause(void);

Return Value

Returns S_OK or E_UNEXPECTED.

Remarks

The Active method calls this method. When the ThreadProc method receives this request, it calls the DoBufferProcessingLoop method.

CSourceStream::QueryId

CSourceStream Class

Retrieves an identifier for the pin.

Syntax

HRESULT QueryId(
    LPWSTR *Id
);

Parameters

Id
Pointer to a variable that receives a string containing the pin identifier.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_NOT_FOUND | Pin was not found on the filter.

Remarks

This method implements the IPin::QueryId method. To construct an identifier string, the pin calls the CSource::FindPinNumber method with itself as the parameter. The FindPinNumber method returns the pin number, indexed from zero. QueryId increments the return value by one and converts the result to a string. For example, the first pin becomes "1"; the second pin becomes "2"; and so forth.

If this method returns VFW_E_NOT_FOUND, it indicates that the filter's array of pins is invalid, presumably caused by a bug in the filter.

CSourceStream::Run

CSourceStream Class

Signals the streaming thread to run.

Syntax

HRESULT Run(void);

Return Value

Returns S_OK or E_UNEXPECTED.

Remarks

In the base class, this method has the same effect as the Pause request, and is not used.

CSourceStream::Stop

CSourceStream Class

Signals the streaming thread to stop.

Syntax

HRESULT Stop(void);

Return Value

Returns S_OK or E_UNEXPECTED.

Remarks

The Inactive method calls this method.

CSourceStream::ThreadProc

CSourceStream Class

Thread procedure. Implements the pure virtual CAMThread::ThreadProc method.

Syntax

virtual DWORD ThreadProc(void);

Return Value

Returns 0 if the thread completed successfully or 1 otherwise. If the return value is 1, the thread's resources might still be allocated.

Remarks

This method waits indefinitely for thread requests, by calling the CAMThread::GetRequest method. If it receives a Run or Pause request, it calls the DoBufferProcessingLoop method. The DoBufferProcessingLoop method pushes data until it receives a Stop request. The thread procedure exits when it receives an Exit request.


CSystemClock Class

CSystemClock class hierarchy

The CSystemClock class implements a system clock that provides time information and timing signals to an application. It uses the CBaseReferenceClock base class to provide most of that functionality, adding persistence.

CSystemClock implements the IPersist interface. For more implementation information, see "OLE Programmers Reference (Vol. 1): Structured Storage Overview."

Member Functions

CreateInstance | Creates an instance of a system clock.
CSystemClock | Constructs a CSystemClock object.

Implemented IPersist Methods

GetClassID Retrieves the class identifier for this clock (CLSID_SystemClock).

Implemented INonDelegatingUnknown Methods

NonDelegatingQueryInterface Passes out pointers to IID_IPersist, and calls the base clock for other interface queries.

CSystemClock::CreateInstance

CSystemClock Class

Creates a new instance when placed in the factory template table.

Syntax

static CUnknown * WINAPI CreateInstance(
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pUnk
Pointer to the controlling IUnknown interface.
phr
Pointer to an HRESULT value in which to return resulting information.

Return Value

Returns a pointer to a new Component Object Model (COM) object.

Remarks

This member function is required to create objects using the class factory. It calls the class constructor.

The phr parameter will be modified only if a failure occurs. If it is a failure code on input, construction can be terminated, but in any case the destructor will be called by the creator when the HRESULT error is detected.

CSystemClock::CSystemClock

CSystemClock Class

Constructs a CSystemClock object.

Syntax

CSystemClock(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    HRESULT *phr
);

Parameters

pName
Pointer to the name of this object (used for debugging only).
pUnk
Pointer to the controlling IUnknown interface.
phr
Pointer to the HRESULT value that will be set if an error occurs.

Return Value

No return value.

Remarks

If phr points to something other than S_OK upon entry, the object will not be constructed. If an error occurs during construction, this variable will be set; otherwise, its contents will not be altered.

CSystemClock::GetClassID

CSystemClock Class

Retrieves the class identifier for this clock.

Syntax

HRESULT GetClassID(
    CLSID *pClsID
);

Parameters

pClsID
Pointer to a CLSID structure that is filled with CLSID_SystemClock.

Return Value

Returns an HRESULT value.

CSystemClock::NonDelegatingQueryInterface

CSystemClock Class

Retrieves an interface and increments the reference count.

Syntax

HRESULT NonDelegatingQueryInterface(
    REFIID riid,
    void **ppv
);

Parameters

riid
Reference identifier.
ppv
Address of a pointer to the interface.

Return Value

Returns E_POINTER if ppv is invalid. Returns NOERROR if the query is successful or E_NOINTERFACE if it is not.

Remarks

This member function implements the INonDelegatingUnknown::NonDelegatingQueryInterface method and passes out references to the IReferenceClock, IPersist, and IUnknown interfaces.


CTransformFilter Class

CTransformFilter class hierarchy

Base class for implementing a transform filter.

Declaration: Transfrm.h

This class is designed for implementing a transform filter with one input pin and one output pin. It uses separate allocators for the input pin and the output pin. To create a filter that processes data in place, use the CTransInPlaceFilter class.

This filter uses the CTransformInputPin class for its input pin, and the CTransformOutputPin class for its output pin. Typically, you do not need to override these pin classes. Most of the pin methods call corresponding methods on the CTransformFilter class, so you can override the filter methods if necessary. The filter creates both pins in the GetPin method. If you do override the pin classes, you must override GetPin to create your custom pins.

By default, the input pin does not propose a media type during the connection process. Therefore, the input connection will be made using a media type proposed by the upstream filter (assuming that any are valid). You should still register the input media types when you register the filter, so that the filter mapper will find it. For more information, see How to Register DirectShow Filters.

The output pin proposes a media type through the filter's GetMediaType method, which the derived class must implement. The output pin will refuse a connection unless the input pin has been connected.

This class does not queue the output data. Each output sample is delivered from inside the IMemInputPin::Receive method.

To use this class, derive a new class from CTransformFilter and implement the following methods:

  • CheckInputType
  • CheckTransform
  • DecideBufferSize
  • GetMediaType
  • Transform

You might need to override other methods as well, depending on the requirements of your filter.

Protected Member Variables
m_bEOSDelivered | Flag that indicates whether the filter has sent an end-of-stream notification.
m_bSampleSkipped | Flag that indicates whether the most recent sample was dropped.
m_bQualityChanged | Flag that indicates whether the quality has changed.
m_csFilter | Critical section that protects the filter state.
m_csReceive | Critical section that protects the streaming state.
m_pInput | Pointer to the input pin.
m_pOutput | Pointer to the output pin.
Public Methods
CTransformFilter | Constructor method.
~CTransformFilter | Destructor method.
GetPinCount | Retrieves the number of pins on the filter. Virtual.
GetPin | Retrieves a pin. Virtual.
Transform | Transforms an input sample to produce an output sample. Virtual.
StartStreaming | Called when the filter switches to the paused state. Virtual.
StopStreaming | Called when the filter switches to the stopped state. Virtual.
AlterQuality | Notifies the filter that a quality change is requested. Virtual.
SetMediaType | Called when the media type is set on one of the filter's pins. Virtual.
CheckConnect | Determines whether a pin connection is suitable. Virtual.
BreakConnect | Releases a pin from a connection. Virtual.
CompleteConnect | Completes a pin connection. Virtual.
Receive | Receives a media sample, processes it, and delivers an output sample to the downstream filter. Virtual.
InitializeOutputSample | Retrieves a new output sample and initializes it.
EndOfStream | Notifies the filter that no additional data is expected from the input pin. Virtual.
BeginFlush | Begins a flush operation. Virtual.
EndFlush | Ends a flush operation. Virtual.
NewSegment | Notifies the filter that media samples received after this call are grouped as a segment. Virtual.
Pure Virtual Methods
CheckInputType | Checks whether a specified media type is acceptable for input.
CheckTransform | Checks whether an input media type is compatible with an output media type.
DecideBufferSize | Sets the output pin's buffer requirements.
GetMediaType | Retrieves a preferred media type for the output pin.
IMediaFilter Methods
Stop | Stops the filter.
Pause | Pauses the filter.
IBaseFilter Methods
FindPin | Retrieves the pin with the specified identifier.

CTransformFilter.m_bEOSDelivered

CTransformFilter Class

Flag that indicates whether the filter has sent an end-of-stream notification.

Syntax

BOOL m_bEOSDelivered;

Syntax

If the filter pauses when it does not have an input connection, it sends an end-of-stream notification downstream and sets this flag to TRUE. The end-of-stream notification ensures that the downstream filter does not wait for samples. Note that the filter's EndOfStream method does not set this flag.

CTransformFilter.m_bSampleSkipped

CTransformFilter Class

Flag that indicates whether the most recent sample was dropped. If the Receive method drops a sample, it sets the value to TRUE.

Syntax

BOOL m_bSampleSkipped;

CTransformFilter.m_bQualityChanged

CTransformFilter Class

Flag that indicates whether the quality has changed. The first time that the filter drops a sample, it sends an EC_QUALITY_CHANGE event to the filter graph manager and sets this flag to TRUE. It does not send this event again until the filter stops and restarts, even if it continues to drop samples in the meantime.

Syntax

BOOL m_bQualityChanged;

CTransformFilter.m_csFilter

CTransformFilter Class

Critical section that protects the filter state. For more information, see Data Flow for Filter Developers.

Syntax

CCritSec m_csFilter;

CTransformFilter.m_csReceive

CTransformFilter Class

Critical section that protects the streaming state. For more information, see Data Flow for Filter Developers.

Syntax

CCritSec m_csReceive;

CTransformFilter.m_pInput

CTransformFilter Class

Pointer to the input pin.

Syntax

CTransformInputPin *m_pInput;

CTransformFilter.m_pOutput

CTransformFilter Class

Pointer to the output pin.

Syntax

CTransformOutputPin *m_pOutput;

CTransformFilter::AlterQuality

CTransformFilter Class

Notifies the filter that a quality change is requested.

Syntax

virtual HRESULT AlterQuality(
    Quality q
);

Parameters

q
Quality structure that contains the quality control message.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | Did not handle the quality message. The message should be passed upstream.
S_OK | Handled the quality message. No further action is necessary.

The base class returns S_FALSE.

Remarks

Override this method if the filter can perform quality control. For more information, see Quality-Control Management.

CTransformFilter::BeginFlush

CTransformFilter Class

Begins a flush operation.

Syntax

virtual HRESULT BeginFlush(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

At the start of a flush operation, the input pin's CTransformInputPin::BeginFlush method calls this method. This method passes the BeginFlush call downstream.

If the derived class uses a worker thread to deliver samples, it should discard any queued data during a flush operation. That can be done either in the BeginFlush method, or in the EndFlush method. However, note that calls to BeginFlush are not synchronized with the streaming thread. If the BeginFlush method discards the queued data, the filter must be careful not to process any more data between the BeginFlush and EndFlush calls. For more information, see Data Flow for Filter Developers.

CTransformFilter::BreakConnect

CTransformFilter Class

Releases a pin from a connection.

Syntax

virtual HRESULT BreakConnect(
    PIN_DIRECTION dir
);

Parameters

dir
Member of the PIN_DIRECTION enumerated type, specifying which pin connection was broken (input or output).

Return Value

Returns S_OK.

Remarks

The CTransformInputPin::BreakConnect and CTransformOutputPin::BreakConnect methods call this method when a pin connection is broken. This method does nothing in the base class. If you override the CheckConnect method, override this method to release any resources obtained in the CheckConnect method, including interface pointers.

CTransformFilter::CheckConnect

CTransformFilter Class

Determines whether a pin connection is suitable.

Syntax

virtual HRESULT CheckConnect(
    PIN_DIRECTION dir,
    IPin *pPin
);

Parameters

dir
Member of the PIN_DIRECTION enumerated type, specifying which pin on the filter is making the connection.
pPin
Pointer to the IPin interface of the other pin in this connection attempt.

Return Value

Returns S_OK.

Remarks

The CTransformInputPin::CheckConnect and CTransformOutputPin::CheckConnect methods call this method during the pin connection process. This method does nothing in the base class. The derived class can override it. For example, the derived class might query the other pin for a particular interface.

CTransformFilter::CheckInputType

CTransformFilter Class

Checks whether a specified media type is acceptable for input.

Syntax

virtual HRESULT CheckInputType(
    const CMediaType *mtIn
) PURE;

Parameters

mtIn
Pointer to a CMediaType object that specifies the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Media type is acceptable.
VFW_E_TYPE_NOT_ACCEPTED | Media type is not acceptable.

Remarks

The derived class must implement this method. Return S_OK if the proposed input format is acceptable, or an error code otherwise.

This method does not need to verify that the input format is compatible with the output format (if any). The input pin verifies that by calling the CheckTransform method.

CTransformFilter::CheckTransform

CTransformFilter Class

Checks whether an input media type is compatible with an output media type.

Syntax

virtual HRESULT CheckTransform(
    const CMediaType *mtIn,
    const CMediaType *mtOut
) PURE;

Parameters

mtIn
Pointer to a CMediaType object that specifies the input type.
mtOut
Pointer to a CMediaType object that specifies the output type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | The media types are compatible.
VFW_E_TYPE_NOT_ACCEPTED | The media types are not compatible.

Remarks

The derived class must implement this method. Return S_OK if the filter can accept both of the specified media types, or an error code otherwise.

CTransformFilter::CompleteConnect

CTransformFilter Class

Completes a pin connection.

Syntax

virtual HRESULT CompleteConnect(
    PIN_DIRECTION direction,
    IPin *pReceivePin
);

Parameters

direction
Member of the PIN_DIRECTION enumerated type, specifying which pin on the filter is making the connection.
pReceivePin
Pointer to the IPin interface of the other pin in this connection attempt.

Return Value

Returns S_OK.

Remarks

The CTransformInputPin::CompleteConnect and CTransformOutputPin::CompleteConnect methods call this method during the pin connection process. This method does nothing in the base class, but the derived class can override it.

CTransformFilter::CTransformFilter

CTransformFilter Class

Constructor method.

Syntax

CTransformFilter(
    TCHAR *pObjectName,
    LPUNKNOWN lpUnk,
    CLSID clsid
);

Parameters

pObjectName
String containing the debug name of the filter. For more information, see CBaseObject.
lpUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
clsid
Class identifier of the filter.

Remarks

The constructor does not create the filter's pins. That happens during the first call to the GetPin method. The constructor initializes the m_pInput and m_pOutput member variables to NULL.

CTransformFilter::~CTransformFilter

CTransformFilter Class

Destructor method.

Syntax

~CTransformFilter(void);

CTransformFilter::DecideBufferSize

CTransformFilter Class

Sets the output pin's buffer requirements.

Syntax

virtual HRESULT DecideBufferSize(
    IMemAllocator *pAlloc,
    ALLOCATOR_PROPERTIES *ppropInputRequest
) PURE;

Parameters

pAlloc
Pointer to the IMemAllocator interface on the output pin's allocator.
ppropInputRequest
Pointer to an ALLOCATOR_PROPERTIES structure that contains buffer requirements from the downstream input pin.

Return Value

Returns S_OK or another HRESULT value.

Remarks

The output pin's CTransformOutputPin::DecideBufferSize method calls this method. The derived class must implement this method. For more information, see CBaseOutputPin::DecideBufferSize.

CTransformFilter::EndFlush

CTransformFilter Class

Ends a flush operation.

Syntax

virtual HRESULT EndFlush(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

At the end of a flush operation, the input pin's CTransformInputPin::EndFlush method calls this method. This method passes the EndFlush call downstream.

If the derived class uses a worker thread to deliver samples, it must discard any queued data before sending the EndFlush call downstream. For more information, see Data Flow for Filter Developers.

CTransformFilter::EndOfStream

CTransformFilter Class

Notifies the filter that no additional data is expected from the input pin.

Syntax

virtual HRESULT EndOfStream(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

The input pin's CTransformInputPin::EndOfStream method calls this method. This method delivers the end-of-stream notification downstream. If the derived class uses a worker thread to deliver media samples, it should override this method and queue the end-of-stream notification.

CTransformFilter::FindPin

CTransformFilter Class

Retrieves the pin with the specified identifier. Implements the IBaseFilter::FindPin method.

Syntax

HRESULT FindPin(
    LPCWSTR Id,
    IPin **ppPin
);

Parameters

Id
Wide-character string that contains the pin identifier.
ppPin
Address of a variable that receives a pointer to the pin's IPin interface. If the method fails, *ppPin is set to NULL.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
VFW_E_NOT_FOUND | Could not find a pin with this identifier.

Remarks

The identifier for the input pin is In, and the identifier for the output pin is Out.

CTransformFilter::GetMediaType

CTransformFilter Class

Retrieves a preferred media type for the output pin.

Syntax

virtual HRESULT GetMediaType(
    int iPosition,
    CMediaType *pMediaType
) PURE;

Parameters

iPosition
Zero-based index value.
pMediaType
Pointer to a CMediaType object that receives the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_S_NO_MORE_ITEMS | Index out of range.
E_INVALIDARG | Index less than zero.

Remarks

The output pin's CTransformOutputPin::GetMediaType method calls this method. The derived class must implement this method. For more information, see CBasePin::GetMediaType.

CTransformFilter::GetPin

CTransformFilter Class

Retrieves a pin.

Syntax

virtual CBasePin *GetPin(
    int n
);

Parameters

n
Number of the specified pin, indexed from zero. On this filter, pin 0 is the input pin, and pin 1 is the output pin.

Return Value

Returns a pointer to the CBasePin object that implements the pin, or NULL if the method fails.

Remarks

This method implements the pure virtual CBaseFilter::GetPin method. The first time the method is called, it creates both pins.

This method does not increment the reference count on the returned pin, so the returned pin does not have an outstanding reference count. If the caller needs to keep a reference on the pin, it should call the IUnknown::AddRef method on the pin.

If the filter uses the default CTransformInputPin and CTransformOutputPin pins, you probably do not need to override this method. If the filter uses pins that extend those classes, however, you must override this method to create pins of that type.

CTransformFilter::GetPinCount

CTransformFilter Class

Retrieves the number of pins on the filter.

Syntax

virtual int GetPinCount(void);

Return Value

Returns 2.

Remarks

This method overrides the CBaseFilter::GetPinCount method. This class supports exactly one input pin and one output pin.

CTransformFilter::InitializeOutputSample

CTransformFilter Class

Retrieves a new output sample and initializes it.

Syntax

HRESULT InitializeOutputSample(
    IMediaSample *pSample,
    IMediaSample **ppOutSample
);

Parameters

pSample
Pointer to the input sample's IMediaSample interface.
ppOutSample
Address of a variable that receives a pointer to the output sample's IMediaSample interface.

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method retrieves a new sample from the output pin's allocator. Then it copies the sample properties from the input sample to the output sample.

CTransformFilter::NewSegment

CTransformFilter Class

Notifies the filter that media samples received after this call are grouped as a segment.

Syntax

virtual HRESULT NewSegment(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop,
    double dRate
);

Parameters

tStart
Start time of the segment, relative to the original source.
tStop
Stop time of the segment, relative to the original source.
dRate
Rate at which the segment should be processed.

Return Value

Returns S_OK.

Remarks

The input pin's CTransformInputPin::NewSegment method calls this method. This method delivers the NewSegment call to the downstream input pin.

CTransformFilter::Pause

CTransformFilter Class

Pauses the filter. Implements the IMediaFilter::Pause method.

Syntax

HRESULT Pause(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method calls the StartStreaming method. The StartStreaming method does nothing in the base class, but the derived class can override it.

CTransformFilter::Receive

CTransformFilter Class

Receives a media sample, processes it, and delivers an output sample to the downstream filter.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample
Pointer to the IMediaSample interface on the input sample.

Return Value

Returns an HRESULT value.

Remarks

The filter's input pin calls this method when it receives a sample. This method calls the InitializeOutputSample method, which prepares a new output sample. Then it calls the Transform method, which the derived class must implement. The Transform method processes the input data and produces output data.

If the Transform method returns S_FALSE, the Receive method drops this sample. On the first dropped sample, the filter sends an EC_QUALITY_CHANGE event to the filter graph manager. Otherwise, if the Transform method returns S_OK, the filter delivers the output sample. To do so, it calls the IMemInputPin::Receive method on the downstream input pin.

CTransformFilter::SetMediaType

CTransformFilter Class

Called when the media type is set on one of the filter's pins.

Syntax

virtual HRESULT SetMediaType(
    PIN_DIRECTION direction,
    const CMediaType *pmt
);

Parameters

direction
Member of the PIN_DIRECTION enumerated type, specifying a pin on the filter (input or output).
pmt
Pointer to a CMediaType object that specifies the media type.

Return Value

Returns S_OK.

Remarks

The CTransformInputPin::SetMediaType and CTransformOutputPin::SetMediaType methods call this method when a pin's media type is set. This method does nothing in the base class, but the derived class can override it.

CTransformFilter::StartStreaming

CTransformFilter Class

Called when the filter switches to the paused state.

Syntax

virtual HRESULT StartStreaming(void);

Return Value

Returns S_OK.

Remarks

This method does nothing in the base class, but the derived class can override it.

CTransformFilter::Stop

CTransformFilter Class

Stops the filter. Implements the IMediaFilter::Stop method.

Syntax

HRESULT Stop(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

After this method decommits both allocators, it calls the StopStreaming method. The StopStreaming method does nothing in the base class, but the derived class can override it.

CTransformFilter::StopStreaming

CTransformFilter Class

Called when the filter switches to the stopped state.

Syntax

virtual HRESULT StopStreaming(void);

Return Value

Returns S_OK.

Remarks

This method does nothing in the base class, but the derived class can override it.

CTransformFilter::Transform

CTransformFilter Class

Transforms an input sample to produce an output sample.

Syntax

virtual HRESULT Transform(
    IMediaSample *pIn,
    IMediaSample *pOut
)

Parameters

pIn
Pointer to the input sample's IMediaSample interface.
pOut
Pointer to the output sample's IMediaSample interface.

Return Value

The base class returns E_UNEXPECTED.

The derived class should return an HRESULT value, indicating success or failure. Possible values include those shown in the following table.

S_FALSE | Do not deliver this sample.
S_OK | Success.

Remarks

Override this method to produce output data. Read the input data from the sample specified by the pIn parameter, and write the new data into the sample specified by the pOut parameter.

Before the filter calls this method, it copies the properties from the input sample to the output sample. The Transform method should set any properties that differ between the two samples, using IMediaSample methods or the IMediaSample2 interface (if available).

If the filter should not deliver this sample (for example, to support quality control), the method should return S_FALSE.


CTransformInputPin Class

CTransformInputPin class hierarchy

Input pin used by the CTransformFilter class.

Declaration: Transfrm.h

Typically, you do not need to derive from this class. Most of the methods in this class call corresponding methods on the CTransformFilter class, which you can override. If you derive from this class, you must override the filter's CTransformFilter::GetPin method to create instances of your derived class.

Protected Member Variables
m_pTransformFilter | Pointer to the owning filter.
Public Methods
CTransformInputPin | Constructor method.
CheckConnect | Determines whether a pin connection is suitable.
BreakConnect | Releases the pin from a connection.
CompleteConnect | Completes a connection to another pin.
CheckMediaType | Determines if the pin accepts a specific media type.
SetMediaType | Sets the media type for the connection.
CheckStreaming | Determines whether the pin can accept samples. Virtual.
CurrentMediaType | Retrieves the media type for the current pin connection.
IPin Methods
QueryId | Retrieves an identifier for the pin.
EndOfStream | Notifies the pin that no additional data is expected.
BeginFlush | Begins a flush operation.
EndFlush | Ends a flush operation.
NewSegment | Notifies the pin that media samples received after this call are grouped as a segment.
IMemInputPin Methods
Receive | Receives the next media sample in the stream.

CTransformInputPin.m_pTransformFilter

CTransformInputPin Class

Pointer to the owning filter.

Syntax

CTransformFilter *m_pTransformFilter;

CTransformInputPin::BeginFlush

CTransformInputPin Class

Begins a flush operation. Implements the IPin::BeginFlush method.

Syntax

HRESULT BeginFlush(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_NOT_CONNECTED | Output pin is not connected.

Remarks

This method calls the pin's CBaseInputPin::BeginFlush method. Then it calls the filter's CTransformFilter::BeginFlush method to deliver the call downstream.

CTransformInputPin::BreakConnect

CTransformInputPin Class

Releases the pin from a connection.

Syntax

HRESULT BreakConnect(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method overrides the CBaseInputPin::BreakConnect method. It calls the filter's CTransformFilter::BreakConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::BreakConnect method.

CTransformInputPin::CheckConnect

CTransformInputPin Class

Determines whether a pin connection is suitable.

Syntax

HRESULT CheckConnect(
    IPin *pPin
);

Parameters

pPin
Pointer to the output pin's IPin interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success
VFW_E_INVALID_DIRECTION | Wrong pin direction

Remarks

This method overrides the CBasePin::CheckConnect method. It calls the filter's CTransformFilter::CheckConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::CheckConnect method to perform additional checks.

CTransformInputPin::CheckMediaType

CTransformInputPin Class

Determines if the pin accepts a specific media type.

Syntax

HRESULT CheckMediaType(
    const CMediaType *mtIn
);

Parameters

mtIn
Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method implements the pure virtual CBasePin::CheckMediaType method. It calls the filter's CTransformFilter::CheckInputType method, which is also pure virtual. The filter's derived class must implement CheckInputType to determine whether a given input type is acceptable.

If the filter's output pin is connected, this method also calls the filter's CTransformFilter::CheckTransform method to determine whether the input type is compatible with the output type. The CheckTransform method is pure virtual as well.

CTransformInputPin::CheckStreaming

CTransformInputPin Class

Determines whether the pin can accept samples.

Syntax

HRESULT CheckStreaming(void);

Return Value

Returns one of the HRESULT values listed in the following table.

S_OK | Success.
S_FALSE | Pin is currently flushing.
VFW_E_NOT_CONNECTED | The output pin is not connected.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

This method overrides the CBaseInputPin::CheckStreaming method.

CTransformInputPin::CompleteConnect

CTransformInputPin Class

Completes a connection to another pin.

Syntax

HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin
Pointer to the other pin's IPin interface.

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method overrides the CBasePin::CompleteConnect method. It calls the filter's CTransformFilter::CompleteConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::CompleteConnect method to perform additional checks.

CTransformInputPin::CTransformInputPin

CTransformInputPin Class

Constructor method.

Syntax

CTransformInputPin(
    TCHAR *pObjectName,
    CTransformFilter *pTransformFilter,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName
String containing the debug name of the object. For more information, see CBaseObject.
pTransformFilter
Pointer to the filter that created this pin, which must be a CTransformFilter object.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.
pName
Unicode™ string containing the pin name.

Remarks

The pName parameter specifies the pin name, which is returned by the IPin::QueryPinInfo method. However, the string is not used for the pin identifier. The pin identifier for this class is always In. For more information, see QueryId.

CTransformInputPin::CurrentMediaType

CTransformInputPin Class

Retrieves the media type for the current pin connection.

Syntax

CMediaType& CurrentMediaType(void);

Return Value

Returns a reference to the CBasePin::m_mt member variable.

CTransformInputPin::EndFlush

CTransformInputPin Class

Ends a flush operation. Implements the IPin::EndFlush method.

Syntax

HRESULT EndFlush(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_NOT_CONNECTED | Output pin is not connected.

Remarks

This method calls the filter's CTransformFilter::EndFlush method to deliver the call downstream. Then it calls the pin's CBaseInputPin::EndFlush method.

CTransformInputPin::EndOfStream

CTransformInputPin Class

Notifies the pin that no additional data is expected. Implements the IPin::EndOfStream method.

Syntax

HRESULT EndOfStream(void);

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
S_FALSE | Pin is currently flushing.
VFW_E_NOT_CONNECTED | The output pin is not connected.
VFW_E_RUNTIME_ERROR | A run-time error occurred.
VFW_E_WRONG_STATE | The pin is stopped.

Remarks

This method calls the filter's CTransformFilter::EndOfStream method to deliver the end-of-stream notification downstream.

CTransformInputPin::NewSegment

CTransformInputPin Class

Notifies the pin that media samples received after this call are grouped as a segment. Implements the IPin::NewSegment method.

Syntax

HRESULT NewSegment(
    REFERENCE_TIME tStart,
    REFERENCE_TIME tStop,
    double dRate
);

Parameters

tStart
Start time of the segment.
tStop
Stop time of the segment.
dRate
Rate of the segment.

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method overrides the CBasePin::NewSegment method. It calls the filter's CTransformFilter::NewSegment method to deliver the call downstream.

CTransformInputPin::QueryId

CTransformInputPin Class

Retrieves an identifier for the pin. Implements the IPin::QueryId method.

Syntax

HRESULT QueryId(
    LPWSTR *Id
);

Parameters

Id
Address of a variable that receives a string containing the pin identifier.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

The pin identifier is used for graph persistence. The pin identifier for this class is In. This class overrides the behavior of the CBasePin class. In the CBasePin class, the pin identifier is the same as the pin name, specified in the class constructor. In the CTransformInputPin class, the pin identifier and the pin name are not the same.

CTransformInputPin::Receive

CTransformInputPin Class

Receives the next media sample in the stream. Implements the IMemInputPin::Receive method.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | Pin is currently flushing; sample was rejected.
S_OK | Success.

Remarks

This method calls the pin's CBaseInputPin::Receive method, which checks the pin's streaming state and checks for format changes in the media type. Then it calls the filter's CTransformFilter::Receive method, which processes the sample and delivers it downstream.

If the filter needs to access the sample after this method returns, it should hold a reference count by calling the IUnknown::AddRef method on the sample. For example, some decoder filters need the current sample in order to decode the next sample.

CTransformInputPin::SetMediaType

CTransformInputPin Class

Sets the media type for the connection.

Syntax

HRESULT SetMediaType(
    const CMediaType *mt
);

Parameters

mt
Pointer to a CMediaType object that specifies the media type.

Return Value

Returns S_OK.

Remarks

This method overrides the CBasePin::SetMediaType method. It calls the filter's CTransformFilter::SetMediaType method to inform the filter.

The pin must verify that the media type is acceptable before calling this method.


CTransformOutputPin Class

CTransformOutputPin class hierarchy

Output pin used by the CTransformFilter class.

Declaration: Transfrm.h

Typically, you do not need to derive from this class. Most of the methods in this class call corresponding methods on the CTransformFilter class, which you can override. If you derive from this class, you must override the filter's CTransformFilter::GetPin method to create instances of your derived class.

Protected Member Variables
m_pTransformFilter | Pointer to the owning filter.
Public Member Variables
m_pPosition | Helper object to pass seek commands upstream.
Public Methods
CTransformOutputPin | Constructor method.
~CTransformOutputPin | Destructor method.
CheckConnect | Determines whether a pin connection is suitable.
BreakConnect | Releases the pin from a connection.
CompleteConnect | Completes a connection to another pin.
CheckMediaType | Determines if the pin accepts a specific media type.
SetMediaType | Sets the media type for the connection.
DecideBufferSize | Sets the buffer requirements.
GetMediaType | Retrieves a preferred media type, by index value.
CurrentMediaType | Retrieves the media type for the current pin connection.
IPin Methods
QueryId | Retrieves an identifier for the pin.
IQualityControl Methods
Notify | Notifies the pin that a quality change is requested.

CTransformOutputPin.m_pTransformFilter

CTransformOutputPin Class

Pointer to the owning filter.

Syntax

CTransformOutputPin *m_pTransformFilter;

CTransformOutputPin.m_pPosition

CTransformOutputPin Class

Helper object to pass seek commands upstream.

Syntax

IUnknown *m_pPosition;

Remarks

When the pin is first queried for the IMediaPosition or IMediaSeeking interface, it creates and aggregates a CPosPassThru helper object.

CTransformOutputPin::BreakConnect

CTransformOutputPin Class

Releases the pin from a connection.

Syntax

HRESULT BreakConnect(void);

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method overrides the CBaseOutputPin::BreakConnect method. It calls the filter's CTransformFilter::BreakConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::BreakConnect method.

CTransformOutputPin::CheckConnect

CTransformOutputPin Class

Determines whether a pin connection is suitable.

Syntax

HRESULT CheckConnect(
    IPin *pPin
);

Parameters

pPin
Pointer to the output pin's IPin interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_UNEXPECTED | The filter's input pin is not connected.

Remarks

This method overrides the CBaseOutputPin::CheckConnect method. It calls the filter's CTransformFilter::CheckConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::CheckConnect method to perform additional checks.

CTransformOutputPin::CheckMediaType

CTransformOutputPin Class

Determines if the pin accepts a specific media type.

Syntax

HRESULT CheckMediaType(
    const CMediaType *mtIn
);

Parameters

mtIn
Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_INVALIDARG | The filter's input pin is not connected.

Remarks

This method implements the pure virtual CBasePin::CheckMediaType method. The method fails if the filter's input pin is not connected. Otherwise, it calls the filter's CTransformFilter::CheckTransform method, which is also pure virtual. The filter's derived class must implement CheckTransform, which determines if the proposed output media type is compatible with the input media type.

CTransformOutputPin::CompleteConnect

CTransformOutputPin Class

Completes a connection to another pin.

Syntax

HRESULT CompleteConnect(
    IPin *pReceivePin
);

Parameters

pReceivePin
Pointer to the other pin's IPin interface.

Return Value

Returns S_OK or another HRESULT value.

Remarks

This method overrides the CBaseOutputPin::CompleteConnect method. It calls the filter's CTransformFilter::CompleteConnect method, which returns S_OK in the base class. The derived class can override the CTransformFilter::CompleteConnect method to perform additional checks.

CTransformOutputPin::CTransformOutputPin

CTransformOutputPin Class

Constructor method.

Syntax

CTransformOutputPin(
    TCHAR *pObjectName,
    CTransformFilter *pTransformFilter,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName
String containing the debug name of the object. For more information, see CBaseObject.
pTransformFilter
Pointer to the filter that created this pin, which must be a CTransformFilter object.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.
pName
Unicode™ string containing the pin name.

Remarks

The pName parameter specifies the pin name, which is returned by the IPin::QueryPinInfo method. However, the string is not used for the pin identifier. The pin identifier for this class is always Out. For more information, see QueryId.

CTransformOutputPin::~CTransformOutputPin

CTransformOutputPin Class

Destructor method.

Syntax

~CTransformOutputPin(void);

CTransformOutputPin::CurrentMediaType

CTransformOutputPin Class

Retrieves the media type for the current pin connection.

Syntax

CMediaType& CurrentMediaType(void);

Return Value

Returns a reference to the CBasePin::m_mt member variable.

CTransformOutputPin::DecideBufferSize

CTransformOutputPin Class

Sets the buffer requirements.

Syntax

HRESULT DecideBufferSize(
    IMemAllocator *pAlloc,
    ALLOCATOR_PROPERTIES *ppropInputRequest
);

Parameters

pAlloc
Pointer to the allocator's IMemAllocator interface.
ppropInputRequest
Pointer an ALLOCATOR_PROPERTIES structure that contains the input pin's buffer requirements.

Return Value

Returns an HRESULT value.

Remarks

This method overrides the CBaseOutputPin::DecideBufferSize method. It calls the filter's pure virtual CTransformFilter::DecideBufferSize method, which the filter's derived class must implement.

CTransformOutputPin::GetMediaType

CTransformOutputPin Class

Retrieves a preferred media type, by index value.

Syntax

HRESULT GetMediaType(
    int iPosition,
    CMediaType *pMediaType
);

Parameters

iPosition
Zero-based index value.
pMediaType
Pointer to a CMediaType object that receives the media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success
VFW_S_NO_MORE_ITEMS | Index out of range

Remarks

This method overrides the CBasePin::GetMediaType method. If the filter's input pin is not connected, the method returns VFW_S_NO_MORE_ITEMS. Otherwise, it calls the filter's CTransformFilter::GetMediaType method to retrieve the media type. The CTransformFilter::GetMediaType method is pure virtual; the filter's derived class must override it.

CTransformOutputPin::Notify

CTransformOutputPin Class

Notifies the pin that a quality change is requested. Implements the IQualityControl::Notify method.

Syntax

HRESULT Notify(
    IBaseFilter *pSelf,
    Quality q
);

Parameters

pSelf
Pointer to the IBaseFilter interface of the filter that delivered the quality control message.
q
Quality structure that contains the quality control message.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_NOT_FOUND | Could not find an object to accept the message.

Remarks

This method calls the filter's CTransformFilter::AlterQuality method. If the filter does not handle the quality message, this method calls the CBaseInputPin::PassNotify method on the filter's input pin. The PassNotify method passes the quality message upstream (or to a custom quality manager, if one was installed).

CTransformOutputPin::QueryId

CTransformOutputPin Class

Retrieves an identifier for the pin. Implements the IPin::QueryId method.

Syntax

HRESULT QueryId(
    LPWSTR *Id
);

Parameters

Id
Address of a variable that receives a string containing the pin identifier.

Return Value

Returns one of the HRESULT values shown in the following table.

S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

The pin identifier is used for graph persistence. The pin identifier for this class is Out. This class overrides the behavior of the CBasePin class. In the CBasePin class, the pin identifier is the same as the pin name, specified in the class constructor. In the CTransformInputPin class, the pin identifier and the pin name are not the same.

CTransformOutputPin::SetMediaType

CTransformOutputPin Class

Sets the media type for the connection.

Syntax

HRESULT SetMediaType(
    const CMediaType *mt
);

Parameters

mt
Pointer to a CMediaType object that specifies the media type.

Return Value

Returns S_OK.

Remarks

This method overrides the CBasePin::SetMediaType method. It calls the filter's CTransformFilter::SetMediaType method to inform the filter.

The pin must verify that the media type is acceptable before calling this method.


CTransInPlaceFilter Class

CTransInPlaceFilter class hierarchy

Base class for implementing an in-place transform filter.

Declaration: Transfrm.h

The CTransInPlaceFilter class is designed for filters that transform data in place, rather than copying the data across buffers.

Whenever possible, the filter uses a single allocator. For details, see CompleteConnect.

To use this class, derive a new class from CTransInPlaceFilter and implement the following methods:

  • CTransformFilter::CheckInputType
  • Transform

This filter uses the CTransInPlaceInputPin class for its input pin, and the CTransInPlaceOutputPin class for its output pin. Typically, you do not need to override these pin classes. The filter creates both pins in the GetPin method. If you do override the pin classes, you must override GetPin to create your custom pins.

Protected Methods
Copy | Copies a media sample.
InputPin | Retrieves a pointer to the filter's input pin.
OutputPin | Retrieves a pointer to the filter's output pin.
TypesMatch | Determines whether the input media type matches the output media type.
UsingDifferentAllocators | Determines whether the input and output pins are using different allocators.
Public Methods
CTransInPlaceFilter | Constructor method.
GetPin | Retrieves a pin.
GetMediaType | Retrieves a preferred media type for the output pin.
DecideBufferSize | Sets the output pin's buffer requirements.
CheckTransform | Checks whether an input media type is compatible with an output media type.
CompleteConnect | Completes a pin connection.
Receive | Receives a media sample, processes it, and delivers it to the downstream filter.
Pure Virtual Methods
Transform | Transforms a sample in place.

CTransInPlaceFilter::CheckTransform

CTransInPlaceFilter Class

Checks whether an input media type is compatible with an output media type.

Syntax

HRESULT CheckTransform(
    const CMediaType *mtIn,
    const CMediaType *mtOut
);

Parameters

mtIn
Pointer to a CMediaType object that specifies the input type.
mtOut
Pointer to a CMediaType object that specifies the output type.

Return Value

Returns S_OK.

Remarks

This method overrides the CTransformFilter::CheckTransform method. The methods in CTransInPlace call the CTransformFilter::CheckInputType method instead of CheckTransform, with the assumption that the input and output types are the same.

CTransInPlaceFilter::CompleteConnect

CTransInPlaceFilter Class

Completes a pin connection.

Syntax

HRESULT CompleteConnect(
    PIN_DIRECTION direction,
    IPin *pReceivePin
);

Parameters

direction
Member of the PIN_DIRECTION enumerated type, specifying which pin on the filter is making the connection.
pReceivePin
Pointer to the IPin interface of the other pin in this connection attempt.

Return Value

Returns an HRESULT. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_NOT_IN_GRAPH | The filter is not in a filter graph.

Remarks

This method overrides the CTransformFilter::CompleteConnect method.

The behavior of the filter depends on the order of the pin connections:

  • If the input pin is connected first, the connection uses a temporary allocator. When the output pin is connected, the filter reconnects the input pin. Reconnecting the input pin causes the upstream filter to renegotiate the allocator. At that point, the input pin proposes an allocator from the downstream filter. For more information, see CTransInPlaceInputPin::GetAllocator.
  • If the output pin is connected first, the output pin does not select an allocator. When the input pin is connected, it negotiates an allocator for both connections. If the input and output media types are not the same, the filter reconnects the output pin using the input type.

The filter performs all pin reconnections by calling the CBaseFilter::ReconnectPin method. The ReconnectPin method, in turn, calls the IFilterGraph2::ReconnectEx method on the filter graph manager.

CTransInPlaceFilter::Copy

CTransInPlaceFilter Class

Copies a media sample.

Syntax

IMediaSample *CTransInPlaceFilter::Copy(
    IMediaSample *pSource
);

Parameters

pSource
Pointer to the IMediaSample interface of the sample.

Return Value

Returns a pointer to the IMediaSample interface on the new sample.

Remarks

This method retrieves an empty buffer from the downstream allocator. It copies all of the sample properties from pSource into the new sample, along with the actual data in the sample. If the filter is using two allocators, it calls this method to copy data across buffers.

CTransInPlaceFilter::CTransInPlaceFilter

CTransInPlaceFilter Class

Constructor method.

Syntax

CTransInPlaceFilter(
    TCHAR *pObjectName,
    LPUNKNOWN lpUnk,
    REFCLSID clsid,
    HRESULT *phr,
    bool bModifiesData = true
);

Parameters

pObjectName
String containing the debug name of the filter. For more information, see CBaseObject.
lpUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.
clsid
Class identifier of the filter.
phr
Ignored.
bModifiesData
Boolean value that specifies whether the filter modifies the input data. If TRUE, the filter modifies the data. Otherwise, the filter passes the data downstream unchanged.

CTransInPlaceFilter::DecideBufferSize

CTransInPlaceFilter Class

Sets the output pin's buffer requirements.

Syntax

HRESULT DecideBufferSize(
    IMemAllocator *pAlloc,
    ALLOCATOR_PROPERTIES *pProperties
);

Parameters

pAlloc
Pointer to the IMemAllocator object used by the output pin.
pProperties
Pointer to the requested allocator properties for count, size, and alignment, as specified by the ALLOCATOR_PROPERTIES structure.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success
E_FAIL | Failure

Remarks

This method overrides the CTransformFilter::DecideBufferSize method. It exists for compatibility with previous versions of the CTransInPlaceFilter class. In the current version, the upstream output pin negotiates directly with the downstream input pin for the allocator. The filter's output pin is not involved.

CTransInPlaceFilter::GetMediaType

CTransInPlaceFilter Class

Retrieves a preferred media type for the output pin.

Syntax

HRESULT GetMediaType(
    int iPosition,
    CMediaType *pMediaType
);

Parameters

iPosition
Zero-based index value.
pMediaType
Pointer to a CMediaType object that receives the media type.

Return Value

Returns E_UNEXPECTED.

Remarks

This method overrides the CTransformFilter::GetMediaType method. In the CTransInPlaceFilter class, each pin calls the opposite connected pin to enumerate preferred media types. The input pin calls the downstream filter's input pin, and the output pin calls the upstream filter's output pin. Therefore, the filter's GetMediaType method is never called.

CTransInPlaceFilter::GetPin

CTransInPlaceFilter Class

Retrieves a pin.

Syntax

virtual CBasePin *GetPin(
    int n
);

Parameters

n
Number of the specified pin, indexed from zero. On this filter, pin 0 is the input pin, and pin 1 is the output pin.

Return Value

Returns a pointer to the CBasePin object that implements the pin, or NULL if the method fails.

Remarks

This method overrides the CTransformFilter::GetPin method. The first time the method is called, it creates both pins.

This method does not increment the reference count on the returned pin, so the returned pin does not have an outstanding reference count. If the caller needs to keep a reference on the pin, it should call the IUnknown::AddRef method on the pin.

If the filter uses the default CTransInPlaceInputPin and CTransInPlaceOutputPin pins, you probably do not need to override this method. If the filter uses pins that extend those classes, however, you must override this method to create pins of that type.

CTransInPlaceFilter::InputPin

CTransInPlaceFilter Class

Retrieves a pointer to the filter's input pin.

Syntax

CTransInPlaceInputPin *InputPin(void);

Return Value

Returns the CTransformFilter.m_pInput member variable.

CTransInPlaceFilter::OutputPin

CTransInPlaceFilter Class

Retrieves a pointer to the filter's output pin.

Syntax

CTransInPlaceOutputPin *OutputPin(void);

Return Value

Returns the CTransformFilter.m_pOutput member variable.

CTransInPlaceFilter::Receive

CTransInPlaceFilter Class

Receives a media sample, processes it, and delivers it to the downstream filter.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample
Pointer to the IMediaSample interface on the sample.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success
E_UNEXPECTED | Unexpected error

Remarks

The filter's input pin calls this method when it receives a sample. The filter calls the Transform method, which the derived class must implement. The Transform method processes the data. If the filter is using only one allocator, it passes pSample directly to the Tranform method. Otherwise, it copies pSample and passes the copy.

If the Transform method returns S_FALSE, the Receive method drops the sample. On the first dropped sample, the filter sends an EC_QUALITY_CHANGE event to the filter graph manager. Otherwise, if the Transform method returns S_OK, the filter delivers the output sample. To do so, it calls the IMemInputPin::Receive method on the downstream input pin.

CTransInPlaceFilter::Transform

CTransInPlaceFilter Class

Transforms a sample in place.

Syntax

virtual HRESULT Transform(
    IMediaSample *pSample
) PURE;

Parameters

pSample
Pointer to the sample's IMediaSample interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_FALSE | Do not deliver this sample.
S_OK | Success.

Remarks

The derived class must implement this method. Transform the sample data in place. If the filter is using two allocators, it copies the data from the input sample to a new sample, and passes the copy to this method.

If the filter should not deliver this sample (for example, to support quality control), the method should return S_FALSE.

CTransInPlaceFilter::TypesMatch

CTransInPlaceFilter Class

Determines whether the input media type matches the output media type.

Syntax

BOOL TypesMatch(void);

Return Value

Returns TRUE if the input and output media types are the same, or FALSE otherwise.

CTransInPlaceFilter::UsingDifferentAllocators

CTransInPlaceFilter Class

Determines whether the input and output pins are using different allocators.

Syntax

BOOL UsingDifferentAllocators(void) const;

Return Value

Returns TRUE if the input and output pins are using different allocators, or FALSE otherwise.


CTransInPlaceInputPin Class

CTransInPlaceInputPin class hierarchy

Input pin used by the CTransInPlaceFilter class.

Declaration: Transip.h

Typically, you do not need to derive from this class. If you do, you must override the filter's CTransInPlaceFilter::GetPin method to create instances of your derived class.

Protected Member Variables
m_bReadOnly | Flag that specifies whether the input stream is read-only.
m_pTIPFilter | Pointer to the filter that created this pin.
Public Methods
CTransInPlaceInputPin | Constructor method.
CheckMediaType | Determines if the pin accepts a specific media type.
PeekAllocator | Retrieves a pointer to the pin's allocator.
ReadOnly | Indicates whether the input stream is read-only.
IPin Methods
EnumMediaTypes | Enumerates the pin's preferred media types.
IMemInputPin Methods
GetAllocator | Retrieves the memory allocator proposed by this pin.
NotifyAllocator | Specifies an allocator for the connection.
GetAllocatorRequirements | Retrieves the allocator properties requested by the pin.

CTransInPlaceInputPin.m_bReadOnly

CTransInPlaceInputPin Class

Flag that specifies whether the input stream is read-only. The upstream filter specifies this information when it calls the NotifyAllocator method. By default, the value is FALSE.

Syntax

BOOL m_bReadOnly;

CTransInPlaceInputPin.m_pTIPFilter

CTransInPlaceInputPin Class

Pointer to the filter that created this pin.

Syntax

CTransInPlaceFilter * const m_pTIPFilter;

CTransInPlaceInputPin::CheckMediaType

CTransInPlaceInputPin Class

Determines if the pin accepts a specific media type.

Syntax

HRESULT CheckMediaType(
    const CMediaType *pmt
);

Parameters

pmt
Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns S_OK if the proposed media type is acceptable. Otherwise, returns S_FALSE or an error code.

Remarks

This method overrides the CTransformInputPin::CheckMediaType method. It calls the filter's CTransformFilter::CheckInputType method to check the input type. If the output pin is connected, this method also calls the IPin::QueryAccept method on the downstream input pin.

CTransInPlaceInputPin::CTransInPlaceInputPin

CTransInPlaceInputPin Class

Constructor method.

Syntax

CTransInPlaceInputPin(
    TCHAR *pObjectName,
    CTransInPlaceFilter *pFilter,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName
String containing the debug name of the object. For more information, see CBaseObject.
pFilter
Pointer to the filter that created this pin, which must be a CTransformFilter object.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.
pName
Unicode™ string containing the pin name.

Remarks

The pName parameter specifies the pin name, which is returned by the IPin::QueryPinInfo method. However, this string is not used for the pin identifier. The pin identifier for this class is always In. For more information, see QueryId.

CTransInPlaceInputPin::EnumMediaTypes

CTransInPlaceInputPin Class

Enumerates the pin's preferred media types. Implements the IPin::EnumMediaTypes method.

Syntax

HRESULT EnumMediaTypes(
    IEnumMediaTypes **ppEnum
);

Parameters

ppEnum
Address of a variable that receives a pointer to the IEnumMediaTypes interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer.
VFW_E_NOT_CONNECTED | The output pin is not connected.

Remarks

This method returns the IEnumMediaTypes interface from downstream input pin.

CTransInPlaceInputPin::GetAllocator

CTransInPlaceInputPin Class

Retrieves the memory allocator proposed by this pin. Implements the IMemInputPin::GetAllocator method.

Syntax

HRESULT GetAllocator(
    IMemAllocator **ppAllocator
);

Parameters

ppAllocator
Address of a variable that receives a pointer to the allocator's IMemAllocator interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_NO_ALLOCATOR | No allocator is available.

Remarks

If the filter's output pin is connected, this method requests an allocator from the downstream filter's input pin.

If the filter's output pin is not connected, this method creates a temporary allocator. Later, when the output pin is connected, the filter will reconnect the input pin and renegotiate the allocator.

CTransInPlaceInputPin::GetAllocatorRequirements

CTransInPlaceInputPin Class

Retrieves the allocator properties requested by the pin. Implements the IMemInputPin::GetAllocatorRequirements method.

Syntax

HRESULT GetAllocatorRequirements(
    ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps
Pointer to an ALLOCATOR_PROPERTIES structure, which is filled in with the requirements.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_NOTIMPL | The output pin is not connected, or the downstream input pin does not support the method.
E_POINTER | Null pointer argument.

Remarks

If the output pin is connected, this method passes the call to the downstream input pin. Otherwise, it returns E_NOTIMPL.

CTransInPlaceInputPin::NotifyAllocator

CTransInPlaceInputPin Class

Specifies an allocator for the connection. Implements the IMemInputPin::NotifyAllocator method.

Syntax

HRESULT NotifyAllocator(
    IMemAllocator *pAllocator,
    BOOL bReadOnly
);

Parameters

pAllocator
Pointer to the allocator's IMemAllocator interface.
bReadOnly
Flag that specifies whether samples from this allocator are read-only. If TRUE, samples are read-only.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success
E_FAIL | Failure
E_POINTER | NULL pointer argument

Remarks

The filter attempts to use the same allocator for both pin connections.

  • If the output pin is not connected, the input pin automatically accepts the allocator. When the output pin is connected, the filter will reconnect the input pin. At that point, the filter will try again to use a single allocator.
  • If the output pin is connected, the input pin accepts the allocator. The output pin also uses the same allocator. It calls NotifyAllocator on the downstream input pin.

The previous case has the following exception:

  • If the proposed allocator is read-only (that is, the bReadOnly parameter is TRUE) and the filter needs to modify the samples, then the filter must use two different allocators. In this case, if the upstream filter is proposing to use the downstream filter's allocator, the method returns E_FAIL.

CTransInPlaceInputPin::PeekAllocator

CTransInPlaceInputPin Class

Retrieves a pointer to the pin's allocator. The method does not increment the reference count on the interface.

Syntax

IMemAllocator *PeekAllocator(void)

Return Value

Returns the CBaseInputPin.m_pAllocator member variable.

CTransInPlaceInputPin::ReadOnly

CTransInPlaceInputPin Class

Indicates whether the input stream is read-only.

Syntax

const BOOL ReadOnly(void);

Return Value

Returns the value of the m_bReadOnly member variable.


CTransInPlaceOutputPin Class

CTransInPlaceOutputPin class hierarchy

Output pin used by the CTransInPlaceFilter class.

Declaration: Transip.h

Typically, you do not need to derive from this class. If you do, you must override the filter's CTransInPlaceFilter::GetPin method to create instances of your derived class.

Protected Member Variables
m_pTIPFilter | Pointer to the filter that created this pin.
Public Methods
CTransInPlaceOutputPin | Constructor method.
DecideAllocator | Selects a memory allocator.
CheckMediaType | Determines if the pin accepts a specific media type.
SetAllocator | Specifies an allocator for the connection.
ConnectedIMemInputPin | Retrieves a pointer to the downstream input pin.
PeekAllocator | Retrieves a pointer to the pin's allocator.
IPin Methods
EnumMediaTypes | Enumerates the pin's preferred media types.

CTransInPlaceOutputPin.m_pTIPFilter

CTransInPlaceOutputPin Class

Pointer to the filter that created this pin.

Syntax

CTransInPlaceFilter * const m_pTIPFilter;

CTransInPlaceOutputPin::CheckMediaType

CTransInPlaceOutputPin Class

Determines if the pin accepts a specific media type.

Syntax

HRESULT CheckMediaType(
    const CMediaType *pmt
);

Parameters

pmt
Pointer to a CMediaType object that contains the proposed media type.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
VFW_E_TYPE_NOT_ACCEPTED | Media type not accepted.

Remarks

This method overrides the CTransformOutputPin::CheckMediaType method.

If the filter is already streaming and is using two allocators, this method rejects any format changes. Otherwise, this method calls the filter's CTransformFilter::CheckInputType method to check the media type. If the input pin is connected, it also calls the IPin::QueryAccept method on the upstream output pin.

CTransInPlaceOutputPin::ConnectedIMemInputPin

CTransInPlaceOutputPin Class

Retrieves a pointer to the downstream input pin. This method returns the CBaseOutputPin.m_pInputPin member variable.

Syntax

IMemInputPin *ConnectedIMemInputPin(void);

Return Value

Returns a pointer to the IMemInputPin interface on the downstream input pin.

CTransInPlaceOutputPin::CTransInPlaceOutputPin

CTransInPlaceOutputPin Class

Constructor method.

Syntax

CTransInPlaceOutputPin(
    TCHAR *pObjectName,
    CTransInPlaceFilter *pFilter,
    HRESULT *phr,
    LPCWSTR pName
);

Parameters

pObjectName
String containing the debug name of the object. For more information, see CBaseObject.
pFilter
Pointer to the filter that created this pin, which must be a CTransInPlaceFilter object.
phr
Pointer to a variable that receives an HRESULT value indicating the success or failure of the method. Initialize the value to S_OK before creating the object. The value is changed only if an error occurs.
pName
Unicode™ string containing the pin name.

Remarks

The pName parameter specifies the pin name, which is returned by the IPin::QueryPinInfo method. However, the string is not used for the pin identifier. The pin identifier for this class is always Out. For more information, see QueryId.

CTransInPlaceOutputPin::DecideAllocator

CTransInPlaceOutputPin Class

Selects a memory allocator.

Syntax

HRESULT DecideAllocator(
    IMemInputPin *pPin,
    IMemAllocator **ppAlloc
);

Parameters

pPin
Pointer to the input pin's IMemInputPin interface.
ppAlloc
Address of a variable that receives a pointer to the allocator's IMemAllocator interface.

Return Value

Returns S_OK.

Remarks

This method overrides the CBaseOutputPin::DecideAllocator method.

This is a dummy method that does nothing, because the output pin for this filter never provides an allocator. Instead, the allocator is decided during the input pin's connection process. The input pin's CTransInPlaceInputPin::NotifyAllocator method calls NotifyAllocator on the downstream input pin.

CTransInPlaceOutputPin::EnumMediaTypes

CTransInPlaceOutputPin Class

Enumerates the pin's preferred media types. Implements the IPin::EnumMediaTypes method.

Syntax

HRESULT EnumMediaTypes(
    IEnumMediaTypes **ppEnum
);

Parameters

ppEnum
Address of a variable that receives a pointer to the IEnumMediaTypes interface.

Return Value

Returns an HRESULT value. Possible values include those shown in the following table.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer.
VFW_E_NOT_CONNECTED | The filter's input pin is not connected.

Remarks

This method returns the IEnumMediaTypes interface from the upstream output pin.

CTransInPlaceOutputPin::PeekAllocator

CTransInPlaceOutputPin Class

Retrieves a pointer to the pin's allocator. The method does not increment the reference count on the interface.

Syntax

IMemAllocator *PeekAllocator(void)

Return Value

Returns the CBaseOutputPin.m_pAllocator member variable.

CTransInPlaceOutputPin::SetAllocator

CTransInPlaceOutputPin Class

Specifies an allocator for the connection.

Syntax

void SetAllocator(
    IMemAllocator *pAllocator
);

Parameters

pAllocator
Pointer to the allocator's IMemAllocator interface.

Remarks

The output pin for this filter never provides an allocator. This method specifies the allocator for the output pin. It sets the value of the CBaseOutputPin.m_pAllocator member variable.


CUnknown Class

CUnknown class hierarchy

Implements the IUnknown interface. Most Component Object Model (COM) objects in Microsoft® DirectShow® derive from CUnknown.

Declaration: Combase.h

If you implement a COM object, you might want to derive it from CUnknown. Deriving from CUknown provides a thread-safe implementation, and saves you the trouble of implementing IUnknown.

For a detailed discussion of how to use this base class, see How to Implement IUnknown. What follows is a brief summary:

  • Include the DECLARE_IUNKNOWN macro in the public section of your class definition. This macro declares the three methods of the IUnknown interface.
  • Override the NonDelegatingQueryInterface method to support interfaces other than IUnknown. Within this method, call the GetInterface function to retrieve interface pointers.
  • In your class constructor, invoke the CUnknown constructor method.
Protected Member Variables
m_cRef | Reference count.
Public Methods
CUnknown | Constructor method.
~CUnknown | Destructor method. Virtual.
GetOwner | Retrieves a pointer to the controlling IUnknown.
INonDelegatingUnknown Methods
NonDelegatingAddRef | Increments the reference count.
NonDelegatingQueryInterface | Retrieves an interface pointer and increments the reference count.
NonDelegatingRelease | Decrements the reference count.

CUnknown.m_cRef

CUnknown Class

Reference count.

Syntax

volatile LONG m_cRef;

Remarks

Use this member variable if you override the NonDelegatingAddRef or NonDelegatingRelease method.

CUnknown::CUnknown

CUnknown Class

Constructor method.

Syntax

CUnknown(
    const TCHAR *pName,
    LPUNKNOWN pUnk
);

Parameters

pName
String containing the name of the object; used in the CBaseObject constructor for debugging.
pUnk
Pointer to the owner of this object. If the object is aggregated, pass a pointer to the aggregating object's IUnknown interface. Otherwise, set this parameter to NULL.

Remarks

The object is initialized with a reference count of zero.

CUnknown::~CUnknown

CUnknown Class

Destructor method.

Syntax

virtual ~CUnknown(void);

CUnknown::GetOwner

CUnknown Class

Retrieves a pointer to the IUnknown interface of the owning component. For an aggregated component, the owner is the outer component. Otherwise, the component owns itself.

Syntax

LPUNKNOWN GetOwner(void);

Return Value

Returns a pointer to the controlling IUnknown interface.

CUnknown::NonDelegatingAddRef

CUnknown Class

Increments the reference count on the object. Implements the INonDelegatingUnknown::NonDelegatingAddRef method.

Syntax

ULONG NonDelegatingAddRef(void);

Return Value

Returns the reference count.

CUnknown::NonDelegatingQueryInterface

CUnknown Class

Retrieves an interface pointer and increments the reference count. Implements the INonDelegatingUnknown::NonDelegatingQueryInterface method.

Syntax

HRESULT NonDelegatingQueryInterface(
    REFIID riid,
    void **ppv
);

Parameters

riid
Identifier of the interface.
ppv
Address of a pointer to receive the interface.

Return Value

Returns one of the HRESULT values shown in the following table.
S_OK | Success.
E_NOINTERFACE | Object does not support this interface.
E_POINTER | NULL pointer argument.

Remarks

The CUnknown class exposes only the IUknown interface. Override this method to expose additional interfaces. For information on how to override this method, see How to Implement IUnknown.

CUnknown::NonDelegatingRelease

CUnknown Class

Decrements the reference count on the object. Implements the INonDelegatingUnknown::NonDelegatingRelease method.

Syntax

ULONG NonDelegatingRelease(void);

Return Value

Returns the reference count.

Remarks

When the reference count reaches zero, the object deletes itself.


CVideoTransformFilter Class

CVideoTransformFilter class hierarchy

The CVideoTransformFilter class is designed primarily as a base class for AVI decompressor filters. It is based on a "copying" transform class and assumes that the output buffer will likely be a video buffer or Microsoft® DirectDraw® buffer, although this could be used as a base class for other types of transform filters. The main feature of this class is that it enables quality-control management in a transform filter. This means that it decides to drop frames based on receiving a quality notification from the renderer, and taking into account other factors about the media stream it is processing and the filter's own behavior.

Every time the CVideoTransformFilter::Receive member function is called, it calls CVideoTransformFilter::ShouldSkipFrame to determine whether to start, continue, or stop skipping frames. This member function starts skipping samples only if all the following conditions are true.

  • The average time to decode is more than one fourth of the frame time.
  • The filter is running at least one frame late.
  • The next anticipated key frame is estimated to be no more than one frame early.
  • The occurrence of key frames is sufficiently frequent.

After the class starts to skip frames, it will skip all frames until a key frame appears, at which time it resets the m_bSkipping flag and processes the sample.

Key frames are defined as AVI key frames or MPEG I frames. These require no history to decode and, if they are skipped, no other frames can be decoded until the next key frame. Non-key frames include AVI non-key frames, MPEG P frames, and MPEG B frames. MPEG B frames are treated the same as other non-key frames by this class. (MPEG B frames can be dropped without the need to skip further frames; however, because this class is aimed primarily at AVI decompressors, it does not allow for this. Once any frame is skipped, all frames are skipped up to the next key frame.)

Protected Data Members

m_bNoSkip | Set to TRUE to prevent skipping to the next key frame (for debugging the filter).
m_bQualityChanged | Status flag that indicates if the stream has degraded. This is set to TRUE in CVideoTransformFilter::Receive if the call to the derived class Transform member function fails. (Receive returns NOERROR in this case because returning S_FALSE indicates that end-of-stream has arrived.)
m_bSkipping | Set to TRUE if the filter is skipping to the next key frame.
m_idFrameType | Performance-measuring frame type identifier. Logs 1 for key frames; logs 2 for nonkey frames.
m_idLate | Performance identifier for measuring lateness (available if PERF is defined).
m_idSkip | Performance identifier for measuring frame skipping.
m_idTimeTillKey | Performance identifier that represents an estimate of the time in milliseconds until the next key frame arrives.
m_itrAvgDecode | Average time required to decode (transform) the sample. If this is less than one-fourth of the frame time, it is assumed the quality problems are not being generated by this filter and no frames are dropped.
m_itrLate | Amount of time that the current frame is late. This is originally set to the value of the Quality structure's Late member passed in the quality control message from the renderer filter. It is decremented by the frame time of each frame that is skipped.
m_nFramesSinceKeyFrame | Used to count frames since the last key frame.
m_nKeyFramePeriod | The largest observed interval between key frames.
m_nWaitForKey | Used to ensure output after a format change before getting the first key frame. When nonzero, frames are not passed to the renderer. Set to 30 when format is changed and decremented on each nonkey frame.
m_tDecodeStart | Time since the start of the decoding.

Member Functions

AlterQuality | Receives a quality-control notification from the output pin and provides an opportunity to alter the quality of the media stream.
CVideoTransformFilter | Constructs a CVideoTransformFilter object.
ShouldSkipFrame | Determines if the filter should start, continue, or stop skipping frames.

Overridable Member Functions

EndFlush | Receives notification of leaving the flushing state and passes it downstream.
Receive | Receives the media sample and either skips the sample or transforms and delivers the media sample.
RegisterPerfId | Registers a performance measurement identifier.
StartStreaming | Overrides CTransformFilter::StartStreaming to reset the quality control information when streaming starts or flushing starts.

CVideoTransformFilter::AlterQuality

CVideoTransformFilter Class

Receives a quality-control notification and provides an opportunity to alter the quality of the media stream.

Syntax

virtual HRESULT AlterQuality(
    Quality q
);

Parameters

q
Quality-control notification message.

Return Value

Returns E_FAIL by default.

Remarks

This member function overrides the CTransformFilter::AlterQuality member function. It is called by the CTransformOutputPin::Notify member function before calling the CBaseInputPin::PassNotify member function to pass the quality control message upstream. This function sets the CVideoTransformFilter::m_itrLate data member to the value Quality structure's Late member so that the filter can determine whether to skip frames. It returns E_FAIL so that the renderer downstream will continue to handle quality control.

CVideoTransformFilter::CVideoTransformFilter

CVideoTransformFilter Class

Constructs a CVideoTransformFilter object.

Syntax

CVideoTransformFilter(
    TCHAR *pName,
    LPUNKNOWN pUnk,
    REFCLSID clsid
);

Parameters

pName
Pointer to the name given to the CVideoTransformFilter object.
pUnk
Pointer to the controlling IUnknown interface.
clsid
Class identifier of the CVideoTransformFilter class.

Return Value

No return value.

CVideoTransformFilter::EndFlush

CVideoTransformFilter Class

Receives notification that the filter is leaving the flushing state and passes it downstream.

Syntax

HRESULT EndFlush(void);

Return Value

Returns VFW_E_NOT_CONNECTED if the filter finds no input pin; otherwise, returns the value that the IPin::EndFlush method returns.

Remarks

This member function overrides the CTransformFilter::EndFlush member function to reset quality management information.

CVideoTransformFilter::Receive

CVideoTransformFilter Class

Receives the media sample and either skips the sample or transforms and delivers the media sample.

Syntax

HRESULT Receive(
    IMediaSample *pSample
);

Parameters

pSample
Pointer to the sample to deliver.

Return Value

Returns an HRESULT value.

Remarks

This member function overrides the CTransformFilter::Receive member function. Override only if you need more control of the process.

CVideoTransformFilter::RegisterPerfId

CVideoTransformFilter Class

Registers performance measurement identifiers.

Syntax

virtual void RegisterPerfId(void);

Return Value

No return value.

Remarks

By default, this member function registers the following performance identifiers.
Performance identifier | Registered string
m_idSkip | Video transform skip frame
m_idFrameType | Video transform frame type
m_idLate | Video transform lateness
m_idTimeTillKey | Video transform estimated time to next key

Override this member function if you want to register performance measurement identifiers in the derived class. If you do this, be sure to register these as well.

CVideoTransformFilter::ShouldSkipFrame

CVideoTransformFilter Class

Determines if the filter should start, continue, or stop skipping frames.

Syntax

BOOL ShouldSkipFrame(
    IMediaSample *pIn
);

Parameters

pIn
Pointer to the received sample to be transformed or skipped.

Return Value

Returns TRUE if the filter should skip this sample; otherwise, returns FALSE.

Remarks

This member function sets the m_bSkipping member variable to FALSE if the sample is a key frame (sync point) and returns FALSE. This stops any skipping that has started. This member function starts skipping samples (sets m_bSkipping to TRUE and returns TRUE) only if all the following conditions are true.

  • The average time to decode is more than one-fourth of the frame time.
  • The filter is running at least one frame late.
  • The next anticipated key frame is estimated to be no more than one frame early.
  • The occurrence of key frames is sufficiently frequent.

This member function sends an EC_QUALITY_CHANGE notification when sample skipping starts. After skipping starts, all samples are skipped until the next key frame arrives.

CVideoTransformFilter::StartStreaming

CVideoTransformFilter Class

Overrides CTransformFilter::StartStreaming to reset the quality control information when streaming starts or flushing starts.

Syntax

virtual HRESULT StartStreaming(void);

Return Value

Returns NOERROR.

Remarks

This member function sets several quality control member variables to 0, including m_itrLate, m_nKeyFramePeriod, m_nFramesSinceKeyFrame, m_bSkipping, and m_tDecodeStart. It sets m_itrAvgDecode to 3000, and sets m_bQualityChanged and m_bSampleSkipped to FALSE.


FOURCCMap Class

FOURCCMap class hierarchy

The FOURCCMap class provides conversion between GUID media subtypes and old-style FOURCC 32-bit media tags. In the original Microsoft® Windows® multimedia APIs, media types were tagged with 32-bit values created from four 8-bit characters and were known as FOURCCs. Microsoft DirectShow® media types have GUIDs for the subtype, partly because these are simpler to create (creation of a new FOURCC requires its registration with Microsoft). Because FOURCCs are unique, a one-to-one mapping has been made possible by allocating a range of 4,000 million GUIDs representing FOURCCs. This range is all GUIDs of the form:

XXXXXXXX-0000-0010-8000-00AA00389B71

This class simplifies conversion between GUIDs and FOURCCs. This is for compatibility only. It is recommended that all new media subtypes be represented by GUIDs created by Guidgen.exe or a similar tool, and not by mapping FOURCCs.

The object is derived from a GUID, with no extra data members, and can be cast to a GUID. The object can be passed a FOURCC at construction time. The default constructor will initialize the FOURCC to zero.

The GetFOURCC and SetFOURCC methods do not check that the fixed portions of the GUID correspond to the FOURCC range. Thus, if you cast a pointer to a GUID into a pointer to a FOURCC and then set or get the FOURCC field, you also need to check separately that the GUID is within the FOURCC range.

Member Functions

FOURCCMap | Constructs a FOURCCMap object.
GetFOURCC | Retrieves the FOURCC from a FOURCCMap object.
SetFOURCC | Sets the FOURCC portion of the FOURCCMap object.

FOURCCMap::FOURCCMap

FOURCCMap Class

Constructs a FOURCCMap object. Provides a mapping between old-style multimedia format DWORD types and new-style GUID types.

Syntax

FOURCCMap( );

FOURCCMap(

  DWORD Fourcc

  );

FOURCCMap(

  const GUID *pguid

  );

Parameters

Fourcc
DWORD media tag formerly used for Microsoft multimedia types.
pguid
Pointer to the globally unique identifier (GUID).

Return Value

No return value.

Remarks

If this object is constructed with the FOURCC code, a GUID is created to match it. If this object is created with an existing GUID, the FOURCC value of the object is set to zero. Thereafter, the FOURCC value can be set or retrieved using the SetFOURCC and GetFOURCC member functions, respectively.

FOURCCMap::GetFOURCC

FOURCCMap Class

Retrieves the FOURCC DWORD from the FOURCCMap object.

Syntax

DWORD GetFOURCC(void);

Return Value

Returns the FOURCC DWORD value. Note that if you construct a GUID that was not originally derived from FOURCC, the return value will be essentially random.

FOURCCMap::SetFOURCC

FOURCCMap Class

Sets the FOURCC portion of the FOURCCMap object.

Syntax

void SetFOURCC(

  const GUID *pguid

  );

Parameters

pguid
Pointer to the returned globally unique identifier (GUID) part of the FOURCCMap object.

Return Value

No return value.


Utility Functions

This section contains reference entries for the Microsoft® DirectShow® utility functions and macros.

  • COM Helper Functions
  • DLL Setup Functions
  • Media Type Functions
  • Miscellaneous Helper Functions
  • Property Page Helper Functions
  • String Functions
  • Video and Image Functions


COM Helper Functions

Declaration: Combase.h

DECLARE_IUNKNOWN | Declares the three methods of the base interface for a new interface.
GetInterface | Retrieves an interface pointer to the requested client.
INonDelegatingUnknown | Nondelegating version of the IUnknown interface.
LoadOLEAut32 | Loads the Automation DLL (OleAut32.dll).

DECLARE_IUNKNOWN

COM Helper Functions

Declares the three methods of the base interface for a new interface.

Syntax

#define DECLARE_IUNKNOWN                                        \
    STDMETHODIMP QueryInterface(REFIID riid, void **ppv) {      \
        return GetOwner()->QueryInterface(riid,ppv);            \
    };                                                          \
    STDMETHODIMP_(ULONG) AddRef() {                             \
        return GetOwner()->AddRef();                            \
    };                                                          \
    STDMETHODIMP_(ULONG) Release() {                            \
        return GetOwner()->Release();                           \
    };

Remarks

When you create a new interface, it must derive from IUnknown, which has three methods: QueryInterface, AddRef, and Release. This macro simplifies the declaration process by declaring each of these methods for the new interface.

GetInterface

COM Helper Functions

Retrieves an interface pointer.

Syntax

HRESULT GetInterface(
    LPUNKNOWN pUnk,
    void **ppv
);

Parameters

pUnk
Pointer to the IUnknown interface.
ppv
Address of a pointer to the retrieved interface.

Return Value

Returns an HRESULT value.

Remarks

This member function performs a thread-safe increment of the reference count. To retrieve the interface and add a reference, call this function from your overriding implementation of the INonDelegatingUnknown::NonDelegatingQueryInterface method.

INonDelegatingUnknown

COM Helper Functions

A version of IUnknown renamed to enable a class to support both nondelegating and delegating IUnknown interfaces in the same COM object. The interface supports the following three methods, in vtable order.

Syntax

interface INonDelegatingUnknown
{
    virtual HRESULT NonDelegatingQueryInterface) (REFIID riid, LPVOID *ppv) PURE;
    virtual ULONG NonDelegatingAddRef)(void) PURE;
    virtual ULONG NonDelegatingRelease)(void) PURE;
};

Remarks

To use INonDelegatingUnknown for multiple inheritance, perform the following steps.

  1. Derive your class from an interface, for example, IMyInterface.
  2. Include DECLARE_IUNKNOWN in your class definition to declare implementations of QueryInterface, AddRef, and Release that call the outer unknown.
  3. Override NonDelegatingQueryInterface to expose IMyInterface with code such as the following:
         if (riid == IID_IMyInterface) {
         return GetInterface((IMyInterface *) this, ppv);
     } else {
         return CUnknown::NonDelegatingQueryInterface(riid, ppv);
     }
  4. Declare and implement the member functions of IMyInterface.

To use INonDelegatingUnknown for nested interfaces, perform the following steps:

  1. Declare a class derived from CUnknown.
  2. Include DECLARE_IUNKNOWN in your class definition.
  3. Override NonDelegatingQueryInterface to expose IMyInterface with the code such as the following:
         if (riid == IID_IMyInterface) {
         return GetInterface((IMyInterface *) this, ppv);
     } else {
         return CUnknown::NonDelegatingQueryInterface(riid, ppv);
     }
  4. Implement the member functions of IMyInterface. Use CUnknown::GetOwner to access the COM object class.
  5. In your COM object class, make the nested class a friend of the COM object class, and declare an instance of the nested class as a member of the COM object class.

    Because you must always pass the outer unknown and an HRESULT to the CUnknown constructor, you can't use a default constructor. You have to make the member variable a pointer to the class and make a new call in your constructor to actually create it.

  6. Override the NonDelegatingQueryInterface with code such as the following:

     if (riid == IID_IMyInterface) {
         return m_pImplFilter->
            NonDelegatingQueryInterface(IID_IMyInterface, ppv);
     } else {
         return CUnknown::NonDelegatingQueryInterface(riid, ppv);
     }

You can have mixed classes that support some interfaces through multiple inheritance and some interfaces through nested classes.

LoadOLEAut32

COM Helper Functions

Loads the Automation dynamic-link library (OleAut32.dll).

Syntax

HINSTANCE LoadOLEAut32( );

Return Value

Returns a handle to an Automation DLL instance.

Remarks

When the CBaseObject destructor destroys the object that loaded OleAut32.dll, it will unload the library if it is still loaded.


DLL and Setup Functions

Microsoft DirectX 8.0

DLL Setup Functions

Declaration: Dllsetup.h.

AMovieDllRegisterServer | Obsolete.
AMovieDllRegisterServer2 | Registers and unregisters filters.
AMovieDllUnregisterServer | Obsolete.
AMovieSetupRegisterFilter | Obsolete.
AMovieSetupRegisterFilter2 | Registers a filter's merit, pins, and media types.

AMovieDllRegisterServer

DLL and Setup Functions

Obsolete. Use AMovieDllRegisterServer2 instead.

Syntax

HRESULT AMovieDllRegisterServer(void);

AMovieDllRegisterServer2

DLL and Setup Functions

Registers and unregisters filters.

Syntax

HRESULT AMovieDllRegisterServer2(
    BOOL bRegister
);

Parameters

bRegister
TRUE indicates register the filter, FALSE indicates unregister it.

Return Value

Returns an HRESULT value of NOERROR if the method succeeds. Otherwise an error code is returned.

Remarks

Use this function to set up your filters. For more information, see How to Register DirectShow Filters and the sample filters included with the SDK.

Note The filter registration process is changing to allow filters to register by category. For example, capture filters and compression filters are enumerated together in their respective categories. The following functions demonstrate how filter registration and unregistration by category might work. The following function uses the IFilterMapper2 interface.

static const WCHAR *g_wszName = L"Sample Compressor Filter" ;

// register sample compressor filter
STDAPI
DllRegisterServer( void )
{

    // register the server
    HRESULT hr = AMovieDllRegisterServer2( TRUE );
    if( FAILED(hr) )
        return hr;

    IFilterMapper2 *pFm2 = 0;

    hr = CoCreateInstance( CLSID_FilterMapper2
                           , NULL
                           , CLSCTX_INPROC_SERVER
                           , IID_IFilterMapper2
                           , (void **)&pFm2 );

    if(FAILED(hr))
        return hr;

    static const AMOVIESETUP_MEDIATYPE sudAVICoTypeOut =  {
        &MEDIATYPE_Video,
        &MEDIASUBTYPE_SampleVideoType };

    static const AMOVIESETUP_MEDIATYPE sudAVICoTypeIn =  {
        &MEDIATYPE_Video,
        &GUID_NULL };

    static const AMOVIESETUP_PIN psudAVICoPins[] =
    {
        {
            L"Input"        // strName
            , FALSE         // bRendered
            , FALSE         // bOutput
            , FALSE         // bZero
            , FALSE         // bMany
            , &CLSID_NULL   // clsConnectsToFilter
            , 0             // strConnectsToPin
            , 1             // nTypes
            , &sudAVICoTypeIn } // lpTypes
        , { L"Output"       // strName
            , FALSE         // bRendered
            , TRUE          // bOutput
            , FALSE         // bZero
            , FALSE         // bMany
            , &CLSID_NULL   // clsConnectsToFilter
            , 0             // strConnectsToPin
            , 1             // nTypes
            , &sudAVICoTypeOut
        }
    };   // lpTypes

    REGFILTER2 rf2;
    rf2.dwVersion = 1;
    rf2.dwMerit = MERIT_DO_NOT_USE;
    rf2.cPins = NUMELMS(psudAVICoPins);
    rf2.rgPins = psudAVICoPins;

    hr = pFm2->RegisterFilter(
        CLSID_SampleCompressorFilter,
        g_wszName,              // name shown to the user
        0,                      // device moniker
        &CLSID_VideoCompressorCategory,
        g_wszName,              // unique instance name
        &rf2);

    pFm2->Release();

    return hr;

}

// unregister sample compressor filter
STDAPI
DllUnregisterServer( void )
{

    HRESULT hr = AMovieDllRegisterServer2( FALSE );
    if( FAILED(hr) )
        return hr;

    IFilterMapper2 *pFm2 = 0;

    hr = CoCreateInstance( CLSID_FilterMapper2
                           , NULL
                           , CLSCTX_INPROC_SERVER
                           , IID_IFilterMapper2
                           , (void **)&pFm2       );

    if(FAILED(hr))
        return hr;

    hr = pFm2->UnregisterFilter(
        &CLSID_VideoCompressorCategory,
        g_wszName,
        CLSID_SampleCompressorFilter);

    pFm2->Release();

    return hr;
}

AMovieDllUnregisterServer

DLL and Setup Functions

Obsolete. Use AMovieDllRegisterServer2 instead.

Syntax

HRESULT AMovieDllUnregisterServer(void);

AMovieSetupRegisterFilter

DLL and Setup Functions

Obsolete. Use AMovieSetupRegisterFilter2 instead.

Syntax

HRESULT AMovieSetupRegisterFilter(
    const AMOVIESETUP_FILTER const *psetupdata,
    IFilterMapper *pIFM,
    BOOL bRegister
);

AMovieSetupRegisterFilter2

DLL and Setup Functions

Registers a filter's merit, pins, and media types in the registry using IFilterMapper2.

Syntax

HRESULT AMovieSetupRegisterFilter2(
    const AMOVIESETUP_FILTER const *psetupdata,
    IFilterMapper2 *pIFM2,
    BOOL bRegister
);

Parameters

psetupdata
Pointer to the AMOVIESETUP_FILTER data.
pIFM
Pointer to IFilterMapper2 interface.
bRegister
Value indicating whether to register the filter; TRUE indicates register the filter, FALSE indicates unregister it.

Return Value

Returns an HRESULT value of NOERROR if the method succeeds. Otherwise, returns an error code.

Remarks

AMovieDllRegisterServer2 uses this helper function to register a filter after the COM server has been registered.

Typically, a filter will use AMovieDllRegisterServer2 and will not call this function directly.


Media Type Functions

Declaration: Mtype.h.

The Mtype.h header file in the Microsoft® DirectShow® base classes provides helper functions for handling media types. These general-purpose functions create, copy and delete a task-allocated AM_MEDIA_TYPE structure. This is useful when using the IEnumMediaTypes interface, because the implementation allocates the structures that must be deleted later.

The functions are paired as follows:

  • CreateMediaType is the opposite of DeleteMediaType.
  • FreeMediaType is the opposite of CopyMediaType.
AreEqualVideoTypes | Compares the format, height, and width of two video sources.
CopyMediaType | Copies a task-allocated AM_MEDIA_TYPE structure.
CreateAudioMediaType | Initializes a media type structure given a wave format structure.
CreateMediaType | Allocates and initializes an AM_MEDIA_TYPE structure.
DeleteMediaType | Deletes a task-allocated AM_MEDIA_TYPE structure.
FreeMediaType | Frees a task-allocated AM_MEDIA_TYPE structure from memory.

AreEqualVideoTypes

Media Type Functions

Determines if two media types have the same video format, width, and height.

Syntax

BOOL WINAPI AreEqualVideoTypes (
    CMediaType *pmt1,
    CMediaType *pmt2
    );

Parameters

pmt1
Pointer to the first media type to compare.
pmt2
Pointer to the second media type to compare.

Return Value

Returns TRUE if pmt1 and pmt2 have the same video format, width, and height or FALSE otherwise.

CopyMediaType

Media Type Functions

Copies a task-allocated AM_MEDIA_TYPE structure.

Syntax

void WINAPI CopyMediaType(
    AM_MEDIA_TYPE *pmtTarget,
    const AM_MEDIA_TYPE *pmtSource
    );

Parameters

pmtTarget
Pointer to an area of memory in which to place the new copy of the structure.
pmtSource
Pointer to a source structure to copy.

Return Value

No return value.

Remarks

Free the resources in the pmtTarget structure by calling FreeMediaType when your code is done with the structure.

CreateAudioMediaType

Media Type Functions

Initializes a media type structure given a wave format structure.

Syntax

STDAPI CreateAudioMediaType(
    const WAVEFORMATEX *pwfx,
    AM_MEDIA_TYPE *pmt,
    BOOL bSetFormat
    );

Parameters

pwfx
Pointer to the supplied WAVEFORMATEX structure.
pmt
Pointer to the AM_MEDIA_TYPE structure to initialize.
bSetFormat
Flag indicating whether to initialize the format section of the AM_MEDIA_TYPE structure, specifically the cbFormat and pbFormat members. Specify TRUE to initialize the format section, FALSE otherwise.

Return Value

Returns E_OUTOFMEMORY if memory could not be allocated for the format data; S_OK otherwise.

CreateMediaType

Media Type Functions

Creates a task-allocated AM_MEDIA_TYPE structure.

Syntax

AM_MEDIA_TYPE * WINAPI CreateMediaType(
    AM_MEDIA_TYPE const *pSrc
    );

Parameters

pSrc
Pointer to an AM_MEDIA_TYPE source structure.

Return Value

Returns a new AM_MEDIA_TYPE structure, or NULL if there is an error.

Remarks

Free the structure and resources allocated by this routine by calling DeleteMediaType when your code is done with the structure.

DeleteMediaType

Media Type Functions

Deletes a task-allocated AM_MEDIA_TYPE structure.

Syntax

void WINAPI DeleteMediaType(
    AM_MEDIA_TYPE *pmt
    );

Parameters

pmt
Pointer to an AM_MEDIA_TYPE structure.

Return Value

No return value.

Remarks

The structure should have been created by a call to CreateMediaType.

FreeMediaType

Media Type Functions

Frees a task-allocated AM_MEDIA_TYPE structure from memory.

Syntax

void WINAPI FreeMediaType(
    AM_MEDIA_TYPE& mt
    );

Parameters

mt
Pointer to the structure.

Return Value

No return value.

Remarks

The structure should have been initialized by a call to CopyMediaType.


Miscellaneous Helper Functions

Declaration: Wxutil.h.

EqualPins | Checks if two pins are on the same object.
Int64x32Div32 | Implements ((a*b)+rnd)/c for 64-bit values of a.
IsEqualObject | Checks if two interfaces are on the same object.
llMulDiv | Implements ((a*b)+rnd)/c for 32-bit values of a.
WaitDispatchingMessages | Waits for an object to be signaled, while dispatching window messages.

EqualPins

Miscellaneous Helper Functions

Checks if two pins are on the same object.

Syntax

BOOL EqualPins(
    IUnknown *pPin1,
    IUnknown *pPin2
);

Parameters

pPin1
Pointer to one pin.
pPin2
Pointer to the other pin.

Return Value

Returns TRUE if both pins are on the same object, or FALSE otherwise.

Int64x32Div32

Miscellaneous Helper Functions

Multiplies a by b, adds rnd to the 96-bit result, then divides by c.

Syntax

LONGLONG WINAPI Int64x32Div32(
  LONGLONG a,
  LONG b,
  LONG c,
  LONG rnd
  );

Return Value

Returns either the (a * b + rnd)/c calculation or one of the following values.

0x7FFFFFFFFFFFFFFF | Overflow occurred because the result is too large (positive).
0x8000000000000000 | Overflow occurred because the result is too large (negative).

Remarks

Rounding on the division is toward zero. Division by zero is counted as an overflow condition.

IsEqualObject

Miscellaneous Helper Functions

Checks if two interfaces are on the same object.

Syntax

BOOL WINAPI IsEqualObject(
    IUnknown *pFirst,
    IUnknown *pSecond
);

Parameters

pFirst
Pointer to one interface.
pSecond
Pointer to the other interface.

Return Value

Returns TRUE if the interfaces are both on the same object, or FALSE otherwise.

llMulDiv

Miscellaneous Helper Functions

Multiplies a by b, adds rnd to the 128-bit result, then divides by c.

Syntax

LONGLONG WINAPI llMulDiv(
  LONGLONG a,
  LONGLONG b,
  LONGLONG c,
  LONGLONG rnd
  );

Return Value

Returns either the (a * b + rnd)/c calculation or one of the following values.

0x7FFFFFFFFFFFFFFF | Overflow occurred because the result is too large (positive).
0x8000000000000000 | Overflow occurred because the result is too large (negative).

Remarks

Rounding on the division is toward zero. Division by zero is counted as an overflow condition.

WaitDispatchingMessages

Miscellaneous Helper Functions

Waits for an object to be signaled, while dispatching window messages.

Syntax

DWORD WINAPI WaitDispatchingMessages(
    HANDLE hObject,
    DWORD dwWait,
    HWND hwnd = NULL,
    UINT uMsg = 0
    HANDLE hEvent = NULL;
);

Parameters

hObject
Handle of the object to wait for.
dwWait
Time-out interval, in milliseconds.
hwnd
Optional handle to a window.
uMsg
Optional window message, specifying a message to dispatch.
hEvent
Optional handle to an event to wait for.

Return Value

Returns the value from the WaitForMultipleObjects function.

Remarks

If an object owns a window, it should dispatch window messages while waiting. This function enables the object to wait for an event, semaphore, or other mutual exclusion object while dispatching messages.


Property Page Helper Functions

The Videoctl.h header file in the Microsoft® DirectShow® base classes provides functions to help with property page implementations.

GetDialogSize | Retrieves the size of a resource dialog box in screen pixels.
StringFromResource | Loads a string from a resource file with the given resource identifier.
WideStringFromResource | Loads a Unicode™ string from a resource file with the given resource identifier.

GetDialogSize

Property Page Helper Functions

Retrieves the size of a resource dialog box.

Syntax

BOOL WINAPI GetDialogSize(
    int iResourceID,
    DLGPROC pDlgProc,
    LPARAM lParam,
    SIZE *pResult
);

Parameters

iResourceID
Dialog box resource identifier.
pDlgProc
Pointer to the dialog box procedure.
lParam
Value passed in the WM_INITDIALOG message sent to the temporary dialog box just after it is created.
pResult
Pointer to a SIZE structure that receives the dimensions of the dialog box, in screen pixels.

Return Value

Returns TRUE if the dialog box resource was found, or FALSE otherwise.

Remarks

Property pages can use this function to return the actual display size they require. Most property pages are dialog boxes and, as such, have dialog box templates stored in resource files. Templates use dialog box units that do not map directly onto screen pixels. However, a property page's GetPageInfo function must return the actual display size in pixels. The property page can call GetDialogSize to calculate the display size.

This function creates a temporary instance of the dialog box. To avoid having the dialog box appear on the screen, the dialog box template in the resource file should not have a WS_VISIBLE property.

StringFromResource

Property Page Helper Functions

Loads a string from a resource file with the given resource identifier.

Syntax

TCHAR * WINAPI StringFromResource(
    TCHAR *pBuffer,
    int iResourceID
);

Parameters

pBuffer
Pointer to the string corresponding to iResourceID.
iResourceID
Resource identifier of the string to retrieve.

Return Value

Returns the same string as pBuffer. If the function is not successful, returns a null string.

Remarks

The pBuffer buffer must be at least STR_MAX_LENGTH bytes.

WideStringFromResource

Property Page Helper Functions

Loads a Unicode™ string from a resource file with the given resource identifier.

Syntax

WCHAR * WINAPI WideStringFromResource(
    WCHAR *pBuffer,
    int iResourceID
);

Parameters

pBuffer
Pointer to the string corresponding to iResourceID.
iResourceID
Resource identifier of the string to retrieve.

Return Value

Returns the same string as pBuffer. If the function is not successful, returns a null string.

Remarks

Property pages are typically called through their COM interfaces, which use Unicode™ strings regardless of how the binary is built. This function allows you to convert a resource string to a Unicode string. The function converts the resource to a Unicode string (if it is not already one) after loading it.


String Functions

Declaration: Wxutil.h

AMGetWideString | Allocates and creates a wide string version of an existing nonwide string.
atoi | Converts a string to an integer.
FreeBSTR | Frees the task-allocated BSTR string.
IntToWstr | Converts an integer to a wide string.
lstrcmpiW | Compares two wide strings, ignoring case.
lstrcmpW | Compares two wide strings.
lstrcpynW | Copies one wide string to another, with a maximum length.
lstrcpyW | Copies one wide string to another.
lstrlenW | Retrieves the length of a wide string in wide characters.
WriteBSTR | Creates a task-allocated BSTR string by allocating task-allocated memory and copying a wide string to it.
WstrToInt | Converts a wide string to an integer.

AMGetWideString

String Functions

Allocates and creates a Unicode™ version of an existing non-Unicode string.

Syntax

STDAPI AMGetWideString(
    LPCWSTR pszString,
    LPWSTR *ppszReturn
    );

Parameters

pszString
Pointer to a non-Unicode source string.
ppszReturn
Address of a pointer to a Unicode™ string that will contain pszString.

Return Value

Returns S_OK if successful, E_POINTER if ppszReturn is NULL, or E_OUTOFMEMORY if not enough memory is available.

atoi

String Functions

Converts a given string to an integer.

Syntax

int WINAPI atoi(
    const TCHAR *sz
    );

Parameters

sz
Pointer to a source character string.

Return Value

Returns the string's integer value.

Remarks

This version of atoi supports only decimal digits, and does not allow leading white space or signs. It supports both Unicode™ and ANSI strings. Other versions can vary.

FreeBSTR

String Functions

Frees a task-allocated BSTR string from memory.

Syntax

STDAPI FreeBSTR(
    BSTR *pstr
    );

Parameters

pstr
Pointer to the BSTR to free.

Return Value

Returns S_OK if successful, or S_FALSE if pstr is null.

Remarks

Memory is allocated for passing between objects across interfaces by calling CoTaskMemAlloc. It is freed by calling CoTaskMemFree. You can allocate, pass, and free memory safely between objects created in different programming languages by using a central memory allocator.

IntToWstr

String Functions

Converts a given integer value to a wide string representation.

Syntax

void IntToWstr(
    int i,
    LPWSTR wstrDest
    );

Parameters

i
Integer value to be converted.
wstrDest
Pointer to the wide-character string that will contain the converted string.

Return Value

No return value.

lstrcmpiW

String Functions

Compares two wide-character strings. The comparison is not case sensitive.

Syntax

int lstrcmpiW(
    LPCWSTR lpszString1,
    LPCWSTR lpszString2
    );

Parameters

lpszString1
Pointer to the first null-terminated wide string to be compared.
lpszString2
Pointer to the second null-terminated wide string to be compared.

Return Value

Returns a negative value if the function succeeds and the string that lpszString1 points to is less than the string that lpszString2 points to. Returns a positive value if the string that lpszString1 points to is greater than the string that lpszString2 points to. Returns zero if the strings are equal.

Remarks

The lstrcmpiW function compares two wide strings by checking the first characters against each other, the second characters against each other, and so on until it finds an inequality or reaches the ends of the strings.

The function returns the difference of the values of the first unequal characters it encounters. For instance, lstrcmpiW determines that L"abcz" is greater than L"abcdefg" and returns the difference of L'z' and L'd'.

The language (locale) is treated as always being English.

lstrcmpW

String Functions

Compares two wide-character strings. The comparison is case sensitive.

Syntax

int lstrcmpW(
    LPCWSTR lpszString1,
    LPCWSTR lpszString2
    );

Parameters

lpszString1
Pointer to the first null-terminated wide string to be compared.
lpszString2
Pointer to the second null-terminated wide string to be compared.

Return Value

Returns a negative value if the function succeeds and the string that lpszString1 points to is less than the string that lpszString2 points to. Returns a positive value if the string that lpszString1 points to is greater than the string that lpszString2 points to. Returns zero if the strings are equal.

Remarks

The lstrcmpW function compares two wide strings by checking the first characters against each other, the second characters against each other, and so on until it finds an inequality or reaches the ends of the strings.

The function returns the difference of the values of the first unequal characters it encounters. For instance, lstrcmpW determines that L"abcz" is greater than L"abcdefg" and returns the difference of L'z' and L'd'.

The language (locale) is treated as always being English.

lstrcpyW

String Functions

Copies a wide string to a buffer.

Syntax

LPWSTR lstrcpyW(
    LPWSTR lpszString1,
    LPCWSTR lpszString2
    );

Parameters

lpszString1
Pointer to a buffer to receive the contents of the string pointed to by the lpszString2 parameter. The buffer must be large enough to contain the string, including the terminating wide null character.
lpszString2
Pointer to the null-terminated wide string to be copied.

Return Value

Returns a pointer to the buffer.

lstrcpynW

String Functions

Copies a wide string to a buffer, up to a specified number of wide characters.

Syntax

LPWSTR lstrcpynW(
    LPWSTR lpszString1,
    LPCWSTR lpszString2,
    int iMaxLength
    );

Parameters

lpszString1
Pointer to a buffer to receive the contents of the string that the lpszString2 parameter points to. The buffer must be large enough to contain the string, including the terminating wide null character.
lpszString2
Pointer to the null-terminated wide string to be copied.
iMaxLength
Maximum number of wide characters to copy, including a terminating null character.

Return Value

Returns a pointer to the buffer.

Remarks

If iMaxLength is nonzero, lstrcpynW always inserts a terminating null wide character in the destination string, which could result in the source string being truncated.

lstrlenW

String Functions

Retrieves the length of the specified wide string.

Syntax

int lstrlenW(
    LPCWSTR lpszString
    );

Parameters

lpszString
Pointer to a null-terminated wide string.

Return Value

If the function succeeds, the return value specifies the length of the string, in wide characters.

WriteBSTR

String Functions

Allocates and fills a task-allocated BSTR string.

Syntax

STDAPI WriteBSTR(
    BSTR *pstrDest,
    LPCWSTR szSrc
    );

Parameters

pstrDest
Pointer to where the allocated BSTR will be stored.
szSrc
Pointer to a wide (Unicode™) string that will be copied to the newly allocated BSTR string.

Return Value

Returns an HRESULT value.

Remarks

Memory is allocated for passing between objects across interfaces by calling CoTaskMemAlloc. It is freed by calling CoTaskMemFree. By using a central memory allocator, memory can be allocated, passed, and freed safely between objects created in different programming languages.

WstrToInt

String Functions

Converts a given wide string value to an integer.

Syntax

int WstrToInt(
    LPCWSTR wstrSrc
    );

Parameters

wstrSrc
Pointer to the source wide-character string.

Return Value

Returns the string's integer value.


Video and Image Functions

Declaration: Wxutil.h

The Wxutil.h header file in the Microsoft® DirectShow® base classes provides functions and macros to help convert between VIDEOINFOHEADER and BITMAPINFO structures.

BIT_MASKS_MATCH | Compares the masks of two video images.
BITMASKS | Retrieves a pointer to the array of bitmasks for the specified VIDEOINFOHEADER structure.
COLORS | Retrieves a pointer to an array of RGBQUAD structures that describes the color palette for the specified VIDEOINFOHEADER structure.
ContainsPalette | Checks if the video image contains a color palette.
ConvertVideoInfoToVideoInfo2 | Converts a VIDEOINFO stream format to a VIDEOINFOHEADER2 format.
DIBSIZE | Calculates the byte size of the specified bitmap
GetBitCount | Finds the number of bits per pixel.
GetBitmapFormatSize | Finds the size (in bytes) needed to build a VIDEOINFOHEADER structure and related data.
GetBitmapPalette | Finds the first palette entry in a VIDEOINFOHEADER structure.
GetBitmapSize | Finds the size (in bytes) needed to hold an image.
GetBitmapSubtype | Finds the GUID subtype for a given bitmap info header structure.
GetSubtypeName | Finds the (debug) name for a given GUID subtype.
GetTrueColorType | Finds the GUID subtype for a given bitmap header.
HEADER | Retrieves a pointer to the image data from the specified video image.
MPEG1_SEQUENCE_INFO | Retrieves the sequence header for the specified MPEG-1 video image.
PALETTISED | Checks if the video image's color palette is 8-bit or less.
PALETTE_ENTRIES | Returns the number of colors in the video image's palette.
RESET_MASKS | Clears the specified video image's bitmasks.
RESET_HEADER | Clears the specified video image.
RESET_PALETTE | Clears the specified video image's color palette.
SIZE_EGA_PALETTE | Calculates the size of the EGA (4-bit) color palette.
SIZE_MASKS | Calculates the size of the mask's color palette.
SIZE_MPEG1VIDEOINFO | Calculates the size of the specified MPEG-1 video image.
SIZE_PALETTE | Calculates the size of the 8-bit color palette.
SIZE_PREHEADER | Calculates the byte offset for the video image's bitmap information.
SIZE_VIDEOHEADER | Calculates the size of the video image.
TRUECOLORINFO | Retrieves a pointer to an array of TRUECOLORINFO structures that describes the bitmasks and color palette for the specified VIDEOINFOHEADER structure.

These functions are made available to help manage VIDEOINFOHEADER structures, which are used throughout DirectShow to describe video data streams. Although similar to the BITMAPINFO structure used in Microsoft® Win32® and existing multimedia, VIDEOINFOHEADER also adds some new video-specific fields.

Global data | Description
bits555 | Array of color bitmasks for an RGB 555 bitmap.
bits565 | Array of color bitmasks for an RGB 565 bitmap.
bits888 | Array of color bitmasks for an RGB 24-bit bitmap.

BIT_MASKS_MATCH

Video and Image Functions

Retrieves the bitmasks for the specified video image.

Syntax

BIT_MASKS_MATCH(
  pbmi1,
  pbmi2
  )

Parameters

pbmi1
Pointer to a Win32 VIDEOINFOHEADER structure that contains the first video image.
pbmi2
Pointer to a Win32 VIDEOINFOHEADER structure that contains the second video image.

Return Value

Returns nonzero if the bitmasks for both video images are identical or zero otherwise.

BITMASKS

Video and Image Functions

Retrieves the bitmasks for the specified video image.

Syntax

BITMASKS(
  pbmi
  )

Parameters

pbmi
Pointer to a Win32 VIDEOINFOHEADER structure that contains the video image.

Return Value

Returns a pointer to the array of bitmasks for the specified VIDEOINFOHEADER structure.

COLORS

Video and Image Functions

Retrieves the color palette for the specified video image.

Syntax

COLORS(
  pbmi
  )

Parameters

pbmi
Pointer to a Win32 VIDEOINFOHEADER structure that contains the video image.

Return Value

Returns a pointer to an array of RGBQUAD structures that describes the color palette for the specified VIDEOINFOHEADER structure.

ContainsPalette

Video and Image Functions

Checks if the specified video image contains a color palette.

Syntax

BOOL ContainsPalette(
  const VIDEOINFOHEADER *pVideoInfo
  );

Parameters

pVideoInfo
Pointer to a VIDEOINFOHEADER structure.

Return Value

Returns TRUE if the VIDEOINFOHEADER structure contains a color palette or FALSE otherwise.

ConvertVideoInfoToVideoInfo2

Video and Image Functions

Converts a VIDEOINFO stream format to a VIDEOINFOHEADER2 format.

Syntax

STDAPI ConvertVideoInfoToVideoInfo2(
    AM_MEDIA_TYPE *pmt
    );

Parameters

pmt
[in/out] Pointer to the AM_MEDIA_TYPE enumerated type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. HRESULT can include one of the following standard constants, or other values not listed.

E_OUTOFMEMORY | Operation ran out of memory.
S_OK | Success.

Remarks

If successful, this function modifies the formattype member of AM_MEDIA_TYPE to change its registered GUID from a VIDEOINFO type to a VIDEOINFOHEADER2 type.

DIBSIZE

Video and Image Functions

Calculates the byte size of the specified (device-independent) bitmap.

Syntax

DIBSIZE(
  bi
  )

Parameters

bi
A Win32 BITMAPINFOHEADER structure that specifies the source bitmap.

Return Value

Returns the byte size of the bi parameter.

GetBitCount

Video and Image Functions

Finds the number of bits per pixel.

Syntax

WORD GetBitCount(
  const GUID *pSubtype
  );

Parameters

pSubtype
Pointer to a GUID for a given video subtype.

Return Value

Returns the number of bits per pixel for this subtype, or USHRT_MAX if an error occurred.

GetBitmapFormatSize

Video and Image Functions

Finds the size (in bytes) needed to build a VIDEOINFOHEADER structure and related data.

Syntax

LONG GetBitmapFormatSize(
  const BITMAPINFOHEADER *pHeader
  );

Parameters

pHeader
Pointer to a Win32 BITMAPINFOHEADER structure.

Return Value

Returns the number of bytes for the VIDEOINFOHEADER structure described by this BITMAPINFOHEADER, including prefix information, the BITMAPINFOHEADER field, and any other color information on the end.

GetBitmapPalette

Video and Image Functions

Finds the first palette for a VIDEOINFOHEADER structure.

Syntax

const RGBQUAD * GetBitmapPalette(
  const VIDEOINFOHEADER *pVideoInfo
  );

Parameters

pVideoInfo
Pointer to a VIDEOINFOHEADER structure.

Return Value

Returns a pointer to the first entry in a palette.

GetBitmapSize

Video and Image Functions

Finds the number of bytes needed to hold an image.

Syntax

DWORD GetBitmapSize(
  const BITMAPINFOHEADER *pHeader
  );

Parameters

pHeader
Pointer to a Win32 BITMAPINFOHEADER structure.

Return Value

Returns the number of bytes needed to hold an image.

GetBitmapSubtype

Video and Image Functions

Finds the subtype for the specified bitmap.

Syntax

const GUID GetBitmapSubtype(
  const BITMAPINFOHEADER *pHeader
  );

Parameters

pHeader
Pointer to a Win32 BITMAPINFOHEADER structure.

Return Value

Returns the video subtype GUID of the bitmap specified by pHeader, or GUID_NULL if pHeader is NULL.

GetSubtypeName

Video and Image Functions

Retrieves the name for a given GUID subtype.

Syntax

TCHAR * GetSubtypeName(
  const GUID *pSubtype
  );

Parameters

pSubtype
Pointer to a GUID for a given video subtype.

Return Value

Returns the debug name of this GUID, or UNKNOWN if the name is not known.

GetTrueColorType

Video and Image Functions

Finds the subtype for the specified 16-bit color bitmap.

Syntax

const GUID GetTrueColorType(
  const BITMAPINFOHEADER *pHeader
  );

Parameters

pHeader
Pointer to a Win32 BITMAPINFOHEADER structure.

Return Value

Returns the video subtype GUID of the 16-bit color bitmap specified by pHeader, or GUID_NULL if pHeader is NULL.

HEADER

Video and Image Functions

Retrieves a pointer to the image data from the specified video image.

Syntax

HEADER(
  pVideoInfo
  )

Parameters

pVideoInfo
Pointer to the VIDEOINFOHEADER structure that specifies the video image.

Return Value

Returns a pointer to the Win32 BITMAPINFOHEADER structure contained in the VIDEOINFOHEADER structure's bmiHeader data member.

MPEG1_SEQUENCE_INFO

Video and Image Functions

Retrieves the sequence header for the specified MPEG-1 video image.

Syntax

MPEG1_SEQUENCE_INFO(
  pv
  )

Parameters

pv
Pointer to an MPEG1VIDEOINFO structure.

Return Value

Returns the bSequenceHeader data member of the specified MPEG1VIDEOINFO structure.

PALETTISED

Video and Image Functions

Checks if the video image's color palette is 8-bit or less.

Syntax

PALETTISED(
  pbmi
  )

Parameters

pbmi
Pointer to the Win32 BITMAPINFOHEADER structure that specifies the video image.

Return Value

Returns nonzero if the video image's palette contains 256 or fewer colors, or zero otherwise.

PALETTE_ENTRIES

Video and Image Functions

Retrieves the number of colors in the video image's palette.

Syntax

PALETTE_ENTRIES(
  pbmi
  )

Parameters

pbmi
Pointer to the Win32 BITMAPINFOHEADER structure that specifies the video image.

Return Value

Returns the number of colors in the video image's palette.

RESET_MASKS

Clears the specified video image's bitmasks.

Syntax

RESET_MASKS(
  pbmi
  )

Parameters

pbmi
Pointer to the Win32 BITMAPINFOHEADER structure that specifies the video image.

Return Value

No return value.

RESET_HEADER

Video and Image Functions

Clears the specified video image.

Syntax

RESET_HEADER(
  pbmi
  )

Parameters

pbmi
Pointer to the Win32 BITMAPINFOHEADER structure that specifies the video image.

Return Value

No return value.

RESET_PALETTE

Video and Image Functions

Clears the specified video image's color palette.

Syntax

RESET_PALETTE(
  pbmi
  )

Parameters

pbmi
Pointer to the Win32 BITMAPINFOHEADER structure that specifies the video image.

Return Value

No return value.

SIZE_EGA_PALETTE

Video and Image Functions

Calculates the size of a 4-bit color palette.

Syntax

SIZE_EGA_PALETTE

Return Value

Returns the size of a 16-color palette, in bytes.

SIZE_MASKS

Video and Image Functions

Calculates the size of a bitmask's color palette.

Syntax

SIZE_MASKS

Return Value

Returns the size, in bytes, of a bitmap mask's color palette, which has three colors.

SIZE_MPEG1VIDEOINFO

Video and Image Functions

Calculates the size of the specified MPEG-1 video image.

Syntax

SIZE_MPEG1VIDEOINFO(
  pv
  )

Parameters

pv
Pointer to the MPEG1VIDEOINFO structure that specifies the video image.

Return Value

Returns the byte size of the specified MPEG1VIDEOINFO structure.

SIZE_PALETTE

Video and Image Functions

Calculates the size of the 8-bit color palette.

Syntax

SIZE_PALETTE

Return Value

Returns the size of the 256-color palette.

SIZE_PREHEADER

Video and Image Functions

Calculates the byte offset for the video image's bitmap information.

Syntax

SIZE_PREHEADER

Return Value

Returns the byte offset of the VIDEOINFOHEADER structure's bmiHeader data member.

SIZE_VIDEOHEADER

Video and Image Functions

Calculates the size of the video image.

Syntax

SIZE_VIDEOHEADER

Return Value

Returns the combined size of all of the VIDEOINFOHEADER structure's data members.

TRUECOLORINFO

Video and Image Functions

Retrieves the color palette and bitmasks for the specified video image.

Syntax

TRUECOLORINFO(
  pbmi
  )

Parameters

pbmi
Pointer to a Win32 VIDEOINFOHEADER structure that contains the video image.

Return Value

Returns a pointer to an array of TRUECOLORINFO structures that describes the bitmasks and color palette for the specified VIDEOINFOHEADER structure.


Debugging Utilities

This section contains reference entries for the macros and functions that Microsoft® DirectShow® supplies to assist debugging. To use these functions, you must build the base class library. For more information, see Debugging with DirectShow.

  • Assert and Breakpoint Macros
  • Critical Section Debugging Functions
  • Debug Output Functions
  • Pointer Validation Macros
  • Wait Debugging Functions


Assert and Breakpoint Macros

The Microsoft® DirectShow® base classes provide several macros that perform asserts or cause breakpoints.

Declaration: Wxdebug.h

Macro | Description
ASSERT | Evaluates an expression, and displays a diagnostic message if the expression is FALSE.
DbgAssertAligned | Tests whether a pointer is aligned to a specified boundary.
DbgBreak | Displays a message box with the specified string, the name of the source file, and the line number.
EXECUTE_ASSERT | Evaluates an expression in debug and retail builds. In debug builds, displays a diagnostic message if the expression is FALSE.
KASSERT | Evaluates an expression, and causes a breakpoint exception if the expression is FALSE.
KDbgBreak | Causes a breakpoint exception, and logs the specified string.

ASSERT

Assert and Breakpoint Macros

Evaluates an expression, and displays a diagnostic message if the expression is FALSE. Ignored in retail builds.

Syntax

ASSERT(
    cond
);

Parameters

cond
Expression to evaluate.

Remarks

In debug builds, if the expression is FALSE, this macro displays a message box with the text of the expression, the name of the source file, and the line number. The user can ignore the assertion, enter the debugger, or quit the application.

Example

ASSERT(rtStartTime <= rtEndTime);

DbgAssertAligned

Assert and Breakpoint Macros

Tests whether a pointer is aligned to a specified boundary. If not, this macro invokes the ASSERT macro. Ignored in retail builds.

Syntax

DbgAssertAligned(
    ptr,
    alignment
);

Parameters

ptr
Pointer variable.
alignment
Required alignment.

DbgBreak

Assert and Breakpoint Macros

Displays a message box with the specified string, the name of the source file, and the line number. The user can ignore the message, enter the debugger, or quit the application. Ignored in retail builds.

Syntax

DbgBreak(
    strLiteral
);

Parameters

strLiteral
Text string.

Example

DbgBreak("Unrecoverable error occurred.");

EXECUTE_ASSERT

Assert and Breakpoint Macros

Evaluates an expression in debug and retail builds. In debug builds, displays a diagnostic message if the expression is FALSE.

Syntax

EXECUTE_ASSERT(
    cond
);

Parameters

cond
Expression to evaluate.

Remarks

Unlike the ASSERT macro, this macro evaluates the expression in retail builds. In debug builds, if the expression is FALSE, the macro displays a message box with the text of the expression, the name of the source file, and the line number. The user can ignore the assertion, enter the debugger, or quit the application.

KASSERT

Assert and Breakpoint Macros

Evaluates an expression, and causes a breakpoint exception if the expression is FALSE. The text of the expression, the name of the source file, and the line number are logged using the DbgLog macro. Ignored in retail builds.

Syntax

KASSERT(
    cond
);

Parameters

cond
Expression to evaluate.

Remarks

Unlike the ASSERT and EXECUTE_ASSERT macros, this macro does not display a message box prompting the user. In debug builds, if the expression is FALSE, the macro automatically causes a breakpoint exception to occur.

KDbgBreak

Assert and Breakpoint Macros

Causes a breakpoint exception, and logs the specified string using the DbgLog macro. Ignored in retail builds.

Syntax

KDbgBreak(
    strLiteral
);

Parameters

strLiteral
Text string.

Remarks

Unlike the DbgBreak macro, this macro does not display a message box prompting the user. In debug builds, it automatically causes a breakpoint exception to occur.


Critical Section Debugging Functions

These functions help to debug critical sections in your code, which can make it easier to find the cause of a deadlock. These functions use the CCritSec helper class.

Declaration: Wxutil.h.

CritCheckIn | Returns TRUE if the current thread owns the specified critical section.
CritCheckOut | Returns FALSE if the current thread owns the specified critical section.
DbgLockTrace | Enables or disables debug logging for a given critical section.

CritCheckIn

Critical Section Debugging Functions

Returns TRUE if the current thread is the owner of the specified critical section.

Syntax

BOOL WINAPI CritCheckIn(
    CCritSec *pcCrit
);

Parameters

pcCrit
Pointer to a CCritSec critical section.

Return Value

In debug builds, returns TRUE if the current thread is the owner of this critical section, or FALSE otherwise. In retail builds, always returns TRUE.

Remarks

This function is especially useful within the ASSERT macro, to test whether a thread owns a given lock.

The following code example shows how to use this function:

{
    CCritSec MyLock;  // Critical section is not locked yet.

    ASSERT(CritCheckIn(&MyLock)); // This assert will fire.

    // Lock the critical section.
    CAutoLock cObjectLock(&MyLock);

    ASSERT(CritCheckIn(&MyLock)); // This assert will not fire.

} // Lock goes out of scope here.

CritCheckOut

Critical Section Debugging Functions

Returns FALSE if the current thread is the owner of the specified critical section.

Syntax

BOOL WINAPI CritCheckOut(
    CCritSec *pcCrit
);

Parameters

pcCrit
Pointer to a CCritSec critical section.

Return Value

In debug builds, returns FALSE if the current thread is the owner of this critical section, or TRUE otherwise. In retail builds, always returns TRUE.

Remarks

This function is the inverse of the CritCheckIn function. If CritCheckIn returns TRUE, CritCheckOut returns FALSE, and vice versa.

DbgLockTrace

Critical Section Debugging Functions

Enables or disables debug logging of a given critical section.

Syntax

void WINAPI DbgLockTrace(
    CCritSec *pcCrit,
    BOOL fTrace
);

Parameters

pcCrit
Pointer to a CCritSec critical section.
fTrace
Value specifying whether logging is enabled. Use TRUE to enable logging or FALSE to disable it.

Remarks

Use this function to trace a specific critical section. By default, debug logging of critical sections is disabled, because of the large number of critical sections.

To trace a critical section, perform the following steps:

  1. Define DEBUG before you include the DirectShow headers.
  2. Enable debug logging for critical sections, by calling DbgSetModuleLevel with the LOG_LOCKING flag.
  3. Call DbgLockTrace on the critical section you want to trace.

The following code example shows how to trace a critical section:

DbgInitialise(g_hInst);
DbgSetModuleLevel(LOG_LOCKING, 3);

{
    CCritSec MyLock;
    DbgLockTrace(&MyLock, TRUE);

    CAutoLock cObjectLock(&MyLock);

    // Protected section of code.
    DbgOutString("This code is inside a critical section.\n");

} // Lock goes out of scope here.

DbgTerminate();

The debug output will look similar to the following:

Example.exe(tid 360)     2012 : Thread 864 now owns lock 12fc2c
This code is inside a critical section.
Example.exe(tid 360)     4887 : Thread 864 releasing lock 12fc2c

If DEBUG is not defined when you include the DirectShow headers, the DbgLockTrace function has no effect.


Debug Output Functions

The Microsoft® DirectShow® base classes provide several macros for displaying debugging information.

Declaration: Wxdebug.h

The debugging facilities in DirectShow can be fine-tuned to display specific types of debug information, while ignoring others. With this feature, you can pinpoint problems in particular areas of your code. DirectShow defines several message types, shown in the following table.

LOG_ERROR | Error notification.
LOG_LOCKING | Locking and unlocking of critical sections.
LOG_MEMORY | Memory allocation, and object creation and destruction.
LOG_TIMING | Timing and performance measurements.
LOG_TRACE | General call tracing.

Every module can set its own debugging level for each message type. (A module is a DLL or executable that can be loaded using the Microsoft® Win32® LoadLibrary function.) A module's logging level for a given message type appears in the registry under the following key:

\HKEY_LOCAL_MACHINE\SOFTWARE\Debug\<Module Name>\<Message Type>

<Message Type> is the message type minus the initial "LOG_"; for example, LOCKING for LOG_LOCKING messages.

When a module is loaded, the debug library looks up the module's logging levels in the registry. If the registry keys do not exist, the debug library creates them. Global logging levels for a message type can be specified in the following key:

\HKEY_LOCAL_MACHINE\SOFTWARE\Debug\GLOBAL\<Message Type>

The debug library uses whichever level is greater. A module can also set its own levels at run time, using the DbgSetModuleLevel function. To send a message to the debug output, call the DbgLog macro. The following example creates a level 3 message of type LOG_TRACE:

DbgLog((LOG_TRACE, 3, "This is a debug message."));

In debug builds, if the current logging level for LOG_TRACE messages is 3 or higher, the message is sent to the debug output. Otherwise, it is ignored. Debug builds must define the preprocessor symbol DEBUG before including the base-class header file, Streams.h.

The debug output location is determined by another registry key:

\HKEY_LOCAL_MACHINE\SOFTWARE\Debug\<Module Name>\LogToFile

If the value is Console, the output goes to the console window. If the value is Deb, Debug, Debugger, or an empty string, the output goes to the debugger window. Otherwise, the output is written to a file specified by the registry key.

Before an executable uses the DirectShow debug library, it must call the DbgInitialise function. Afterward, it must call the DbgTerminate function. DLLs do not need to call these functions.

Function | Description
DbgCheckModuleLevel | Checks whether logging is enabled for the given message types and level.
DbgDumpObjectRegister | Displays information about active objects.
DbgInitialise | Initializes the debug library.
DbgLog | Sends a string to the debug output location, if logging is enabled for the specified type and level.
DbgOutString | Sends a string to the debug output location.
DbgSetModuleLevel | Sets the logging level for one or more message types.
DbgTerminate | Cleans up the debug library.
DisplayType | Sends information about a media type to the debug output location.
DumpGraph | Sends information about a filter graph to the debug output location.
NAME | Generates a debug-only string.
NOTE | Sends a string to the debug output location.
REMIND | Generates a reminder at compile time.

DbgCheckModuleLevel

Debug Output Functions

Checks whether logging is enabled for the given message types and level. Ignored in retail builds.

Syntax

BOOL DbgCheckModuleLevel(
    DWORD Types,
    DWORD Level
);

Parameters

Types
Bitwise combination of one or more message types.
Level
Logging level

Return Value

Returns TRUE if logging for any of the specified message types is set to the specified level or higher. Otherwise, returns FALSE.

DbgDumpObjectRegister

Debug Output Functions

Displays information about active objects. Ignored in retail builds.

Syntax

void DbgDumpObjectRegister(void);

Remarks

In debug builds, the debug library maintains a list of active objects. The list includes any objects that derive from CBaseObject, were created by the current module, and have not been destroyed. The CBaseObject constructor and destructor methods update the list.

This function generates several LOG_MEMORY messages. At logging level 1, the function displays only the total number of objects. At logging level 2 or higher, it displays a list of the objects.

DbgInitialise

Debug Output Functions

Initializes the debug library. Ignored in retail builds.

Syntax

void DbgInitialise(
    HINSTANCE hInst
);

Parameters

hInst
Handle to the module instance.

Remarks

In an executable, call this method before using the DirectShow debug facilities. Before the executable quits, call the DbgTerminate function to clean up the debug library.

In a DLL that links to the base-class library (Strmbase.lib), it is not necessary to call this function. The function is called automatically when the DLL is loaded.

DbgLog

Debug Output Functions

Sends a string to the debug output location, if logging is enabled for the specified type and level. Ignored in retail builds.

Syntax

void DbgLog((
    DWORD Types,
    DWORD Level,
    const TCHAR *pFormat,
    ...
));

Parameters

Types
Bitwise combination of one or more message types.
Level
Logging level for this message.
pFormat
A printf-style format string.
...
Additional arguments for the format string.

Remarks

If debug logging for any of the message types is set to the specified level or higher, this macro sends the formatted string to the debug output location.

Example

DbgLog((LOG_TRACE, 3, TEXT("Connected input pin %d"), nPinNumber));

Note that an additional set of parentheses must enclose the macro parameters.

DbgOutString

Debug Output Functions

Sends a string to the debug output location. Ignored in retail builds.

Syntax

void DbgOutString(
    LPCTSTR psz
);

Parameters

psz
String to output.

Remarks

In debug builds, this function always outputs the string, regardless of the current debug output levels. For finer control over the output, use the DbgLog macro.

Example

DbgOutString("Creating the filter graph...\n");

DbgSetModuleLevel

Debug Output Functions

Sets the logging level for one or more message types. Ignored in retail builds.

Syntax

void DbgSetModuleLevel(
    DWORD Types,
    DWORD Level
);

Parameters

Types
Bitwise combination of one or more message types.
Level
Logging level for the specified message types.

DbgTerminate

Debug Output Functions

Cleans up the debug library. Ignored in retail builds.

Syntax

void DbgTerminate(void);

Remarks

Call this function if you call the DbgInitialise function.

DisplayType

Debug Output Functions

Sends information about a media type to the debug output location. Ignored in retail builds.

Syntax

void DisplayType(
    LPSTR label,
    const AM_MEDIA_TYPE *pmtIn
);

Parameters

label
String that contains a message to display with the media type information.
pmtIn
Pointer to the AM_MEDIA_TYPE structure that contains the media type.

Remarks

This function generates several LOG_TRACE messages. At logging level 2 or higher, the function displays the major type, subtype, and format type, and data from the format block. At logging level 5 or higher, the function displays additional information, such as the source and target rectangles for video types.

DumpGraph

Debug Output Functions

Sends information about a filter graph to the debug output location. Ignored in retail builds.

Syntax

void DumpGraph(
    IFilterGraph *pGraph,
    DWORD dwLevel
)

Parameters

pGraph
Pointer to the IFilterGraph interface on the filter graph manager.
dwLevel
Logging level. The function generates a LOG_TRACE message with the specified logging level.

NAME

Debug Output Functions

Generates a debug-only string.

Syntax

NAME(
    strLiteral
);

Parameters

strLiteral
Text string.

Remarks

In debug builds, this macro is equivalent to the TEXT macro. In retail builds, it resolves to (TCHAR*) NULL. This macro is useful when declaring the name of an object that derives from the CBaseObject class.

Example

pObject = new CBaseObject(NAME("My Object"));

NOTE, NOTE1, NOTE2, NOTE3, NOTE4, NOTE5

Debug Output Functions

Sends a string to the debug output location. Ignored in retail builds.

Syntax

NOTE(
    pFormat
);

NOTEn(
    pFormat,
    arg1 ... arg5
);

Parameters

pFormat
A printf-style format string.
arg1 – arg5
Additional arguments for the format string. The number of arguments must match the macro name. For example, NOTE1 takes one argument, and NOTE5 takes five arguments.

Remarks

These macros are variants of the DbgLog macro. They generate level 5 LOG_TRACE messages.

Example

NOTE("Warning, failed to created graph.");

NOTE2("Width: %d, Height: %d", width, height);

REMIND

Debug Output Functions

Generates a reminder at compile time. This macro generates a string that includes the parameter string, the name of the source file, and the line number.

Syntax

REMIND(
    strLiteral
);

Parameters

strLiteral
Text string.

Example

This macro is useful for generating compile-time warnings:

#pragma message (REMIND("TO DO: Add support for IDispatch."))


Pointer Validation Macros

Microsoft® DirectShow® provides several macros for validating pointers.

Declaration: Wxdebug.h

Macro | Description
CheckPointer | Checks whether a pointer is NULL.
ValidateReadPtr | Verifies that the calling process has read access to a memory block.
ValidateReadWritePtr | Verifies that the calling process has read/write access to a memory block.
ValidateStringPtr | Verifies that the calling process has read access to a string.
ValidateStringPtrA | Verifies that the calling process has read access to an ANSI string.
ValidateStringPtrW | Verifies that the calling process has read access to a wide-character string.
ValidateWritePtr | Verifies that the calling process has write access to a memory block.

CheckPointer

Pointer Validation Macros

Checks whether a pointer is NULL. If the pointer is NULL, the function or method in which the macro appears returns the specified value.

Syntax

CheckPointer(
    p,
    ret
);

Parameters

p
Pointer to check.
ret
Value that the function or method returns if p is NULL.

Example

HRESULT MyFunction(VOID *pSomeParameter)
{
    CheckPointer(pSomeParameter, E_INVALIDARG)

    // Rest of the function (not shown).
}

ValidateReadPtr

Pointer Validation Macros

Verifies that the calling process has read access to a memory block. If not, the macro calls the DbgBreak macro.

Syntax

ValidateReadPtr(
    const void *p,
    UINT cb
);

Parameters

p
Pointer to a memory block.
cb
Size of the memory block, in bytes.

Remarks

This macro is ignored unless DEBUG or VFWROBUST is defined when the DirectShow base-class header file is included. This macro can have a significant performance cost.

ValidateReadWritePtr

Pointer Validation Macros

Verifies that the calling process has read/write access to a memory block. If not, the macro calls the DbgBreak macro.

Syntax

ValidateReadWritePtr(
    const void *p,
    UINT cb
);

Parameters

p
Pointer to a memory block.
cb
Size of the memory block, in bytes.

Remarks

This macro is ignored unless DEBUG or VFWROBUST is defined when the DirectShow base-class header file is included. This macro can have a significant performance cost.

ValidateStringPtr

Pointer Validation Macros

Verifies that the calling process has read access to a string. If not, the macro calls the DbgBreak macro.

Syntax

ValidateStringPtr(
    LPCTSTR p
);

Parameters

p
Pointer to a NULL-terminated TCHAR string.

Remarks

This macro is ignored unless DEBUG or VFWROBUST is defined when the DirectShow base-class header file is included. This macro can have a significant performance cost.

ValidateStringPtrA

Pointer Validation Macros

Verifies that the calling process has read access to an ANSI string. If not, the macro calls the DbgBreak macro.

Syntax

ValidateStringPtrA(
    LPCSTR p
);

Parameters

p
Pointer to a NULL-terminated ANSI string.

Remarks

This macro is ignored unless DEBUG or VFWROBUST is defined when the DirectShow base-class header file is included.

ValidateStringPtrW

Pointer Validation Macros

Verifies that the calling process has read access to a wide-character string. If not, the macro calls the DbgBreak macro.

Syntax

ValidateStringPtrW(
    LPCWSTR p
);

Parameters

p
Pointer to a NULL-terminated wide-character string.

Remarks

This macro is ignored unless DEBUG or VFWROBUST is defined when the DirectShow base-class header file is included. This macro can have a significant performance cost.

ValidateWritePtr

Pointer Validation Macros

Verifies that the calling process has write access to a memory block. If not, the macro calls the DbgBreak macro.

Syntax

ValidateWritePtr(
    const void *p,
    UINT cb
);

Parameters

p
Pointer to a memory block.
cb
Size of the memory block, in bytes.

Remarks

This macro is ignored unless DEBUG or VFWROBUST is defined when the DirectShow base-class header file is included. This macro can have a significant performance cost.


Wait Debugging Functions

Microsoft® DirectShow® provides several functions for debugging infinite waits.

Declaration: Wxdebug.h

In retail builds, the DbgWaitForMultipleObjects and DbgWaitForSingleObject functions work like their Microsoft® Win32® counterparts, WaitForMultipleObjects and WaitForSingleObject, with infinite time-out intervals.

In debug builds, these functions use a global time-out value. If the time-out expires, the function triggers an assert. The following registry key specifies the time-out value, in milliseconds:

\HKEY_LOCAL_MACHINE\SOFTWARE\Debug\<Module Name>\TIMEOUT

If the key does not exist, the time-out value defaults to INFINITE. You can use the DbgSetWaitTimeout function to override the registry entry.

Function | Description
DbgSetWaitTimeout | Sets the debugging time-out value.
DbgWaitForMultipleObjects | Waits for any (or all) of the specified objects to be signaled.
DbgWaitForSingleObject | Waits for an object to become signaled.

DbgSetWaitTimeout

Wait Debugging Functions

Sets the debugging time-out value. Ignored in retail builds.

Syntax

void DbgSetWaitTimeout(
    DWORD dwTimeout
);

Parameters

dwTimeout
Time-out value in milliseconds, or INFINITE to wait indefinitely.

Remarks

In debug builds, the DbgWaitForMultipleObjects and DbgWaitForSingleObject functions use this value as the time-out interval.

DbgWaitForMultipleObjects

Wait Debugging Functions

Waits for any (or all) of the specified objects to be signaled.

In a debug build, this function triggers an assert if the time-out interval expires before the objects are signaled. To set the time-out interval, call the DbgSetWaitTimeout function.

In a retail build, this function is equivalent to the WaitForMultipleObjects function with a time-out interval of INFINITE.

Syntax

DWORD DbgWaitForMultipleObjects(
    DWORD nCount,
    CONST HANDLE *lpHandles,
    BOOL bWaitAll
);

Parameters

nCount
Number of objects.
lpHandles
Array of handles to objects, of size nCount.
bWaitAll
Boolean value that specifies whether to wait for all of the objects. If TRUE, the function waits for all of the objects to be signaled. Otherwise, it waits for at least one object to be signaled.

DbgWaitForSingleObject

Wait Debugging Functions

Waits for an object to become signaled.

In a debug build, this function triggers an assert if the time-out interval expires before the object is signaled. To set the time-out interval, call the DbgSetWaitTimeout function.

In a retail build, this function is equivalent to the WaitForSingleObject function with a time-out interval of INFINITE.

Syntax

DWORD DbgWaitForSingleObject(
    HANDLE h
);

Parameters

h
Handle to the object.


DirectShow Samples

The Microsoft® DirectShow® SDK samples are divided into categories according to functionality:

  • Base Classes
  • BDA Sample Application
  • Sample Capture Applications
  • DMO Samples
  • Sample DVD Applications
  • Sample DirectShow Filters
  • Miscellaneous DirectShow Samples
  • Sample Player Applications
  • Sample Video Editing Applications

The base classes are a set of C++ classes that are useful for creating filters, manipulating media types, and performing other DirectShow tasks.

Note Many of the DirectShow samples link to the base class library. You must build the library in order to build those samples.

The easiest way to build the samples is with the workspace file DShow.dsw, which is located in the DirectShow samples root directory. This workspace includes references to all of the sample project files.

  • To build all of the projects, choose Batch Build from the Build menu.
  • To build a particular sample (including its dependencies), right-click the project name in the FileView pane. From the pop-up menu, click Build.

Separate project files are also included for each sample, and you can use these to build, modify, or debug samples. If you build a sample this way, without using the DShow.dsw workspace, remember to build the base class library first.

See Also

Setting Up the Build Environment


Base Classes

Description

The Microsoft® DirectShow® base classes are a set of C++ classes and utility functions that you can use to implement DirectShow filters. For complete documentation of the base classes, see DirectShow Base Classes.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\BaseClasses


BDA Sample Application

Description

Demonstrates how to construct a filter graph based on digital TV tuner cards that support the new Microsoft® Broadcast Driver Architecture (BDA). The sample also shows how to perform tuning based on the new Microsoft® Tuning Model. The sample is discussed in more detail in the article Writing Digital TV Applications.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\BDA\BDASample

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\Bdasample.exe

Note: To build this sample you must have strmbasd.lib or strmbase.lib present on your system. This library is created when you build the DirectShow base classes. For more information, see Using the DirectShow Base Classes.


Sample Capture Applications

The Microsoft® DirectShow® SDK includes the following sample capture applications.

C++ Applications

  • AmCap Sample
  • DVApp Sample
  • PlayCap Sample


AmCap Sample

Description

Video capture application.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Capture\AMCap

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\AMCap.exe

User's Guide

This sample application demonstrates the following tasks related to audio and video capture:

  • Capture to a file
  • Live preview
  • Allocation of the capture file
  • Display of device property pages
  • Device enumeration
  • Stream control

Further Reading

Video Capture


DVApp Sample

Description

Digital Video (DV) capture application.

This sample demonstrates how to build various types of filter graphs for controlling DV camcorders. It also shows how to perform capture, preview, transmit, and device control with a DV camcorder.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Capture\DVApp

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\DVApp.exe

User's Guide

The DVApp application supports the following modes:

  • Preview: Renders DV from the camcorder to a video window.
  • DV to type-1 file: Captures DV data from the camcorder to a type-1 DV file.
  • Type-1 file to DV: Transmits data from a type-1 DV file to the camcorder.
  • DV to type-2 file: Captures DV data from the camcorder to a type-2 DV file.
  • Type-2 file to DV: Transmits data from a type-2 DV file to the camcorder.

The capture and transmit modes also perform preview. Each of those modes has a No Preview option as well, which disables preview. Capturing without preview is more efficient and can reduce the number of dropped frames. For information about type-1 files versus type-2 files, see Digital Video in DirectShow.

The application starts in preview mode. To select another mode, choose a mode from the Graph Mode menu. For each mode, DVApp builds a filter graph that supports the functionality of that mode. To save the graph as a GraphEdit (.grf) file, select Save Graph to File from the File menu. Quit DVApp before opening the file in GraphEdit.

To capture to a file:

  1. From the Graph Mode menu, select a DV to File mode (type 1 or type 2, with or without preview).
  2. From the File menu, choose Set Output File and enter a file name.
  3. Click Record.
  4. If the camcorder is in VTR mode, click Play.
  5. To stop capturing, click Stop.

To transmit from a file to the camcorder:

  1. From the Graph Mode menu, select a File to DV mode (type 1 or type 2, with or without preview).
  2. From the File menu, click Set Input File and select a DV file. The file must match the selected mode (type 1 or type 2).
  3. Click Play.
  4. To record the data to tape, click Record.
  5. To stop transmitting, click Stop.

If the camcorder is in VTR mode, the user can control the transport mechanism through the application's VCR-style buttons. To seek the tape, enter the target timecode and click the seek button.

To limit how much data the application captures, choose Capture Size from the File menu.

To check the tape format (NTSC or PAL), choose Check Tape from the Options menu.

To change the size of the preview window, choose Change Decode Size from the Options menu.

Programming Notes

The main purpose of this application is to show how to build various DV capture and transmit graphs. Applications can use the ICaptureGraphBuilder2 interface to build preview graphs and type-1 file capture graphs. The other types of DV graph must be built one filter at a time. The DVApp sample uses ICaptureGraphBuilder2 only to build preview graphs.

The following diagram shows the filter graph that captures to a type-1 file:

Type-1 DV File Capture Graph

Interleaved audio-video data is sent from MSDV to the Smart Tee filter. Data from the Smart Tee filter's capture pin is written to a file, while data from the preview pin is sent to the video and audio renderers.

The following diagram shows the filter graph that transmits from a type-2 file to the camcorder:

Type-2 DV File Transmit Graph

The AVI Splitter filter parses the AVI file, and the DV Muxer filter multiplexes the two streams, producing an interleaved audio-video stream. The Infinite Pin Tee filter splits the stream into two identical streams. One stream goes to MSDV, while the other goes through the DV Splitter filter for previewing. Other graph configurations might be equivalent.

Device Arrival and Removal

The application handles device arrival and removal, using two different techniques. For device arrival, the application's message loop responds to WM_DEVICECHANGE messages. For device removal, the application responds to EC_DEVICE_LOST events from the filter graph manager. Either approach works, although the EC_DEVICE_LOST event depends on the existence of the device in the filter graph.

The application only handles one device at a time. If the current device is removed, the application looks for another DV device on the system.

On some DV camcorders, the user must shut off the device when switching it between camera mode and VTR mode, which triggers a device-lost message. The application responds by enabling or disabling the appropriate menu commands. However, if the user toggles rapidly between modes, the camcorder might not generate a device-lost message. You can force the menus to update by choosing Refresh Mode from the Options menu. Some DV camcorders can toggle modes without shutting off, but send a device-lost message only when they switch to VTR mode.

Note Microsoft® Windows® 95 and Microsoft® Windows NT® 4.0 and earlier do not support the data types used for device arrival. In order to compile the application for these platforms, the data types are conditionally included if WINVER is less than 0x500. However, the application does not support device detection on those platforms.

Device Control

The functionality of the application's Play and Record button depends on the current mode:

  • Preview: The filter graph runs automatically. The Play button starts the transport.
  • Capture to file: The Record button runs the graph, and the Play button starts the transport.
  • Transmit to device: The Play button runs the graph, and the Record button starts the transport.

The sample application does not perform frame-accurate capture. At various points, the application calls the Sleep function to wait for the device to respond. Newer DV camcorders send a notification when the state of the device changes. Older devices might not support notification; for the purposes of a sample, calling Sleep is a simpler solution. For more information, see Controlling a DV Camcorder.


PlayCap Sample

Description

Simple capture application.

This application creates a preview window for the first video capture device that it locates on the user's system (if any). It demonstrates a simple example of using the ICaptureGraphBuilder2 and ICreateDevEnum interfaces to build a capture graph.

For a sample capture application that supports more features, see AmCap.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Capture\PlayCap

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\PlayCap.exe

Further Reading

Video Capture


DMO Samples

The Microsoft® DirectShow® SDK includes the following Microsoft® DirectX® Media Object (DMO) samples:

  • DMO Demo
  • DMO Sample
  • Gargle DMO Sample


DMO Demo

Description

This sample application demonstrates how to use Microsoft® DirectX® Media Objects (DMO). It streams audio data from a WAV file through an audio effect DMO to a Microsoft® DirectSound® buffer.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\DMO\DMODemo

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\DMODemo.exe

User's Guide

Click the Sound File button to load a sound file. Use the drop-down combo box to select an audio effect DMO. Click the Play button to hear the sound file played with the audio effect.


DMO Sample

Description

DMO Sample is a sample Microsoft® DirectX® Media Object (DMO). It takes MPEG-1 video packets as input and produces two output streams. The first output stream contains video frames in RGB 565 format. Each frame displays the time code taken from the MPEG-1 video, and is otherwise blank. The second output stream is an optional text stream with the time code.

DMO Sample uses the IMediaObjectImpl base-class template to implement the IMediaObject interface. For information about using this template, see Using the DMO Base Class. The Active Template Library (ATL) handles various COM details, including registration, aggregation, IUnknown, and the DLL entry points.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\DMO\DMOSample

User's Guide

The project workspace builds a DLL named Dmosample.dll. Use the Regsvr32 utility to register the DLL. To see the DMO in action, you can use the Microsoft® DirectShow® GraphEdit utility. You will need an MPEG-1 video file. Perform the following steps:

  1. Run GraphEdit.
  2. Render an MPEG-1 file:
    • From the File menu, click Render Media File.
    • Select an MPEG-1 video file and click Open.
  3. Remove the MPEG-1 Video Decoder filter from the filter graph by selecting the filter and pressing DELETE.
  4. Insert the DMO Sample in the graph:
    • From the Graph menu, click Insert Filters.
    • Expand the DirectShow Filters list.
    • Select DMO Sample and click Insert Filters.
    • Click Close.
  5. Connect the MPEG-1 Stream Splitter to the DMO Sample by dragging the mouse from the small box labeled Video on the MPEG-1 Stream Splitter to the box labeled in0 on the DMO Sample. (See illustration.)
  6. Connect the DMO Sample to the Video Renderer:
    • Drag the mouse from the box labeled out0 on the DMO Sample to the box labeled Input on the Video Renderer
      • .
    • GraphEdit might automatically insert a Color Space Converter filter to convert between RGB types.
  7. Press the play button on the GraphEdit toolbar, or click Play from the Graph menu.

When the graph runs, a video window appears that displays the time codes.

Connecting the DMO Sample filter.

Programming Notes

The DMO Sample contains the following source and header files:

  • Dmosample.cpp: Code for implementing basic COM functionality in ATL.
  • Resource.h: Resource constants.
  • Sample.h, Sample.cpp: The CSample class, which implements the DMO.
  • State.h, State.cpp: The CStreamState class, a helper class that generates time stamps from the MPEG data.
  • Stdafx.h, Stdafx.cpp: Basic functions required by ATL.
  • Util.h, Util.cpp: Utility functions for drawing the output image.

The DMO Sample also uses the following resource files:

  • Dmosample.rc: Defines a resource with version information, and links to the Sample.rgs file.
  • Sample.rgs: Defines a text resource with registry information. ATL uses this resource to create registry entries when it registers the DLL.

The following remarks describe the implementation in greater detail.

Dmosample.cpp

The file contains the object map that ATL uses to create and register the DMO object. It also contains the exported DLL functions. These include the entry-point function (DllMain), and the functions that COM requires (DllCanUnloadNow, DllGetClassObject, DllRegisterServer, and DllUnregisterServer).

The ATL COM AppWizard automatically generates most of the code contained in this file. Two things are added:

  • The DllRegisterServer function calls DMORegister to add registry information about the DMO. The DMO is registered in the DMOCATEGORY_VIDEO_DECODER category.
  • The DllUnregisterServer function calls DMOUnregister.

Resource.h

The one constant declared in this header file, IDR_SAMPLE, is used by ATL's self-registration mechanism. The constant IDR_SAMPLE identifies a text resource, which is defined in the resource file Sample.rgs and imported by the resource file Dmosample.rc. The header file Sample.h contains the line:

DECLARE_REGISTRY_RESOURCEID(IDR_SAMPLE)

which causes ATL to use the registration information declared in the IDR_SAMPLE resource.

Sample.h

The DEFINE_GUID macro declares the class identifier (CLSID) of the DMO.

The CSample class derives from the following classes:

  • IMediaObjectImpl. The DMO base class. The template parameters specify that the DMO has one input stream and two output streams.
  • CComObjectRootEx. An ATL class that declares the threading model. The template parameter, CComMultiThreadModel, creates a thread-safe object and provides the Lock and Unlock methods.
  • CComCoClass. An ATL class that declares a standard COM object.

CSample aggregates the Free Threaded Marshaler, which is an object that performs custom marshaling. If the COM library marshals a CSample pointer across threads within the sample process, the exact same pointer is returned. If the COM library tries to marshal the object across processes or across machines, it fails. ATL adds all of the code need to aggregrate the Free Threaded Marshaler. This code appears in the FinalConstruct and FinalRelease methods. The COM_INTERFACE_ENTRY_AGGREGATE entry in the COM map delegates the IMarshal interface to the Free Threaded Marshaler.

The CSample class declares the following member variables:

m_pUnkMarshaler | Pointer to the Free Threaded Marshaler object.
m_pBuffer | Pointer to the input buffer. The DMO holds a reference count on the buffer until it processes all of the input.
m_pbData | Pointer to the next byte in the input buffer.
m_cbData | Number of bytes remaining to process.
m_rtFrame | Time stamp from the most recent output frame.
m_StreamState | Instance of the CStreamState helper class, which parses MPEG data.
m_bPicture | Boolean flag that indicates whether the DMO has picture information to output.

Sample.cpp

This file implements the methods in the CSample class.

InternalGetInputStreamInfo

The DMO can process any number of bytes, aligned on any boundary, so this method returns zero flags.

InternalGetOutputStreamInfo

The first output stream produces whole fixed-sized samples, one at a time, which is typical for video decoders. The second output stream is optional. The returned flags indicate these attributes.

InternalCheckInputType

The input type must be MPEG-1 Video Payload, with a format type of FORMAT_MPEGVideo. After the input type is set, the method rejects format changes.

InternalCheckOutputType

This method validates output formats. There are two output streams:

  • Stream 0. The only media type supported by this stream is RGB-565. A real video decoder would typically support a range of formats. Also, the frame size of the output must match the frame size of the input—which is generally the case for real video decoders. This stream cannot be set unless the input type is set.
  • Stream 1. The media type must be MEDIATYPE_Text.

After the types are set, the method fails unless the new type matches the current type. If a DMO cannot handle format changes while streaming, it should include similar code. In fact, the sample DMO could easily accept format changes, because it generates output one frame at a time.

InternalGetInputType

This method returns no types. Therefore, any index value is out of range, and the return value is DMO_E_NO_MORE_ITEMS. For more information, see IMediaObject::GetInputType.

InternalGetOutputType

If the input type is not set, this method returns no types. Otherwise, it returns one type for each stream. For stream 0, it returns RGB-565 with a frame size equal to the input size. For stream 1, it returns MEDIATYPE_Text.

InternalGetInputSizeInfo

The minimum buffer size for the input stream is one byte, with no alignment requirements. The stream does not perform lookahead.

InternalGetOutputSizeInfo

For stream 0, the buffers must be large enough to hold an output sample. For stream 1, the buffers must be large enough to hold a text string with a time stamp.

InternalFlush

This method releases the input buffer by setting m_pBuffer (an ATL smart pointer) to NULL. It also calls the InternalDiscontinuity method, which resets the CStreamState object.

InternalProcessInput

This method processes as much input data as possible. It performs the following steps:

  • Calls the IMediaBuffer::GetBufferAndLength method to retrieve a pointer to the input data and the size of the input.
  • Holds a reference count on the input buffer. The m_pBuffer variable is an ATL smart pointer, so assigning to the variable has the effect of calling the IUnknown::AddRef method
    • .
  • Passes the time stamp to the CStreamState object. If the sample does not have a time stamp, the method uses the value INVALID_TIME.
  • Calls the Process helper method to process the data.

InternalProcessOutput

If there is no data to output, this method returns S_FALSE. Otherwise, it generates output data. For stream 0, it performs the following steps:

  • Checks whether the output buffer is large enough to hold the output data. If not, the method returns an error.
  • Calls the OurFillRect method to draw the background, and the DrawOurText method to draw the text.
  • Sets the time stamp. If there is a valid time stamp for this frame, it is used. Otherwise, the previous time stamp is incremented by the average frame rate.
  • Calls the Process method again to process any data that might remain in the input buffer. If this results in more output data, the DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE flag is set.

Stream 1 is optional, so the caller might not allocate a buffer for that stream. Assuming that stream 1 does have an output buffer, however, the DMO writes the time code as a text string. The time stamps and processing flags are taken from stream 0.

InternalAcceptingInput

If the DMO is still holding a reference count on the previous input buffer, it does not accept any more input.

Process

This private method steps through the input data one byte at a time, updating the CStreamState object. If the CStreamState object finds a picture boundary before the input data is exhausted, the Process method returns S_OK. Otherwise, it returns S_FALSE.


Gargle DMO Sample

Description

This sample is a Microsoft® DirectX® Media Object (DMO) that creates a gargle effect, similar to the Gargle Filter sample for Microsoft® DirectShow®.

This sample demonstrates how to implement the the following interfaces:

  • IMediaObject
  • IMediaObjectInPlace
  • IMediaParamInfo
  • IMediaParams

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\DMO\GargleDMO

User's Guide

To use this DMO, build and register GargleDMO.dll. The sample project builds several intermediate libraries. To build the DLL in Microsoft® Visual Studio®, select Batch Build from the Build menu.

You can use the DMO in the DMO Demo sample application, or with the DirectShow GraphEdit utility. GraphEdit automatically wraps the DMO in the DMO Wrapper filter.

You can also use the DMO in Microsoft® DirectMusic® applications, including the Microsoft® DirectMusic® Producer application included with the SDK. In DirectMusic Producer, use the Audiopath Designer to insert the DMO into an audiopath. To control media parameters, use the Parameter Control track. Insert a curve in the track and assign it to control any of the properties on the DMO. For more information, see the Audiopath Designer and Parameter Control Track topics in the DirectMusic Producer application help.

The Gargle DMO provides a property page for the user to set the shape of the modulating waveform (square or triangular) and the frequency. It also supports a custom interface, IGargleDMOSample, for setting these properties.

Programming Notes

The Gargle DMO sample is built with the Active Template Library (ATL). The source code is organized into three libraries:

ControlBase Library

  • Controlhelp.h, Controlhelp.cpp: Helper classes for the user interface controls; used by the property page.

GargleDMO Library

  • Gargle.h, Gargle.cpp: Implements the Gargle DMO, including the IMediaObjectInPlace interface and the custom IGargleDMOSample interface.
  • GargleDMO.cpp: Implements the DLL entry-point function, and the DLL functions needed by the COM library, such as DllGetClassObject.
  • GargleDMO.def: Exports the DLL functions needed by the COM library.
  • GargleDMOProp.h, GargleDMOProp.cpp: Implements the property page. The property pages uses ATL's IPropertyPageImpl class template.
  • IGargle.h: Declares the IGargleDMOSample interface.
  • Resource.h: Resource constants.
  • Stdafx.h, Stdafx.cpp: Basic functions required by ATL.

MedParamBase Library

  • Alist.h, Alist.cpp: Simple linked-list class.
  • Param.h, Param.cpp: Contains the CParamsManager class, which implements the IMediaParams and IMediaParamInfo interfaces for media parameters.

The Gargle DMO does not use the IMediaObjectImpl base class. It uses an older set of DMO base classes, which the IMediaObjectImpl class is designed to replace.

The IMediaObjectImpl class offers the following improvements:

  • Implements better parameter checking.
  • Enforces a stricter calling sequence.
  • Provides a simpler model for initializing streaming resources in the IMediaObject::AllocateStreamingResources methods.

In future releases, Gargle DMO might be rewritten to use IMediaObjectImpl.


Sample DVD Applications

The Microsoft® DirectShow® SDK includes the following sample DVD applications.

C++ Applications

  • DVD Sample

Microsoft® Visual Basic® Applications

  • WebDVD Sample


DVD Sample

Description

DVDSample is a C++ DVD application. It demonstrates all basic playback and navigation functions as well as advanced features such as parental level management, bookmarks, karaoke, and command synchronization.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\DVD\DVDSample

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\DVDSample.exe


WebDVD Sample

Description

Simple Microsoft® Visual Basic® DVD application.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectShow\WebDVD

Executable: (SDK root)\Samples\Multimedia\VBSamples\DirectShow\Bin\VB_WebDVDSample.exe

User's Guide

The WebDVD sample shows how to use the MSWebDVD Microsoft® Active X® control to perform all aspects of DVD-Video playback and navigation.

You can initiate playback by calling the Play method. Once the DVD is playing, you can alter the path or behavior of playback by through the following methods:

  • Stop: Stops playback.
  • Eject: Ejects the DVD disk from the drive.
  • Pause Pauses playback for as long as you wish.
  • ActivateButton: Activates the currently selected button. You can select a button by:
    • Hovering over the button and see it get highlighted. The DisableAutoMouseProcessing property must be false (the default value) for this to have an effect.
    • Calling SelectAtPosition, SelectLeftButton, SelectRightButton, SelectLowerButton, or SelectUpperButton.
  • PlayNextChapter: Plays the next chapter within the current title.
  • PlayPrevChapter: Plays the previous chapter within the same title.

You can show six possible menus that may exist on a disk with the ShowMenu method:

  • Title
  • Root
  • Subpicture
  • Audio
  • Angle
  • Chapter

If the menu does not exist, you will get an error indicating that the specified menu does not exist.

Finally, you can change the size of the video display through the methods GetClipVideoRect and GetVideoSize. GetClipVideoRect returns the video's current size, which is not necessarily the native (maximum) size. For the native size, use the GetVideoSize method.


Sample DirectShow Filters

The Microsoft® DirectShow® SDK includes the following sample filters:

  • Async Filter Sample
  • Ball Filter Sample
  • Contrast Filter Sample
  • Dump Filter Sample
  • EZRGB24 Filter Sample
  • Gargle Filter Sample
  • InfTee Filter Sample
  • NullIP Filter Sample
  • NullNull Filter Sample
  • SampVid Filter Sample
  • Scope Filter Sample
  • Synth Filter Sample
  • TextOut Filter Sample
  • WavDest Filter Sample


Async Filter Sample

Description

File reader filter that supports progressive download. This sample filter implements the IAsyncReader and IFileSourceFilter interfaces. It supports MPEG files, but not AVI files.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\Async

User's Guide

This sample includes a small command-line application, Memfile.exe, that demonstrates the filter. The command-line arguments specify a media file and a bit rate, in kilobytes per second. The application reads the file into memory at the specified rate and plays the file. To do so, it creates an instance of the filter, adds the filter to the filter graph, and renders the filter's output pin.

Usage:

Memfile Filename BitRate

The Async sample filter does not support AVI files, because it cannot connect to the AVI Splitter filter. The Async filter's output pin proposes MEDIATYPE_Stream and MEDIASUBTYPE_NULL for the media type. The input pin on the AVI Splitter filter does not accept MEDIASUBTYPE_NULL, and does not propose any types of its own. Therefore, the pin connection fails. The Async filter could be enhanced to offer MEDIASUBTYPE_Avi when appropriate. For example, it could examine the file format, or use the file extension.


Ball Filter Sample

Description

Video source filter that produces an image of a bouncing ball. This sample illustrates format negotiation and the use of the source filter base classes CSource and CSourceStream.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\Ball

User's Guide

The code in Fball.h and Fball.cpp manages the filter interfaces. Those two files contain approximately the minimum code required for a source filter. The Ball.h and Ball.cpp files contain the code that bounces the ball.

This filter has a single output pin, which provides a video stream that shows a ball bouncing around in the frame. The Ball filter also accepts quality management requests from the downstream graph, which illustrates a simple quality management strategy. This filter implements the IQualityControl interface for that purpose.


Contrast Filter Sample

Description

Video transform filter that implements a contrast effect. This sample illustrates how to define and implement a simple custom interface. It also demonstrates how to use the CTransformFilter class to implement a simple effect filter.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\Contrast

User's Guide

The Contrast filter is a simple transform filter that adjusts the contrast of the video stream that is passed through it. It provides a custom interface for adjusting the contrast. The Contrast filter also uses the CBasePropertyPage class to provide a property page for applications that do not provide a user interface.

The Contrast filter adjusts the contrast by using a trick with palettes. The color palette of an image effectively determines how the image is interpreted. By changing the palette, the filter can change the contrast without changing the image pixels themselves.


Dump Filter Sample

Description

Renderer filter that writes the media samples it receives to a text file.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\Dump

User's Guide

This sample illustrates the use of the base filter class CBaseFilter and the rendered input pin class CRenderedInputPin. This sample also uses the IFileSinkFilter interface. The Dump filter demonstrates how to override the Receive method of the rendered input pin class to process actual media samples. The Dump filter delivers the EC_COMPLETE notification to the filter graph when it receives a call to CDumpInputPin::EndOfStream on its input pin.

This filter is a useful debugging tool. For example, you can verify, bit by bit, the results of a transform filter. You can build a graph manually by using GraphEdit, and connect the Dump filter to the output of a transform filter or any other output pin. You can also connect a tee filter and put the Dump filter on one leg of the tee filter and the typical output on another leg to monitor the results in a real-time scenario.

The Dump filter has a single input pin, which is dumped to a file. The filter prompts the user for a file name when it is instantiated and closes the file when it is freed.


EZRGB24 Filter Sample

Description

Image processing filter. This filter performs a number of individual video effects, including red, green, blue, darken, XOR, blur, gray, and emboss effects.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\EZRGB24

User's Guide

This sample shows how to use several Microsoft® DirectShow® classes, including CTransformFilter, CPersistStream, and CBasePropertyPage.


Gargle Filter Sample

Description

Audio effect filter.

The Gargle filter modulates the waveform passing through it by multiplying the waveform by another waveform that is mathematically generated within the filter. The modulating waveform is, by default, a triangular wave. The property sheet also offers the alternative of a square wave. You can set the frequency of the modulating wave through the filter's property sheet. At low modulation frequencies, the effect sounds like a tremolo. At higher modulation frequencies, it sounds like a distortion, adding extra frequencies above and below the original unmodulated sound.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\Gargle


InfTee Filter Sample

Description

Infinite-pin tee filter. This filter has one input pin and a dynamic number of output pins. All data samples sent to the filter are delivered down all paths simultaneously, thereby teeing the input into multiple separate output streams.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\InfTee

User's Guide

The filter sends the same data down all of the output pins; therefore, the pins must have negotiated the same media type during connection. The infinite-pin tee filter handles this negotiation so that the input pin and both output pins converge when using the same media type. If a suitable media type cannot be found, then the connection is rejected.

The filter always uses the suggested allocator; the filter that provides the data suggests the allocator. The data arriving at the input pin is not copied before it is sent to the output pins. The filter also ensures that the data is delivered to the downstream filters, to guarantee that both outputs receive timely service. In particular, if one of the outputs can block in the COutputQueue::Receive member function, then the tee spins off a thread to deliver the sample. If there were no thread to deliver the sample, then the thread that delivers the sample to the tee input pin might pass the data to a downstream filter; at that point, it might block, keeping data from the other downstream filter for long periods of time.


NullIP Filter Sample

Description

Null in-place transform filter. This sample transform filter passes all data from its input pin to its output pin, without modifying the data.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\NullIP


NullNull Filter Sample

Description

Minimal null filter. This sample transform filter illustrates the simplest filter possible. The filter supports no functionality.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\NullNull


SampVid Filter Sample

Description

Sample video renderer filter.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\SampVid


Scope Filter Sample

Description

Renderer filter that displays sound data as wave forms.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\Scope

User's Guide

To use this filter, open GraphEdit and render an audio file (or a video file with an audio stream). Disconnect the audio renderer temporarily and insert the Infinite-Pin Tee (InfTee) sample filter. Reconnect the audio renderer. Then connect the Infinite-Pin Tee filter's second output pin to the Scope filter. Now run the graph.

The Scope window is implemented as a dialog box, not as an actual window. Developers creating control panels to alter filter parameters in real time might want to use a technique like this rather than property pages.

The Scope filter demonstrates setting up a separate thread to process data. In this case, the data is just copied to a separate buffer on the IMemInputPin::Receive method, and is then drawn on the Scope window on the separate thread.

The Scope filter also enables you to monitor audio output to determine if you are clipping, so you can adjust the gain.

This filter appears in GraphEdit as "Oscilloscope."


Synth Filter Sample

Description

Source filter that generates audio waveforms.

This filter illustrates dynamic graph building. It can switch between uncompressed PCM audio and compressed MS_ADPCM (Microsoft Adaptive Delta Pulse Code Modulation) format.

This filter appears in GraphEdit as "Audio Synthesizer Filter."

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\Synth

User's Guide

The Synth filter enables the user to set the waveform, frequency, number of channels, and other properties through the property page. To set either the upper or lower endpoint of the swept frequency range, hold down SHIFT while adjusting the frequency slider. The filter also supports a custom interface, ISynth2, for setting these properties.

To demonstrate the dynamic graph building feature, do the following:

  1. Build the filter and register it with the Regsvr32 utility.
  2. Launch GraphEdit.
  3. Insert the Audio Synthesizer filter. It appears in the DirectShow Filters category.
  4. Render the filter's output pin.
  5. Click the Play button.
  6. Open the filter's property page.
  7. In the Output Format area, select PCM or Microsoft ADPCM.

Programming Notes

This sample contains the following files:

  • Dynsrc.h, Dynsrc.cpp: Contains two base classes for source filters that support dynamic graph building, CDynamicSource and CDynamicSourceStream.
  • ISynth.h: Declares the custom ISynth2 interface for setting properties on the filter.
  • Resource.h: Contains resource constants.
  • Synth.def: Exports the DLL functions needed by the COM library.
  • Synth.h, Synth.cpp: Contains the CAudioSynth class, which generates the audio data, and the CSynthFilter class, which implements the filter.
  • Synth.rc: Contains resources used by the filter.
  • Synthprp.h, Synthprp.cpp: Implements the filter's property page.

The CDynamicSource class is adapted from the CSource base class. It uses one or more output pins derived from the CDynamicSourceStream class. The CDynamicSourceStream class is adapted from the CSourceStream class, but derives from the CDynamicOutputPin class rather than the CBaseOutputPin class.

The CDynamicSource class has the following methods not found in CSource:

  • Stop: Signals the stop event (CDynamicOutputPin.m_hStopEvent), and shuts down the worker thread for all unconnected pins. On a connected pin, the pin's Inactive method will shut down the worker thread.
  • Pause: Resets the stop event.
  • JoinFilterGraph: Calls the CDynamicOutputPin::SetConfigInfo method on each pin.

The CDynamicSourceStream class has the following methods not found in CSourceStream:

  • DestroySourceThread: Shuts down the worker thread.
  • FatalError: Signals an error to the filter graph manager.
  • OutputPinNeedsToBeReconnected: Signals that the output pin should be reconnected. When this method is called, the worker thread calls the CDynamicOutputPin::DynamicReconnect method to reconnect the pin.


TextOut Filter Sample

Description

Renderer filter that displays text data.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\TextOut


WavDest Filter Sample

Description

Writes an audio stream to a WAV file. It takes a single audio stream as input, and its output pin must be connected to the File Writer filter. This sample filter is based on the CTransformFilter class.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Filters\WavDest


Miscellaneous DirectShow Samples

The Microsoft® DirectShow® SDK includes the following miscellanous samples.

C++ Applications

  • ASFCopy Sample
  • SysEnum Sample

Microsoft® Visual Basic® Applications

  • Builder Sample


ASFCopy Sample

Description

Transcodes one or more files to an ASF file.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Misc\ASFCopy

User's Guide

To build this sample, you must install the Microsoft® Windows Media™ Format SDK and obtain a software certificate. After you obtain the software certificate, build the sample by linking two additional libraries: WMStub.lib and WMVCore.lib.

Usage:

ASFCopy [/v] /p profile file1 [file2 ...] target

The following command-line switches are supported.

Switch | Description
/p | Specifies the profile number.
/v | Verbose mode.

Specify an ASF profile using the /p switch. If you omit this switch, ASFCopy displays a list of the standard system profiles.

Specify the name of one or more source files, and the name of the target file. If you specify more than one source file, the application multiplexes all of the source files. You must specify a profile that matches the streams contained in the source files, or else the application will not work correctly. For example, if you specify Video for Web Servers (56 Kbps), the combined source files must have exactly one video stream and one audio stream.

Further Reading

Windows Media Applications


SysEnum Sample

Description

Demonstrates the use of the system device enumerator for enumerating devices. For more information, see Enumerating Devices and Filters.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Misc\SysEnum

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\SysEnum.exe


Builder Sample

Description

Graph building application for Microsoft® Visual Basic®.

This sample application demonstrates how to build custom filter graphs in Visual Basic.

Path

Source: (SDK root)Samples\Multimedia\VBSamples\DirectShow\Builder


Sample Player Applications

The Microsoft® DirectShow® SDK includes the following sample player applications:

C++ Applications

  • BGMusic Sample
  • CutScene Sample
  • Jukebox Sample
  • PlayWnd Sample
  • Texture3D Sample

Microsoft® Visual Basic® Applications

  • VBDemo Sample


BGMusic Sample

Description

Playback application that cycles through a set of audio files.

This sample shows how to swap source filters in a filter graph. When the application begins, it renders the first audio file in the sequence and sets a timer. Whenever the timer goes off, the application removes the source filter and replaces it with a source filter for the next file. The files are all of the same type, so there is no need to rebuild the entire graph.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Players\BGMusic

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\BGMusic.exe


CutScene Sample

Description

Plays a video file in full-screen mode until the user types ESC, ENTER, or the SPACEBAR.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Players\CutScene

User's Guide

Run this sample from the command line, with the name of a video file as a command-line argument.


Jukebox Sample

Description

Video jukebox application.

This application scans a directory for media files and displays a list of the file names. The user can play an individual file or play all of the files in order. The jukebox also displays information about the filter graphs that it creates, including the names of the filters, the names of the pins, and the event codes that are generated.

Note This sample requires Microsoft Foundation Class Library 4.2 (Mfc42.dll).

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Players\Jukebox

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\Jukebox.exe

User's Guide

If a directory name is specified as a command-line argument, the jukebox scans that directory at start-up. Otherwise, it scans the default SDK media directory, which is located at Samples\Multimedia\Media under the SDK root directory. The jukebox displays a list of all the media files in the directory, from which the user can select a file to play.

The jukebox offers the following user-interface elements:

  • Play, Stop, Pause, and FrameStep buttons: Use these buttons to control graph playback. (The FrameStep button might be disabled, if the graph does not support IVideoFrameStep.)
  • Thru and Loop buttons: Click the Thru button to play through the entire file list, starting from the current selection. Click the Loop button to loop the same file repeatedly. These two buttons are mutually exclusive.
  • Mute button: Mutes the audio.
  • Filters, Input Pins, and Output Pins: When the jukebox creates a graph, it displays a list of the filters in the graph. If the user selects one of the filter names, the jukebox displays a list of the filter's input pins and a list of the filter's output pins.
  • Display Events: If this box is checked, the jukebox displays the event codes that it receives. To clear the list, click the Clear button.
  • Properties button: To view a filter's property pages, select the filter name and click the Properties button. If the filter does not support property pages, the button is disabled.


PlayWnd Sample

Description

Simple media player application.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Players\PlayWnd

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\PlayWnd.exe

User's Guide

The playback file can be specified as a command-line argument. Otherwise, the application displays an Open File dialog box on start-up. The selected file automatically begins playing.


Texture3D Sample

Description

Draws video on a Microsoft® DirectX® 8.0 texture surface.

Note This sample does not support changing the display properties of the monitor while the sample is running.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Players\Texture3D

Executable: (SDK root)\Samples\Multimedia\DirectShow\Bin\Texture3D.exe


VBDemo Sample

Description

Simple media player application for Microsoft® Visual Basic®.

Path

Source: (SDK root)Samples\Multimedia\VBSamples\DirectShow\VBDemo


Sample Video Editing Applications

The Microsoft® DirectShow® SDK includes the following sample applications related to video editing.

C++ Applications

  • SampGrabCB Sample
  • StillCap Sample
  • Timeline Test Sample
  • XTLTest Sample

Microsoft® Visual Basic® Applications

  • DexterVB Sample
  • SlideShowVB Sample
  • TrimmerVB Sample
  • XTLTestVB Sample


SampGrabCB Sample

Description

Displays information about media samples as they move through the filter graph.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Editing\SampGrabCB

User's Guide

This console application uses the IMediaDet interface to create a filter graph that contains the Sample Grabber filter. The application uses a callback function to retrieve samples from the video file.

Usage:

SampGrabCB Filename

The output from the application will look similar to the following:

Sample received = 00000  Clock = 4464847
Sample received = 00001  Clock = 4464848
Sample received = 00002  Clock = 4464849
Sample received = 00003  Clock = 4464850
Sample received = 00004  Clock = 4464853


StillCap Sample

Description

Video capture application that writes still images to bitmap files.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Editing\StillCap

User's Guide

This application uses the ISampleGrabber interface to capture still images from a live capture stream to a bitmap file. It demonstrates how to put the Sample Grabber filter into a filter graph, and how to retrieve sample data in real time through a callback function.

The application builds a capture graph using the first video capture device it finds. To capture a still image, click the Snap Still button. By default, the bitmap is saved with the file name StillCap0000.bmp. If you select the check box labeled Increment filename after each capture?, the application saves each image under a new file name. Otherwise, the previous image is overwritten when you capture a new image.

This application also can capture video files. Click Video Capture in the Capture Type area; video capture starts automatically. To end the capture session, click Start Playback. The recorded file automatically plays back.

For simplicity, this sample uses 24-bit RGB format. If your video driver is set to 16-bit color, you might notice flicker when the application runs. To resolve this problem, set the bit depth of your display to 24 bits or 32 bits.


Timeline Test Sample

Description

This sample application builds a timeline with a transition. It demonstrates the following tasks in Microsoft® DirectShow® Editing Services:

  • Creating a timeline.
  • Adding tracks, sources, transitions, and effects to the timeline.
  • Creating a SMPTE wipe transition.
  • Creating an audio crossfade using the Volume Envelope effect.
  • Setting properties on timeline objects.
  • Modifying a timeline and rendering the filter graph again.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Editing\TimelineTest


XTLTest Sample

Description

Command-line tool for rendering and previewing video editing projects. This tool renders Microsoft® DirectShow® Editing Services (DES) project files.

To enable ASF support in this application, link the project to a Microsoft® Windows Media™ Format (WMF) SDK certificate and define USE_WMF_CERT when you compile the application. See the WMF SDK documentation for instructions on obtaining a certificate.

Note This application requires Internet Explorer 4.0 or later. If it is not present, the application displays the following error message: Unexpected error - DShow not installed correctly. For more information, see IXml2Dex.

Path

Source: (SDK root)\Samples\Multimedia\DirectShow\Editing\Xtltest

User's Guide

This sample application demonstrates the following tasks related to video editing:

  • Previewing timelines and writing the rendered output to a file.
  • Setting timeline options when rendering timelines.

Usage:

xtltest.exe [switches] input.xtl

By default, the application previews the project. The following command-line switches are supported.

Switch | Description
/C | No clock. Render the project as quickly as possible, without synchronizing audio and video.
/D | Load source files dynamically. For more information, see IRenderEngine::SetDynamicReconnectLevel.
/[double-double] | Set the rendering start and stop times. For example, /[3-4] renders one second of the timeline, starting 3 seconds into the project.
/G filename.grf | Output a GraphEdit file in .grf format.
/N | No rendering. The project is not previewed or rendered to a file. This option is useful for validating the input file, or with the /G switch.
/P [number] | Choose an ASF compression profile. Available only if the application is compiled with a WMF SDK certificate.
/P | List available ASF profiles. Available only if the application is compiled with a WMF SDK certificate.
/R | Activate smart recompression. The application uses the first clip in the timeline for the compression format. Use the /W switch with this option. For more information, see About the Render Engines.
/W filename | Render the timeline to a file. The file type is determined by the file extension. The application supports AVI and WAV files. If the application is compiled with a WMF SDK certificate, it also supports ASF files. This option suppresses preview.
/X filename.xtl | Save the project as an XML file. The new file is functionally identical to the input file, although the XML tags may differ.

Programming Notes

This sample demonstrates all of the steps required to read an XML project file, and then preview it or output it to a file.

For smart recompression, the application uses the format of the first non-muted source in the timeline. (It will fail if the first souce is an audio file.) The GetFirstSourceOnTimeline function retrieves the first non-muted source. This function demonstrates how to traverse the objects in a timeline. The GetSourceVideoType function retrieves the media type of the first video stream in a source. The application uses this media type when it calls IAMTimelineGroup::SetSmartRecompressFormat to set the recompression format. For more information, see Rendering a Project.

To handle error logging, the application defines a custom class, CErrorReporter. The class exposes the IAMErrorLog interface; however, it is not a true COM object, because it does not correctly handle reference counting. Therefore, the application must create it statically. For more information, see Logging Errors.

If USE_WMF_CERT is defined, the application includes support for writing WMF files. The CKeyProvider class implements the IServiceProvider interface. It calls the WMCreateCertificate function to create the WMF certificates. The helper function ListWMSDKProfiles lists the standard profiles that the WMF SDK provides. For more information, see Windows Media Applications and the Windows Media Format SDK.


DexterVB Sample

Description

Video editing application for Microsoft® Visual Basic®.

This sample application is a graphical tool for creating Microsoft® DirectShow® Editing Services timelines. It demonstrates the following tasks:

  • Loading and saving XTL project files
  • Adding, editing, and deleting timeline objects
  • Previewing a timeline

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectShow\Editing\DexterVB

User's Guide

The following illustration shows the DexterVB application window.

DexterVB User Interface

The left pane displays a tree-view control that contains the timeline. The right pane displays information about the timeline. To view information about an object in the timeline, select the object's icon in the tree view.

To create a new timeline, choose New from the File menu. To open a project file, choose Open from the File menu. To save the current timeline to a project file, choose Save As from the File menu.

To modify the timeline, or any of the objects in the timeline, right-click the corresponding icon in the left pane. DexterVB displays a pop-up menu for that object. The following illustration shows the pop-up menu for the timeline.

Timeline Pop-Up Menu

For each object, the pop-up menu contains only the commands that apply to that object. The following commands are supported:

  • Add (Object Type): Inserts a new child of the specified type.
  • Collapse: Collapses the tree-view node for this object.
  • Delete: Removes the object from the timeline.
  • Edit: Enables the user to edit properties on the object.
  • Expand: Expands the tree-view node for this object.

The following commands are specific to the timeline itself:

  • Clear Render Engine: Deletes the filter graph.
  • Insert Group: Inserts a new group into the timeline.
  • Play: Previews the project. The user must render the timeline first.
  • Pause: Pauses preview.
  • Render Timeline: Builds a preview graph from this timeline.
  • Stop: Stops preview.


SlideShowVB Sample

Description

Microsoft® Visual Basic® application that creates a slide show from a series of video clips or image files.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectShow\Editing\SlideShowVB

User's Guide

This sample application demonstrates the following tasks:

  • Using the MediaDet object to obtain a poster frame from a source clip.
  • Saving a timeline as an XTL file.
  • Writing a timeline to an AVI file.
  • Loading media clips.

To use this application, do the following:

  • Drag video files or image files from your computer to the cells in the application window, starting from the cell in the upper-left corner.
  • Enter the length of time that each clip should play, in seconds.
  • Select a transition, using the combo box. The transitions have a fixed two-second duration.
  • To preview the slide show, click Play.
  • To save the slide show as an XTL project, click Write XTL.
  • To save the slide show as an AVI file, click Write AVI.


TrimmerVB Sample

Description

Microsoft® Visual Basic® application that trims a source clip and writes the trimmed clip to a new file.

Path

Source: (SDK root)\Samples\Multimedia\VBSamples\DirectShow\Editing\TrimmerVB

User's Guide

This application enables the user to open a video source file, trim a desired amount from the front and the end of the clip, and then save the remaining portion to a new file.

To use this application, do the following:

  1. To choose a source file, click the Browse button. The first frame of the clip appears in all three preview areas.
  2. To select the start position, move the slider or click the frame step buttons. The preview frame in the Current Video Frame area is updated.
  3. To set the start position, click the Set Trim Preview Start Position button. The poster frame in Video Start Frame area is updated.
  4. To select the stop position, move the slider or click the frame step buttons.
  5. To set the stop position, click the Set Trim Preview Stop Position button. The poster frame in the Video Stop Frame area is updated.
  6. To write the new file, click the Write button. Wait for the progress indicator to complete.
  7. To view the new file, click the Playback button.


XTLTestVB Sample

Description

Microsoft® Visual Basic® application that previews video editing project files.

To use this application, drag a Microsoft® DirectShow® Editing Services XTL file to the application window.

Path

Source: (SDK root)Samples\Multimedia\VBSamples\DirectShow\Editing\XTLTestVB


DirectX Media Objects

This section describes Microsoft® DirectX® Media Objects (DMOs).

  • Introduction to DirectX Media Objects
  • Using DirectX Media Objects
  • DMOs and Media Types
  • Using DMOs in a DirectShow Application
  • DMO Reference


Introduction to DirectX Media Objects

Microsoft® DirectX® Media Objects (DMOs) are a new way to write data-streaming components. In some respects, DMOs are similar to Microsoft® DirectShow® filters. Like a DirectShow filter, a DMO takes input data and uses it to produce output data. However, the application programming interfaces (APIs) for DMOs are much simpler than the corresponding APIs for DirectShow. As a result, DMOs are easier to create, easier to test, and easier to use.

DMOs are fully compatible with DirectShow, but applications can use DMOs without using DirectShow. Within a DirectShow application, DMOs are wrapped by a DirectShow filter called the DMO Wrapper filter. The distinction between filters and DMOs is transparent to the application, which does not need to use the DMO APIs. On the other hand, applications not based on DirectShow can use DMOs directly. Thus, by writing a DMO, you create a component that can be used in a wide range of applications.

  • How DMOs Differ from DirectShow Filters
  • Why DMOs?
  • DMO Test Application

How DMOs Differ from DirectShow Filters

DirectShow filters work only within a DirectShow filter graph. The filter graph manager mediates between the application and the filters in the graph. DMOs do not have this requirement; an application can use a DMO by itself.

In DirectShow, filters do much of the work required to stream data. This includes:

  • Allocating buffers.
  • Negotiating media types and connections to other filters.
  • Pushing data through the filter graph.
  • Sending events to the filter graph manager.
  • Synchronizing multiple threads.

In contrast, a DMO does none of these things. Instead, these kinds of tasks become the responsibility of the client using the DMO. The client allocates buffers and fills them with data. Then it delivers the buffers to the DMO, which processes them. The client retrieves the output buffers.

Within DirectShow, the DMO Wrapper filter is the client of the DMO, so it handles all of these tasks. Other applications can provide their own implementations.

Why DMOs?

DMOs offer the following advantages:

  • They are generally smaller and simpler than DirectShow filters because they support less functionality.
  • They are more flexible than DirectShow filters because they do not require a filter graph. You can use them with DirectShow when you need the services that DirectShow provides, such as graph synchronization, intelligent connection, automatic handling of data flow, and thread management. If you do not need these services, you can access the DMO directly.
  • DMOs always perform synchronous data processing, which eliminates many of the threading issues that filter developers must consider.
  • Unlike ACM and VCM codecs, DMOs are based on the Component Object Model (COM), so they can be extended through QueryInterface.
  • DMOs support a more generalized streaming model than ACM or VCM codecs. Like DirectShow filters, DMOs can support multiple inputs and multiple outputs.

For these reasons, you should implement a DMO rather than a DirectShow filter whenever possible. However, there may be situations when a DMO is not suitable. For example:

  • Unusual transport requirements. The DMO Wrapper filter uses the IMemInputPin transport. If you need some other transport mechanism within a DirectShow application, you must write a filter.
  • Dynamic graph building. If your application performs dynamic graph building, you might need to write your own filter. For example, you might need to control how allocators are created.

DMO Test Application

The DirectX 8.0 SDK includes a DMO test application, named DMOTest. The test application can help verify that a DMO meets the DMO specifications. The application is installed in the Bin\DXUtils directory, under the SDK root directory. If you develop a DMO, you should include the DMO test application as part of your testing.

To use DMOTest, you must generate test data for the DMO. The SDK includes a DirectShow filter for this purpose. It is located in the DLL file DMODump.dll. You will need to register the filter with the Regsvr32 utility.

Details about the test application can be found in the DMOTest application help. In the application, choose Contents from the Help menu. The help includes step-by-step instructions for generating test data and running the test application.


Using DirectX Media Objects

This article describes how to use a Microsoft® DirectX® Media Object (DMO) in an application. This article applies only to applications that access DMOs directly. To use a DMO in a Microsoft® DirectShow® filter graph, use the DMO Wrapper filter.

This article contains the following sections.

  • Streams and Buffers
  • Data Flow
  • How to Process Data
  • Discardable and Optional Streams
  • In-Place DMOs

Streams and Buffers

Conceptually, a DMO is an object that takes m inputs and produces n outputs. The inputs and outputs are called streams. Every DMO has at least one stream. It's possible for a DMO to have no input streams or no output streams, but a typical DMO has both inputs and outputs.

Note Unlike pins in DirectShow, streams are not distinct COM objects. They are referenced on the DMO object itself, using a zero-based index.

A DMO receives data through its input streams. It processes the data and produces output through its output streams. All data is typed using a media type. The media type defines how to interpret the contents of the data. For example, 320 x 240 24-bit RGB video is one type; 44.1-kilohertz (kHz) 16-bit stereo PCM audio is another type. Media types are described using the DMO_MEDIA_TYPE structure.

Each stream on a DMO can accept a certain range of media types. Depending on the DMO, it might accept a wide range of types (video at any bit depth) or a narrow range (only 16-bit video). Also, a DMO might be limited to certain combinations of inputs and outputs. For example, if an input stream is set to 16-bit video, an output stream might require the same bit depth. The application can enumerate each stream's preferred types and then test specific combinations.

Examples:

  • A DMO that creates AVI data might have two input streams, one for video and one for audio. It would produce one output stream for the interleaved audio-video data.
  • A DMO that posterizes RGB images might have 24-bit RGB video input and 8-bit RGB video output.

The application delivers input data grouped in blocks of memory. Each block of memory is encapsulated by a COM object called a buffer that supports the IMediaBuffer interface. This interface contains methods for setting the length of the data in the buffer, retrieving a pointer to the data, and retrieving the allocated size of the buffer. The application is responsible for allocating all buffers used by the DMO, both input and output.

Data Flow

This section describes how data moves between the application and the DMO.

An application alternates between delivering input buffers and requesting output. It delivers input buffers by calling the IMediaObject::ProcessInput method on the DMO. It requests output by calling the IMediaObject::ProcessOutput method.

There are two ways to stop the flow of input data:

  • Discontinuity: When the application reaches the end of the input data, or there is a break in the data, the application signals a discontinuity. A discontinuity informs the DMO that no further input is expected. At that point, the DMO might still have data to process, so the application should request output until the DMO signals there is none left.
  • Flushing: The application can interrupt the data flow by flushing the DMO. If the DMO was buffering data internally, it releases that data.

Streaming begins when the application first calls IMediaObject::ProcessInput on the DMO. A DMO will not begin streaming until the application sets media types for all the streams. (Optional streams are an exception; see Discardable and Optional Streams.) Streaming stops when the application flushes the DMO, or signals a discontinuity on every input stream and then processes all of the output. These actions return the DMO to a non-streaming state. The DMO retains all of its media type settings, but it releases all IMediaBuffer pointers. At that point, it cannot generate any more output until the application calls ProcessInput at least once.

To stream data, perform the following steps.

  1. Query the DMO for the number of streams it supports and the preferred media types for each stream.
  2. Set media types for all the streams.
  3. Allocate input buffers and output buffers.
  4. Fill the input buffers with data and call ProcessInput.
  5. Call ProcessOutput and retrieve the output data. Repeat steps 4 and 5 until all of the input data is processed.
  6. Signal a discontinuity and process any remaining output.

You can interrupt steps 4 through 6 by flushing the data.

How to Process Data

This section explains in more detail the steps listed in the previous section.

Step 1. Query the DMO

First, query the DMO for the number of streams it supports and the preferred media types for each stream. To retrieve the number of input streams and output streams, call the IMediaObject::GetStreamCount method.

For each stream, the DMO ranks its preferred media types in order of preference and assigns each type an index, starting from zero. To retrieve a preferred media type for a particular stream, call the IMediaObject::GetInputType method or IMediaObject::GetOutputType method. Specify a stream number and a media-type index. To enumerate all the media types on a stream, use a loop that increments the media-type index until the method returns DMO_E_NO_MORE_ITEMS, as shown in the following psuedo-code.

DWORD cInputs, cOutputs, type = 0
DMO_MEDIA_TYPE mt

pDMO->GetStreamCount(&cInputs, &cOutputs)

for (DWORD i = 0; i < cInputs; i++)
{
    while (pDMO->GetInputType(i, type, &mt) != DMO_E_NO_MORE_ITEMS)
    {
        if ( this media type is one you want )
            break
        MoFreeMediaType(&mt)
        type++
    }
}

The GetInputType and GetOutputType methods return a DMO_MEDIA_TYPE structure with the media type. The following structure members are relevant:

  • majortype: A globally unique identifier (GUID) that specifies the major type of the stream. The major type is the general classification, such as video or audio. For a list of major types, see Major Types.
  • subtype: A GUID that specifies the subtype of the stream. The subtype further classifies the type. For example, MEDIASUBTYPE_RGB24 specifies 24-bit RGB video. For a list of subtypes, see Media Types.
  • pbFormat: Pointer to a structure that describes the format in detail. The format structure specifies information such as the width and height of a video image, or the sample rate of an audio sample. Different media types use different format structures. Most video data uses the VIDEOINFOHEADER structure. Audio data uses the WAVEFORMATEX structure.
  • formattype: Specifies the format structure contained in pbFormat.

The media type might have a NULL format structure, indicated by a value of GUID_NULL for the formattype member. A NULL format indicates that the DMO can accept a range of formats within the specified media type. For example, a stream that requires PCM audio might accept a range of sample rates. Therefore, it returns MEDIATYPE_Audio for the major type, MEDIASUBTYPE_PCMAudio for the subtype, and a NULL format.

The application must call the MoFreeMediaType function to free the pbFormat member.

Step 2. Set Media Types

After finding the DMO's preferred media types, set the media type for each stream by calling the IMediaObject::SetInputType and IMediaObject::SetOutputType methods.

Not every combination of media types reported by the DMO is guaranteed to be valid. For example, the output type might need to match the input type. You can test a media type by calling SetInputType or SetOutputType with the DMO_SET_TYPEF_TEST_ONLY flag. For a decoder, you would generally set the input type and then choose an output type. For an encoder, you would set the output type and then choose an input type.

Because the settings on one stream can affect another stream, you might need to clear a media type that you set previously. To do this, call SetInputType or SetOutputType with the DMO_SET_TYPEF_CLEAR flag.

Step 3. Allocate Buffers

After you set the media types, query the DMO for each stream's buffer requirements. These can change depending on the media type. For each stream, call the IMediaObject::GetInputSizeInfo or IMediaObject::GetOutputSizeInfo method. These methods return three values:

  • Minimum buffer size, in bytes.
  • Alignment requirements, if any. A buffer is aligned if the start address is a multiple of some specified integer.
  • For input buffers, the maximum amount of data that the DMO will hold for lookahead. Some DMOs need to hold multiple input buffers to process the data; the lookahead value specifies this requirement.

You must allocate sufficient buffers to handle these requirements.

In addition to the size requirements, an input stream might require that each buffer contain only whole samples, or contain exactly one sample, or use a fixed sample size. To determine these requirements, call the IMediaObject::GetInputStreamInfo method.

Step 4. Process Input

At this point, you can deliver input buffers to the DMO.

For each input stream, fill one or more input buffers with media data. You can write data directly into a buffer, or use an output buffer from another DMO. Call the ProcessInput method to deliver each buffer. Typically, the DMO holds a reference count on the buffer. It releases the buffer when it has generated all of the output that it can, or when the application flushes the DMO. Do not re-use the buffer until the DMO releases it.

To determine whether an input stream can accept more data, call the IMediaObject::GetInputStatus method. If the stream can accept more data, the method returns the DMO_INPUT_STATUSF_ACCEPT_DATA flag.

Step 5. Process Output

Whereas ProcessInput delivers one input buffer at a time, ProcessOutput generates output for all the output streams at once. The application passes an array of DMO_OUTPUT_DATA_BUFFER structures, with one structure for every output stream. The structure contains a pointer to an output buffer (allocated by the application) and various fields that are filled in by the DMO.

In the ProcessOutput method, the DMO generates as much data as possible, given the size of the output buffers. If it fills an output buffer before it processes all of the data, it sets the DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE flag in the structure's dwStatus member. When the method returns, check each structure for this flag. If the flag is present, call ProcessOutput again.

After streaming begins, the DMO can always accept input, or produce output, or both. Therefore, either GetInputStatus returns the DMO_INPUT_STATUSF_ACCEPT_DATA flag, or ProcessOutput returns the DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE flag. The application keeps data flowing by testing for these flags and calling ProcessInput or ProcessOutput.

Step 6: Signal a Discontinuity

When you have delivered all available input data to a particular input stream, call the IMediaObject::Discontinuity method. The DMO does not accept further input to that stream until you process any remaining output.

Discardable and Optional Streams

A DMO can designate some of its output streams as discardable or optional:

  • A discardable stream contains data that the application can discard, either completely or on occasional samples.
  • An optional stream is a secondary stream that not all applications will need, or that contains additional information about a primary stream.

To query whether a stream is discardable or optional, call the IMediaObject::GetOutputStreamInfo method and check the pdwFlags parameter. The DMO_OUTPUT_STREAMF_DISCARDABLE flag indicates the stream is discardable. The DMO_OUTPUT_STREAMF_OPTIONAL flag indicates that the stream is optional. In general, at least one stream should be non-optional.

When you call the IMediaObject::ProcessOutput method, you can discard data from one or more streams by setting the DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER flag in the dwFlags parameter. For each stream that you want to discard, set the pBuffer member of the DMO_OUTPUT_DATA_BUFFER structure to NULL. The DMO attempts to discard the data from those streams, as follows:

  • If the stream is discardable or optional, the DMO is guaranteed to discard the data.
  • Otherwise, the DMO discards the data if possible. However, there is no guarantee that it can do so.

If a pBuffer member is NULL but you do not set the DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER flag, the DMO does not discard the data, even if the stream is discardable or optional. In cases where pBuffer is NULL but no data was discarded, the DMO signals the DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE flag to indicate that the stream still has data. If you do not process an output stream, but do not discard it, the DMO might be unable to generate data for other output streams.

If you will never use an optional stream, you do not have to set its media type. The same is not true for discardable streams; you must always set the media type on a discardable stream. This is the only functional difference between optional and discardable streams.

In-Place DMOs

Certain data transformations can be accomplished by directly modifying the data. This is known as in-place processing. Many audio and video effects can be done in place. In-place processing is more efficient than copying data to another buffer. To process data in-place, make a single call to the IMediaObjectInPlace::Process method, rather than separate calls to ProcessInput and ProcessOutput. Pass an array of bytes that contains the input data. When the method returns, the byte array contains the output data.

A DMO that supports IMediaObjectInPlace must still support all of the IMediaObject methods. You can choose whether to use in-place processing or create separate input and output buffers. However, do not mix the two types of processing. If you call Process, do not call ProcessInput or ProcessOutput, and vice-versa.

An in-place DMO might create some additional output after the input stops. This is known as an effect tail. For example, a reverb effect continues after the input reaches silence. If the DMO produces an effect tail, the application must call the Process method with zeroed input buffers until the tail is completely processed. For more information, see IMediaObjectInPlace::Process.


DMOs and Media Types

A media type is a description of the format associated with a stream of media data. This article describes how Microsoft® DirectX® Media Objects (DMOs) handle media types. It is primarily intended for developers who are writing their own custom DMOs. For applications that use DMOs, see Using DirectX Media Objects.

This article contains the following topics:

  • Overview
  • Media Types in the Registry
  • Preferred Media Types
  • Setting the Media Types
  • Examples

Overview

Three main pieces of information describe a media type:

  • Major type: A globally unique identifier (GUID) that defines a broad category for the data, such as audio or video.
  • Subtype: A GUID that defines more specific aspects of the type, such as 24-bit RGB for video data.
  • Format block: A type-specific structure that fully specifies the format.

For more information, refer to the DMO_MEDIATYPE structure.

When an application first creates an instance of a DMO, the streams in the DMO have no particular media type. Before the application can use the DMO to process data, it must specify media types for all the streams. (Optional streams are an exception; see Discardable and Optional Streams.)

To find an acceptable media type for a particular stream, the application queries the DMO. The DMO enumerates possible types, and the application selects one. Setting a media type on one stream can change the possible types available for other streams. For example, an audio-effect DMO might support a range of sample rates, but require the output rate to match the input rate. Setting the input type would therefore restrict the set of possible output types.

Media Types in the Registry

The DMORegister function adds information about a DMO to the registry, including a list of media types for input and output. An application uses this information to find DMOs that match its requirements. The information is not meant to be comprehensive. Typically, you would include only the main types that the DMO supports.

Although the registry information lists input and output types, it does not distinguish among individual streams. For example, if a DMO has separate input streams for audio and video, the registry information would list them both under input types.

For the DMORegister function, media types are specified using a DMO_PARTIAL_MEDIATYPE structure. The function differs in this respect from the IMediaObject interface, which uses DMO_MEDIATYPE. The DMO_PARTIAL_MEDIATYPE structure contains only two fields, for the major type and the subtype. It does not have fields for format block. Typically, the format contains information that is too granular to include in the registry, such as the height and width of a video image.

Preferred Media Types

To query a DMO for its supported types, an application calls the IMediaObject::GetInputType and IMediaObject::GetOutputType methods. These two methods enumerate the preferred types on a specified stream, in order of preference. A stream's preferred types can change dynamically when the application sets media types on other streams. For example, the preferred output types might change depending on the input types, or vice versa. A stream might not even have a preferred type until other streams have types. However, the DMO is not required to update its preferred types in this way. The application cannot assume that every type it receives is valid. For this reason, the SetInputType and SetOutputType methods support a flag for testing a specific type.

Sometimes a fully specified media type is too specific to use as a preferred type. To indicate a more general type, the DMO can return an incomplete type. A media type is incomplete if it has the value GUID_NULL for the major type, the subtype, or the format type. The GetInputType and GetOutputType methods usually set the format type to GUID_NULL.

After the application has set all of the input types, however, the DMO should generally return at least one complete type for each output stream. Having a complete type facilitates testing, and applications can use it as a reasonable default. (Note that some media types are complete without a format type.) The DMO test application included with the SDK relies on the DMO behaving this way (see DMO Test Application).

Setting the Media Types

Applications use the IMediaObject::SetInputType and IMediaObject::SetOutputType methods to test, set, or clear types on a stream. The types must be fully specified, so that the DMO can process the data correctly. For each stream, the DMO must verify that the proposed type is compatible with the types on other streams. The DMO_SET_TYPEF_CLEAR flag clears a stream's type, so that the application can "back out" and try another combination.

Examples

The following examples describe some typical scenarios, to illustrate the points made in the previous sections.

Decoders

In a typical video decoder, the output format is determined partly by the input format. For example, the output stream usually must have the same frame rate and video size as the input stream. One option is for the decoder to return no output types until the input type is set. Another option is to enumerate a set of incomplete types with no format block. In that case, use the subtype to indicate the supported uncompressed types, such as 16-bit RGB, 24-bit RGB, and so forth.

Also, video decoders generally do not support an application setting the output type before it sets the input type. The usual scenario is to decode from a known input format, so this limitation is reasonable.

An audio decoder might support a fixed set of output formats. If so, it might be able to enumerate output formats before the application sets the input format.

Compressors

Usually, a video compressor cannot fully specify its preferred output formats until the application sets the input format, and vice versa. Instead, it should return an incomplete type with no format block. For both audio and video compression, applications usually need to control various format parameters, such as the output bit rate. However, if the input type is set, the compressor should enumerate at least one complete output type, for the reasons mentioned previously.


Using DMOs in a DirectShow Application

This article describes how to use Microsoft® DirectX® Media Objects (DMOs) in a Microsoft® DirectShow® application. For information about using DMOs outside of DirectShow, see Using DirectX Media Objects.

This article contains the following sections.

  • Overview of DMOs in DirectShow
  • Using the DMO Wrapper Filter
  • Finding DMOs with the System Device Enumerator

Overview of DMOs in DirectShow

The DMO Wrapper filter enables a DirectShow application to use a DMO within a filter graph. This filter wraps the DMO and handles all the details of using the DMO, such as passing data to and from the DMO. Also, the filter aggregates the DMO, so the application can query the filter for any COM interfaces that the DMO exposes.

However, all stream control should occur between the application and the filter (or between the application and the filter graph manager). Do not call any methods on DMO interfaces that might change the state of the DMO. For example, do not set the media type on a stream, process any buffers, flush the DMO, lock the DMO, enable or disable quality control, or set video optimizations. The DMO Wrapper filter handles all streaming for the DMO, and directly calling these methods might cause an error.

There are two ways to add a DMO to a filter graph:

  • If you know the class identifier (CLSID) of a specific DMO that you want to use, you can initialize the DMO Wrapper filter with that DMO.
  • Otherwise, you can enumerate an entire category of devices, including DMOs and DirectShow filters, by using the system device enumerator.

The following sections describe each approach.

Using the DMO Wrapper Filter

Start by creating an instance of the DMO Wrapper filter. Query the DMO Wrapper filter for the IDMOWrapperFilter interface. Then call the IDMOWrapperFilter::Init method. This method takes the CLSID of the DMO and the GUID of the DMO's category.

You can use the DMOEnum function to enumerate DMOs registered on the user's system. DMOs are registered using a different set of category GUIDs from the ones used for DirectShow filters. For a list of DMO categories, see Category GUIDs.

The following code example shows how to use the IDMOWrapperFilter interface.

// IMediaObject

// Create the DMO Wrapper filter.
IBaseFilter *pFilter;
HRESULT hr = CoCreateInstance(CLSID_DMOWrapperFilter, NULL,
    CLSCTX_INPROC, IID_IBaseFilter, (void **)&pFilter);

if (SUCCEEDED(hr))
{
    IDMOWrapperFilter *pWrap;
    hr = pFilter->QueryInterface(IID_IDMOWrapperFilter, (void **)&pWrap);

    if (SUCCEEDED(hr)) {     // Initialize the filter.
        hr = pWrap->Init(CLSID_MyDMO, CLSID_MyDMOCategory);
        pWrap->Release();
    }

    if (SUCCEEDED(hr)) {     // Add the filter to the graph.
        hr = pGraph->AddFilter(pFilter, L"My DMO");
    }
    pFilter->Release();
}

Finding DMOs with the System Device Enumerator

The system device enumerator includes DMOs when it enumerates certain DirectShow device categories. It maps the following DMO categories to their DirectShow equivalents.

DMO Category | DirectShow Equivalent
DMOCATEGORY_AUDIO_ENCODER | CLSID_AudioCompressorCategory
DMOCATEGORY_AUDIO_DECODER | CLSID_LegacyAmFilterCategory
DMOCATEGORY_VIDEO_ENCODER | CLSID_VideoCompressorCategory
DMOCATEGORY_VIDEO_DECODER | CLSID_LegacyAmFilterCategory

In addition, you can use the system device enumerator to enumerate any DMO categories, including DMOCATEGORY_AUDIO_EFFECT and DMOCATEGORY_VIDEO_EFFECT. For more information on using the system device enumerator, see Using the System Device Enumerator. The IMoniker::BindToObject method automatically wraps the DMO in the DMO Wrapper filter.


DMO Reference

This section contains all the Microsoft® DirectX® Media Object (DMO) reference information.

  • Interfaces
  • Structures
  • Enumerated Types
  • Functions
  • DMO Error Codes
  • Globally Unique Identifiers (GUIDs)
  • Base Class Reference


Interfaces

This section contains reference entries for all the Microsoft® DirectX® Media Object (DMO) COM interfaces and their methods.

  • IDMOQualityControl
  • IDMOVideoOutputOptimizations
  • IEnumDMO
  • IMediaBuffer
  • IMediaObject
  • IMediaObjectInPlace


IDMOQualityControl Interface

Supports quality control on a Microsoft® DirectX® Media Object (DMO).

A DMO exposes this interface if it can respond to late samples. When quality control is enabled, the DMO attempts to process samples on time, discarding late samples if necessary. When quality control is disabled, the DMO processes every sample. By default, quality control is disabled.

Applications use this interface to enable or disable quality control. Using quality control is appropriate when you are viewing media data in real time. If you are capturing data to a file, do not enable quality control, because the DMO might discard samples. It does not matter in file capture whether samples arrive late, and you do not want to lose the data.

To use quality control, perform the following steps:

  1. Call the SetNow method with the reference time of the earliest sample to be processed.
  2. Call the SetStatus method with the DMO_QUALITY_STATUS_ENABLED flag.

To disable quality control, call SetStatus with no flag.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDMOQualityControl methods | Description
SetNow | Specifies the earliest time stamp for which the DMO should deliver data.
SetStatus | Enables or disables quality control.
GetStatus | Determines whether quality control is active.

IDMOQualityControl::SetNow

IDMOQualityControl Interface

Specifies the earliest time stamp that the DMO will deliver.

Syntax

HRESULT SetNow(
    REFERENCE_TIME rtNow
);

Parameters

rtNow
[in] Reference time specifying the earliest time stamp to deliver.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_FAIL | Failure

Remarks

If quality control is enabled, the DMO discards any samples whose time stamp is less than rtNow. Samples whose time stamp is rtNow or later are processed as efficiently as possible. Depending on the implementation, the DMO might drop some samples to keep pace.

If quality control is disabled, this method has no immediate effect. However, the DMO stores the specified reference time. It uses this value if quality control is enabled at a later time. To enable quality control, call the SetNow method.

If incoming samples are not time-stamped, the DMO never performs quality control. The application sets the time stamp in the IMediaObject::ProcessInput method.

IDMOQualityControl::SetStatus

IDMOQualityControl Interface

Enables or disables quality control.

Syntax

HRESULT SetStatus(
    DWORD dwFlags
);

Parameters

dwFlags
[in] Value that specifies whether to enable or disable quality control. Use DMO_QUALITY_STATUS_ENABLED to enable quality control, or zero to disable quality control.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_INVALIDARG | Invalid argument

Remarks

With quality control enabled, the DMO attempts to deliver samples on time. It can skip late samples if necessary. With quality control disabled, the DMO delivers every sample. If you enable quality control, call the SetNow method to specify the earliest time stamp that the DMO should process. Otherwise, the call to SetStatus succeeds but the DMO does not perform quality control.

By default, quality control is disabled.

IDMOQualityControl::GetStatus

IDMOQualityControl Interface

Determines whether quality control is active.

Syntax

HRESULT GetStatus(
    DWORD *pdwFlags
);

Parameters

pdwFlags
[out] Pointer to a variable that receives the quality control status. If quality control is disabled, the value is zero. If quality control is enabled, the value is DMO_QUALITY_STATUS_ENABLED.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_POINTER | NULL pointer value


IDMOVideoOutputOptimizations Interface

Supports video optimizations on a Microsoft® DirectX® Media Object (DMO).

This interface enables an application to negotiate with a DMO about video output optimizations. A DMO exposes this interface when it can perform optimizations that require support from the application. The application can query the DMO for its preferred features, and then agree (or not agree) to provide them. The DMO must process output even if the application rejects the optimizations.

For example, a video decoder might generate an output frame by applying deltas to the previous output frame. When queried, it requests that the application supply the previous frame in the output buffer. The application can agree to this request or not.

Video optimizations are negotiated separately for each output stream.

The following psuedo-code shows how an application might negotiate with the DMO:

IDMOVideoOutputOptimizations *pVidOpt;
// Query the DMO for IDMOVideoOutputOptimizations (not shown).

BOOL  bWantsPreviousBuffer = FALSE;
DWORD wFlags;
pVidOpt->QueryOperationModePreferences(0,&dwFlags);

if (dwFlags & DMO_VOSF_NEEDS_PREVIOUS_SAMPLE)
{
    // Agree to the request.
    pVidOpt->SetOperationMode(0, DMO_VOSF_NEEDS_PREVIOUS_SAMPLE);
    bWantsPreviousBuffer = TRUE;
}

// Processing loop
while (there is input)
{
    ProcessInput(0, ...);
    if (bWantsPreviousBuffer)
        pDMO->ProcessOutput(0, ...) // Use the same buffer as last time.
    else
        pDMO->ProcessOutput(0, ...) // OK to use a new buffer.
}

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDMOVideoOutputOptimizations methods | Description
QueryOperationModePreferences | Retrieves the DMO's preferred optimization features.
SetOperationMode | Notifies the DMO of the optimization features in effect.
GetCurrentOperationMode | Retrieves the optimization features in effect.
GetCurrentSampleRequirements | Retrieves the optimization features required to process the next sample, given the features already agreed to by the application.

IDMOVideoOutputOptimizations::QueryOperationModePreferences

IDMOVideoOutputOptimizations Interface

Retrieves the DMO's preferred optimization features.

Syntax

HRESULT QueryOperationModePreferences(
    ULONG ulOutputStreamIndex,
    DWORD *pdwRequestedCapabilities
);

Parameters

ulOutputStreamIndex
Zero-based index of an output stream on the DMO.
pdwRequestedCapabilities
Pointer to a variable that receives the DMO's requested features. The returned value is a bitwise combination of zero or more flags from the DMO_VIDEO_OUTPUT_STREAM_FLAGS enumeration.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_POINTER | NULL pointer argument

IDMOVideoOutputOptimizations::SetOperationMode

IDMOVideoOutputOptimizations Interface

Notifies the DMO of the optimization features in effect.

Syntax

HRESULT SetOperationMode(
    ULONG ulOutputStreamIndex,
    DWORD dwEnabledFeatures
);

Parameters

ulOutputStreamIndex
Zero-based index of an output stream on the DMO.
dwEnabledFeatures
Bitwise combination of zero or more flags from the DMO_VIDEO_OUTPUT_STREAM_FLAGS enumeration.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_INVALIDARG | Invalid argument

Remarks

Before calling this method, call the QueryOperationModePreferences method to determine which features the DMO requests. Then call this method to inform the DMO which of those features you are providing. If you are not providing any of them, it is not necessary to call this method. The DMO does not assume that any of them will be provided.

The application must provide all the features it has agreed to. For some features, however, the DMO might not require the feature on every sample. To determine if the DMO can dispense with any features on the next sample, call the GetCurrentSampleRequirements method. In effect, this enables the DMO to waive an agreed-upon feature for one sample.

Before streaming begins, subsequent calls to this method override earlier calls. To set multiple features, you must do so in a single method call. Once streaming begins, this method returns an error. Streaming begins when the applications calls IMediaObject::ProcessInput on at least one input stream.

When streaming ends, the application can renegotiate the features. Streaming ends if the application calls the IMediaObject::Flush method, or if the application calls IMediaObject::Discontinuity on all the input streams and then processes all of the remaining output.

IDMOVideoOutputOptimizations::GetCurrentOperationMode

IDMOVideoOutputOptimizations Interface

Retrieves the optimization features in effect.

Syntax

HRESULT GetCurrentOperationMode(
    ULONG ulOutputStreamIndex,
    DWORD *pdwEnabledFeatures
);

Parameters

ulOutputStreamIndex
Zero-based index of an output stream on the DMO.
pdwEnabledFeatures
Pointer to a variable that receives the current features. The returned value is a bitwise combination of zero or more flags from the DMO_VIDEO_OUTPUT_STREAM_FLAGS enumeration.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_POINTER | NULL pointer argument

IDMOVideoOutputOptimizations::GetCurrentSampleRequirements

IDMOVideoOutputOptimizations Interface

Retrieves the optimization features required to process the next sample, given the features already agreed to by the application.

Syntax

HRESULT GetCurrentSampleRequirements(
    ULONG ulOutputStreamIndex,
    DWORD *pdwRequestedFeatures
);

Parameters

ulOutputStreamIndex
Zero-based index of an output stream on the DMO.
pdwRequestedFeatures
Pointer to a variable that receives the required features. The returned value is a bitwise combination of zero or more flags from the DMO_VIDEO_OUTPUT_STREAM_FLAGS enumeration.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_POINTER | NULL pointer argument

Remarks

After an application calls the SetOperationMode method, it must provide all the features it has agreed to. However, the DMO might not require every feature on every sample. This method enables the DMO to waive an agreed-upon feature for one sample.

Before processing a sample, the application can call this method. If the DMO does not require a given feature in order to process the next sample, it omits the corresponding flag from the pdwRequestedFeatures parameter. For the next sample only, the application can ignore the feature. The results of this method are valid only for the next call to the IMediaObject::ProcessOutput method.

The DMO will return only the flags that were agreed to in the SetOperationMode method. In other words, you cannot dynamically enable new features with this method.


IEnumDMO Interface

This interface provides methods for enumerating Microsoft® DirectX® Media Objects (DMOs). It is based on the OLE enumeration interfaces. For more information, see the IEnumXXXX topic in the Platform SDK.

To enumerate registered DMOs, call the DMOEnum function.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IEnumDMO methods | Description
Next | Retrieves a specified number of items in the enumeration sequence.
Skip | Skips over a specified number of items in the enumeration sequence.
Reset | Resets the enumeration sequence to the beginning.
Clone | Not implemented.

IEnumDMO::Next

IEnumDMO Interface

Retrieves a specified number of items in the enumeration sequence.

Syntax

HRESULT Next(
    DWORD cItemsToFetch,
    CLSID *pCLSID,
    WCHAR **Names,
    DWORD *pcItemsFetched
);

Parameters

cItemsToFetch
Number of items to retrieve.
pCLSID
[out] Array of size cItemsToFetch that is filled with the CLSIDs of the enumerated DMOs.
Names
[out] Array of size cItemsToFetch that is filled with the friendly names of the enumerated DMOs.
pcItemsFetched
[out] Pointer to a variable that receives the actual number of items retrieved. Can be NULL if cItemsToFetch equals 1.

Return Value

Returns an HRESULT value. Possible values include the following:

S_FALSE | Retrieved fewer items than requested.
S_OK | Retrieved the requested number of items.
E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

If the method succeeds, the arrays given by the pCLSID and Names parameters are filled with CLSIDs and wide-character strings. The value of *pcItemsFetched specifies the number of items returned in these arrays.

The method returns S_OK if it retrieves the requested number of items (in other words, if *pcItemsFetched equals cItemsToFetch). Otherwise, it returns S_FALSE or an error code.

The caller must free the memory allocated for each string returned in the Names parameter, using the CoTaskMemFree function.

IEnumDMO::Skip

IEnumDMO Interface

Skips over a specified number of items in the enumeration sequence.

Syntax

HRESULT Skip(
    DWORD cItemsToSkip
);

Parameters

cItemsToSkip
Number of items to skip.

Return Value

Returns S_OK if the number items skipped equals cItemsToSkip. Otherwise, returns S_FALSE.

IEnumDMO::Reset

IEnumDMO Interface

Resets the enumeration sequence to the beginning.

Syntax

HRESULT Reset(void);

Return Value

Returns S_OK.

IEnumDMO::Clone

IEnumDMO Interface

This method is not implemented.

Syntax

HRESULT Clone(
    IEnumDMO **ppEnum
);

Return Value

Returns E_NOTIMPL.


IMediaBuffer Interface

This interface provides methods for manipulating a data buffer. Any buffer passed to a Microsoft® DirectX® Media Object (DMO) must implement this interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaBuffer methods | Description
SetLength | Specifies the length of the data currently in the buffer.
GetMaxLength | Retrieves the maximum number of bytes this buffer can hold.
GetBufferAndLength | Retrieves the buffer and the size of the valid data in the buffer.

IMediaBuffer::SetLength

IMediaBuffer Interface

Specifies the length of the data currently in the buffer.

Syntax

HRESULT SetLength(
   DWORD cbLength
);

Parameters

cbLength
Size of the data, in bytes. The value must not exceed the buffer's maximum size. Call the GetMaxLength method to obtain the maximum size.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

This method sets the size of the valid data currently in the buffer, not the buffer's allocated size.

IMediaBuffer::GetMaxLength

IMediaBuffer Interface

Retrieves the maximum number of bytes this buffer can hold.

Syntax

HRESULT GetMaxLength(
    DWORD *pcbMaxLength
);

Parameters

pcbMaxLength
[out] Pointer to a variable that receives the buffer's maximum size, in bytes.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

IMediaBuffer::GetBufferAndLength

IMediaBuffer Interface

Retrieves the buffer and the size of the valid data in the buffer.

Syntax

HRESULT GetBufferAndLength(
    BYTE **ppBuffer,
    DWORD *pcbLength
);

Parameters

ppBuffer
[out] Address of a pointer that receives the buffer array. Can be NULL if pcbLength is not NULL.
pcbLength
[out] Pointer to a variable that receives the size of the valid data, in bytes. Can be NULL if ppBuffer is not NULL.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success
E_POINTER | NULL pointer argument

Remarks

Either parameter can be NULL, in which case it does not receive a value. At least one parameter must be non-NULL. If both parameters are NULL, the method returns E_POINTER.

The value returned in the pcbLength parameter is the size of the valid data in the buffer, not the buffer's allocated size. To obtain the buffer's allocated size, call the GetMaxLength method.


IMediaObject Interface

This interface provides methods for manipulating a Microsoft® DirectX® Media Object (DMO).

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaObject methods | Description
GetStreamCount | Retrieves the number of input and output streams.
GetInputStreamInfo | Retrieves information about a specified input stream.
GetOutputStreamInfo | Retrieves information about a specified output stream.
GetInputType | Retrieves a preferred media type for a specified input stream.
GetOutputType | Retrieves a preferred media type for a specified output stream.
SetInputType | Sets the media type on an input stream, or tests whether a particular media type is acceptable.
SetOutputType | Sets the media type on an output stream, or tests whether a particular media type is acceptable.
GetInputCurrentType | Retrieves the media type that was previously set for an input stream, if any.
GetOutputCurrentType | Retrieves the media type that was previously set for an output stream, if any.
GetInputSizeInfo | Retrieves the buffer requirements for a specified input stream.
GetOutputSizeInfo | Retrieves the buffer requirements for a specified output stream.
GetInputMaxLatency | Retrieves the maximum latency on a specified input stream.
SetInputMaxLatency | Sets the maximum latency on a specified input stream.
Flush | Flushes all internally buffered data.
Discontinuity | Signals a discontinuity on the specified input stream.
AllocateStreamingResources | Allocates any resources needed by the DMO.
FreeStreamingResources | Frees resources allocated by the DMO.
GetInputStatus | Queries whether a specified input stream can accept more input data.
ProcessInput | Delivers a buffer to the specified input stream.
ProcessOutput | Generates output from the current input data.
Lock | Acquires or releases a lock on the DMO.

IMediaObject::GetStreamCount

IMediaObject Interface

Retrieves the number of input and output streams.

Syntax

HRESULT GetStreamCount(
    DWORD *pcInputStreams,
    DWORD *pcOutputStreams
);

Parameters

pcInputStreams
[out] Pointer to a variable that receives the number of input streams. Cannot be NULL.
pcOutputStreams
[out] Pointer to a variable that receives the number of output streams. Cannot be NULL.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_POINTER | NULL pointer argument

Remarks

The DMO might have zero input streams or zero output streams. The number of streams does not change; a DMO cannot dynamically add or remove streams.

IMediaObject::GetInputStreamInfo

IMediaObject Interface

Retrieves information about an input stream, such as any restrictions on the number of samples per buffer, and whether the stream performs lookahead on the input data. This information never changes.

Syntax

HRESULT GetInputStreamInfo(
    DWORD dwInputStreamIndex,
    DWORD *pdwFlags
);

Parameters

dwInputStreamIndex
Zero-based index of an input stream on the DMO.
pdwFlags
[out] Pointer to a variable that receives a bitwise combination of zero or more DMO_INPUT_STREAM_INFO_FLAGS flags.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_POINTER | NULL pointer argument

Remarks

The DMO_INPUT_STREAMF_HOLDS_BUFFERS flag indicates that the DMO performs lookahead on the incoming data.

The application must be sure to allocate sufficient buffers for the DMO to process the input. Call the GetInputSizeInfo method to determine the buffer requirements.

IMediaObject::GetOutputStreamInfo

IMediaObject Interface

Retrieves information about an output stream; for example, whether the stream is discardable, and whether it uses a fixed sample size. This information never changes.

Syntax

HRESULT GetOutputStreamInfo(
    DWORD dwOutputStreamIndex,
    DWORD *pdwFlags
);

Parameters

dwOutputStreamIndex
Zero-based index of an output stream on the DMO.
pdwFlags
[out] Pointer to a variable that receives a bitwise combination of zero or more DMO_OUTPUT_STREAM_INFO_FLAGS flags.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_POINTER | NULL pointer argument

IMediaObject::GetInputType

IMediaObject Interface

Retrieves a preferred media type for a specified input stream.

Syntax

HRESULT GetInputType(
    DWORD dwInputStreamIndex,
    DWORD dwTypeIndex,
    DMO_MEDIA_TYPE *pmt
);

Parameters

dwInputStreamIndex
Zero-based index of an input stream on the DMO.
dwTypeIndex
Zero-based index on the set of acceptable media types.
pmt
[out] Pointer to a DMO_MEDIA_TYPE structure allocated by the caller. The method fills the structure with the media type. The format block might be NULL, in which case the format type GUID is GUID_NULL.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Success.
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_NO_MORE_ITEMS | Type index is out of range.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

Call this method to enumerate an input stream's preferred media types. The DMO assigns each media type an index value in order of preference. The most preferred type has an index of zero. To enumerate all the types, make successive calls while incrementing the type index until the method returns DMO_E_NO_MORE_ITEMS.

If the method succeeds, call MoFreeMediaType to free the format block.

To set the media type, call the SetInputType method. Setting the media type on one stream can change another stream's preferred types. In fact, a stream might not have a preferred type until the type is set on another stream. For example, a decoder might not have a preferred output type until the input type is set. However, the DMO is not required to update its preferred types dynamically in this fashion. Thus, the types returned by this method are not guaranteed to be valid; they might fail when used in the SetInputType method. Conversely, the DMO is not guaranteed to enumerate every media type that it supports. To test whether a particular media type is acceptable, call SetInputType with the DMO_SET_TYPEF_TEST_ONLY flag.

IMediaObject::GetOutputType

IMediaObject Interface

Retrieves a preferred media type for a specified output stream.

Syntax

HRESULT GetOutputType(
    DWORD dwOutputStreamIndex,
    DWORD dwTypeIndex,
    DMO_MEDIA_TYPE *pmt
);

Parameters

dwOutputStreamIndex
Zero-based index of an output stream on the DMO.
dwTypeIndex
Zero-based index on the set of acceptable media types.
pmt
[out] Pointer to a DMO_MEDIA_TYPE structure allocated by the caller. The method fills the structure with the media type. The format block might be NULL, in which case the format type GUID is GUID_NULL.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Success.
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_NO_MORE_ITEMS | Type index is out of range.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

Call this method to enumerate an output stream's preferred media types. The DMO assigns each media type an index value, in order of preference. The most preferred type has an index of zero. To enumerate all the types, make successive calls while incrementing the type index, until the method returns DMO_E_NO_MORE_ITEMS.

If the method succeeds, call MoFreeMediaType to free the format block.

To set the media type, call the SetOutputType method. Setting the media type on one stream can change another stream's preferred types. In fact, a stream might not have a preferred type until the type is set on another stream. For example, a decoder might not have a preferred output type until the input type is set. However, the DMO is not required to update its preferred types dynamically in this fashion. Thus, the types returned by this method are not guaranteed to be valid; they might fail when used in the SetOutputType method. Conversely, the DMO is not guaranteed to enumerate every media type that it supports. To test whether a particular media type is acceptable, call SetOutputType with the DMO_SET_TYPEF_TEST_ONLY flag.

IMediaObject::SetInputType

IMediaObject Interface

Sets the media type on an input stream, or tests whether a media type is acceptable.

Syntax

HRESULT SetInputType(
    DWORD dwInputStreamIndex,
    const DMO_MEDIA_TYPE *pmt,
    DWORD dwFlags
);

Parameters

dwInputStreamIndex
Zero-based index of an input stream on the DMO.
pmt
[in] Pointer to a DMO_MEDIA_TYPE structure that specifies the media type.
dwFlags
Bitwise combination of zero or more flags from the DMO_SET_TYPE_FLAGS enumeration.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Media type was set successfully, or is acceptable.
S_FALSE | Media type is not acceptable.
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_TYPE_NOT_ACCEPTED | Media type was not accepted.

Remarks

Call this method to test, set, or clear the media type on an input stream:

  • To test the media type without setting it, use the DMO_SET_TYPEF_TEST_ONLY flag. If the media type is not acceptable, the method returns S_FALSE.
  • To set the media type, set dwFlags to zero. If the media type is not acceptable, the method returns DMO_E_TYPE_NOT_ACCEPTED.
  • To clear the current media type (if any), use the DMO_SET_TYPEF_CLEAR flag and set pmt to NULL. When the method returns, the stream no longer has a media type. The DMO cannot process samples until the application sets a new media type.

The media types that are currently set on other streams can affect whether the media type is acceptable.

IMediaObject::SetOutputType

IMediaObject Interface

Sets the media type on an output stream, or tests whether a media type is acceptable.

Syntax

HRESULT SetOutputType(
    DWORD dwOutputStreamIndex,
    const DMO_MEDIA_TYPE *pmt,
    DWORD dwFlags
);

Parameters

dwOutputStreamIndex
Zero-based index of an output stream on the DMO.
pmt
[in] Pointer to a DMO_MEDIA_TYPE structure that specifies the media type.
dwFlags
Bitwise combination of zero or more flags from the DMO_SET_TYPE_FLAGS enumeration.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Media type was set successfully, or is acceptable.
S_FALSE | Media type is not acceptable.
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_TYPE_NOT_ACCEPTED | Media type was not accepted.

Remarks

Call this method to test, set, or clear the media type on an output stream:

  • To test the media type without setting it, use the DMO_SET_TYPEF_TEST_ONLY flag. If the media type is not acceptable, the method returns S_FALSE.
  • To set the media type, set dwFlags to zero. If the media type is not acceptable, the method returns DMO_E_TYPE_NOT_ACCEPTED.
  • To clear the current media type (if any), use the DMO_SET_TYPEF_CLEAR flag and set pmt to NULL. When the method returns, the stream no longer has a media type. The DMO cannot process samples until the application sets a new media type, unless the stream is optional.

The media types that are currently set on other streams can affect whether the media type is acceptable.

IMediaObject::GetInputCurrentType

IMediaObject Interface

Retrieves the media type that was set for an input stream, if any.

Syntax

HRESULT GetInputCurrentType(
    DWORD dwInputStreamIndex,
    DMO_MEDIA_TYPE *pmt
);

Parameters

dwInputStreamIndex
Zero-based index of an input stream on the DMO.
pmt
[out] Pointer to a DMO_MEDIA_TYPE structure allocated by the caller. The method fills the structure with the media type.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Success.
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_TYPE_NOT_SET | Media type was not set.
E_OUTOFMEMORY | Insufficient memory.

Remarks

The caller must set the media type for the stream before calling this method. To set the media type, call the SetInputType method.

If the method succeeds, call MoFreeMediaType to free the format block.

IMediaObject::GetOutputCurrentType

IMediaObject Interface

Retrieves the media type that was set for an output stream, if any.

Syntax

HRESULT GetOutputCurrentType(
    DWORD dwOutputStreamIndex,
    DMO_MEDIA_TYPE *pmt
);

Parameters

dwOutputStreamIndex
Zero-based index of an output stream on the DMO.
pmt
[out] Pointer to a DMO_MEDIA_TYPE structure allocated by the caller. The method fills the structure with the media type.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Success.
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_TYPE_NOT_SET | Media type was not set.
E_OUTOFMEMORY | Insufficient memory.

Remarks

The caller must set the media type for the stream before calling this method. To set the media type, call the SetOutputType method.

If the method succeeds, call MoFreeMediaType to free the format block.

IMediaObject::GetInputSizeInfo

IMediaObject Interface

Retrieves the buffer requirements for a specified input stream.

Syntax

HRESULT GetInputSizeInfo(
    DWORD dwInputStreamIndex,
    DWORD *pcbSize,
    DWORD *pcbMaxLookahead,
    DWORD *pcbAlignment
);

Parameters

dwInputStreamIndex
Zero-based index of an input stream on the DMO.
pcbSize
[out] Pointer to a variable that receives the minimum size of an input buffer for this stream, in bytes.
pcbMaxLookahead
[out] Pointer to a variable that receives the maximum amount of data that the DMO will hold for lookahead, in bytes. If the DMO does not perform lookahead on the stream, the value is zero.
pcbAlignment
[out] Pointer to a variable that receives the required buffer alignment, in bytes. If the input stream has no alignment requirement, the value is 1.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Success.
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_TYPE_NOT_SET | Media type was not set.

Remarks

The buffer requirements may depend on the media types of the various streams. Before calling this method, set the media type of each stream by calling the SetInputType and SetOutputType methods. If the media types have not been set, this method might return an error.

If the DMO performs lookahead on the input stream, it returns the DMO_INPUT_STREAMF_HOLDS_BUFFERS flag in the GetInputStreamInfo method. During processing, the DMO holds up to the number of bytes indicated by the pcbMaxLookahead parameter. The application must allocate enough buffers for the DMO to hold this much data.

A buffer is aligned if the buffer's start address is a multiple of *pcbAlignment. The alignment must be a power of two. Depending on the microprocessor, reads and writes to an aligned buffer might be faster than to an unaligned buffer. Also, some microprocessors do not support unaligned reads and writes.

IMediaObject::GetOutputSizeInfo

IMediaObject Interface

Retrieves the buffer requirements for a specified output stream.

Syntax

HRESULT GetOutputSizeInfo(
    DWORD dwOutputStreamIndex,
    DWORD *pcbSize,
    DWORD *pcbAlignment
);

Parameters

dwOutputStreamIndex
Zero-based index of an output stream on the DMO.
pcbSize
[out] Pointer to a variable that receives the minimum size of an output buffer for this stream, in bytes.
pcbAlignment
[out] Pointer to a variable that receives the required buffer alignment, in bytes. If the output stream has no alignment requirement, the value is 1.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Success.
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_TYPE_NOT_SET | Media type was not set.

Remarks

The buffer requirements may depend on the media types set for each of the streams.

Before calling this method, set the media type of each stream by calling the SetInputType and SetOutputType methods. If the media types have not been set, this method might return an error. However, if a stream is optional, and the application will not use the stream, you do not have to set the media type for the stream.

A buffer is aligned if the buffer's start address is a multiple of *pcbAlignment. Depending on the architecture of the microprocessor, it is faster to read and write to an aligned buffer than to an unaligned buffer. On some microprocessors, reading and writing to an unaligned buffer is not supported and can cause the program to crash. Zero is not a valid alignment.

IMediaObject::GetInputMaxLatency

IMediaObject Interface

Retrieves the maximum latency on a specified input stream.

Syntax

HRESULT GetInputMaxLatency(
    DWORD dwInputStreamIndex,
    REFERENCE_TIME *prtMaxLatency
);

Parameters

dwInputStreamIndex
Zero-based index of an input stream on the DMO.
prtMaxLatency
[out] Pointer to a variable that receives the maximum latency.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Success.
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
E_FAIL | Failure.
E_NOTIMPL | Not implemented. Assume zero latency.

The latency is the difference between a time stamp on the input stream and the corresponding time stamp on the output stream. The maximum latency is the largest possible difference in the time stamps. For a DMO, determine the maximum latency as follows:

  • Process input buffers until the DMO can produce output.
  • Process as many output buffers as possible.
  • The maximum latency is the largest delta between input time stamps and output time stamps (taken as an absolute value).

Under this definition, latency does not include the time that it takes to process samples. Nor does it include any latency introduced by the size of the input buffer.

For the special case where a DMO processes exactly one sample at a time, the maximum latency is simply the difference in time stamps.

Latency is defined only when samples have time stamps, and the time stamps increase or decrease monotonically. Maximum latency might depend on the media types for the input and output streams.

IMediaObject::SetInputMaxLatency

IMediaObject Interface

Sets the maximum latency on a specified input stream. For the definition of maximum latency, see GetInputMaxLatency.

Syntax

HRESULT SetInputMaxLatency(
    DWORD dwInputStreamIndex,
    REFERENCE_TIME rtMaxLatency
);

Parameters

dwInputStreamIndex
Zero-based index of an input stream on the DMO.
rtMaxLatency
Maximum latency.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Success
DMO_E_INVALIDSTREAMINDEX | Invalid stream index
E_FAIL | Failure
E_NOTIMPL | Not implemented

IMediaObject::Flush

IMediaObject Interface

Flushes all internally buffered data.

Syntax

HRESULT Flush(void);

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

The DMO performs the following actions when this method is called:

  • Releases any IMediaBuffer references it holds.
  • Discards any values that specify the time stamp or sample length for a media buffer.
  • Reinitializes any internal states that depend on the contents of a media sample.

Media types, maximum latency, and locked state do not change.

When the method returns, every input stream accepts data. Output streams cannot produce any data until the application calls the ProcessInput method on at least one input stream.

IMediaObject::Discontinuity

IMediaObject Interface

Signals a discontinuity on the specified input stream.

Syntax

HRESULT Discontinuity(
    DWORD dwInputStreamIndex
);

Parameters

dwInputStreamIndex
Zero-based index of an input stream on the DMO.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Success
DMO_E_INVALIDSTREAMINDEX | Invalid stream index

Remarks

A discontinuity represents a break in the input. A discontinuity might occur because no more data is expected, the format is changing, or there is a gap in the data. After a discontinuity, the DMO does not accept further input on that stream until all pending data has been processed. The application should call the ProcessOutput method until none of the streams returns the DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE flag.

IMediaObject::AllocateStreamingResources

IMediaObject Interface

Allocates any resources needed by the DMO. Calling this method is always optional.

Syntax

HRESULT AllocateStreamingResources(void);

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

An application can call this method as a streaming optimization. It gives the DMO an opportunity to perform any time-consuming initializations before streaming begins. If you call this method, do so after you set the media types on the DMO, but before you make the first calls to ProcessInput or ProcessOutput.

This method is optional in the following sense:

  • If the DMO does not support this method, the method returns S_OK.
  • If the application never calls this method, the DMO allocates resources within a call to ProcessInput or ProcessOutput.

If the DMO supports this method, it should also support the FreeStreamingResources method.

IMediaObject::FreeStreamingResources

IMediaObject Interface

Frees resources allocated by the DMO. Calling this method is always optional.

Syntax

HRESULT FreeStreamingResources(void);

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

This method releases any resources that the AllocateStreamingResources method initializes.

If the DMO does not support this method, the method returns S_OK. If you call this method during streaming, the method fails and the DMO does not release any resources.

Regardless of whether the method fails or succeeds, the application can continue to call other methods on the DMO. The DMO might need to re-initialize resources that were previously freed.

IMediaObject::GetInputStatus

IMediaObject Interface

Queries whether an input stream can accept more input data.

Syntax

HRESULT GetInputStatus(
    DWORD dwInputStreamIndex,
    DWORD *dwFlags
);

Parameters

dwInputStreamIndex
Zero-based index of an input stream on the DMO.
dwFlags
[out] Pointer to a variable that receives either zero or DMO_INPUT_STATUSF_ACCEPT_DATA.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Success
DMO_E_INVALIDSTREAMINDEX | Invalid stream index

Remarks

If the input stream will accept more data, the method returns the DMO_INPUT_STATUSF_ACCEPT_DATA flag in the dwFlags parameter. Otherwise, it sets this parameter to zero. If the stream will accept more data, the application can call the ProcessInput method.

The status of an input stream can change only as the result of one of the following method calls:

  • Discontinuity
  • Flush
  • ProcessInput
  • ProcessOutput

IMediaObject::ProcessInput

IMediaObject Interface

Delivers a buffer to the specified input stream.

Syntax

HRESULT ProcessInput(
    DWORD dwInputStreamIndex,
    IMediaBuffer *pBuffer,
    DWORD dwFlags,
    REFERENCE_TIME rtTimestamp,
    REFERENCE_TIME rtTimelength
);

Parameters

dwInputStreamIndex
Zero-based index of an input stream on the DMO.
pBuffer
Pointer to the buffer's IMediaBuffer interface.
dwFlags
Bitwise combination of zero or more flags from the DMO_INPUT_DATA_BUFFER_FLAGS enumeration.
rtTimestamp
Time stamp that specifies the start time of the data in the buffer. If the buffer has a valid time stamp, set the DMO_INPUT_DATA_BUFFERF_TIME flag in the dwFlags parameter. Otherwise, the DMO ignores this value.
rtTimelength
Reference time specifying the duration of the data in the buffer. If this value is valid, set the DMO_INPUT_DATA_BUFFERF_TIMELENGTH flag in the dwFlags parameter. Otherwise, the DMO ignores this value.

Return Value

Returns an HRESULT value. The following are possible return values.

S_FALSE | No output to process.
S_OK | Success.
DMO_E_INVALIDSTREAMINDEX | Invalid stream index.
DMO_E_NOTACCEPTING | Data cannot be accepted.

Remarks

If the DMO does not process all the data in the buffer, it keeps a reference count on the buffer. It releases the buffer once it has generated all the output, unless it needs to perform lookahead on the data. (To determine whether a DMO performs lookahead, call the GetInputStreamInfo method.)

If this method returns DMO_E_NOTACCEPTING, call the ProcessOutput method until the input stream can accept more data. To determine whether the stream can accept more data, call the GetInputStatus method.

If the method returns S_FALSE, no output was generated from this input and the application does not need to call ProcessOutput. However, a DMO is not required to return S_FALSE in this situation; it might return S_OK.

IMediaObject::ProcessOutput

IMediaObject Interface

Generates output from the current input data.

Syntax

HRESULT ProcessOutput(
    DWORD dwFlags,
    DWORD cOutputBufferCount,
    DMO_OUTPUT_DATA_BUFFER *pOutputBuffers,
    DWORD *pdwStatus
);

Parameters

dwFlags
Bitwise combination of zero or more flags from the DMO_PROCESS_OUTPUT_FLAGS enumeration.
cOutputBufferCount
Number of output buffers.
pOutputBuffers
[in, out] Pointer to an array of DMO_OUTPUT_DATA_BUFFER structures containing the output buffers. Specify the size of the array in the cOutputBufferCount parameter.
pdwStatus
[out] Pointer to a variable that receives a reserved value (zero). The application should ignore this value.

Return Value

Returns an HRESULT value. The following are possible return values.

S_FALSE | No output was generated.
S_OK | Success.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument.
E_POINTER | NULL pointer argument.

Remarks

The pOutputBuffers parameter points to an array of DMO_OUTPUT_DATA_BUFFER structures. The application must allocate one structure for each output stream. To determine the number of output streams, call the GetStreamCount method. Set the cOutputBufferCount parameter to this number.

Each DMO_OUTPUT_DATA_BUFFER structure contains a pointer to a buffer's IMediaBuffer interface. The application allocates these buffers. The other members of the structure are status fields. The DMO sets these fields if the method succeeds. If the method fails, their values are undefined.

When the application calls ProcessOutput, the DMO processes as much input data as possible. It writes the output data to the output buffers, starting from the end of the data in each buffer. (To find the end of the data, call the IMediaBuffer::GetBufferAndLength method.) The DMO never holds a reference count on an output buffer.

If the DMO fills an entire output buffer and still has input data to process, the DMO returns the DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE flag in the DMO_OUTPUT_DATA_BUFFER structure. The application should check for this flag by testing the dwStatus member of each structure.

If the method returns S_FALSE, no output was generated. However, a DMO is not required to return S_FALSE in this situation; it might return S_OK.

Discarding data:

You can discard data from a stream by setting the DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER flag in the dwFlags parameter. For each stream that you want to discard, set the pBuffer member of the DMO_OUTPUT_DATA_BUFFER structure to NULL.

For each stream in which pBuffer is NULL:

  • If the DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER flag is set, and the stream is discardable or optional, the DMO discards the data.
  • If the flag is set but the stream is neither discardable nor optional, the DMO discards the data if possible. It is not guaranteed to discard the data.
  • If the flag is not set, the DMO does not produce output data for that stream, but does not discard the data.

To check whether a stream is discardable or optional, call the GetOutputStreamInfo method.

IMediaObject::Lock

IMediaObject Interface

Acquires or releases a lock on the DMO. Call this method to keep the DMO serialized when performing multiple operations.

Syntax

HRESULT Lock(
    LONG bLock
);

Parameters

bLock
Value that specifies whether to acquire or release the lock. If the value is non-zero, a lock is acquired. If the value is zero, the lock is released.

Return Value

Returns an HRESULT value. The following are possible return values.

S_OK | Success
E_FAIL | Failure

Remarks

This method prevents other threads from calling methods on the DMO. If another thread calls a method on the DMO, the thread blocks until the lock is released.


IMediaObjectInPlace Interface

This interface provides methods for processing data in place. A Microsoft® DirectX® Media Object (DMO) can expose this interface if it meets the following conditions:

  • It has one input stream and one output stream.
  • Both streams use the same media type.
  • The output is produced in place on the buffer; that is, without copying data.

This interface provides an optimized way to process data. The application calls a single Process method instead of the IMediaObject::ProcessInput and IMediaObject::ProcessOutput methods. However, any DMO that implements this interface must also implement the IMediaObject interface. Therefore, an application is never obligated to use this interface, and a DMO is never guaranteed to implement it.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaObjectInPlace methods | Description
Process | Processes a block of data.
Clone | Creates a copy of the DMO in its current state.
GetLatency | Retrieves the latency introduced by this DMO.

IMediaObjectInPlace::Process

IMediaObjectInPlace Interface

Processes a block of data. The application supplies a pointer to a block of input data. The DMO processes the data in place.

Syntax

HRESULT Process(
    ULONG ulSize,
    BYTE *pData
    REFERENCE_TIME refTimeStart,
    DWORD dwFlags
);

Parameters

ulSize
[in] Size of the data, in bytes.
pData
[in, out] Pointer to a buffer of size ulSize. On input, the buffer holds the input data. If the method returns successfully, the buffer contains the output data.
refTimeStart
[in] Start time of the data.
dwFlags
[in] Either DMO_INPLACE_NORMAL or DMO_INPLACE_ZERO. See Remarks for more information.

Return Value

Returns an HRESULT value. Possible values include those listed in the following table.

S_FALSE | Success. There is still data to process.
S_TRUE | Success. There is no remaining data to process.
E_FAIL | Failure.

Remarks

If the method fails, the buffer might contain garbage. The application should not use the contents of the buffer.

The DMO might produce output data beyond the length of the input data. This is called an effect tail. For example, a reverb effect continues after the input reaches silence. If the DMO has an effect tail, this method returns S_FALSE.

While the application has input data for processing, call the Process method with the dwFlags parameter set to DMO_INPLACE_NORMAL. If the last such call returns S_FALSE, call Process again, this time with a zeroed input buffer and the DMO_INPLACE_ZERO flag. The DMO will now fill the zeroed buffer with the effect tail. Continue calling Process in this way until the return value is S_TRUE, indicating that the DMO has finished processing the effect tail.

If the DMO has no effect tail, this method always returns S_TRUE (or an error code).

IMediaObjectInPlace::Clone

IMediaObjectInPlace Interface

Creates a copy of the DMO in its current state.

Syntax

HRESULT Clone(
    IMediaObjectInPlace **ppMediaObject
);

Parameters

ppMediaObject
[out] Address of a pointer to receive the new DMO's IMediaObjectInPlace interface.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

If the method succeeds, the IMediaObjectInPlace interface that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IMediaObjectInPlace::GetLatency

IMediaObjectInPlace Interface

Retrieves the latency introduced by this DMO.

Syntax

HRESULT GetLatency(
    REFERENCE_TIME *pLatencyTime
);

Parameters

pLatencyTime
[out] Pointer to a variable that receives the latency, in 100-nanosecond units.

Return Value

Returns S_OK if successful. Otherwise, returns an HRESULT value indicating the cause of the error.

Remarks

This method returns the average time required to process each buffer. This value usually depends on factors in the run-time environment, such as the processor speed and the CPU load. One possible way to implement this method is for the DMO to keep a running average based on historical data.


Structures

This section describes the Microsoft® DirectX® Media Object (DMO) structures.

Structure | Description
DMO_MEDIA_TYPE | Describes the format of the data used by a stream in a DMO.
DMO_OUTPUT_DATA_BUFFER | Describes an output buffer used by a DMO.
DMO_PARTIAL_MEDIATYPE | Partially describes a media type used by a DMO.


DMO_MEDIA_TYPE Structure

Structures

Describes the format of the data used by a stream in a Microsoft® DirectX® Media Object (DMO).

Note This structure is identical to the Microsoft® DirectShow® AM_MEDIA_TYPE structure.

Syntax

typedef struct _DMOMediaType {
    GUID     majortype;
    GUID     subtype;
    BOOL     bFixedSizeSamples;
    BOOL     bTemporalCompression;
    ULONG    lSampleSize;
    GUID     formattype;
    IUnknown *pUnk;
    ULONG    cbFormat;
    [size_is(cbFormat)] BYTE * pbFormat;
} DMO_MEDIA_TYPE;

Members

majortype
Major type GUID of the stream.
subtype
Subtype GUID of the stream.
bFixedSizeSamples
If TRUE, samples are of a fixed size. This field is informational only. For audio, it is generally set to TRUE. For video, it is usually TRUE for uncompressed video and FALSE for compressed video.
bTemporalCompression
If TRUE, samples are compressed using temporal (interframe) compression. (A value of TRUE indicates that not all frames are key frames.) This field is informational only.
lSampleSize
Size of the sample in bytes. For compressed data, the value can be zero.
formattype
GUID specifying the format type. The pbFormat member points to the corresponding format structure. Format types include the following:
Format Type | Format Structure
FORMAT_None | No format type
FORMAT_MPEGVideo | MPEG1VIDEOINFO
FORMAT_MPEG2Video | MPEG2VIDEOINFO
FORMAT_VideoInfo | VIDEOINFOHEADER
FORMAT_VideoInfo2 | VIDEOINFOHEADER2
FORMAT_WaveFormatEx | WAVEFORMATEX
pUnk
Not used.
cbFormat
Size of the format block of the media type.
pbFormat
Pointer to the format structure. The structure type is specified by the formattype member. The format structure must be present, unless formattype is GUID_NULL or FORMAT_None.

Remarks

The bFixedSizeSamples, bTemporalCompression, and lSampleSize members are for compatibility with DirectShow. Other DMO clients are not required to use them.


DMO_OUTPUT_DATA_BUFFER Structure

Structures

Describes an output buffer used by a Microsoft® DirectX® Media Object (DMO).

Syntax

typedef struct _DMO_OUTPUT_DATA_BUFFER {
    IMediaBuffer *pBuffer;
    DWORD dwStatus;
    REFERENCE_TIME rtTimestamp;
    REFERENCE_TIME rtTimelength;
} DMO_OUTPUT_DATA_BUFFER, *PDMO_OUTPUT_DATA_BUFFER;

Members

pBuffer
[in] Pointer to the IMediaBuffer interface of a buffer allocated by the application.
dwStatus
[out] Status flags. After processing output, the DMO sets this member to a bitwise combination of zero or more DMO_OUTPUT_DATA_BUFFER_FLAGS flags.
rtTimestamp
[out] Time stamp that specifies the start time of the data in the buffer. If the buffer has a valid time stamp, the DMO sets this member and also sets the DMO_OUTPUT_DATA_BUFFERF_TIME flag in the dwStatus member. Otherwise, ignore this member.
rtTimelength
[out] Reference time specifying the length of the data in the buffer. If the DMO sets this member to a valid value, it also sets the DMO_OUTPUT_DATA_BUFFERF_TIMELENGTH flag in the dwStatus member. Otherwise, ignore this member.

See Also

IMediaObject::ProcessOutput


DMO_PARTIAL_MEDIATYPE Structure

Structures

Partially describes a media type used by a Microsoft® DirectX® Media Object (DMO). The DMO registration functions use this structure to specify supported media types.

Syntax

typedef struct _DMO_PARTIAL_MEDIATYPE {
    GUID type;
    GUID subtype;
} DMO_PARTIAL_MEDIATYPE, *PDMO_PARTIAL_MEDIATYPE;

Members

type
Major type GUID. Use GUID_NULL to match any major type.
subtype
Subtype GUID. Use GUID_NULL to match any subtype.


Enumerated Types

This section describes the Microsoft® DirectX® Media Object (DMO) enumerated types.

Enumerated Type | Description
DMO_ENUM_FLAGS | Defines flags that specify search criteria when enumerating DMOs.
DMO_INPUT_DATA_BUFFER_FLAGS | Defines flags that describe an input buffer.
DMO_INPUT_STREAM_INFO_FLAGS | Defines flags that describe an input stream.
DMO_OUTPUT_DATA_BUFFER_FLAGS | Defines flags that describe an output buffer.
DMO_OUTPUT_STREAM_INFO_FLAGS | Defines flags that describe an output stream.
DMO_PROCESS_OUTPUT_FLAGS | Defines flags that specify output processing requests.
DMO_REGISTER_FLAGS | Defines flags that specify registry information for a DMO.
DMO_SET_TYPE_FLAGS | Defines flags for setting the media type on a stream.
DMO_VIDEO_OUTPUT_STREAM_FLAGS | Defines flags that describe requested features for video optimizations.


DMO_ENUM_FLAGS Enumeration

Enumerated Types

Defines flags that specify search criteria when enumerating Microsoft® DirectX® Media Objects (DMOs).

Syntax

enum DMO_ENUM_FLAGS {
    DMO_ENUMF_INCLUDE_KEYED = 0x00000001
};

Elements

DMO_ENUMF_INCLUDE_KEYED
The enumeratioun should include DMOs whose use is restricted by a software key. If this flag is absent, keyed DMOs are omitted from the enumeration.

Remarks

A software key enables the developer of a DMO to control who uses the DMO. If a DMO has a software key, applications must unlock the DMO to use it. The method for unlocking the DMO depends on the implementation. Consult the documentation for the particular DMO.

See Also

DMOEnum


DMO_INPUT_DATA_BUFFER_FLAGS Enumeration

Enumerated Types

Defines flags that describe an input buffer.

Syntax

enum _DMO_INPUT_DATA_BUFFER_FLAGS {
    DMO_INPUT_DATA_BUFFERF_SYNCPOINT       = 0x00000001,
    DMO_INPUT_DATA_BUFFERF_TIME            = 0x00000002,
    DMO_INPUT_DATA_BUFFERF_TIMELENGTH      = 0x00000004
};

Elements

DMO_INPUT_DATA_BUFFERF_SYNCPOINT
The beginning of the data is a synchronization point.
DMO_INPUT_DATA_BUFFERF_TIME
The buffer's time stamp is valid.
DMO_INPUT_DATA_BUFFERF_TIMELENGTH
The buffer's indicated time length is valid.

See Also

IMediaObject::ProcessInput


DMO_INPUT_STREAM_INFO_FLAGS Enumeration

Enumerated Types

Defines flags that describe an input stream.

Syntax

enum _DMO_INPUT_STREAM_INFO_FLAGS {
    DMO_INPUT_STREAMF_WHOLE_SAMPLES            = 0x00000001,
    DMO_INPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER = 0x00000002,
    DMO_INPUT_STREAMF_FIXED_SAMPLE_SIZE        = 0x00000004,
    DMO_INPUT_STREAMF_HOLDS_BUFFERS            = 0x00000008
};

Elements

DMO_INPUT_STREAMF_WHOLE_SAMPLES
The stream requires whole samples. Samples must not span multiple buffers, and buffers must not contain partial samples.
DMO_INPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER
Each buffer must contain exactly one sample.
DMO_INPUT_STREAMF_FIXED_SAMPLE_SIZE
All the samples in this stream must be the same size.
DMO_INPUT_STREAMF_HOLDS_BUFFERS
The DMO performs lookahead on the incoming data, and may hold multiple input buffers for this stream.

See Also

IMediaObject::GetInputStreamInfo


DMO_OUTPUT_DATA_BUFFER_FLAGS Enumeration

Enumerated Types

Defines flags that describe an output buffer.

Syntax

enum _DMO_OUTPUT_DATA_BUFFER_FLAGS {
    DMO_OUTPUT_DATA_BUFFERF_SYNCPOINT       = 0x00000001,
    DMO_OUTPUT_DATA_BUFFERF_TIME            = 0x00000002,
    DMO_OUTPUT_DATA_BUFFERF_TIMELENGTH      = 0x00000004,
    DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE      = 0x01000000
};

Elements

DMO_OUTPUT_DATA_BUFFERF_SYNCPOINT
The beginning of the data is a synchronization point.
DMO_OUTPUT_DATA_BUFFERF_TIME
The buffer's time stamp is valid.
DMO_OUTPUT_DATA_BUFFERF_TIMELENGTH
The buffer's indicated time length is valid.
DMO_OUTPUT_DATA_BUFFERF_INCOMPLETE
There is still input data available for processing, but the output buffer is full.

See Also

IMediaObject::ProcessOutput


DMO_OUTPUT_STREAM_INFO_FLAGS Enumeration

Enumerated Types

Defines flags that describe an output stream.

Syntax

enum _DMO_OUTPUT_STREAM_INFO_FLAGS {
    DMO_OUTPUT_STREAMF_WHOLE_SAMPLES            = 0x00000001,
    DMO_OUTPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER = 0x00000002,
    DMO_OUTPUT_STREAMF_FIXED_SAMPLE_SIZE        = 0x00000004,
    DMO_OUTPUT_STREAMF_DISCARDABLE              = 0x00000008,
    DMO_OUTPUT_STREAMF_OPTIONAL                 = 0x00000010
};

Elements

DMO_OUTPUT_STREAMF_WHOLE_SAMPLES
The stream contains whole samples. Samples do not span multiple buffers, and buffers do not contain partial samples.
DMO_OUTPUT_STREAMF_SINGLE_SAMPLE_PER_BUFFER
Each buffer contains exactly one sample.
DMO_OUTPUT_STREAMF_FIXED_SAMPLE_SIZE
All the samples in this stream are the same size.
DMO_OUTPUT_STREAMF_DISCARDABLE
The stream is discardable. Within calls to IMediaObject::ProcessOutput, the DMO can discard data for this stream without copying it to an output buffer.
DMO_OUTPUT_STREAMF_OPTIONAL
The stream is optional. An optional stream is discardable. Also, the application can ignore this stream entirely; it does not have to set the media type for the stream. Optional streams generally contain additional information, or data not needed by all applications.

Remarks

The DMO_OUTPUT_STREAMF_DISCARDABLE and DMO_OUTPUT_STREAMF_OPTIONAL flags are mutually exlusive. The DMO can set one of these flags (or neither), but not both.

See Also

IMediaObject::GetOutputStreamInfo


DMO_PROCESS_OUTPUT_FLAGS Enumeration

Enumerated Types

Defines flags that specify output processing requests.

Syntax

enum _DMO_PROCESS_OUTPUT_FLAGS {
    DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER = 0x00000001
};

Elements

DMO_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER
Discard the output when the pointer to the output buffer is NULL.

See Also

IMediaObject::ProcessOutput


DMO_REGISTER_FLAGS Enumeration

Enumerated Types

Defines flags that specify registry information for a Microsoft® DirectX® Media Object (DMO).

Syntax

enum DMO_REGISTER_FLAGS {
    DMO_REGISTERF_IS_KEYED = 0x00000001
};

Elements

DMO_REGISTERF_IS_KEYED
Use of the DMO is restricted by a software key.

Remarks

A software key enables the developer of a DMO to control who uses the DMO. If a DMO has a software key, applications must unlock the DMO to use it. The method for unlocking the DMO depends on the implementation. Consult the documentation for the particular DMO.

See Also

DMORegister


DMO_SET_TYPE_FLAGS Enumeration

Enumerated Types

Defines flags for setting the media type on a stream.

Syntax

enum _DMO_SET_TYPE_FLAGS {
    DMO_SET_TYPEF_TEST_ONLY = 0x00000001,
    DMO_SET_TYPEF_CLEAR     = 0x00000002
};

Elements

DMO_SET_TYPEF_TEST_ONLY
Test the media type but do not set it.
DMO_SET_TYPEF_CLEAR
Clear the media type that was set for the stream.

Remarks

The DMO_SET_TYPEF_TEST_ONLY and DMO_SET_TYPEF_CLEAR flags are mutually exclusive. Do not set both flags.

See Also

IMediaObject::SetInputType, IMediaObject::SetOutputType


DMO_VIDEO_OUTPUT_STREAM_FLAGS Enumeration

Enumerated Types

Defines flags that describe requested features, for video optimizations.

Syntax

enum _DMO_VIDEO_OUTPUT_STREAM_FLAGS {
    DMO_VOSF_NEEDS_PREVIOUS_SAMPLE = 0x00000001
};

Elements

DMO_VOSF_NEEDS_PREVIOUS_SAMPLE
Requests that every output buffer passed to the DMO contain the previous data that was generated.

See Also

IDMOVideoOutputOptimizations


Functions

This section describes the Microsoft® DirectX® Media Object (DMO) functions.

  • DMO Registration Functions
  • Media Type Helper Functions


DMO Registration Functions

The DMO registration functions enable an application to register and enumerate Microsoft® DirectX® Media Objects (DMOs). These functions are declared in the file Dmoreg.h.

DMORegister | Registers a DMO.
DMOUnregister | Unregisters a DMO.
DMOEnum | Enumerates registered DMOs.
DMOGetTypes | Retrieves the media types registered for a DMO.
DMOGetName | Retrieves the registered name of a DMO.

DMORegister

DMO Registration Functions

Registers a DMO.

Syntax

HRESULT DMORegister(
   LPCWSTR szName,
   REFCLSID clsidDMO,
   REFGUID guidCategory,
   DWORD dwFlags,
   DWORD cInTypes,
   const DMO_PARTIAL_MEDIATYPE *pInTypes,
   DWORD cOutTypes,
   const DMO_PARTIAL_MEDIATYPE *pOutTypes
);

Parameters

szName
NULL-terminated string that contains a descriptive name for the DMO. Names longer than 79 characters might be truncated.
clsidDMO
Class identifier (CLSID) of the DMO.
guidCategory
Category GUID that specifies the category of the DMO.
dwFlags
Bitwise combination of zero or more flags from the DMO_REGISTER_FLAGS enumeration.
cInTypes
Number of input media types to register. Can be zero.
pInTypes
Pointer to an array of DMO_PARTIAL_MEDIATYPE structures that specify the input media types. The size of the array is specified in the cInTypes parameter.
cOutTypes
Number of output media types to register.
pOutTypes
Pointer to an array of DMO_PARTIAL_MEDIATYPE structures that specify the output media types. The size of the array is specified in the cOutTypes parameter. Can be zero.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_FAIL | Failure
E_INVALIDARG | Invalid argument

Remarks

This function adds information about a DMO to the registry. Applications or software components can use this information to locate the DMOs they need to use, by calling the DMOEnum function. For example, to encode a video stream, you would search in the DMOCATEGORY_VIDEO_ENCODER category for a DMO whose media types matched your requirements.

The media types registered by this function are only for the purpose of finding the DMO. They do not necessarily match the types returned by the IMediaObject::GetInputType and IMediaObject::GetOutputType methods. For example, a decoder might register just its main input types. After the DMO is created and its input type has been set, its GetOutputType method will return all of the decompressed types it can generate.

DMOUnregister

DMO Registration Functions

Unregisters a DMO.

Syntax

HRESULT DMOUnregister(
   REFCLSID clsidDMO,
   REFGUID guidCategory
);

Parameters

clsidDMO
Class identifier (CLSID) of the DMO.
guidCategory
Category GUID that specifies the category from which to remove the DMO. Use GUID_NULL to unregister the DMO from every category.

Return Value

Returns an HRESULT value. Possible values include the following:

S_FALSE | This CLSID was not registered in the specified category.
S_OK | Success.
E_INVALIDARG | Invalid argument.

DMOEnum

DMO Registration Functions

Enumerates registered DMOs. The caller can search by category, media type, or both.

Syntax

HRESULT DMOEnum(
    REFGUID guidCategory,
    DWORD dwFlags,
    DWORD cInTypes,
    const DMO_PARTIAL_MEDIATYPE *pInTypes,
    DWORD cOutTypes,
    const DMO_PARTIAL_MEDIATYPE *pOutTypes,
    IEnumDMO **ppEnum
);

Parameters

guidCategory
Category GUID that specifies which category of DMO to search. Use GUID_NULL to search every category.
dwFlags
Bitwise combination of zero or more flags from the DMO_ENUM_FLAGS enumeration.
cInTypes
Number of input media types to use in the search criteria. Use zero to match any input type.
pInTypes
Pointer to an array of DMO_PARTIAL_MEDIATYPE structures that contain the input media types. Specify the size of the array in the cInTypes parameter.
cOutTypes
Number of output media types to use in the search criteria. Use zero to match any output type.
pOutTypes
Pointer to an array of DMO_PARTIAL_MEDIATYPE structures that contain the output media types. Specify the size of the array in the cOutTypes parameter.
ppEnum
Address of a variable to receive the IEnumDMO interface of the enumerator.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_FAIL | Failure
E_OUTOFMEMORY | Insufficient memory

Remarks

This method returns a pointer to an enumerator object that supports the IEnumDMO interface. The application uses the IEnumDMO interface to enumerate over the set of DMOs that match the search criteria.

DMOGetTypes

DMO Registration Functions

Retrieves the media types registered for a DMO.

Syntax

HRESULT DMOGetTypes(
    REFCLSID clsidDMO,
    unsigned long ulInputTypesRequested,
    unsigned long *pulInputTypesSupplied,
    DMO_PARTIAL_MEDIATYPE *pInputTypes,
    unsigned long ulOutputTypesRequested,
    unsigned long *pulOutputTypesSupplied,
    DMO_PARTIAL_MEDIATYPE *pOutputTypes
);

Parameters

clsidDMO
Class identifier (CLSID) of the DMO.
ulInputTypesRequested
Size of the array passed in the pInputTypes parameter.
pulInputTypesSupplied
Pointer to a variable that receives the number of DMO_PARTIAL_MEDIATYPE structures in pInputTypes that the function fills in.
pInputTypes
Pointer to a caller-allocated array of DMO_PARTIAL_MEDIATYPE structures. The size of the array is given in the ulInputTypesRequested parameter. The function fills the array with the input types registered for the DMO.
ulOutputTypesRequested
Size of the array passed in the pOutputTypes parameter.
pulOutputTypesSupplied
Pointer to a variable that receives the number of DMO_PARTIAL_MEDIATYPE structures in pOutputTypes that the function fills in.
pOutputTypes
Pointer to a caller-allocated array of DMO_PARTIAL_MEDIATYPE structures. The size of the array is given in the ulOutputTypesRequested parameter. The function fills the array with the DMO output types registered for the DMO.

Return Value

Returns an HRESULT value. Possible values include the following:

S_FALSE | Array too small
S_OK | Success
E_FAIL | Failure

Remarks

If one of the arrays is too small to hold all of the registered types, the function fills the array but returns S_FALSE.

If the DMO did not register any media types, the function returns S_OK and sets *pulInputTypesSupplied and *pulOutputTypesSupplied to zero.

DMOGetName

DMO Registration Functions

Retrieves the registered name of a DMO.

Syntax

HRESULT DMOGetName(
   REFCLSID clsidDMO,
   WCHAR szName[]
);

Parameters

clsidDMO
Class identifier (CLSID) of the DMO.
szName
Array of 80 Unicode characters that receives the name of the DMO. The caller must allocate the array. The name is a NULL-terminated string.

Return Value

Returns an HRESULT value. Possible values include the following:

S_FALSE | No name was registered for this DMO, or the name has zero length.
S_OK | Success.
E_FAIL | Failure.

Remarks

If the method returns S_FALSE, szName is set to '\0'.


Media Type Helper Functions

These functions manipulate the DMO_MEDIA_TYPE structure. They are declared in the file Dmort.h.

MoInitMediaType | Initializes a media type structure.
MoFreeMediaType | Frees the allocated members of a media type structure.
MoCopyMediaType | Copies the members of one media type structure into another media type structure.
MoCreateMediaType | Allocates a new media type structure.
MoDeleteMediaType | Deletes a media type structure that was previously allocated.
MoDuplicateMediaType | Duplicates a media type structure.

MoInitMediaType

DMO Registration Functions

Initializes a media type structure.

Syntax

HRESULT MoInitMediaType(
    DMO_MEDIA_TYPE *pmt,
    DWORD cbFormat
);

Parameters

pmt
Pointer to an uninitialized DMO_MEDIA_TYPE structure allocated by the caller.
cbFormat
Number of bytes to allocate for the format block. Can be zero.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

This function allocates the format block and sets the cbFormat and pbFormat members of the DMO_MEDIA_TYPE structure.

The caller must free the media type by calling the MoFreeMediaType function.

MoFreeMediaType

DMO Registration Functions

Frees the allocated members of a media type structure.

Syntax

HRESULT MoFreeMediaType(
    DMO_MEDIA_TYPE *pmt
);

Parameters

pmt
Pointer to an initialized DMO_MEDIA_TYPE structure.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_POINTER | NULL pointer argument

Remarks

This function frees the format block pointed to by the pbFormat member of the DMO_MEDIA_TYPE structure.

MoCopyMediaType

DMO Registration Functions

Copies the members of one media type structure into another media type structure.

Syntax

HRESULT MoCopyMediaType(
    DMO_MEDIA_TYPE *pmtDest,
    const DMO_MEDIA_TYPE *pmtSrc
);

Parameters

pmtDest
Pointer to the target DMO_MEDIA_TYPE structure. The caller must allocate, but not initialize, this structure.
pmtSrc
Pointer to the source DMO_MEDIA_TYPE structure.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

This function copies all the members of pmtSrc to pmtDest and copies the format block.

The caller must free the target media type by calling the MoFreeMediaType function.

MoCreateMediaType

DMO Registration Functions

Allocates a new media type structure.

Syntax

HRESULT MoCreateMediaType(
    DMO_MEDIA_TYPE **ppmt,
    DWORD cbFormat
);

Parameters

ppmt
Address of a pointer to a DMO_MEDIA_TYPE structure that receives the allocated structure.
cbFormat
Number of bytes to allocate for the format block. Can be zero.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

This function allocates a new DMO_MEDIA_TYPE structure and then initializes it by calling the MoInitMediaType function.

The caller must delete the media type structure by calling the MoDeleteMediaType function.

MoDeleteMediaType

DMO Registration Functions

Deletes a media type structure that was previously allocated.

Syntax

HRESULT MoDeleteMediaType(
    DMO_MEDIA_TYPE *pmt
);

Parameters

pmt
Pointer to an initialized DMO_MEDIA_TYPE structure.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_POINTER | NULL pointer argument

Remarks

This function frees the allocated members of the media type structure by calling MoFreeMediaType. Then it frees the media type structure itself.

MoDuplicateMediaType

DMO Registration Functions

Duplicates a media type structure.

Syntax

HRESULT MoDuplicateMediaType(
    DMO_MEDIA_TYPE **ppmtDest,
    const DMO_MEDIA_TYPE *pmtSrc
);

Parameters

ppmtDest
Address of a pointer to a DMO_MEDIA_TYPE structure that receives the duplicated structure.
pmtSrc
Pointer to the media type structure to duplicate.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success
E_OUTOFMEMORY | Insufficient memory
E_POINTER | NULL pointer argument

Remarks

This method is equivalent to calling MoCreateMediaType and MoCopyMediaType.

The caller must delete the returned media type structure by calling the MoDeleteMediaType function.


DMO Error Codes

The following table contains error codes that are specific to Microsoft® DirectX® Media Objects (DMOs). These error codes are defined in the header file Mediaerr.h.

Return code | Description | Hexadecimal value
DMO_E_INVALIDSTREAMINDEX | Invalid stream index. | 0x80040201
DMO_E_INVALIDTYPE | Invalid media type. | 0x80040202
DMO_E_TYPE_NOT_SET | Media type was not set. One or more streams require a media type before this operation can be performed. | 0x80040203
DMO_E_NOTACCEPTING | Data cannot be accepted on this stream. You might need to process more output data; see IMediaObject::ProcessInput. | 0x80040204
DMO_E_TYPE_NOT_ACCEPTED | Media type was not accepted. | 0x80040205
DMO_E_NO_MORE_ITEMS | Media-type index is out of range. | 0x80040206


DMO GUIDs

This article lists some of the globally unique identifiers (GUIDs) defined for Microsoft® DirectX® Media Objects (DMOs).

  • Category GUIDs

Category GUIDs

The following table lists GUIDs for the DMO categories. To enumerate the DMOs registered in a category, pass the corresponding GUID to the DMOEnum function.

GUID | Description
DMOCATEGORY_AUDIO_DECODER | Audio decoder
DMOCATEGORY_AUDIO_EFFECT | Audio effect
DMOCATEGORY_AUDIO_ENCODER | Audio encoder
DMOCATEGORY_VIDEO_DECODER | Video decoder
DMOCATEGORY_VIDEO_EFFECT | Video effect
DMOCATEGORY_VIDEO_ENCODER | Video encoder
DMOCATEGORY_AUDIO_CAPTURE_EFFECT | Audio capture effect.


DMO Base Class Reference

Microsoft® DirectX® 8.0 includes a base-class template for creating DirectX Media Objects (DMOs). You do not have to use the template to create a DMO. However, the template handles various tasks that are common to all DMOs. Using the template, you can focus on the functionality that is specific to your DMO. In addition, the template helps to ensure that you create a robust implementation.

This section contains the following topics:

  • Using the DMO Base Class
  • IMediaObjectImpl Class Template


Using the DMO Base Class

The Microsoft® DirectX® 8.0 SDK includes a base-class template for creating DMOs, IMediaObjectImpl. You do not have to use the class template when you create a DMO, as long as your DMO fully supports the IUnknown and IMediaObject interfaces. However, the class template provided by Microsoft handles many of the "bookkeeping" tasks, such as validating input parameters. By using the template, you can focus on the functionality that is specific to your DMO. In addition, the template helps to ensure that you create a robust implementation.

This article contains the following topics:

  • Overview of IMediaObjectImpl
  • Declaring the Derived Class
  • Implementing the DMO Methods

Overview of IMediaObjectImpl

The IMediaObjectImpl template is a class template that inherits the IMediaObject interface. To create a DMO using the template, define a new class that derives from IMediaObjectImpl. The template implements all of the IMediaObject methods. In most cases, the template method calls a corresponding internal method, which the derived class must provide. Thus, the template provides generic functionality, such as validating parameters, while the derived class provides the core functionality for the DMO.

The template provides the following features:

  • Basic parameter checking. The template methods verify that required parameters are not NULL, that stream indexes are within range, and that flags are valid.
  • Locking. The template methods call two internal methods, Lock and Unlock, to serialize operations on the DMO. This feature ensures that the DMO is thread-safe.
  • Media types. The template stores the media types that are set for the streams in the DMO. It also provides accessor methods for the media types.
  • Streaming. The template prevents streaming until the client has set media types for all non-optional streams. Also, the ProcessInput and ProcessOutput methods automatically call AllocateStreamingResources.

The derived class must implement the IUnknown interface; the template does not provide this interface. You can use the Active Template Library (ATL) to implement IUnknown, or you can provide some other implementation.

The template also does not implement the locking mechanism. The derived class must implement the Lock and Unlock methods. If you create your class using ATL, however, the default ATL implementations for these methods are probably sufficient.

Declaring the Derived Class

The IMediaObjectImpl template is declared in the header file Dmoimpl.h, which is located in the Include directory of the SDK. It has the following declaration:

template <class _DERIVED_, int NUMBEROFINPUTS, int NUMBEROFOUTPUTS>
class IMediaObjectImpl : public IMediaObject

The template has three parameters, as shown in the following table.

_DERIVED_ | Derived class type
NUMBEROFINPUTS | Number of input streams
NUMBEROFOUTPUTS | Number of output streams

For example, to create a derived class named CMyDmoClass that supports one input stream and one output stream, you would declare it as follows:

class CMyDmoClass :
    public IMediaObjectImpl<CMyDmoClass, 1, 1>  // 1 input, 1 output

DMOs cannot dynamically create or destroy streams, so the stream numbers are constant.

Implementing the DMO Methods

The template provides partial implementations for the following IMediaObject methods. The derived class must provide a corresponding method, which the IMediaObject method calls internally. The internal methods have Internal- prefixed to the method name. The internal methods use the same parameters as the interface methods.

IMediaObject Method | Derived Class Method
AllocateStreamingResources | InternalAllocateStreamingResources
Discontinuity | InternalDiscontinuity
Flush | InternalFlush
FreeStreamingResources | InternalFreeStreamingResources
GetInputMaxLatency | InternalGetInputMaxLatency
GetInputSizeInfo | InternalGetInputSizeInfo
GetInputStreamInfo | InternalGetInputStreamInfo
GetInputType | InternalGetInputType
GetOutputSizeInfo | InternalGetOutputSizeInfo
GetOutputStreamInfo | InternalGetOutputStreamInfo
GetOutputType | InternalGetOutputType
ProcessInput | InternalProcessInput
ProcessOutput | InternalProcessOutput
SetInputMaxLatency | InternalSetInputMaxLatency

For the remaining IMediaObject methods, there is not a one-to-one correspondence between interface methods and internal methods. The following table summarizes which methods are fully implemented by the template, and which methods call helper methods from the derived class.

IMediaObject Method | IMediaObjectImpl Implementation
GetInputCurrentType | Fully implemented.
GetOutputCurrentType | Fully implemented.
GetStreamCount | Fully implemented.
GetInputStatus | Calls InternalAcceptingInput.
Lock | Implemented as DMOLock. Calls Lock or Unlock.
SetInputType | Calls InternalCheckInputType.
SetOutputType | Calls InternalCheckOutputType.

For more information, see IMediaObjectImpl.


IMediaObjectImpl Class Template

Provides a base implementation for the IMediaObject interface.

For more information on using this template, see Using the DMO Base Class.

Helper Classes
LockIt | Internal helper class that handles locking and unlocking.
IMediaObjectImpl Methods
CheckTypesSet | Determines whether all of the non-optional streams have media types.
InputType | Retrieves an input stream's media type.
InputTypeSet | Queries whether the media type was set on an input stream.
OutputType | Retrieves an output stream's media type.
OutputTypeSet | Queries whether the media type was set on an output stream.
IMediaObject Methods | Methods that implement the IMediaObject interface.
Derived Class Methods
InternalAcceptingInput | Queries whether an input stream can accept more input.
InternalCheckInputType | Queries whether an input stream can accept a given media type.
InternalCheckOutputType | Queries whether an output stream can accept a given media type.
Lock | Locks the object.
Unlock | Unlocks the object.

LockIt Internal Class

Internal helper class that handles locking and unlocking.

Syntax

LockIt(
    _DERIVED_ *p
);

Parameters

p
Pointer to the derived object.

Remarks

The constructor method locks the object, and the destructor method unlocks the object. To lock the object from inside your derived class, declare a local variable of type LockIt, as shown in the following example:

{
    LockIt lck(static_cast<_DERIVED_ *>(this)); // Locks the object.

} // lck goes out of scope, object is unlocked.

The methods in IMediaObjectImpl handle locking, so in most cases the derived class does not need to lock the object.

IMediaObjectImpl::CheckTypesSet

Determines whether all of the non-optional streams have media types.

Syntax

bool CheckTypesSet(void);

Return Value

Returns TRUE if all of the object's non-optional streams have media types. Otherwise, returns FALSE.

Remarks

Call this method after any operation that changes the media type on a stream. This method sets a private flag within the class. Some IMediaObjectImpl methods test this flag to determine whether certain operations are permitted. These methods generally return DMO_E_TYPE_NOT_SET if the flag is FALSE.

The only two methods in IMediaObject that change the media type on a stream are SetInputType and SetOutputType. The class template implements both of these methods.

IMediaObjectImpl::InputType

Retrieves an input stream's media type.

Syntax

const DMO_MEDIA_TYPE *InputType(
    DWORD ulInputStreamIndex
);

Parameters

ulInputStreamIndex
Index of an input stream.

Return Value

Returns a pointer to the DMO_MEDIA_TYPE structure that describes the media type, or NULL if the type was not set.

IMediaObjectImpl::InputTypeSet

Queries whether the media type was set on an input stream.

Syntax

bool InputTypeSet(
    DWORD ulInputStreamIndex
);

Parameters

ulInputStreamIndex
Index of an input stream.

Return Value

Returns TRUE if the media type was set on this stream, or FALSE otherwise.

IMediaObjectImpl::OutputType

Retrieves an output stream's media type.

Syntax

const DMO_MEDIA_TYPE *OutputType(
    DWORD ulOutputStreamIndex
);

Parameters

ulOutputStreamIndex
Index of an output stream.

Return Value

Returns a pointer to the DMO_MEDIA_TYPE structure that describes the media type, or NULL if the type was not set.

IMediaObjectImpl::OutputTypeSet

Queries whether the media type was set on an output stream.

Syntax

bool OutputTypeSet(
    DWORD ulOutputStreamIndex
);

Parameters

ulOutputStreamIndex
Index of an output stream.

Return Value

Returns TRUE if the media type was set on this stream, or FALSE otherwise.

_DERIVED_::InternalAcceptingInput

Queries whether an input stream can accept more input. The derived class must declare and implement this method.

Syntax

HRESULT InternalAcceptingInput(
    DWORD dwInputStreamIndex
);

Parameters

dwInputStreamIndex
Index of an input stream.

Return Value

Returns S_OK if the input stream can accept input, or S_FALSE otherwise.

_DERIVED_::InternalCheckInputType

Queries whether an input stream can accept a given media type. The derived class must declare and implement this method.

Syntax

HRESULT InternalCheckInputType(
    DWORD dwInputStreamIndex,
    const DMO_MEDIA_TYPE *pmt
);

Parameters

dwInputStreamIndex
Index of an input stream.
pmt
Pointer to a DMO_MEDIA_TYPE structure that describes the media type.

Return Value

Returns S_OK if the media type is valid, or DMO_E_INVALIDTYPE otherwise.

_DERIVED_::InternalCheckOutputType

Queries whether an output stream can accept a given media type. The derived class must declare and implement this method.

Syntax

HRESULT InternalCheckOutputType(
    DWORD dwOutputStreamIndex,
    const DMO_MEDIA_TYPE *pmt
);

Parameters

dwOutputStreamIndex
Index of an output stream.
pmt
Pointer to a DMO_MEDIA_TYPE structure that describes the media type.

Return Value

Returns S_OK if the media type is valid, or DMO_E_INVALIDTYPE otherwise.

_DERIVED_::Lock

Locks the object. The derived class must declare and implement this method.

Syntax

void Lock(void);

Remarks

If you implement your derived class using the Active Template Library (ATL), you can use ATL's default implementation of this method.

_DERIVED_::Unlock

Unlocks the object. The derived class must declare and implement this method.

Syntax

void Unlock(void);

Remarks

If you implement your derived class using the Active Template Library (ATL), you can use ATL's default implementation of this method.

IMediaObject Methods

Most of the IMediaObject methods are wrappers that call an internal version of the same method. The derived class must implement the internal versions, which have the prefix Internal-.

For a list of methods the derived class must implement, see DMO Base Class. The following remarks give details about some of the implementations.

AllocateStreamingResources

The template keeps a private flag that indicates whether this method has been called. If the method is called when the flag is already TRUE, it returns S_OK without calling the InternalAllocateStreamingResources method. The FreeStreamingResources method resets the flag to FALSE.

DMOLock

This method implements the IMediaObject::Lock method. To avoid name conflicts with ATL, IMediaObjectImpl has renamed the method as DMOLock.

Note When you build the derived class, define FIX_LOCK_NAME before you include the DMO header file. The FIX_LOCK_NAME directive causes the preprocessor to substitute DMOLock for Lock in the declaration of the IMediaObject interface. Applications can still invoke the method using the name Lock, because the vtable order does not change.

#define FIX_LOCK_NAME
#include <dmo.h>

This method calls Lock if the parameter is TRUE or Unlock if the parameter is FALSE. The derived class must implement the Lock and Unlock methods.

Flush

The template keeps a private flag that indicates the object's flushed state. The Flush method sets the flag to TRUE, and the ProcessInput method resets it to FALSE. If Flush is called when the flag is already TRUE, the method returns S_OK without calling the InternalFlush method.

GetInputSizeInfo, GetOutputSizeInfo

These methods return DMO_E_TYPE_NOT_SET unless all of the non-optional streams have media types. Therefore, in the derived class, the internal methods can assume that all of the non-optional streams have media types.

GetInputStatus

This method calls the InternalAcceptingInput method, which the derived class must implement. The InternalAcceptingInput method returns S_OK if the specified input stream can accept input. Otherwise, it returns S_FALSE.

Unless all of the non-optional streams have media types, the GetInputStatus method returns DMO_E_TYPE_NOT_SET. Therefore, the implementation of InternalAcceptingInput does not have to check for this condition.

ProcessInput

Before this method calls InternalProcessInput, it calls AllocateStreamingResources and InternalAcceptingInput. Therefore, the implementation of InternalProcessInput can assume the following:

  • All resources have been allocated.
  • The input stream can accept data.

ProcessOutput

Before this method calls InternalProcessOutput, it calls AllocateStreamingResources. Therefore, the implementation of InternalProcessOutput can assume that all resources have been allocated.

SetInputType

This method tests, sets, or clears the media type on an input stream. It calls the InternalCheckInputType method, which the derived class must implement. The InternalCheckInputType method returns S_OK if the media type is acceptable, or an error code otherwise. The SetInputType method implements the rest of the functionality.

This method does not allocate any resources. When the DMO switches to a streaming state, it calls the AllocateStreamingResources method. The derived class should use the InternalAllocateStreamingResources method to allocate any resources that it needs, such as memory buffers.

SetOutputType

This method tests, sets, or clears the media type on an output stream. It calls the InternalCheckOutputType method, which the derived class must implement. The InternalCheckOutputType method returns S_OK if the media type is acceptable, or an error code otherwise. The SetOutputType method implements the rest of the functionality.

This method does not allocate any resources. When the DMO switches to a streaming state, it calls the AllocateStreamingResources method. The derived class should use the InternalAllocateStreamingResources method to allocate any resources that it needs, such as memory buffers.


Media Parameters

Media parameters are a new set of APIs that support run-time changes to an object's properties. They offer precise control over properties that change rapidly and require both high performance and repeatability. They enable a property to follow an exact curve, such as a sine wave or inverse-square curve, in real time.

Using media parameters, data transform objects can support a standard interface for controlling run-time behavior. In conjunction with Microsoft® DirectX® Media Objects (DMOs), they are particularly useful for writing audio effects. For example, in an echo effect, the ratio of wet (processed) signal to dry (unprocessed) signal can follow a smooth curve. This type of behavior is critical in audio engineering, to avoid introducing artifacts into the recording.

This section contains the following topic.

  • Media Parameter Reference


Media Parameter Reference

This section contains all the media parameter reference information.

  • Interfaces
  • Structures
  • Enumerated Types
  • Constants
  • Globally Unique Identifiers (GUIDs)


Interfaces

This section contains reference entries for all the Microsoft® DirectX® media parameter COM interfaces and their methods.

  • IMediaParamInfo
  • IMediaParams


IMediaParamInfo Interface

Retrieves information about the parameters that an object supports. The set of parameters that an object supports will not change over the lifetime of an application. To set parameter values, use the IMediaParams interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaParamInfo methods | Description
GetParamCount | Retrieves the number of parameters that the object supports.
GetParamInfo | Retrieves information about a specified parameter.
GetParamText | Retrieves an array of text strings that describe the parameter.
GetNumTimeFormats | Retrieves the number of time formats that the object supports.
GetSupportedTimeFormat | Retrieves a supported time format.
GetCurrentTimeFormat | Retrieves the current time format.

IMediaParamInfo::GetParamCount

IMediaParamInfo Interface

Retrieves the number of parameters that the object supports.

Syntax

HRESULT GetParamCount(
    DWORD *pdwParams
);

Parameters

pdwParams
[out] Pointer to a variable that receives the number of parameters.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_POINTER | NULL pointer argument.

IMediaParamInfo::GetParamInfo

IMediaParamInfo Interface

Retrieves information about a specified parameter.

Syntax

HRESULT GetParamInfo(
    DWORD dwParamIndex,
    MP_PARAMINFO *pInfo
);

Parameters

dwParamIndex
[in] Zero-based index of the parameter.
pInfo
[out] Pointer to an MP_PARAMINFO structure that is filled with the parameter information.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_INVALIDARG | Index out of range.
E_POINTER | NULL pointer argument.

Remarks

Call the GetParamCount method to retrieve the number of parameters that the object supports.

IMediaParamInfo::GetParamText

IMediaParamInfo Interface

Retrieves a series of text strings that describe the parameter.

Syntax

HRESULT GetParamText(
    DWORD dwParamIndex,
    WCHAR **ppwchText
);

Parameters

dwParamIndex
[in] Zero-based index of the parameter.
ppwchText
[out] Address of a variable that receives a pointer to a series of Unicode™ strings.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_INVALIDARG | Index out of range.
E_POINTER | NULL pointer argument.

Return Value

If the method succeeds, *ppwchText points to a string with the following format:

Name\0Unit\0Enum1\0Enum2\0...EnumN\0\0

where

  • Name is the name of the parameter.
  • Unit is the name of the units; for example, milliseconds.
  • Enum1 through EnumN are descriptive names for the parameter's enumerated values. (Applies only to parameters of type MPT_ENUM.)

The application can display these values within its user interface. They are not guaranteed to follow a consistent naming scheme. If the user's computer is using an international code page, the method might return a localized string corresponding to that code page.

The object uses the CoTaskMemAlloc function to allocate memory for the string. After you call this method, call CoTaskMemFree to free the buffer.

IMediaParamInfo::GetNumTimeFormats

IMediaParamInfo Interface

Retrieves the number of time formats that the object supports.

Syntax

HRESULT GetNumTimeFormats(
    DWORD *pdwNumTimeFormats
);

Parameters

pdwNumTimeFormats
[out] Pointer to a variable that receives the number of supported time formats.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_POINTER | NULL pointer argument.

IMediaParamInfo::GetSupportedTimeFormat

IMediaParamInfo Interface

Retrieves a supported time format.

Syntax

HRESULT GetSupportedTimeFormat(
    DWORD dwFormatIndex,
    GUID *pguidTimeFormat
);

Parameters

dwFormatIndex
[in] Index of the time format to retrieve.
pguidTimeFormat
[out] Pointer to a variable that receives a time format GUID.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_INVALIDARG | Index out of range.
E_POINTER | NULL pointer argument.

Remarks

Call the GetNumTimeFormats method to retrieve the number of time formats that the object supports.

IMediaParamInfo::GetCurrentTimeFormat

IMediaParamInfo Interface

Retrieves the current time format.

Syntax

HRESULT GetCurrentTimeFormat(
    GUID *pguidTimeFormat,
    MP_TIMEDATA *pTimeData
);

Parameters

pguidTimeFormat
[out] Pointer to a variable that receives a time format GUID.
pTimeData
[out] Pointer to a variable that receives an MP_TIMEDATA value specifying the unit of measure for the new format.

Return Value

Returns an HRESULT value. Possible values include the following:

S_OK | Success.
E_POINTER | NULL pointer argument.

Remarks

The meaning of the value returned in the pTimeData parameter depends on the time format GUID. For more information, see IMediaParams::SetTimeFormat.


IMediaParams Interface

Sets and retrieves envelope-following parameters on an object.

To reduce overhead, parameters are referenced by index value, and all parameter values are 32 bits, defined as type MP_DATA. Use the IMediaParamInfo interface to determine whether a given parameter is an integer, floating-point value, Boolean value, or member of an enumerated type.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaParams methods | Description
GetParam | Retrieves the most recent value of the specified parameter.
SetParam | Sets the value of a parameter.
AddEnvelope | Adds an envelope to a parameter.
FlushEnvelope | Flushes envelope data for a specified parameter over the specified time range.
SetTimeFormat | Specifies the time format for the object.

IMediaParams::GetParam

IMediaParams Interface

Retrieves the current value of the specified parameter. If the parameter is currently within an envelope segment, the returned value is the value on the most recently processed sample.

Syntax

HRESULT GetParam(
    DWORD dwParamIndex,
    MP_DATA *pValue
);

Parameters

dwParamIndex
[in] Zero-based index of the parameter.
pValue
[out] Pointer to a variable of type MP_DATA that receives the parameter value.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | Index out of range.
E_POINTER | NULL pointer argument.

Remarks

To enumerate the parameters supported by this object, along with their index values, use the IMediaParamInfo interface.

IMediaParams::SetParam

IMediaParams Interface

Sets the value of a parameter.

Syntax

HRESULT SetParam(
    DWORD dwParamIndex,
    MP_DATA value
);

Parameters

dwParamIndex
[in] Zero-based index of the parameter, or DWORD_ALLPARAMS to apply the value to every parameter.
value
[in] New value of the parameter.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | Index out of range, or illegal parameter value.

Remarks

If the parameter is currently within an envelope segment, the envelope segment will overwrite the new value. To remove an envelope segment, call the FlushEnvelope method.

To enumerate the parameters supported by this object, along with their index values, use the IMediaParamInfo interface.

IMediaParams::AddEnvelope

IMediaParams Interface

Adds an envelope to a parameter.

Syntax

HRESULT AddEnvelope(
    DWORD dwParamIndex,
    DWORD cPoints,
    MP_ENVELOPE *pEnvelope,
);

Parameters

dwParamIndex
[in] Zero-based index of the parameter, or DWORD_ALLPARAMS to add the envelope to every parameter.
cPoints
[in] Number of segments in the envelope.
pEnvelope
[in] Pointer to an array of MP_ENVELOPE structures that define the envelope segments. The size of the array is given in the cPoints parameter.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | Index out of range.
E_OUTOFMEMEORY | Insufficient memory.
E_POINTER | NULL pointer argument.

Remarks

If the envelope overlaps an existing envelope, the new envelope takes precedence.

To enumerate the parameters supported by this object, along with their index values, use the IMediaParamInfo interface.

IMediaParams::FlushEnvelope

IMediaParams Interface

Flushes envelope data for a specified parameter over the specified time range.

Syntax

HRESULT FlushEnvelope(
    DWORD dwParamIndex,
    REFERENCE_TIME refTimeStart,
    REFERENCE_TIME refTimeEnd
);

Parameters

dwParamIndex
[in] Zero-based index of the parameter, or DWORD_ALLPARAMS to flush envelope data from every parameter.
refTimeStart
[in] Start time of the envelope data to flush.
refTimeEnd
[in] Stop time of the envelope data to flush.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_INVALIDARG | Index out of range.

Remarks

If the time span specified by refTimeStart and refTimeEnd overlaps an envelope segment, the entire segment is flushed. On the other hand, if it falls on the boundary of an envelope segment, the entire segment is retained. Thus:

  • If the start time falls inside an envelope segment, the segment is flushed.
  • If the end time falls inside an envelope segment, the segment is flushed.
  • If the start time equals the end time of an envelope segment, the segment is retained.
  • If the end time equals the start time of an envelope segment, the segment is retained.

To enumerate the parameters supported by this object, along with their index values, use the IMediaParamInfo interface.

IMediaParams::SetTimeFormat

IMediaParams Interface

Specifies the time format for the object.

Syntax

HRESULT SetTimeFormat(
    GUID guidTimeFormat,
    MP_TIMEDATA mpTimeData
);

Parameters

guidTimeFormat
[in] Time format GUID that specifies the time format.
mpTimeData
[in] Value of type MP_TIMEDATA that specifies the unit of measure for the new format.

Return Value

Returns an HRESULT value. Possible values include the following.

S_OK | Success.
E_DMOTIMESTAMPFORMAT | Object does not support this time format.

Remarks

Objects can support more than one time format. Every object must support reference time, in which each unit of time is 100 nanoseconds (ns). Other formats are optional. The application must ensure that time stamps on the input buffers match whatever time format was set using this method.

The meaning of the mpTimeData parameter depends on the value of the guidTimeFormat parameter:

Time Format | Meaning of Time Data
GUID_TIME_REFERENCE | Ignored.
GUID_TIME_MUSIC | Parts per quarter note.
GUID_TIME_SAMPLES | Samples per second.

When you call this method, you should also call the FlushEnvelope method, to flush any envelopes that were set using the previous time format.

To determine what time formats an object supports, call the IMediaParamInfo::GetSupportedTimeFormat method. To retrieve the current format, call the IMediaParamInfo::GetCurrentTimeFormat method.


Structures

This section describes the Microsoft® DirectX® media parameter structures.

Structure | Description
MP_ENVELOPE | Defines an envelope segment used by an envelope-following parameter.
MP_PARAMINFO | Contains information about a parameter.


MP_ENVELOPE Structure

Structures

Defines an envelope segment used by an envelope-following parameter.

Syntax

typedef struct _MP_ENVELOPE {
    REFERENCE_TIME   rtStart;
    REFERENCE_TIME   rtEnd;
    MP_DATA          valStart;
    MP_DATA          valEnd;
    MP_CURVE_TYPE    iCurve;
    MP_FLAGS         flags;
} MP_ENVELOPE;

Members

rtStart
Start time of the segment, relative to the time stamp on the first buffer, in 100-nanosecond units.
rtEnd
Stop time of the segment, relative to the time stamp on the first buffer, in 100-nanosecond units.
valStart
Initial value of the parameter, at the start of the segment.
valEnd
Final value of the parameter, at the end of the segment.
iCurve
Member of the MP_CURVE_TYPE enumerated type that specifies the curve followed by the parameter.
flags
Bitwise combination of envelope flags.


MP_PARAMINFO Structure

Structures

Contains information about a parameter.

Syntax

typedef struct _MP_PARAMINFO {
    MP_TYPE    mpType;
    MP_CAPS    mopCaps;
    MP_DATA    mpdMinValue;
    MP_DATA    mpdMaxValue;
    MP_DATA    mpdNeutralValue;
    WCHAR      szUnitText[32];
    WCHAR      szLabel[32];
} MP_PARAMINFO;

Members

mpType
Member of the MP_TYPE enumeration that specifies the valid data type for this parameter.
mopCaps
Bitwise combination of one or more capabilities flags that specify which envelope curves are supported. For Boolean and enumeration parameters, only MP_CAPS_CURVE_JUMP is valid.
mpdMinValue
Minimum value of the parameter. Used only for parameters with numeric values.
mpdMaxValue
Maximum value of the parameter. Used only for parameters with numeric values.
mpdNeutralValue
Default or "neutral" value of the parameter.
szUnitText
NULL-terminated Unicode™ string that contains the name of the units for the parameter.
szLabel
NULL-terminated Unicode™ string that contains the name of the parameter.

Members

The szUnitText and szLabel members always contain English-language strings. For international support, use the IMediaParamInfo::GetParamText method.


Enumerated Types

This section describes the Microsoft® DirectX® media parameter enumerated types.

Enumerated Type | Description
MP_CURVE_TYPE | Defines the curve that a media parameter follows within an envelope segment.
MP_TYPE | Specifies the data type for a parameter.


MP_CURVE_TYPE Enumeration

Enumerated Types

Defines the curve that a media parameter follows within an envelope segment.

Syntax

typedef enum _MP_CURVE_TYPE {
    MP_CURVE_JUMP       = 0x0001,
    MP_CURVE_LINEAR     = 0x0002,
    MP_CURVE_SQUARE     = 0x0004,
    MP_CURVE_INVSQUARE  = 0x0008,
    MP_CURVE_SINE       = 0x0010,
    MP_CURVE_CURRENTVAL = 0x8000,
} MP_CURVE_TYPE;

Elements

MP_CURVE_JUMP
No interpolation. Jump to the next point.
MP_CURVE_LINEAR
Linear interpolation.
MP_CURVE_SQUARE
Parabolic curve.
MP_CURVE_INVSQUARE
Inverse square curve.
MP_CURVE_SINE
Sine curve.
MP_CURVE_CURRENTVAL
Ignore the start value specified for this segment. Start from the final value of the previous segment.

Remarks

The following table lists the defined curves and their mathematical equivalents.

Value | Curve to Fit | Range
MP_CURVE_LINEAR | y = x | 0.0 – 1.0
MP_CURVE_SQUARE | y = x2 | 0.0 – 1.0
MP_CURVE_INVSQUARE | y = 1 – x2 | 0.0 – 1.0
MP_CURVE_SINE | y = sin(x) | –π/2 – π/2

For Boolean and enumeration parameters, only MP_CURVE_JUMP is valid.

See Also

MP_ENVELOPE


MP_TYPE Enumeration

Enumerated Types

Specifies the data type for a parameter.

Syntax

typedef enum _MP_Type {
    MPT_INT,
    MPT_FLOAT,
    MPT_BOOL,
    MPT_ENUM,
    MPT_MAX,
} MP_TYPE;

Elements

MPT_INT
Value is a signed 32-bit integer.
MPT_FLOAT
Value is a 32-bit IEEE floating-point value.
MPT_BOOL
Value is Boolean. Use the following constants for Boolean parameters:
Constant | Description
MP_DATA MPBOOL_TRUE | TRUE
MP_DATA MPBOOL_FALSE | FALSE
MPT_ENUM
Value is taken from a set of consecutive integers.
MPT_MAX
Reserved.

Remarks

To reduce type conversions at run time, all parameters have 32-bit float values, defined as type MP_DATA. The members of this enumeration specify how a given parameter should be interpreted.

See Also

MP_PARAMINFO


Constants

The following constants are defined for Microsoft® DirectX® media parameters.

  • Parameter Capabilities Flags
  • Envelope Flags

Parameter Capabilities Flags

These flags specify which envelope curves are supported.

Constant | Description
MP_CAPS_CURVE_JUMP | Jump to the next point without interpolation. See MP_CURVE_JUMP.
MP_CAPS_CURVE_LINEAR | Linear interpolation. See MP_CURVE_LINEAR.
MP_CAPS_CURVE_SQUARE | Parabolic curve. See MP_CURVE_SQUARE.
MP_CAPS_CURVE_INVSQUARE | Inverse square curve. See MP_CURVE_INVSQUARE.
MP_CAPS_CURVE_SINE | Sine curve. See MP_CURVE_SINE.

Envelope Flags

These flags specify information about envelope segments.

Constant | Description
MPF_ENVLP_STANDARD | Use all the information provided with the envelope segment.
MPF_ENVLP_BEGIN_CURRENTVAL | Ignore the specified start value. Start from the current value.
MPF_ENVLP_BEGIN_NEUTRALVAL | Ignore the specified start value. Start from the neutral value. (See MP_PARAMINFO.)

See Also

MP_ENVELOPE


Media Parameter GUIDs

This article lists some of the globally unique identifiers (GUIDs) defined for Microsoft® DirectX® media parameters.

  • Time Format GUIDs

Time Format GUIDs

The following table lists GUIDs for the media parameter time formats.

GUID | Description
GUID_TIME_REFERENCE | Reference time, in 100-nanosecond units.
GUID_TIME_MUSIC | Music time, in parts per quarter note.
GUID_TIME_SAMPLES | Samples per second.


Appendixes

  • Controlling Filter Graphs Using C
  • Deprecated Interfaces
  • DirectShow Graph File Format
  • Filter Graph Markup Language (XGR)
  • International Analog TV Tuning
  • Multimedia Streaming
  • SMPTE Timecode
  • Using DirectShow with Visual Basic
  • Further Reading


Controlling Filter Graphs Using C

If you are writing your Microsoft® DirectShow® application in C (rather than C++), you must use a vtable pointer to call methods. The following example illustrates how to call to the IUnknown::QueryInterface method from an application written in C:

pGraph->lpVtbl->QueryInterface(pGraph, &IID_IMediaEvent, (void **)&pEvent);

The following shows the equivalent call in C++:

pGraph->QueryInterface(IID_IMediaEvent, (void **)&pEvent);

In C, interfaces are defined as structures. The lpVtbl member is a pointer to a table of interface methods (the vtable). All methods take an additional parameter, which is a pointer to the interface.


Deprecated Interfaces

The following interfaces have been deprecated. They will continue to be supported for backward compatibility with existing applications, but new applications should not use them.

  • IAMovieSetup
  • IAMDevMemoryAllocator
  • IAMDevMemoryControl
  • IAMPhysicalPinInfo
  • ICaptureGraphBuilder
  • IDirectDrawFactory
  • IDirectDraw3
  • IDvdControl
  • IDvdInfo
  • IEnumRegFilters
  • IFilterMapper


IAMovieSetup Interface

Note This interface has been deprecated. It is used by two obsolete functions, AMovieDllRegisterServer and AMovieDllUnregisterServer. These functions are now replaced by AMovieDllRegisterServer2, which does not require IAMovieSetup. However, IAMovieSetup will continue to be supported for backward compatibility with existing applications.

In Microsoft® ActiveMovie® 1.0, filters implemented self-registration as follows:

  • Inside the DllRegisterServer function, the filter's DLL called the AMovieDllRegisterServer function. This function queries each filter for its IAMovie interface and calls the IAMovieSetup::Register method.
  • Inside the DllUnregisterServer function, the filter's DLL called the AMovieDllUnregisterServer function. This function also queries each filter for its IAMovie interface, but calls the IAMovieSetup::Unregister method.

As noted, you should now use the AMovieDllRegisterServer2 function. Filters registered with this function do not need to implement IAMovieSetup. For more information, see How to Register DirectShow Filters.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMovieSetup methods | Description
Register | Adds the filter to the registry.
Unregister | Removes the filter from the registry.

IAMovieSetup::Register

IAMovieSetup Interface

Adds the filter to the registry.

Syntax

HRESULT Register(void);

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method registers the filter, its pins, and the media type associated with the pins. It should be implemented to use IFilterMapper methods to accomplish this. See the CBaseFilter::Register member function for a description of its implementation.

IAMovieSetup::Unregister

IAMovieSetup Interface

Removes the filter from the registry.

Syntax

HRESULT Unregister(void);

Return Value

Returns an HRESULT value that depends on the implementation. HRESULT can be one of the following standard constants, or other values not listed.
E_FAIL | Failure.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
E_NOTIMPL | Method isn't supported.
S_OK or NOERROR | Success.

Remarks

This method should be implemented to use the IFilterMapper::UnregisterFilter method to remove the filter from the registry. This effectively removes the pins and media types as well.


IAMDevMemoryAllocator Interface

Note This interface has been deprecated. It was defined to support older hardware decoders that required that AVI files be read into their hardware memory directly. The interface enables the AVI Parser to allocate memory from the downstream filter but still provide its own allocator. There should be no need for any newer devices to support this interface.

The IAMDevMemoryAllocator interface enables the creation of third-party memory allocators by using an on-board memory manager object. Many codec hardware manufacturers put on-board mapped memory for the codecs to improve the efficiency of buffer manipulation. This interface allocates that memory and provides the GetDevMemoryObject method to retrieve a device memory control object, which supports the IAMDevMemoryControl interface. Devices that share the same device ID can use the memory.

The global memory manager object exposes this interface to allocate memory from memory that is on a particular device.

Implement this interface when your pin must support the creation of on-board memory allocators. Source filters that are aware of on-board memory and need to create their own allocators should query for this interface, request an amount of memory and then create an allocator (aggregating the device memory control object). Source filters that don't need to create their own allocator could just use the allocator of the downstream pin (which also aggregates the device memory control object). The hardware-based filter can confirm the usage of its on-board memory by calling methods on the aggregated allocator.

Use this interface when applications need to control the memory of codecs with on-board memory.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMDevMemoryAllocator methods | Description
GetInfo | Retrieves information about the memory capabilities.
CheckMemory | Tests whether the particular device of the allocator allocated a memory pointer.
Alloc | Allocates a memory buffer.
Free | Frees the previously allocated memory.
GetDevMemoryObject | Retrieves an IUnknown interface pointer to a device memory control object that can be aggregated with a custom allocator.

IAMDevMemoryAllocator::Alloc

IAMDevMemoryAllocator Interface

Allocates a memory buffer.

Syntax

HRESULT Alloc(
    BYTE **ppBuffer,
    DWORD *pdwcbBuffer
);

Parameters

ppBuffer
[out] Pointer that will receive the address of the allocated memory buffer.
pdwcbBuffer
[in, out] Pointer to a DWORD whose input value is the number of bytes to allocate and whose output value is the actual number of bytes allocated.

Return Value

Returns S_OK if the desired quantity of memory was allocated, S_FALSE if memory was unavailable.

Remarks

Call this method to allocate a block of memory from the available pool.

See Also

IAMDevMemoryAllocator::Free

IAMDevMemoryAllocator::CheckMemory

IAMDevMemoryAllocator Interface

Tests whether the specific instance (device) of the allocator allocated a memory pointer.

Syntax

HRESULT CheckMemory(
    const BYTE *pBuffer
);

Parameters

pBuffer
[in] Pointer to the allocated memory buffer's address.

Return Value

Returns S_OK if the on-board allocator allocated the memory, or S_FALSE if not. Memory that is on the particular device but not allocated will also return S_FALSE.

Remarks

The hardware filter typically uses this method to test whether the pointer actually points to on-board memory.

IAMDevMemoryAllocator::Free

IAMDevMemoryAllocator Interface

Frees the previously allocated memory.

Syntax

HRESULT Free(
    BYTE *pBuffer
);

Parameters

pBuffer
[in] Pointer to the allocated memory.

Return Value

Returns E_INVALIDARG if the specified allocator didn't allocate the memory (that is, CheckMemory fails).

Remarks

This method frees a block of memory from the pool.

IAMDevMemoryAllocator::GetDevMemoryObject

IAMDevMemoryAllocator Interface

Retrieves an IUnknown interface pointer to a device memory control object that can be aggregated with a custom allocator.

Syntax

HRESULT GetDevMemoryObject(
    IUnknown **ppUnkInner,
    IUnknown *pUnkOuter
);

Parameters

ppUnkInner
[out] Address of a pointer to the newly created control object's own IUnknown. This inner IUnknown interface should be released when the outer object is destroyed. The custom allocator should call the QueryInterface method on this pointer to obtain the IAMDevMemoryControl interface.
pUnkOuter
[in] Pointer to the custom allocator's own IUnknown interface. This interface aggregates the device memory control object inside the custom allocator.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The device memory control object is necessary to aggregate with the custom allocator, because renderers that require the use of on-board memory will query for IAMDevMemoryControl when they receive a new allocator, to verify that the memory is from the same device. This occurs because the hardware filter will receive an IMemAllocator object, which might or might not use the on-board memory. To decide if it is a compatible allocator, the object would query for the IAMDevMemoryControl interface to access specific methods. The IAMDevMemoryControl creates an aggregated object that implements the methods of IAMDevMemoryControl (these are often hardware-specific).

See COM documentation for rules on how the outer object implements aggregation.

IAMDevMemoryAllocator::GetInfo

IAMDevMemoryAllocator Interface

Retrieves information about the memory capabilities.

Syntax

HRESULT GetInfo(
    DWORD *pdwcbTotalFree,
    DWORD *pdwcbLargestFree,
    DWORD *pdwcbTotalMemory,
    DWORD *pdwcbMinimumChunk
);

Parameters

pdwcbTotalFree
[out] Pointer to the total free memory size.
pdwcbLargestFree
[out] Pointer to the returned largest free memory size.
pdwcbTotalMemory
[out] Pointer to the returned total memory size.
pdwcbMinimumChunk
[out] Pointer to the returned minimum chunk size, giving granularity and alignment rules.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

Use this method to find out the total amount of memory available. This method returns values for the entire on-board memory that is available on that device. If multiple filters (devices) share the memory, it will return the amount available to that specific device, which might be a portion of the total amount of on-board memory. This amount will be implementation-specific. For example, the on-board memory manager on the codec might be able to access all 32 megabytes (MB) of memory on the card. However, individual pin implementations of IAMDevMemoryAllocator only report a portion of this memory.


IAMDevMemoryControl Interface

Note This interface has been deprecated. It was defined to support certain older hardware decoders that required that AVI files be read into their hardware memory directly. The interface enables the AVI Parser to allocate memory from the downstream filter but still provide its own allocator. There should be no need for any newer devices to support this interface.

A device memory control object supports IAMDevMemoryControl. This object is aggregated with an IMemAllocator object that is used in the connection. Typically, filters will call the IAMDevMemoryAllocator::GetDevMemoryObject method to obtain a pointer to this interface.

Implement this interface with the IAMDevMemoryAllocator interface when pins need to have greater control of memory allocation.

Use this interface to synchronize the completion of writing data to a memory allocator, and to get the device ID of the on-board memory allocator.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMDevMemoryControl methods | Description
QueryWriteSync | Checks if the memory supported by the allocator requires the use of the WriteSync method.
WriteSync | Used to synchronize with the completed write operation by returning when any data being written to the specified allocator region is fully written into the memory.
GetDevId | Retrieves the device ID of the on-board memory allocator.

IAMDevMemoryControl::GetDevId

IAMDevMemoryControl Interface

Retrieves the device ID of the on-board memory allocator.

Syntax

HRESULT GetDevId(
  DWORD *pdwDevId
  );

Parameters

pdwDevId
[out] Pointer to the device ID.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method retrieves a unique ID that the hardware filter can use to verify that the specified allocator passed uses its on-board memory (because there can be more than one). The ID will be the same one as used to create the allocator object (using CoCreateInstance). For another filter to be able to use the on-board memory, it must have the same device ID as the on-board memory allocator.

IAMDevMemoryControl::QueryWriteSync

IAMDevMemoryControl Interface

Checks if the memory supported by the allocator requires the use of the IAMDevMemoryControl::WriteSync method.

Syntax

HRESULT QueryWriteSync(void);

Return Value

Returns S_OK if the method is required, or S_FALSE otherwise.

Remarks

Not all on-board memory needs to have WriteSync called to synchronize with the completed write. This method is used to check if the call is necessary.

IAMDevMemoryControl::WriteSync

IAMDevMemoryControl Interface

Used to synchronize with the completed write. This method returns when any data being written to the particular allocator region is fully written into the memory.

Syntax

HRESULT WriteSync(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Common return values include:
E_FAIL | A time-out has occurred without this method confirming that data was written.
S_OK | The data was successfully written into memory.
VFW_E_NOT_COMMITTED | The allocator hasn't called the IMemAllocator::Commit method.

Remarks

This method guarantees that all prior write operations to allocated memory have succeeded. Subsequent memory write operations require another call to WriteSync.

This method is implementation dependent, and is used (when necessary) to synchronize memory write operations to the memory. The driver of the on-board memory provides the implementation.

The IAMDevMemoryControl interface is typically found on memory that is accessed through a Peripheral Component Interconnect (PCI) bridge. (A PCI is a local bus for personal computers that provides a high-speed data path between the processor and peripheral devices.) Memory behind a PCI bridge must be synchronized after a memory write operation completes, if another device will access that memory from behind the PCI bridge. This is because the host access to the memory is buffered through the PCI bridge FIFO (first in first out), and the host will assume the write is completed before the bridge actually writes the data. A subsequent action by a device behind the bridge, such as a SCSI controller, might read the memory before the write is completed, if the IAMDevMemoryControl::WriteSync method is not called.


IAMPhysicalPinInfo Interface

Note This interface has been deprecated. It will continue to be supported for backward compatibility with existing applications, but new applications and filters should not use it.

Enables an application or filter to retrieve the type and name of the physical pin. It is implemented on pins that represent physical hardware connections.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMPhysicalPinInfo method | Description
GetPhysicalType | Retrieves the type and name of the physical pin.

IAMPhysicalPinInfo::GetPhysicalType

IAMPhysicalPinInfo Interface

Retrieves the type and name of the physical pin.

Syntax

HRESULT GetPhysicalType(
    long *pType
     LPOLESTR *ppszType
);

Parameters

pType
[out] Pointer to a variable that receives a value indicating the pin's type. The PhysicalConnectorType enumeration defines the pin type values.
ppszType
[out] Address of a pointer to a buffer that receives a human-readable string identifying the pin type.

Return Value

Returns S_OK if a valid physical pin value is found. Otherwise, returns VFW_E_NO_ACCEPTABLE_TYPES.


ICaptureGraphBuilder Interface

Note This interface has been deprecated. It will continue to be supported for backward compatibility with existing applications, but new applications should use the ICaptureGraphBuilder2 interface.

The ICaptureGraphBuilder interface enables you to easily build capture graphs, preview graphs, file recompression graphs, or even unusual custom graphs.

When you use this interface to build a capture graph that uses WDM filters, you need to add additional upstream filters to the graph, such as the TV Tuner and the Analog Video CrossBar. These filters are brought into the filter graph when you call the RenderStream method or the FindInterface method.

Do not implement this interface. Microsoft® DirectShow® implements it for you.

Use this interface in your capture and recompression applications to make it easier to build filter graphs.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
ICaptureGraphBuilder methods | Description
SetFiltergraph | Tells the graph builder object which filter graph to use.
GetFiltergraph | Retrieves the filter graph that the builder is using.
SetOutputFileName | Creates the rendering section of the filter graph, which will save bits to disk with the specified file name.
FindInterface | Looks for the specified interface on the filter, upstream and downstream from the filter, and, optionally, only on the output pin of the given category.
RenderStream | Connects a source filter's pin, of an optionally specified category, to the rendering filter, and optionally through another filter.
ControlStream | Sends stream control messages to the pin of the specified category on one or more capture filters in a graph.
AllocCapFile | Preallocates a capture file to a specified size.
CopyCaptureFile | Copies the valid media data from the preallocated capture file.

ICaptureGraphBuilder::AllocCapFile

ICaptureGraphBuilder Interface

Preallocates a capture file to a specified size.

Syntax

HRESULT AllocCapFile(
    LPCOLESTR lpwstr,
    DWORDLONG dwlSize
);

Parameters

lpwstr
[in] Pointer to a Unicode™ string containing the name of the file to create or resize.
dwSize
[in] Size, in bytes, of the file to be allocated.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The call will fail if the file is read-only. For best capture results, always capture to a defragmented, preallocated capture file that is larger than the size of the capture data.

Note that under the current DirectShow implementation of this interface, a call to this method will be much quicker on a Windows 9x platform than it will be on a Windows NT® 4.x or Windows 2000 platform.

ICaptureGraphBuilder::ControlStream

ICaptureGraphBuilder Interface

Sends stream control messages to the pin of the specified category on one or more capture filters in a graph.

Syntax

HRESULT ControlStream(
    const GUID *pCategory,
    IBaseFilter *pFilter,
    REFERENCE_TIME *pstart,
    REFERENCE_TIME *pstop,
    WORD wStartCookie,
    WORD wStopCookie
);

Parameters

pCategory
[in] Pointer to a GUID specifying the output pin category. Typical values include the following. See AMPROPERTY_PIN_CATEGORY for a list of all pin categories. This value cannot be NULL.
  • PIN_CATEGORY_CAPTURE
  • PIN_CATEGORY_PREVIEW
pFilter
[in] Pointer to an IBaseFilter interface on the filter to control. Specifying NULL controls all capture filters in the graph. You will get one notification for each capture filter.
pstart
[in] Pointer to the start time for capture. NULL means start now. MAX_TIME means cancel previous request, or take no action if there is no previous request.
pstop
[in] Pointer to the stop time for capture. NULL means stop now. MAX_TIME means cancel previous request, or take no action if there is no previous request.
wStartCookie
[in] Specifies a particular value to be sent when the start occurs.
wStopCookie
[in] Specifies a particular value to be sent when the stop occurs.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. The current DirectShow implementation returns S_FALSE if the stop notification is sent before the last sample sent by the capture filter is rendered, otherwise returns S_OK.

If this method returns S_FALSE, the application might want to wait before stopping the filter graph to allow all samples to pass through the graph and be rendered. Otherwise, samples might be lost.

If there are no pins matching the description you provide, or if stream control cannot be supported on all of the indicated pins, this function will return a failure code.

Remarks

Use this method for frame-accurate capture, or for individual control of capture and preview. For example, you could turn off writing of the captured image to disk if you only want to preview the captured image.

This method calls the IAMStreamControl interface on the pins.

This method sends one notification for each filter found with a pin of the specified category.

ICaptureGraphBuilder::CopyCaptureFile

ICaptureGraphBuilder Interface

Copies the valid media data from the preallocated capture file.

Syntax

HRESULT CopyCaptureFile(
    LPOLESTR lpwstrOld,
    LPOLESTR lpwstrNew,
    int fAllowEscAbort,
    IAMCopyCaptureFileProgress *pCallback
);

Parameters

lpwstrOld
[in] Pointer to a Unicode™ string containing the source file name.
lpwstrNew
[in] Pointer to a Unicode string containing the destination file name. Valid data is copied to this file.
fAllowEscAbort
[in] Value indicating whether pressing the ESC key will abort the copy operation. TRUE indicates that it will; FALSE indicates that this method will ignore that keystroke.
pCallback
[in] Optional pointer to an IAMCopyCaptureFileProgress interface that you implement to show the progress (percentage complete) of the copy operation.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The new file will contain only valid data and therefore can be much shorter than the source file. Typically, you will always capture to the same huge preallocated file and use this method to copy the data you want to save from each capture to a new file.

If you specify pCallback, the Progress method on the IAMCopyCaptureFileProgress interface will be called periodically with an integer between 0 and 100 representing the percentage complete.

ICaptureGraphBuilder::FindInterface

ICaptureGraphBuilder Interface

Looks for the specified interface on the filter, upstream and downstream from the filter, and, optionally, only on the output pin of the given category.

Syntax

HRESULT FindInterface(
    const GUID *pCategory,
    IBaseFilter *pf,
    REFIID riid,
    void **ppint
);

Parameters

pCategory
[in] Pointer to a GUID specifying the output pin category. Typical values include the following. See AMPROPERTY_PIN_CATEGORY for a list of all pin categories. NULL indicates search all the output pins regardless of category.
  • PIN_CATEGORY_CAPTURE
  • PIN_CATEGORY_PREVIEW
  • NULL
pf
[in] Pointer to the IBaseFilter interface of the filter.
riid
[in] Reference ID of the desired interface.
ppint
[out] Address of a void pointer. If the interface was found, this method initializes ppint so that it contains the address of a pointer to the found interface. Call the Release method to decrement the reference count when you're done with the interface.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method looks for the interface on the filter, and upstream and downstream of the filter, unless a category is given. If a category is given, it only looks downstream of the output pin of that category. It can be used to find interfaces on renderers, multiplexers, TV tuners, crossbars, and so forth.

If pCategory == &LOOK_UPSTREAM_ONLY, then the graph builder will look upstream of the filter given in parameter pf, but not on the filter itself, nor downstream of the filter.

If pCategory == &LOOK_DOWNSTREAM_ONLY, then the graph builder will look downstream of the filter given in parameter pf, but not on the filter itself, nor upstream of the filter.

For example, capture graphs can have two crossbars in them, a video crossbar (upstream of the video capture filter) and an audio crossbar (upstream of the video crossbar). You can find the video crossbar filter that implements the IAMCrossbar interface, as shown in the following code.

IAMCrossbar *pVideoCrossbar;
FindInterface(NULL, pVideoCaptureFilter, IID_IAMCrossbar, (void **)&pVideoCrossbar);

You can then find the IAMCrossbar filter of the audio crossbar, as shown in the following code.

IBaseFilter *pBaseFilter;
IAMCrossbar *pAudioCrossbar;
pVideoCrossbar->QueryInterface(IID_IBaseFilter, (void **)pBaseFilter);
FindInterface(
    &LOOK_UPSTREAM_ONLY, pBaseFilter, IID_IAMCrossbar, (void **)&pAudioCrossbar);
pBaseFilter->Release();

ICaptureGraphBuilder::GetFiltergraph

ICaptureGraphBuilder Interface

Retrieves the filter graph that the builder is using.

Syntax

HRESULT GetFiltergraph(
    IGraphBuilder **ppfg
);

Parameters

ppfg
[out] Address of a pointer to an IGraphBuilder interface.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

This method increments the reference count on the IGraphBuilder interface; be sure to decrement the reference count on IGraphBuilder by calling the Release method.

ICaptureGraphBuilder::RenderStream

ICaptureGraphBuilder Interface

Connects a source filter's pin, of an optionally specified category, to the rendering filter, and optionally through another filter.

Syntax

HRESULT RenderStream(
    const GUID *pCategory,
    IUnknown *pSource,
    IBaseFilter *pfCompressor,
    IBaseFilter *pfRenderer
);

Parameters

pCategory
[in] Pointer to a GUID specifying which output pin of the source filter to connect. Typical values include the following. See AMPROPERTY_PIN_CATEGORY for a list of all pin categories. NULL indicates render the only output pin, regardless of category.
  • PIN_CATEGORY_CAPTURE
  • PIN_CATEGORY_PREVIEW
  • NULL
pSource
[in] Pointer to an IBaseFilter or an IPin interface representing either the source filter or an output pin. Source filters are typically a file source filter, such as an AVI file source filter or a capture filter.
pfCompressor
[in] Pointer to an IBaseFilter interface representing the optional compression filter.
pfRenderer
[in] Pointer to an IBaseFilter interface representing the renderer. You can use the ppf (multiplexer) parameter from ICaptureGraphBuilder::SetOutputFileName to supply this value.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Returns VFW_S_NOPREVIEWPIN if the capture filter has a capture pin but no preview pin, and you call RenderStream with the &PIN_CATEGORY_PREVIEW category on the capture pin. In this case, RenderStream will render the preview pin of the Smart Tee filter. For more information, see Remarks.

Remarks

If you specify a non-NULL AMPROPERTY_PIN_CATEGORY for pCategory and a capture filter for pSource, this method instantiates and connects additional required upstream filters, such as TV tuners and crossbars. It then renders the capture pin of pSource.

If pSource is a pin, then specify NULL for pCategory and this method renders the stream from that pin.

If the source filter has only one output pin, specify NULL for pCategory.

pSource, pfCompressor, and pfRenderer filters given as parameters must be present in the graph before this method is called.

If you are building a capture graph that is using WDM capture filters, this method will build all necessary upstream filters as well as the downstream filters.

Some capture filters that work with new WDM VPE (Video Port Extension) video capture hardware have VIDEO PORT pins instead of PREVIEW pins meant for previewing. These VIDEO PORT pins do not connect directly to a video renderer, but instead to a special filter called the Overlay Mixer. Your application does not need to worry about this. All you have to do is call RenderStream with &PIN_CATEGORY_PREVIEW and the capture graph builder will correctly render the VIDEO PORT pin through an overlay mixer if that is what is necessary.

When you render a capture or preview pin of a video capture filter (using RenderStream with the &PIN_CATEGORY_CAPTURE or &PIN_CATEGORY_PREVIEW category) and the capture filter has a capture pin but no preview pin, the Smart Tee filter (Qcap.dll) will be used automatically to allow simultaneous capture and preview. For example, calling RenderStream with the &PIN_CATEGORY_CAPTURE category will actually connect a Smart Tee filter to the capture pin of the filter, and then render the capture pin of the Smart Tee. If you then call RenderStream with the &PIN_CATEGORY_PREVIEW category on the capture pin, it will actually render the preview pin of the Smart Tee. If calling RenderStream with &PIN_CATEGORY_PREVIEW results in using the capture pin and a Smart Tee filter, RenderStream will return VFW_S_NOPREVIEWPIN to indicate this. Thus, if FindInterface fails to find a preview interface, you may need to call FindInterface with the &PIN_CATEGORY_PREVIEW category and with the &PIN_CATEGORY_CAPTURE category, because the preview interface can be found by looking downstream of the capture pin of the capture filter.

ICaptureGraphBuilder::SetFiltergraph

ICaptureGraphBuilder Interface

Tells the graph builder object which filter graph to use.

Syntax

HRESULT SetFiltergraph(
    IGraphBuilder *pfg
);

Parameters

pfg
[in] Pointer to an IGraphBuilder interface that specifies the filter graph to use for subsequent calls to the IFilterGraph::AddFilter method.

Return Value

Returns an HRESULT value that depends on the implementation of the interface.

Remarks

The graph builder will automatically create a filter graph if you don't call this method. If you call this method after the graph builder has created its own filter graph, the call will fail.

ICaptureGraphBuilder::SetOutputFileName

ICaptureGraphBuilder Interface

Creates the rendering section of the filter graph, which will save bits to disk with the specified file name.

Syntax

HRESULT SetOutputFileName(
    const GUID *pType,
    LPCOLESTR lpwstrFile,
    IBaseFilter **ppf,
    IFileSinkFilter **pSink
);

Parameters

pType
[in] Pointer to a GUID representing the media subtype. Must be &MEDIASUBTYPE_Avi because AVI is currently the only supported output format.
lpwstrFile
[in] Pointer to a Unicode™ string containing the output file name.
ppf
[out] Address of a pointer to an IBaseFilter interface representing the multiplexer filter. This method increments the reference count on the IBaseFilter interface so you must decrement the reference count by using the Release method on this parameter when done using the filter.
pSink
[out] Address of a pointer to an IFileSinkFilter interface representing the file writer. This method increments the reference count on the IFileSinkFilter interface so you must decrement the reference count using Release when done using the filter.

Return Value

Returns an HRESULT value indicating the status of the operation.
E_FAIL | Failure.
E_INVALIDARG | Invalid argument. Audio-Video Interleaved (AVI) is the only supported output format.
E_OUTOFMEMORY | Out of memory.
E_POINTER | Null pointer argument.
E_UNEXPECTED | Unexpected error occurred.
NOERROR | Success.
S_OK | Instance of the AVI multiplexer filter was successfully created.

Remarks

This method inserts the multiplexer and the file writer into the filter graph and calls IFileSinkFilter::SetFileName to set the output file name.

You can use the ppf parameter returned by this method as the pfRenderer parameter in calls to RenderStream.

You can use the pSink parameter from this method in a call to SetFileName to change the file name set by ICaptureGraphBuilder::SetOutputFileName.


IDirectDrawFactory Interface

Note This interface has been deprecated. New applications should not use it.

The IDirectDrawFactory interface is used to create and enumerate DirectDraw objects that support extended features.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDirectDrawFactory methods | Description
CreateDirectDraw | Creates a DirectDraw object and retrieves pointers to the IUnknown and the IDirectDraw interfaces.
DirectDrawEnumerate | Enumerates the DirectDraw surfaces installed on the system.

IDirectDrawFactory::CreateDirectDraw

IDirectDrawFactory Interface

Creates a DirectDraw object and retrieves a pointer to its IDirectDraw interface.

Syntax

STDMETHOD CreateDirectDraw(
    GUID *pGUID,
    HWND hWnd,
    DWORD dwCoopLevelFlags,
    DWORD dwReserved,
    IUnknown *pUnkOuter,
    IDirectDraw **ppDirectDraw
) PURE;

Parameters

pGUID
[out] Pointer to the globally unique identifier (GUID) that represents the driver to be created. Set this to NULL to indicate the active display driver, or you can pass one of the following flags to restrict the active display driver's behavior for debugging purposes.
DDCREATE_EMULATIONONLY | The DirectDraw object will use emulation for all features; it will not take advantage of any hardware-supported features.
DDCREATE_HARDWAREONLY | The DirectDraw object will never emulate features not supported by the hardware. Attempts to call methods that require unsupported features will fail, returning DDERR_UNSUPPORTED (operation not supported).
hWnd
[in] Window handle to the application.
dwCoopLevelFlags
[in] Application's top-level behavior. Specify one or more of the following flags.
DDSCL_ALLOWMODEX | Enables the use of Mode X display modes. You must use this flag with the DDSCL_EXCLUSIVE and DDSCL_FULLSCREEN flags.
DDSCL_ALLOWREBOOT | Enables the user to reboot by pressing CTRL+ALT+DEL while the application is in full-screen exclusive mode.
DDSCL_EXCLUSIVE | Requests the exclusive level. You must use this flag with the DDSCL_FULLSCREEN flag. At the full screen and exclusive cooperative level, you can use the hardware to its fullest. In this mode, you can set custom and dynamic palettes, change display resolutions, compact memory, and implement page flipping. The exclusive (full-screen) mode does not prevent other applications from allocating surfaces, nor does it exclude them from using DirectDraw or GDI. However, it does prevent applications other than the one currently with exclusive access from changing the display mode or palette.
DDSCL_FULLSCREEN | Indicates that the exclusive-mode owner will be in control of the entire primary surface. You must use this flag with the DDSCL_EXCLUSIVE flag.
DDSCL_NORMAL | Indicates that the application will function as a regular Microsoft® Windows® application. You can't use this flag with the DDSCL_ALLOWMODEX, DDSCL_EXCLUSIVE, or DDSCL_FULLSCREEN flags.
DDSCL_NOWINDOWCHANGES | Indicates that DirectDraw can't minimize or restore the application window when the application is activated.
dwReserved
[in] Reserved for future use. Must be NULL.
pUnkOuter
[in] Must be NULL. Created for future compatibility with COM aggregation features. Currently, CreateDirectDraw returns an error if this parameter is anything but NULL.
ppDirectDraw
[out] Address of a pointer to an IDirectDraw interface.

Return Value

Returns DD_OK if successful, or one of the following error values otherwise.

E_OUTOFMEMORY | There isn't enough memory available to create a DirectDraw object.
DDERR_GENERIC | There is an undefined error condition.
DDERR_UNSUPPORTED | DirectDraw doesn't support the operation.
DDERR_DIRECTDRAWALREADYCREATED | A DirectDrawEx object representing this driver has already been created for this process.
DDERR_INVALIDDIRECTDRAWGUID | The GUID passed to this method is not a valid DirectDrawEx driver identifier.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the method are incorrect.
DDERR_NODIRECTDRAWHW | Hardware-only DirectDrawEx object creation isn't possible; the driver doesn't support any hardware.

Remarks

This method creates DirectDraw objects in the same way that the DirectDraw DirectDrawCreate function is used to create DirectDraw objects, and sets cooperative levels the same way the IDirectDraw2::SetCooperativeLevel method sets cooperative levels. However, in addition to creating a DirectDraw object, successful calls to the IDirectDrawFactory::CreateDirectDraw method will obtain a pointer to the IUnknown and IDirectDraw interfaces, which are exposed on the DirectDraw object. Applications can now query the DirectDraw object to obtain the address of a pointer to an IDirectDraw3 interface.

IDirectDrawFactory::DirectDrawEnumerate

IDirectDrawFactory Interface

Enumerates the available DirectDraw compatible devices in the system.

Syntax

STDMETHOD DirectDrawEnumerate(
    LPDDENUMCALLBACK lpCallback,
    LPVOID lpContext
) PURE;

Parameters

lpCallback
[in] Pointer to a DDEnumCallback function that will be called with a description of each DirectDrawEx-enabled hardware abstraction layer (HAL) installed in the system.
lpContext
[in] Address of an application-defined structure that the system will pass to the callback function each time the function is called.

Return Value

Returns DD_OK if successful, or DDERR_INVALIDPARAMS otherwise.

Remarks

This method functions in a similar manner to the DirectDraw function DirectDrawEnumerate, defined in the DirectX SDK.


IDirectDraw3 Interface

Note This interface has been deprecated. New applications should not use it.

The IDirectDraw3 interface is available to applications that have created a DirectDraw object through the IDirectDrawFactory::CreateDirectDraw method. This method retrieves the address of a pointer to an IDirectDraw interface, which your application can use to query for the IDirectDraw3 interface.

The IDirectDraw3 interface extends the IDirectDraw and the IDirectDraw2 interfaces by adding the IDirectDraw3::GetSurfaceFromDC method and providing new behavior for the IDirectDraw3::CreateSurface method.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDirectDraw3 methods | Description
CreateSurface | Creates a DirectDrawSurface object from a DirectDraw object.
GetSurfaceFromDC | Retrieves a pointer to an IDirectDrawSurface interface from a handle to a device context.

IDirectDraw3::CreateSurface

IDirectDraw3 Interface

Creates a DirectDrawSurface object from a DirectDraw object.

Syntax

STDMETHOD CreateSurface(
    LPDDSURFACEDESC lpDDSurfaceDesc,
    LPDIRECTDRAWSURFACE FAR *lplpDDSurface,
    IUnknown FAR *pUnkOuter
    ) PURE;

Parameters

lpDDSurfaceDesc
[in] Pointer to the DDSURFACEDESC structure that describes the requested surface. You should set any unused members of DDSURFACEDESC to zero before calling this method. A DDSCAPS structure is a member of DDSURFACEDESC.
lplpDDSurface
[out] Address of a pointer to be initialized with a valid DirectDrawSurface pointer if the call succeeds.
pUnkOuter
[in] Pointer to an IUnknown interface on an outer object that will be aggregated with an inner object's IUnknown interface.

Return Value

Returns DD_OK if successful, or one of the following error values otherwise.

DDERR_INCOMPATIBLEPRIMARY | The primary surface creation request does not match the existing primary surface.
DDERR_INVALIDCAPS | One or more of the capability bits passed to the callback function are incorrect.
DDERR_INVALIDOBJECT | DirectDraw received a pointer to an invalid DirectDraw object.
DDERR_INVALIDPARAMS | One or more of the parameters passed to the method are incorrect.
DDERR_INVALIDPIXELFORMAT | The pixel format was invalid as specified.
DDERR_NOALPHAHW | No alpha acceleration hardware is present or available, which caused the requested operation to fail.
DDERR_NOCOOPERATIVELEVELSET | The IDirectDraw2::SetCooperativeLevel method was not called before the surface was created.
DDERR_NODIRECTDRAWHW | Hardware-only DirectDraw object creation isn't possible; the driver doesn't support any hardware.
DDERR_NOEMULATION | Software emulation isn't available.
DDERR_NOEXCLUSIVEMODE | The operation requires the application to have exclusive mode, but the application doesn't have exclusive mode.
DDERR_NOFLIPHW | Flipping visible surfaces isn't supported.
DDERR_NOMIPMAPHW | The operation can't be carried out because no mipmap texture mapping hardware is present or available.
DDERR_NOOVERLAYHW | The operation can't be carried out because no overlay hardware is present or available.
DDERR_NOZBUFFERHW | The operation to create a z-buffer in display memory or to perform a blit using a z-buffer can't be carried out because there is no hardware support for z-buffers.
DDERR_OUTOFMEMORY | DirectDraw doesn't have enough available memory to perform the operation.
DDERR_OUTOFVIDEOMEMORY | DirectDraw doesn't have enough display memory to perform the operation.
DDERR_PRIMARYSURFACEALREADYEXISTS | The application has already created a primary surface.
DDERR_UNSUPPORTEDMODE | The operation isn't supported.

Remarks

Passing in NULL for the pUnkOuter parameter will return the address of a DirectDraw surface in the lplpDDSurface parameter. However, if you pass in a pointer to an outer interface you want to aggregate with an inner interface, you will get back an IUnknown pointer for the lplpDDSurface parameter.

DirectDrawEx now also provides the DDSCAPS_DATAEXCHANGE flag for the dwcaps member of the DDSCAPS structure, which is defined as a combination of DDSCAPS_SYSTEMMEMORY and DDSCAPS_VIDEOMEMORY in Ddrawex.h. When a surface is created using the DDSCAPS_DATAEXCHANGE flag, the surface will be automatically moved into video memory if there is enough video memory available; otherwise, a system memory surface will be created. Also, setting this flag in conjunction with the DDSCAPS_OWNDC flag enables applications to call the IDirectDrawSurface::GetDC method to lock the device context for as long they require, without holding a lock on the surface.

This method calls the IDirectDraw::CreateSurface and IDirectDraw2::CreateSurface methods.

IDirectDraw3::GetSurfaceFromDC

IDirectDraw3 Interface

Retrieves a pointer to an IDirectDrawSurface interface from a handle to a device context.

Syntax

STDMETHOD GetSurfaceFromDC(
  HDC hdc,
  IDirectDrawSurface **ppSurface
  ) PURE;

Parameters

hdc
[in] Handle of the device context (DC).
ppSurface
[out] Address of a pointer to an IDirectDrawSurface interface.

Return Value

Returns S_OK if successful, or one of the following values otherwise.

E_POINTER | Invalid pointer to IDirectDrawSurface.
DDERR_NOTFOUND | The requested item wasn't found.


IDvdControl Interface

Note This interface has been deprecated. It will continue to be supported for backward compatibility with existing applications, but new applications should use IDvdControl2.

The IDvdControl interface controls the playback and search mechanisms of a DVD title that contains one or more video movies.

The DVD file system is very different from a format such as CD-ROM, which contains a linear series of tracks not easily customizable by the author. The author of DVD-formatted media files can control track layout and navigation much more precisely; the media file itself has many parts and control mechanisms, which enables the author to arrange and rearrange the playback order as needed. You can locate a specific portion of a file by time (in hours, minutes, seconds, and frames) or by chapter value.

A media file is made up of a list of program chains (PGCs), each of which is made up of a list of programs, each of which is made up of a list of cells, each of which is made up of a list of video object units (VOBUs), each of which is made up of a list of packs, and each of which is made up of actual MPEG data.

To obtain a copy of the DVD-Video specification, "DVD Specifications for Read-Only Disc, Part 3, Video Specifications," contact Toshiba Corporation at 1-1, Shibaura 1-Chrome, Minato-ku, Tokyo 105-01, Japan, Tel. +81-3-5444-9580, Fax. +81-3-5444-9430.

This interface is implemented by the Microsoft® DirectShow® DVD Navigator to enable DVD playback.

Use this interface to control playback (set root drive, play, stop, and so forth) or use DVD-specific functionality such as menus and buttons when playing DVD-Video files.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDvdControl methods | Description
TitlePlay | Finds the media file with the specified title index and plays it back.
ChapterPlay | Plays the media file with the specified title index and chapter value.
TimePlay | Plays the media file with the specified title index, starting at the specified time.
StopForResume | Transitions playback to the DVD_DOMAIN_Stop state after saving resume information.
GoUp | Halts playback of the current media file and starts playback of the designated previous program chain (PGC).
TimeSearch | Halts playback of the current chapter and starts playback from the specified time in the same media file.
ChapterSearch | Halts playback of the current chapter and starts playback from the specified chapter value in the same media file.
PrevPGSearch | Halts playback of the current program and starts playback from the previous program within the program chain (PGC).
TopPGSearch | Halts playback of the current program and restarts playback of the current program within the program chain (PGC).
NextPGSearch | Halts playback of the current program and starts playback from the next program within the program chain (PGC).
ForwardScan | Searches forward through the current disc at the specified speed.
BackwardScan | Searches backward through the current disc at the specified speed.
MenuCall | Displays the specified menu on the screen.
Resume | Returns to playing back a title from a menu.
UpperButtonSelect | Selects the upper directional button from the displayed menu.
LowerButtonSelect | Selects the lower directional button from the displayed menu.
LeftButtonSelect | Selects the left directional button from the displayed menu.
RightButtonSelect | Selects the right directional button from the displayed menu.
ButtonActivate | Activates the selected button.
ButtonSelectAndActivate | Selects and activates the specified button.
StillOff | Resumes playback, canceling still mode.
PauseOn | Pauses the current media file playback.
PauseOff | Unpauses the current media file playback.
MenuLanguageSelect | Sets the displayed language for navigation menus.
AudioStreamChange | Sets the current audio stream.
SubpictureStreamChange | Selects the new subpicture stream and enables or disables it for display.
AngleChange | Sets the new display angle.
ParentalLevelSelect | Sets the parental access level for the current media file.
ParentalCountrySelect | Sets the current country for controlling parental access levels.
KaraokeAudioPresentationModeChange | Sets the audio playback mode to karaoke.
VideoModePreferrence | Sets the video display mode the user prefers.
SetRoot | Sets the root directory containing the DVD-Video volume.
MouseActivate | Selects and activates a DVD button in response to a mouse click.
MouseSelect | Selects a DVD button in response to mouse movement.
ChapterPlayAutoStop | Start playing at the specified chapter within the specified title and play the number of chapters specified.

IDvdControl::AngleChange

IDvdControl Interface

Sets the new display angle.

Syntax

HRESULT AngleChange(
    ULONG ulAngle
);

Parameters

ulAngle
[in] Value of the new angle, which must be from 1 through 9.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

IDvdControl::AudioStreamChange

IDvdControl Interface

Sets the current audio stream.

Syntax

HRESULT AudioStreamChange(
    ULONG nAudio
);

Parameters

nAudio
[in] Value that specifies the audio track to use, which must be from 0 through 7.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

AudioStreamChange affects the audio of the current Video Title Set (VTS). When called from within a menu, this method sets the audio stream of the title from which the menu was called.

IDvdControl::BackwardScan

IDvdControl Interface

Searches backward through the current disc at the specified speed.

Syntax

HRESULT BackwardScan(
    double dwSpeed
);

Parameters

dwSpeed
[in] Value that specifies how quickly DirectShow will search through the media file. This value is a multiplier, where 1.0 is the authored speed, so a value of 2.5 will search backward at two and one-half times the authored speed, while a value of 0.5 will search backward at half the authored speed. The actual speed of playback depends on the capabilities of the video decoder, and might differ from the specified rate.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::ButtonActivate

IDvdControl Interface

Activates the selected button.

Syntax

HRESULT ButtonActivate(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

"Selecting" a DVD button simply highlights the button but does not "activate" the button. Selecting is the Microsoft® Windows® equivalent of tabbing to a button but not pressing the SPACEBAR or ENTER key. Activating is the Windows equivalent of pressing the SPACEBAR or ENTER key after tabbing to a button.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

IDvdControl::ButtonSelectAndActivate

IDvdControl::ButtonSelectAndActivate

IDvdControl Interface

Selects and activates the specified button.

Syntax

HRESULT ButtonSelectAndActivate(
    ULONG uiButton
);

Parameters

uiButton
[in] Value that specifies the button that will be selected and activated, which must be from 1 through 36.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

Electronic remote control devices typically have a number of buttons that activate various functions of a DVD playback unit. Typically, you call this method when a user clicks a button on the control device; DirectShow then indicates that the button was selected (by playing a sound or changing a graphic, for example) and calls methods appropriate to which button was selected, such as ButtonActivate.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::ChapterPlay

IDvdControl Interface

Plays the media file with the specified title index and chapter value.

Syntax

HRESULT ChapterPlay(
    ULONG uiTitle,
    ULONG uiChapter
);

Parameters

uiTitle
[in] Value that specifies the title number DirectShow will play back; this value must be from 1 through 99.
uiChapter
[in] Value that specifies the chapter within the specified title where DirectShow will start playback; this value must be from 1 through 999.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

IDvdControl::ChapterPlayAutoStop

IDvdControl Interface

Instructs the DVD player to start playing at the specified chapter within the specified title and play the number of chapters specified.

Syntax

HRESULT ChapterPlayAutoStop(
    ULONG ulTitle,
    ULONG ulChapter,
    ULONG ulChaptersToPlay
);

Parameters

ulTitle
[in] Title number for playback.
ulChapter
[in] Chapter number to start playback.
ulChaptersToPlay
[in] Number of chapters to play from the start chapter.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

Chapters range from 1 through 999. See EC_DVD_CHAPTER_AUTOSTOP for more information.

IDvdControl::ChapterSearch

IDvdControl Interface

Halts playback of the current chapter and starts playback from the specified chapter within the same title.

Syntax

HRESULT ChapterSearch(
    ULONG Chapter
);

Parameters

Chapter
Chapter value that specifies the point where playback will begin.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::ForwardScan

IDvdControl Interface

Searches forward through the current disc at the specified speed.

Syntax

HRESULT ForwardScan(
    double dwSpeed
);

Parameters

dwSpeed
[in] Value that specifies how quickly DirectShow will search through the media file. This value is a multiplier, where 1.0 is the authored speed, so a value of 2.5 will search forward at two and one-half times the authored speed, while a value of 0.5 will search forward at half the authored speed. Note that the actual speed of playback depends on the capabilities of the video decoder, and might differ from the specified rate.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::GoUp

IDvdControl Interface

Halts playback of the current media file and starts playback of the designated previous program chain (PGC).

Syntax

HRESULT GoUp(void);

Return Value

Returns an HRESULT value.

Remarks

Each PGC is associated with a previous PGC at authoring time, which this method sets as the new playback file.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::KaraokeAudioPresentationModeChange

IDvdControl Interface

Sets the audio playback mode to karaoke.

Syntax

HRESULT KaraokeAudioPresentationModeChange(
    ULONG ulMode
);

Parameters

ulMode
[in] Requested audio playback mode.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

Karaoke support is currently not implemented.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

IDvdControl::LeftButtonSelect

IDvdControl Interface

Selects the left directional button from the displayed menu.

Syntax

HRESULT LeftButtonSelect(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

On physical or electronic remote control devices, there is often a group of four directional buttons used for certain types of operations (such as menu navigation). This method tells DirectShow that something (the user, probably) triggered the left directional button.

"Selecting" a DVD button simply highlights the button but does not "activate" the button. Selecting is the Windows equivalent of tabbing to a button but not pressing the SPACEBAR or ENTER key. Activating is the Windows equivalent of pressing the SPACEBAR or ENTER key after tabbing to a button.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::LowerButtonSelect

IDvdControl Interface

Selects the lower directional button from the displayed menu.

Syntax

HRESULT LowerButtonSelect(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

On physical or electronic remote control devices, there is often a group of four directional buttons used for certain types of operations (such as menu navigation). This method tells DirectShow that something (the user, probably) triggered the lower directional button.

"Selecting" a DVD button simply highlights the button but does not "activate" the button. Selecting is the Windows equivalent of tabbing to a button but not pressing the SPACEBAR or ENTER key. Activating is the Windows equivalent of pressing the SPACEBAR or ENTER key after tabbing to a button.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::MenuCall

IDvdControl Interface

Displays the specified menu on the screen.

Syntax

HRESULT MenuCall(
    DVD_MENU_ID MenuID
);

Parameters

MenuID
[in] Value that specifies the menu to display. Member of the DVD_MENU_ID enumerated data type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

IDvdControl::MenuLanguageSelect

IDvdControl Interface

Sets the displayed language for navigation menus.

Syntax

HRESULT MenuLanguageSelect(
    LCID LanguageCode
);

Parameters

LanguageCode
Value that specifies the new language.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method selects the default language for menus.

This method returns an error unless the domain is DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

Applications specify languages with standard Windows LCIDs.

IDvdControl::MouseActivate

IDvdControl Interface

Selects and activates a DVD button in response to a mouse click.

Syntax

HRESULT MouseActivate(
    POINT point );

Parameters

point
[in] Specified point within the display window.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method checks the specified point within the display window to see if it is within a current DVD button's highlight rectangle. If it is, this method selects and then activates the button.

DVD buttons do not all necessarily have highlight rectangles. Button rectangles can overlap, and the rectangles do not always correspond to the visual representation of DVD buttons.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::MouseSelect

IDvdControl Interface

Selects a DVD button in response to mouse movement.

Syntax

HRESULT MouseSelect(
    POINT point );

Parameters

point
[in] Specified point within the display window.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

This method checks the specified point within the display window to see if it is within a current DVD button's highlight rectangle. If it is, this method selects the button.

DVD buttons do not all necessarily have highlight rectangles. Button rectangles can overlap, and the rectangles do not always correspond to the visual representation of DVD buttons.

IDvdControl::NextPGSearch

IDvdControl Interface

Halts playback of the current program and starts playback from the next program within the program chain (PGC).

Syntax

HRESULT NextPGSearch(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

A program is usually equivalent to a chapter, and a PGC is usually equivalent to a title. In the case of One_Sequential_PGC_Titles, each program is required to be a chapter and each title has only one PGC, but in other cases (especially with random/shuffle PGCs and parental blocks) there can be more than one program between chapters and there can be more than one PGC in a title.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::ParentalCountrySelect

IDvdControl Interface

Sets the current country for controlling parental access levels.

Syntax

HRESULT ParentalCountrySelect(
    WORD wCountry
);

Parameters

wCountry
[in] Value that specifies the current country according to the Alpha-2 Code defined in ISO3166. See Remarks.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

The ISO3166 2-letter country codes in the wCountry parameter must be supplied to this method as a WORD. The conversion is demonstrated for the United States (US) in the following line of code.

WORD wCountry  =  ( WORD( 'U' ) << 8 ) | 'S';

See Also

IDVDControl::ParentalLevelSelect

IDvdControl::ParentalLevelSelect

IDvdControl Interface

Sets the parental access level for the current media file.

Syntax

HRESULT ParentalLevelSelect(
    ULONG ulParentalLevel
);

Parameters

ulParentalLevel
Value that specifies the current media file parental access level. Should be a value from 1 to 8, inclusive. Predefined parental levels are as follows:
1 | The rating is G, General.
3 | The rating is PG, Parental Guidance Suggested.
4 | The rating is PG-13, Parental Guidance Suggested, not recommended for those under 13.
6 | The rating is R, Restricted.
7 | The rating is NC-17.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

This method sets the current user's access level; this access level determines what media files the user can play back. Higher levels can play lower-level content; lower levels can't play higher-level content. For example, adults can watch child-safe content, but children can't watch adult content.

The DVD Navigator filter provides no restriction on setting the parental level. DVD player applications can enforce restrictions on the parental level setting, such as providing password protection for raising the current parental level. Parental management in the DVD Navigator is disabled by default.

To disable parental management, pass 0xffffffff for ulParentalLevel. If parental management is disabled, then the player will play the first program chain (PGC) in a parental block regardless of parental IDs.

See Also

IDVDControl::ParentalCountrySelect

IDvdControl::PauseOff

IDvdControl Interface

Resumes playback of the current media file after a pause.

Syntax

HRESULT PauseOff(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

If the media file was not paused in playback, this method does nothing.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

IDvdControl::PauseOn

IDvdControl::PauseOn

IDvdControl Interface

Pauses the current media file playback.

Syntax

HRESULT PauseOn(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method freezes playback and any internal timers, similar to IMediaControl::Pause. If the media file was not running, this method does nothing.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

See Also

IDvdControl::PauseOff

IDvdControl::PrevPGSearch

IDvdControl Interface

Halts playback of the current program and starts playback from the previous program within the program chain (PGC).

Syntax

HRESULT PrevPGSearch(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

A program is usually equivalent to a chapter, and a PGC is usually equivalent to a title. In the case of One_Sequential_PGC_Titles, each program is required to be a chapter and each title has only one PGC, but in other cases (especially with random/shuffle PGCs and parental blocks) there can be more than one program between chapters and there can be more than one PGC in a title.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::Resume

IDvdControl Interface

Returns to playing back a title from a menu.

Syntax

HRESULT Resume(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

If the file is stopped or already running, this method does nothing.

This method returns to title playback in DVD_DOMAIN_Title. Applications typically call this method after MenuCall which puts the DVD Navigator in DVD_DOMAIN_VideoTitleSetMenu or DVD_DOMAIN_VideoManagerMenu.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu or DVD_DOMAIN_VideoTitleSetMenu. For more information, see DVD_DOMAIN.

IDvdControl::RightButtonSelect

IDvdControl Interface

Selects the right directional button from the displayed menu.

Syntax

HRESULT RightButtonSelect(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

On physical or electronic remote control devices, there is often a group of four directional buttons used for certain types of operations (such as menu navigation). This method tells DirectShow that something (the user, probably) triggered the right directional button.

"Selecting" a DVD button simply highlights the button but does not "activate" the button. Selecting is the Windows equivalent of tabbing to a button but not pressing the SPACEBAR or ENTER key. Activating is the Windows equivalent of pressing the SPACEBAR or ENTER key after tabbing to a button.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::SetRoot

IDvdControl Interface

Sets the root directory containing the DVD-Video volume.

Syntax

HRESULT SetRoot(
    LPCWSTR pszPath
);

Parameters

pszPath
[in] Pointer to the directory name to set as the root directory.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

If you haven't set the root directory before calling IDvdControl::TitlePlay, the first drive starting from C: that contains a VIDEO_TS directory in the top level directory will be used as the root.

IDvdControl::StillOff

IDvdControl Interface

Resumes playback, canceling still mode.

Syntax

HRESULT StillOff(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

If the display image was not in still-store mode, this method does nothing.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::StopForResume

IDvdControl Interface

Transitions playback to the DVD_DOMAIN_Stop state after saving resume information.

Syntax

HRESULT StopForResume(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

If no file is playing or paused, this method does nothing.

The DVD Navigator filter transfers to the stopped state, but the filter graph remains in the DirectShow run state.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::SubpictureStreamChange

IDvdControl Interface

Selects the new subpicture stream and enables or disables it for display.

Syntax

HRESULT SubpictureStreamChange(
    ULONG nSubPicture,
    BOOL bDisplay
);

Parameters

nSubPicture
Value that specifies the source of the subpicture, which must be from 0 through 32, or 63.
0-31 | Indicates that the stream is valid.
32 | Enables you to toggle the display without changing the current stream (that is, change bDisplay without altering the current stream).
63 | Indicates that the stream is the dummy stream.
bDisplay
Value that specifies whether the subpicture is enabled; TRUE makes the subpicture visible and FALSE hides it.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

IDvdControl::TimePlay

IDvdControl Interface

Plays the media file with the specified title index, starting at the specified time.

Syntax

HRESULT TimePlay(
    ULONG uiTitle,
    ULONG bcdTime
);

Parameters

uiTitle
Value that specifies the title number DirectShow will play back; this value must be from 1 through 99.
bcdTime
Pointer to the DVD_TIMECODE structure where DirectShow will start playback.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

IDvdControl::TimeSearch

IDvdControl Interface

Halts playback of the current chapter and starts playback from the specified time in the same media file.

Syntax

HRESULT TimeSearch(
    ULONG bcdTime
);

Parameters

bcdTime
Pointer to the DVD_TIMECODE structure where DirectShow will start playback.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::TitlePlay

IDvdControl Interface

Finds the media file with the specified title index and plays it back.

Syntax

HRESULT TitlePlay(
    ULONG uiTitle
);

Parameters

uiTitle
Value that specifies the title number DirectShow will play back; this value must be from 1 through 99.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.

IDvdControl::TopPGSearch

IDvdControl Interface

Halts playback of the current program and restarts playback of the current program within the program chain (PGC).

Syntax

HRESULT TopPGSearch(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
E_UNEXPECTED | DVD is not initialized.
S_OK | Success.

Remarks

A program is usually equivalent to a chapter, and a PGC is usually equivalent to a title. In the case of One_Sequential_PGC_Titles, each program is required to be a chapter and each title has only one PGC, but in other cases (especially with random/shuffle PGCs and parental blocks) there can be more than one program between chapters and there can be more than one PGC in a title.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::UpperButtonSelect

IDvdControl Interface

Selects the upper directional button from the displayed menu.

Syntax

HRESULT UpperButtonSelect(void);

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_NOTIMPL | Method is not supported.
S_OK | Success.

Remarks

On physical or electronic remote control devices, there is often a group of four directional buttons used for certain types of operations (such as menu navigation). This method tells DirectShow that something (the user, probably) triggered the upper directional button.

"Selecting" a DVD button simply highlights the button but does not "activate" the button. Selecting is the Windows equivalent of tabbing to a button but not pressing the SPACEBAR or ENTER key. Activating is the Windows equivalent of pressing the SPACEBAR or ENTER key after tabbing to a button.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdControl::VideoModePreferrence

IDvdControl Interface

Sets the video display mode the user prefers.

Syntax

HRESULT VideoModePreferrence(
    ULONG ulPreferredDisplayMode
);

Parameters

ulPreferredDisplayMode
[in] Value that specifies the new display mode for DVD content. Member of the DVD_PREFERRED_DISPLAY_MODE enumerated data type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_NOTIMPL | Method is not supported.
S_OK | Success.

Remarks

This method changes the default video window's aspect ratio, and can also specify a default aspect ratio conversion mechanism.

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, DVD_DOMAIN_Title, or DVD_DOMAIN_Stop. For more information, see DVD_DOMAIN.


IDvdInfo Interface

Note This interface has been deprecated. It will continue to be supported for backward compatibility with existing applications, but new applications should use IDvdInfo2.

The IDvdInfo interface enables an application to query for attributes of available DVD titles and the DVD player status. It also allows for control of a DVD player beyond Annex J in the DVD specification.

Do not implement this interface; Microsoft® DirectShow® implements it for you.

Use this interface in your application to retrieve details about a DVD-Video or about the current state of the DVD player filter graph.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDvdInfo methods | Description
GetCurrentDomain | Retrieves the current DVD domain of the DVD player.
GetCurrentLocation | Retrieves the current playback location.
GetTotalTitleTime | Retrieves the total playback time for the current title.
GetCurrentButton | Retrieves the number of available buttons and the currently selected button number.
GetCurrentAngle | Retrieves the number of available angles and the currently selected angle number.
GetCurrentAudio | Retrieves the number of available audio streams and the number of the currently selected audio stream.
GetCurrentSubpicture | Retrieves the number of available subpicture streams, the currently selected subpicture stream number, and whether the subpicture display is disabled.
GetCurrentUOPS | Retrieves which IDvdControl methods are valid.
GetAllSPRMs | Retrieves the current contents of all system parameter registers (SPRMs).
GetAllGPRMs | Retrieves the current contents of all general parameter registers (GPRMs).
GetAudioLanguage | Retrieves the language of the specified audio stream within the current title.
GetSubpictureLanguage | Retrieves the language of the specified subpicture stream within the current title.
GetTitleAttributes | Retrieves attributes of all video, audio, and subpicture streams for the specified title, including menus.
GetVMGAttributes | Retrieves attributes of all video, audio, and subpicture streams for video manager (VMG) menus.
GetCurrentVideoAttributes | Retrieves the current video attributes for the current title or menu.
GetCurrentAudioAttributes | Retrieves the attributes for the current audio stream in the current title or menu.
GetCurrentSubpictureAttributes | Retrieves the attributes for the current subpicture stream in the current title or menu.
GetCurrentVolumeInfo | Retrieves the current DVD volume information.
GetDVDTextInfo | Retrieves the TXTDT_MG structure, which can contain text descriptions for title name, volume name, producer name, vocalist name, and so on, in various languages.
GetPlayerParentalLevel | Retrieves the current parental level and country code settings for the DVD player.
GetNumberOfChapters | Retrieves the number of chapters that are defined for a given title.
GetTitleParentalLevels | Retrieves the parental levels that are defined for a particular title.
GetRoot | Retrieves the root directory that is set in the player.

IDvdInfo::GetAllGPRMs

IDvdInfo Interface

Retrieves the current contents of all general parameter registers (GPRMs).

Syntax

HRESULT GetAllGPRMs(
    GPRMARRAY *pRegisterArray
    );

Parameters

pRegisterArray
[out] Pointer to the retrieved array of general parameter registers.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

Use of GPRMs is title specific. GPRMs are general parameter registers. For an explanation of GPRMs, see the DVD specifications.

IDvdInfo::GetAllSPRMs

IDvdInfo Interface

Retrieves the current contents of all system parameter registers (SPRMs).

Syntax

HRESULT GetAllSPRMs(
    SPRMARRAY *pRegisterArray
    );

Parameters

pRegisterArray
[out] Pointer to the retrieved array of system parameter registers.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

For use of individual registers, see the DVD-Video specification.

IDvdInfo::GetAudioLanguage

IDvdInfo Interface

Retrieves the language of the specified audio stream within the current title.

Syntax

HRESULT GetAudioLanguage(
    ULONG nStream,
    LCID *pLanguage
    );

Parameters

nStream
[in] Stream number.
pLanguage
[out] Pointer to the retrieved language.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

This method does not return languages for menus. This method sets the value pointed to by pLanguage to zero if the stream does not include language. Call the Win32 GetLocaleInfo function as follows to create a human-readable string name from pLanguage. LOCALE_SENGLANGUAGE is the locale information type, pszString is a pointer to a buffer to receive the requested data, and cbSize specifies the size of pszString.

GetLocaleInfo(*pLanguage, LOCALE_SENGLANGUAGE, pszString, cbSize);

IDvdInfo::GetCurrentAngle

IDvdInfo Interface

Retrieves the number of available angles and the currently selected angle number.

Syntax

HRESULT GetCurrentAngle(
    ULONG *pnAnglesAvailable,
    ULONG *pnCurrentAngle
    );

Parameters

pnAnglesAvailable
[out] Pointer to the retrieved number of available angles. If the value pointed to equals 1, then the current video does not contain multiple angles.
pnCurrentAngle
[out] Pointer to the retrieved current angle number.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

Angles are interleaved video streams that presumably contain the same scene shot from different camera angles.

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdInfo::GetCurrentAudio

IDvdInfo Interface

Retrieves the number of available audio streams and the number of the currently selected audio stream.

Syntax

HRESULT GetCurrentAudio(
    ULONG *pnStreamsAvailable,
    ULONG *pnCurrentStream
    );

Parameters

pnStreamsAvailable
[out] Pointer to the retrieved number of available audio streams
pnCurrentStream
[out] Pointer to the current stream number.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdInfo::GetCurrentAudioAttributes

IDvdInfo Interface

Retrieves the attributes for the current audio stream in the current title or menu.

Syntax

HRESULT GetCurrentAudioAttributes(
    DVD_AudioATR *pATR
    );

Parameters

pATR
[out] Pointer to the retrieved audio attributes.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

For information about the DVD_AudioATR data type, see the DVD-Video specification.

IDvdInfo::GetCurrentButton

IDvdInfo Interface

Retrieves the number of available buttons and the currently selected button number.

Syntax

HRESULT GetCurrentButton(
    ULONG *pnButtonsAvailable,
    ULONG *pnCurrentButton
    );

Parameters

pnButtonsAvailable
[out] Pointer to the number of buttons available.
pnCurrentButton
[out] Pointer to the number of the current button.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

If buttons are not present this method returns zero for both pnButtonsAvailable and pnCurrentButton.

This method is valid in any domain. For more information, see DVD_DOMAIN.

IDvdInfo::GetCurrentDomain

IDvdInfo Interface

Retrieves the current DVD domain of the DVD player.

Syntax

HRESULT GetCurrentDomain(
    DVD_DOMAIN *pDomain
    );

Parameters

pDomain
[out] Pointer to the current domain that is a member of the DVD_DOMAIN enumerated type.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

IDvdInfo::GetCurrentLocation

IDvdInfo Interface

Retrieves the current playback location.

Syntax

HRESULT GetCurrentLocation(
    DVD_PLAYBACK_LOCATION *pLocation
    );

Parameters

pLocation
[out] Pointer to the retrieved playback location information in a DVD_PLAYBACK_LOCATION structure.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

The default implementation of this method returns E_UNEXPECTED if the current domain is not DVD_DOMAIN_Title.

Remarks

This method retrieves information sufficient to restart playback of a video from the current playback location in titles that don't explicitly disable seeking to the current location.

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdInfo::GetCurrentSubpicture

IDvdInfo Interface

Retrieves the number of available subpicture streams, the currently selected subpicture stream number, and whether the subpicture display is disabled.

Syntax

HRESULT GetCurrentSubpicture(
    ULONG *pnStreamsAvailable,
    ULONG *pnCurrentStream,
    BOOL *pIsDisabled
    );

Parameters

pnStreamsAvailable
[out] Pointer to the retrieved number of available subpicture streams.
pnCurrentStream
[out] Pointer to the retrieved number of the currently selected subpicture stream.
pIsDisabled
[out] Pointer to a value indicating whether the subpicture display is disabled.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

Subpicture streams authored as forcedly activated streams will be displayed even if the application has disabled subpicture display with the IDvdControl::SubpictureStreamChange method.

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

IDvdInfo::GetCurrentSubpictureAttributes

IDvdInfo Interface

Retrieves the attributes for the current subpicture stream in the current title or menu.

Syntax

HRESULT GetCurrentSubpictureAttributes(
    DVD_SubpictureATR *pATR
    );

Parameters

pATR
[out] Pointer to the retrieved subpicture attributes.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_FAIL | The specified subpicture has no attributes.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

For information about DVD_SubpictureATR, see the DVD-Video specification.

IDvdInfo::GetCurrentUOPS

IDvdInfo Interface

Retrieves which IDvdControl methods are currently valid.

Syntax

HRESULT GetCurrentUOPS(
    VALID_UOP_SOMTHING_OR_OTHER *pUOP
    );

Parameters

pUOP
[out] Pointer to a DWORD value containing bits for all user operations (UOP). Each bit in the DWORD represents the state (valid or not valid) of a user operation. If the bit corresponding to a user operation is set, then that user operation is prohibited. For more information, see Remarks.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

The value of pUOP is a bit field defined as follows:

Bit | Flag | User function
0 | UOP_FLAG_Title_Or_Time_Play | TitlePlay, TimePlay
1 | UOP_FLAG_Chapter_Search_Or_Play | ChapterSearch, ChapterPlay
2 | UOP_FLAG_Title_Play | TitlePlay
3 | UOP_FLAG_Stop | StopForResume
4 | UOP_FLAG_GoUp | GoUp
5 | UOP_FLAG_Time_Or_Chapter_Search | TimeSearch, ChapterSearch
6 | UOP_FLAG_Prev_Or_Top_PG_Search | PrevPGSearch, TopPGSearch
7 | UOP_FLAG_Next_PG_Search | NextPGSearch
8 | UOP_FLAG_Forward_Scan | ForwardScan
9 | UOP_FLAG_Backward_Scan | BackwardScan
10 | UOP_FLAG_Title_Menu_Call | MenuCall with a parameter value of 2 (DVD_MENU_Title)
11 | UOP_FLAG_Root_Menu_Call | MenuCall with a parameter value of 3 (DVD_MENU_Root)
12 | UOP_FLAG_SubPic_Menu_Call | MenuCall with a parameter value of 4 (DVD_MENU_Subpicture)
13 | UOP_FLAG_Audio_Menu_Call | MenuCall with a parameter value of 5 (DVD_MENU_Audio)
14 | UOP_FLAG_Angle_Menu_Call | MenuCall with a parameter value of 6 (DVD_MENU_Angle)
15 | UOP_FLAG_Chapter_Menu_Call | MenuCall with a parameter value of 7 (DVD_MENU_Chapter)
16 | UOP_FLAG_Resume | Resume
17 | UOP_FLAG_Button_Select_Or_Activate | UpperButtonSelect, LowerButtonSelect, LeftButtonSelect, RightButtonSelect, ButtonActivate, ButtonSelectAndActivate
18 | UOP_FLAG_Still_Off | StillOff
19 | UOP_FLAG_Pause_On | PauseOn, MenuLanguageSelect
20 | UOP_FLAG_Audio_Stream_Change | AudioStreamChange
21 | UOP_FLAG_SubPic_Stream_Change | SubpictureStreamChange
22 | UOP_FLAG_Angle_Change | AngleChange, ParentalLevelSelect
23 | UOP_FLAG_Karaoke_Audio_Pres_Mode_Change | KaraokeAudioPresentationModeChange
24 | UOP_FLAG_Video_Pres_Mode_Change | VideoModePreferrence

This method is useful because DVD titles can enable or disable individual user operations at almost any point during playback.

IDvdInfo::GetCurrentVideoAttributes

IDvdInfo Interface

Retrieves the current video attributes for the current title or menu.

Syntax

HRESULT GetCurrentVideoAttributes(
    DVD_VideoATR *pATR
    );

Parameters

pATR
[out] Pointer to the retrieved video attributes.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method returns an error unless the domain is DVD_DOMAIN_VideoManagerMenu, DVD_DOMAIN_VideoTitleSetMenu, or DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

For information about DVD_VideoATR, see the DVD-Video specification.

IDvdInfo::GetCurrentVolumeInfo

IDvdInfo Interface

Retrieves the current DVD volume information.

Syntax

HRESULT GetCurrentVolumeInfo(
    ULONG *pNumOfVol,
    ULONG *pThisVolNum,
    DVD_DISC_SIDE *pSide,
    ULONG *pNumOfTitles
    );

Parameters

pNumOfVol
[out] Pointer to the retrieved number of volumes in the volume set.
pThisVolNum
[out] Pointer to the retrieved volume number for this root directory.
pSide
[out] Pointer to the retrieved current disc side (DVD_DISC_SIDE).
pNumOfTitles
[out] Pointer to the retrieved number of titles available in this volume.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

IDvdInfo::GetDVDTextInfo

IDvdInfo Interface

Retrieves the TXTDT_MG structure, which can contain text descriptions for title name, volume name, producer name, vocalist name, and so on, in various languages.

Syntax

HRESULT GetDVDTextInfo(
    BYTE *pTextManager,
    ULONG cbBufSize,
    ULONG *pcbActualSize
    );

Parameters

pTextManager
[out, size_is(cbBufSize)] Pointer to the retrieved text manager.
cbBufSize
[in] Size of the buffer for pTextManager, in bytes.
pcbActualSize
[out] Pointer to a value containing the number of bytes of data returned.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

If the supplied buffer size in cbBufSize is too small for the data, (for example if cbBufSize equals zero), then this method returns E_OUTOFMEMORY and sets the value pointed to by pcbActualSize to the required size.

For more information, refer to Section 4.1.6 and Annex A of the DVD-Video specification.

IDvdInfo::GetNumberOfChapters

IDvdInfo Interface

Retrieves the number of chapters that are defined for a given title.

Syntax

HRESULT GetNumberOfChapters(
    ULONG ulTitle,
    ULONG *pNumberOfChapters
    );

Parameters

ulTitle
[in] Title for which to retrieve the number of chapters.
pNumberOfChapters
[out] Pointer to the retrieved number of chapters for the specified title.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

IDvdInfo::GetPlayerParentalLevel

IDvdInfo Interface

Retrieves the current parental level and country code settings for the DVD player.

Syntax

HRESULT GetPlayerParentalLevel(
    ULONG *pParentalLevel,
    ULONG *pCountryCode
    );

Parameters

pParentalLevel
[out] Pointer to a value indicating the current parental level.
pCountryCode
[out] Pointer to a value indicating the current country code.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

For the defined parental levels, see Table 3.3.4-1 of the DVD-Video specification .

Valid parental levels are 1 through 8 if parental management is enabled, 0xffffffff if parental management is disabled.

For the country codes, see ISO3166 : Alpha-2 Code.

IDvdInfo::GetRoot

IDvdInfo Interface

Retrieves the root directory that is set in the player.

Syntax

HRESULT GetRoot(
    LPSTR pRoot,
    ULONG cbBufSize,
    ULONG *pcbActualSize
    );

Parameters

pRoot
[out, size_is(cbBufSize)] Pointer to the buffer to receive the root string. Note that the root string uses ANSI characters, despite the COM convention for passing Unicode™-style strings.
cbBufSize
[in] Size of buffer passed in, in bytes.
pcbActualSize
[out] Pointer to a value containing the size of the actual data returned.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

If a valid root was found, this method returns the root string. Otherwise, it returns zero for pcbActualSize, indicating that a valid root directory has not been found or initialized.

IDvdInfo::GetSubpictureLanguage

IDvdInfo Interface

Retrieves the language of the specified subpicture stream within the current title.

Syntax

HRESULT GetSubpictureLanguage(
    ULONG nStream,
    LCID *pLanguage );

Parameters

nStream
[in] Stream number.
pLanguage
[out] Pointer to the retrieved language.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

This method does not return languages for menus. This method sets the value pointed to by pLanguage to zero if the stream does not include language. Call the Win32 GetLocaleInfo function as follows to create a human-readable string name from pLanguage. LOCALE_SENGLANGUAGE is the locale information type, pszString is a pointer to a buffer to receive the requested data, and cbSize specifies the size of pszString.

GetLocaleInfo(*pLanguage, LOCALE_SENGLANGUAGE, pszString, cbSize);

IDvdInfo::GetTitleAttributes

IDvdInfo Interface

Retrieves attributes of all video, audio, and subpicture streams for the specified title, including menus.

Syntax

HRESULT GetTitleAttributes(
    ULONG nTitle,
    DVD_ATR *pATR );

Parameters

nTitle
[in] Requested title number. Specify 0xFFFFFFFF for the current title.
pATR
[out] Pointer to the retrieved attributes structure (DVD_ATR).

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

IDvdInfo::GetTitleParentalLevels

IDvdInfo Interface

Retrieves the parental levels that are defined for a particular title.

Syntax

HRESULT GetTitleParentalLevels(
    ULONG ulTitle,
    ULONG *pParentalLevels
    );

Parameters

ulTitle
[in] Title for which parental levels are requested.
pParentalLevels
[out] Pointer to a logical OR combination of the parental levels defined for the title. A higher setting will block out more content than a lower setting. Valid parental levels are the following:
  • DVD_PARENTAL_LEVEL_8
  • DVD_PARENTAL_LEVEL_7
  • DVD_PARENTAL_LEVEL_6
  • DVD_PARENTAL_LEVEL_5
  • DVD_PARENTAL_LEVEL_4
  • DVD_PARENTAL_LEVEL_3
  • DVD_PARENTAL_LEVEL_2
  • DVD_PARENTAL_LEVEL_1

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

IDvdInfo::GetTotalTitleTime

IDvdInfo Interface

Retrieves the total playback time for the current title.

Syntax

HRESULT GetTotalTitleTime(
    ULONG *pTotalTime
    );

Parameters

pTotalTime
[out] Pointer to the total time in DVD_TIMECODE format, which includes hours, minutes, seconds, and frames.

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method returns an error unless the domain is DVD_DOMAIN_Title. For more information, see DVD_DOMAIN.

The method is restricted to simple linear movies by design.

IDvdInfo::GetVMGAttributes

IDvdInfo Interface

Retrieves attributes of all video, audio, and subpicture streams for video manager (VMG) menus.

Syntax

HRESULT GetVMGAttributes(
    DVD_ATR *pATR
    );

Parameters

pATR
[out] Pointer to the retrieved attributes structure (DVD_ATR).

Return Value

Returns an HRESULT value that depends on the implementation of the interface. Typical return values might include one of the following:
E_FAIL | Failure.
E_INVALIDARG | Input argument is invalid.
E_NOTIMPL | Method is not supported.
E_OUTOFMEMORY | Out of memory (insufficient buffer space).
E_POINTER | NULL pointer argument.
E_UNEXPECTED | DVD is not initialized or domain is not DVD_DOMAIN_Title.
VFW_E_DVD_OPERATION_INHIBITED | Requested action cannot occur at this point in the movie due to the authoring of the current DVD-Video disc.
S_OK | Success.
VFW_E_DVD_INVALIDDOMAIN | Requested action is not supported on this domain (DVD_DOMAIN).

Remarks

This method is valid in any domain. For more information, see DVD_DOMAIN.

The video manager contains a separate group of streams, such as the DVD_MENU_Title menus, and the streams are not associated with any particular title number.


IEnumRegFilters Interface

Note This interface has been deprecated. New applications should call IFilterMapper2::EnumMatchingFilters, which enumerates monikers and returns a pointer to the IEnumMoniker interface.

This interface provides methods for enumerating registered filters. The IFilterMapper::EnumMatchingFilters method returns a pointer to this interface. However, IFilterMapper has been deprecated in favor of IFilterMapper2.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IEnumRegFilters methods | Description
Next | Fills an array with the next filters that meet the requirements.
Skip | Not currently implemented.
Reset | Makes the Next method start again, beginning at the first filter.
Clone | Not currently implemented.

IEnumRegFilters::Clone

IEnumRegFilters Interface

Creates another enumerator with the same enumeration state as the current one.

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT Clone(
    IEnumRegFilters **ppEnum
);

Parameters

ppEnum
[out] Address of a pointer to the duplicate enumerator interface.

Return Value

Returns E_NOTIMPL.

IEnumRegFilters::Next

IEnumRegFilters Interface

Fills the array with descriptions of the next set of filters (specified by the cFilters parameter) that meet the requirements specified upon creation of the enumerator.

Syntax

HRESULT Next(
    ULONG cFilters,
    REGFILTER **apRegFilter,
    ULONG *pcFetched
);

Parameters

cFilters
[in] Number of filters.
apRegFilter
[out] Address of a pointer to an array of REGFILTER pointers.
pcFetched
[out] Pointer to the actual number of filters passed.

Return Value

Returns one of the following HRESULT values.

E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.
E_POINTER | Null pointer argument.
E_UNEXPECTED | Unexpected error.
S_FALSE | Fewer filters were retrieved than requested.
S_OK | Success.
VFW_E_ENUM_OUT_OF_SYNC | The enumerator has become invalid. For more information, see Remarks.

Remarks

The calling application must use the Microsoft Win32 CoTaskMemFree function to free each REGFILTER pointer returned in the array. Do not free the Name member of the REGFILTER structure separately, because IEnumRegFilters::Next allocates memory for this string as part of the REGFILTER structure.

If the number of registered filters changes, the state of the enumerator will no longer be consistent with the state of the registry. As a result, this method will return VFW_E_ENUM_OUT_OF_SYNC. You should discard any data obtained from previous calls to the enumerator, because it might be invalid, and update the enumerator by calling the Reset method. You can then call the Next method safely.

IEnumRegFilters::Reset

IEnumRegFilters Interface

Resets the enumerator so that the next call to the IEnumRegFilters::Next method begins again at the first filter, if any.

Syntax

HRESULT Reset(void);

Return Value

Returns S_OK, which indicates success.

IEnumRegFilters::Skip

IEnumRegFilters Interface

Skips a specified number of items in the enumeration sequence.

This method is not currently implemented and returns E_NOTIMPL.

Syntax

HRESULT Skip(
  ULONG celt
);

Parameters

celt
[in] Number of items to skip.

Return Value

Returns E_NOTIMPL.


IFilterMapper Interface

Note This interface has been deprecated. It will continue to be supported for backward compatibility with existing applications, but new applications should use the IFilterMapper2 interface.

This interface provides methods for registering and unregistering filters, and for looking up filters based on their characteristics.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IFilterMapper methods | Description
RegisterFilter | Records the details of a filter in the registry.
RegisterFilterInstance | Registers an identifiable instance of a filter.
RegisterPin | Records the details of a pin in the registry.
RegisterPinType | Adds a type for the pin to the registry.
UnregisterFilter | Deletes a filter from the registry.
UnregisterFilterInstance | Deletes an identifiable instance of a filter.
UnregisterPin | Deletes a pin from the registry.
EnumMatchingFilters | Finds all filters matching specific requirements.

IFilterMapper::EnumMatchingFilters

IFilterMapper Interface

Provides an enumerator that enumerates registered filters that meet specified requirements.

Syntax

HRESULT EnumMatchingFilters(
    IEnumRegFilters **ppEnum,
    DWORD dwMerit,
    BOOL bInputNeeded,
    CLSID clsInMaj,
    CLSID clsInSub,
    BOOL bRender,
    BOOL bOutputNeeded,
    CLSID clsOutMaj,
    CLSID clsOutSub
);

Parameters

ppEnum
[out] Address of a pointer to the enumerator returned.
dwMerit
[in] Minimum merit value of filters to enumerate.
bInputNeeded
Value indicating whether there must be at least one input pin; TRUE indicates at least one input pin is required.
clsInMaj
[in] Input major type required. Set to GUID_NULL if you do not care.
clsInSub
[in] Input subtype required. Set to GUID_NULL if you do not care.
bRender
[in] Flag that specifies whether the filter must render the input; TRUE means that it must.
bOutputNeeded
Value indicating whether there must be at least one output pin; TRUE indicates at least one output pin is required.
clsOutMaj
[in] Output major type required. Set to GUID_NULL if you do not care.
clsOutSub
[in] Output subtype required. Set to GUID_NULL if you do not care.

Return Value

Returns an HRESULT value.

Remarks

Set the ppEnum parameter to be an enumerator for filters matching the requirements. For a description of merit values for the dwMerit parameter, see the IFilterMapper::RegisterFilter method.

IFilterMapper::RegisterFilter

IFilterMapper Interface

Adds a filter to the registry; the filter can then be enumerated.

Syntax

HRESULT RegisterFilter(
    CLSID clsid,
    LPCWSTR Name,
    DWORD dwMerit
);

Parameters

clsid
[in] Globally unique identifier (GUID) of the filter.
Name
[in] Descriptive name for the filter.
dwMerit
[in] Position in the order of enumeration. Filters with higher merit are enumerated first.

Return Value

Returns an HRESULT value.

Remarks

The merit (as defined by the dwMerit parameter) controls the order in which the filter graph manager tries filters when performing an operation as a result of a call to IGraphBuilder::Connect, IGraphBuilder::Render, or IGraphBuilder::RenderFile. The filter graph manager finds all filters registered with the correct media type and then tries the one with the highest merit, using other criteria in the registration to choose between filters with equal merit.

The following predefined values exist for the dwMerit parameter. Other values, such as MERIT_NORMAL + 1, can be used. Using the formula (MERIT_NORMAL+MERIT_UNLIKELY)/2 to calculate the merit value is advisable, because it leaves some low-order bits available for making even finer distinctions.
0x900000 | Hardware renderer filter. Filters with this merit value are tried first.
MERIT_PREFERRED (0x800000) | Filter, such as a renderer, that is likely to complete the operation directly.
0x680000 | MPEG decompression filter. These are tried before AVI decompressors because the latter require more time to determine if they work in the filter graph.
MERIT_NORMAL (0x600000) | Filter that might contribute to the completion of a connection. AVI decompression filters and splitter transform filters are registered to this value.
MERIT_UNLIKELY (0x400000) | Filter that may contribute to the completion of a connection (a color space conversion filter, for example). The filter graph manager uses this filter only if other options have failed. Register source filters with this value.
MERIT_DO_NOT_USE (0x200000) | Filter that will never contribute to the completion of a connection. Filters registered with this value (or less) will never be tried by the filter graph manager when automatically building a filter graph. Use this to register filters that must be added explicitly, either as part of a predefined filter graph or by adding them using IFilterGraph::AddFilter. Examples include tee filters or effects filters.
MERIT_HW_COMPRESSOR (0x100050) | Hardware compressor filter. Filters registered with this value will never be tried by the filter graph manager when automatically building a filter graph.
MERIT_SW_COMPRESSOR (0x100000) | Software compressor filter. Filters registered with this value will never be tried by the filter graph manager when automatically building a filter graph.

IFilterMapper::RegisterFilterInstance

IFilterMapper Interface

Registers an identifiable instance of a filter.

Syntax

HRESULT RegisterFilterInstance(
    CLSID clsid,
    LPCWSTR Name,
    CLSID *MRId
);

Parameters

clsid
[in] GUID of the filter.
Name
[in] Descriptive name of the instance.
MRId
[out] Pointer to the returned media resource ID. This parameter is a locally unique identifier for this instance of this filter.

Return Value

Returns an HRESULT value.

Remarks

This method handles cases such as when two similar sound cards that are driven by the same driver are available, and it is necessary to choose which card will emit the sound. This is not needed if there is only one instance of the filter (such as when there is only one sound card in the computer), or if all instances of the filter are equivalent.

The filter itself must have already been registered.

IFilterMapper::RegisterPin

IFilterMapper Interface

Records the details of the pin in the registry.

Syntax

HRESULT RegisterPin(
    CLSID Filter,
    LPCWSTR Name,
    BOOL bRendered,
    BOOL bOutput,
    BOOL bZero,
    BOOL bMany,
    CLSID ConnectsToFilter,
    LPWSTR ConnectsToPin
);

Parameters

Filter
[in] GUID of the filter.
Name
[in] Name of the pin. This should be unique within the filter. It has no significance other than to indicate type information. You should not use pin names longer than 99 characters, because this causes filter enumeration problems.
bRendered
[in] Value specifying whether the filter renders this input. Set to TRUE if it does; otherwise, set to FALSE.
bOutput
[in] Value specifying whether this is an output pin. Set to TRUE if it is; otherwise, set to FALSE.
bZero
[in] Value specifying whether the filter can have zero instances of this pin. If it can, set to TRUE; otherwise, set to FALSE. For example, a decompression filter doesn't need to create a sound output pin for a movie without a sound track.
bMany
[in] Value specifying whether the filter can have many instances of this pin. If it can, set to TRUE; otherwise, set to FALSE. For example, a mixer might have multiple instances of its input pin.
ConnectsToFilter
[in] Reserved. Must be NULL. (This is intended for filters such as system-wide mixers that have connections outside the filter graph. It is not yet implemented.)
ConnectsToPin
[in] Reserved. Must be NULL.

Return Value

Returns an HRESULT value.

IFilterMapper::RegisterPinType

IFilterMapper Interface

Registers this pin type.

Syntax

HRESULT RegisterPinType(
    CLSID clsFilter,
    LPCWSTR strName,
    CLSID clsMajorType,
    CCLSID clsSubType
);

Parameters

clsFilter
Class identifier (CLSID) of the filter to which the pin belongs.
strName
Name by which it is known.
clsMajorType
Major type of the media sample supported by this pin class.
clsSubType
Subtype of the media sample supported by this pin class.

Return Value

Returns an HRESULT value.

Remarks

The clsMajorType and clsSubType parameters specify the media type of the pin and correspond to the AM_MEDIA_TYPE structure's majortype and subtype members, respectively.

IFilterMapper::UnregisterFilter

IFilterMapper Interface

Removes the registration of this filter from the registry.

Syntax

HRESULT UnregisterFilter(
    CLSID Filter
);

Parameters

Filter
[in] GUID of the filter.

Return Value

Returns an HRESULT value.

IFilterMapper::UnregisterFilterInstance

IFilterMapper Interface

Removes the registration of this filter instance from the registry.

Syntax

HRESULT UnregisterFilterInstance(
    CLSID MRId
);

Parameters

MRId
[in] Media resource identifier of this instance.

Return Value

Returns an HRESULT value.

IFilterMapper::UnregisterPin

IFilterMapper Interface

Removes the registration of this pin from the registry.

Syntax

HRESULT UnregisterPin(
    CLSID Filter,
    LPCWSTR Name
);

Parameters

Filter
[in] GUID of the filter that this pin is part of.
Name
[in] Name of the pin.

Return Value

Returns an HRESULT value.


DirectShow Graph File Format

This article describes the format of a saved Microsoft® DirectShow® graph file (.grf) created by GraphEdit.

The docfile (storage file) contains a stream called ActiveMovieGraph. This single stream contains within it all the filters, filter names, file names, connections, and so on.

To load such a graph, either:

  • Pass the storage file name to RenderFile. It will recognize that this is not a media file but a saved graph, and will restore the graph.

or:

  1. Open the storage file (by using StgOpenStorage).
  2. Query the filter graph manager for IPersistStream.
  3. Open the L"ActiveMovieGraph" stream (by using IStorage::OpenStream).
  4. Pass the stream to the filter graph (by using IPersistStream::Load).

The syntax of the graph within the stream follows:

<graph> ::= <version3><filters><connections><clock>END | <version2><filters><connections>END
<version3> ::= 0003\r\n
<version2> ::= 0002\r\n
<clock> ::= CLOCK <b> <required><b><clockid>\r\n
<required> ::= 1|0
<clockid> ::= <n>|<class id>
<filters ::= FILTERS <b>[<filter list><b>]
<connections> ::= CONNECTIONS [<b> <connection list>]
<filter list> ::= [<filter> <b>] <filter list>
<connection list> ::= [<connection><b>]<connection list>
<filter> ::= <n><b>"<name>"<b><class id><b>[<file>]<length><b1><filter data>
<file> ::= SOURCE "<name>"<b> | SINK "<name>"<b>
<class id> ::= class id of the filter in standard string form
<name> ::= any sequence of characters NOT including "
<length> ::= character string representing unsigned decimal number, for example, 23
             this is the number of bytes of data that follow the following space.
<b> ::= any combination of space, \t, \r, or \n
<b1> ::= exactly one space character
<n> ::= an identifier that will in fact be an integer, 0001, 0002, 0003, etc.
<connection> ::= <n1><b>"<pin1 id>"<b><n2><b>"<pin2 id>" <media type>
<n1> ::= identifier of first filter
<n2> ::= identifier of second filter
<pin1 id> ::= <name>
<pin2 id> ::= <name>
<media type> ::= <major type><b><sub type><b><flags><length><b1><format>
<major type> ::= <class id>
<sub type> ::= <class id>
<flags> ::= <FixedSizeSamples><b><TemporalCompression><b>
<FixedSizeSamples> ::= 1|0
<TemporalCompression> ::= 1|0
<Format> ::= <SampleSize><b><FormatType><b><FormatLength><b1><FormatData>
<FormatType> ::= class id of the format in standard string form
<FormatLength> ::= character string representing unsigned decimal number
             this is the number of bytes of data that follow the following space.
<FormatData> ::= binary data

On output there will be a new line (\r\n) per filter, one per connection, and one for each of the keywords FILTERS and CONNECTIONS. Each other case of <B> will be a single space. The keywords FILTERS, CONNECTIONS, and END are not localizable. Note also that the filter data and the format data are binary, so they might contain incorrect line breaks, null values, and so on.

The following approximates what the output looks like (a connection line is long and so has been split for presentation here, <with comments enclosed like this>).

0002
<version 2 of the syntax>
FILTERS
0001 "Source" {00000000-0000-0000-0000-000000000001} SOURCE "MyFile.mpg" 0000000000
<id   name   guid of the filter (need this to load it)
         source file name   no private data>
0002 "another filter" {00000000-0000-0000-0000-000000000002} 0000000008 XXXXXXXX
<id   name   guid   (this one is not a file source or sink)   8 bytes private data>
CONNECTIONS
0001 "Output pin" 0002 "In"   <no line break here>
<filter id pin id   filter id pin id  (output pin is first, then input pin)>
    0000000172 {00000000-0000-0000-0000-000000000003}   <no line break here>
<sample size,   media type major-type>
    {00000000-0000-0000-0000-000000000004} 1 0   <no line break here>
<media type sub-type, fixed size samples, no temporal compression>
    0000000093 {00000000-0000-0000-0000-000000000005} 18 YYYYYYYYYYYYYYYYYY
<length of format   format type   18 bytes of binary format data>
END

where:

  • XXX... represents filter data
  • YYY... represents format data

The strings and characters in the file are always in Unicode™.


DirectShow Filter Graph Markup Language (XGR)

Microsoft DirectX 8.0

Filter Graph Markup Language (XGR)

The XML interface for the DirectShow Graph Builder provides a new persistence format for DirectShow graphs. This format is intended for debugging purposes only to allow a human-readable form of graph persistence; it is not intended for use in applications.

To save a graph in XGR format from GraphEdit, choose Save As XML from the File menu.

Contents:

  • FGML Rules and Conventions
  • Naming Conflicts
  • XML Tags for XGR
    • GRAPH
    • FILTER
    • PARAM
    • CONNECT
    • RENDER
    • FILESOURCE
    • INCLUDE
    • VIDEOCOMPRESS
    • AUDIOCOMPRESS
    • SUBGRAPH
    • FRAGMENT
  • FGML Schema

FGML Rules and Conventions

The default file extension of an FGML file is .XGR. In this document, XGR and FGML are using as synonyms.

FGML follows the XML 1.0 standard for file formatting, tokenization and parsing.

In addition, the following rules are added to deal with issues specific to DirectShow filter graphs:

Naming Conflicts

Each filter and pin definition in the XGR file should define a unique identifier. If this is not the case, then the XGR reader resolves conflicts automatically. As the XGR file is read, filters are instantiated and pins are named as specified in the document. If the case of a conflict, the second filter or pin attempting to use that name will be given a different name. This name will be based on the requested name with a suffix added for uniqueness. Note that the XGR reader will not inform the client code of any such renames which occur, so it will be the responsibility of the client to ensure that they refer to the objects using the correct name after the XGR file is loaded.

In order to avoid naming conflicts, scoping operators have been added to the XGR specifications. These are defined using the <SUBGRAPH> tag. All filters defined within the subgraph can be referred to using the compound name of "subgraph_name.child_filter_name". While the current release of DirectShow does not support subgraphs natively, this may change in future releases. The same naming conventions will apply with native DirectShow subgraphs, with the '.' operator becoming a means of separating the containing subgraph filter from the child filter names.

XML Tags for XGR

GRAPH Element

The GRAPH element is a root element of the graph builder document. It has no defined parameters. GRAPH tags cannot be nested in an XGR file.

Syntax:

<GRAPH version="{number} >
...
</GRAPH>

Attribute | Required | Description
version | N | Specifies the version of the XGR file specification to which this file conforms. This defaults to a value of "1", which is currently the only valid version.

Related tags

Parent Elements | Child Elements
None | FILTER
 | CONNECT
 | SUBGRAPH

Example

<GRAPH>

<FILTER id="videocompress" clsid="{…}" />

</GRAPH>

FILTER Element

Description

The FILTER element is used to define a filter in the graph. The graph builder will use the information defined in this element to select the appropriate filter and creates it. The element also defines the properties that are set on the filter. You must specify one of the 'category' or 'clsid' attributes, but not both of them, in order for the FILTER element to be valid. If both are specified, the 'clsid' will be used and the 'category' and 'instance' attributes will be ignored.

Syntax:

<FILTER
id="filter_name"
clsid="{GUID}"
category="category_name"
instance="instance name"
/>

Attribute | Required | Description
id | Y | Specifies the name of the filter instance in the graph
clsid | N | Specifies the class id for the filter. Graph builder uses this to create an instance of the filter. If clsid is specified then the category and instance attributes cannot be used.
category | N | Specifies the category of the filter for the graph builder. The graph builder uses this to find the filter. If no 'instance' is specified then the default filter from this category is instantiated. If clsid is specified this attribute is ignored.
instance | N | When a category is specified, the 'Instance' attribute is used to specify which filter in that category is to be instantiated. If clsid is specified this attribute is ignored.

Remarks

Parent Elements | Child Elements
GRAPH | PARAM

Example

<FILTER id="asfmux" clsid="{….} />

<FILTER id="capture" category="{Video Capture Sources}" instance="winnov" />

<FILTER id="videocompress" clsid="{…}">

<PARAM name="bitrate" value="24000" />

</FILTER>

PARAM Element

Description

The PARAM element defines a generic way of setting the properties on the filter. It defines a name/value pair that is passed to the filter. The name/value pairs are defined as attributes to PARAM element.

Syntax:

<PARAM name="fps" value="15" />

Attribute | Required | Description
name | Y | Specifies the name property
Value | Y | Specifies the value of the property

Remarks

Parent Elements | Child Elements
FILTER | None

Example

<FILTER id="videocompress" clsid="{…}">

<PARAM name="bitrate" value="24000" />

<PARAM name="fps" value="15" />

</FILTER>

CONNECT Element

Description

The CONNECT Element is used to define a connection between two filters. If the pin to be used is not specified, CONNECT will look for unconnected pins in the correct direction on the filter and choose one of them. The pin chosen in this case is not guaranteed to be the same on subsequent instantiations of the graph from XGR, so if you require a certain pin it must be fully specified.

Syntax:

<CONNECT
src="src_filter_name"
srcpin="src_pin_name"
dest="dest_filter_name"
destpin="dest_pin_name"
CONNECT/>

Attribute | Required | Description
src | Y | Fully qualified name of the filter to be used as the data source for the connection.
srcpin | N | Name of the specific pin from the data source to connect to.
dest | Y | Fully qualified name of the filter to be used as the data sink for the connection.
destpin | N | Name of the specific pin from the data sink to connect to.

Remarks

Parent Elements | Child Elements
GRAPH | None

Example

<CONNECT src="vidcap.video" srcpin='pin1' dest='renderer' destpin='pin3' />

RENDER Element

Description

The RENDER element informs the graph builder that the specified filter and pin should be rendered.

Syntax:

<RENDER id="filter_name" pin="pin_name />

Attribute | Required | Description
Id | Y | Name of the filter to use for rendering
pin | Y | Name of the pin to use.

Remarks

Parent Elements | Child Elements
GRAPH | None

Example

<FILTER id="waveout" clsid="{….} />

<RENDER id="waveout">

FILESOURCE Element

Description

The FILESOURCE element specifies a URL from which a file is to be played. Based on the media type of this URL a source filter with the given id will be instantiated.

ISSUE – Does this create a single filter or an input subgraph.

Syntax:

<FILESOURCE id="source_filter_name" url="file url" />

Attribute | Required | Description
id | Y | Name to be used for the instantiated source filter.
url | Y | URL which identifies the media file to be opened by the source filter.

Remarks

Parent Elements | Child Elements
GRAPH | None

Example

<FILESOURCE id="ASF1" url="http://example.microsoft.com/" />

INCLUDE Element

Description

The INCLUDE element is used to include another XGR file or a FRAGMENT into the current XGR stream. This allows you to use code snippets from a common source to build a complicated graph from smaller pieces. Any file INCLUDED may not contain the GRAPH element since this breaks the rule against nesting GRAPH elements. If the "url" attribute is set than any "fragment" attributes are ignored, these attributes are mutually exclusive. If the specified url or fragment does not exist then the INCLUDE element is ignored.

Syntax:

< INCLUDE
url="url_for_file"
fragment="fragment_name"
subgraph="subgraph_name"
/>

Attribute | Required | Description
url | N | URL which points to the XGR file to be included into the graph. Must be specified if the fragment attribute is not set.
fragment | N | Name of the XGR FRAGMENT element which is to be included. Must be specified if the url attribute is not set, ignored if url is set.
subgraph | N | If a subgraph is specified, the file fragment is assumed to create a distinct subgraph in the graph. This is equivalent to wrapping the INCLUDE element in a SUBGRAPH element. If no subgraph attribute is used then the file is loaded into the default namespace.

Remarks

Parent Elements | Child Elements
GRAPH | None

Example

<INCLUDE url="http://example.microsoft.com/" subgraph="capture"/>

VIDEOCOMPRESS Element

Description

The VIDEOCOMPRESS element is used to instantiate a standard set of filters which take an input video stream in one format and convert it to the required output format. This is a shortcut method of instantiating the complete set of filters necessary to complete this task. If the pin to be used is not specified, the first available pin on the filter is used. The choice of which pin is used by default is not guaranteed to be the same on subsequent instantiations of the graph from XGR, so if you require a certain pin it must be fully specified.

Syntax:

< VIDEOCOMPRESS
src="src_filter_name"
srcpin="src_filter_pin_name"
dest="dest_filter"
destpin="dest_filter_pin_name"
width="{number}"
size="{number}"
codec="codec_name"
datarate="{number}"
keyframespacing="{number}"
frametime="{number}"
subgraph="subgraph_name"
/>

Attribute | Required | Description
src | Y | Fully qualified name of the filter to be used as the data source for the connection.
srcpin | N | Name of the specific pin from the data source to connect to.
dest | Y | Fully qualified name of the filter to be used as the data sink for the connection.
destpin | N | Name of the specific pin from the data sink to connect to.
width | Y | Width, in pixels, of the output stream
height | Y | Height, in pixels, of the output stream
codec | Y | Codec to be used to do the video conversion
datarate | Y | This is the datarate, in kb/sec, of the output stream
keyframespacing | Y | This defines the keyframespacing
frametime | Y | This defines the frametime
subgraph | N | If a subgraph is specified, the video compression filters are assumed to be in a distinct subgraph in the graph. This is equivalent to wrapping the VIDEOCOMPRESS element in a SUBGRAPH element. If no subgraph attribute is used then the file is loaded into the default namespace.

Remarks

Parent Elements | Child Elements
GRAPH | None

Example

AUDIOCOMPRESS Element

Description

The AUDIOCOMPRESS element is used to instantiate a standard set of filters which take an input audio stream in one format and convert it to the required output format. This is a shortcut method of instantiating the complete set of filters necessary to complete this task. If the pins to be used are not specified, the first available pin on the filter is used. The choice of which pin is used by default is not guaranteed to be the same on subsequent instantiations of the graph from XGR, so if you require a certain pin it must be fully specified.

Syntax:

< AUDIOCOMPRESS
src="src_filter_name"
srcpin="src_filter_pin_name"
dest="dest_filter"
destpin="dest_filter_pin_name"
samplerate="{number}"
sampledepth="{number}"
channels="{number}"
subgraph="subgraph_name"
/>

Attribute | Required | Description
src | Y | Fully qualified name of the filter to be used as the data source for the connection.
srcpin | N | Name of the specific pin from the data source to connect to.
dest | Y | Fully qualified name of the filter to be used as the data sink for the connection.
destpin | N | Name of the specific pin from the data sink to connect to.
samplerate | Y | Sample rate, in k/s, of the output stream
sampledepth | Y | Sample size, in bits, of each audio sample
channels | N | Number of distinct audio channels in the output stream. If not specified, the default is "1".
subgraph | N | If a subgraph is specified, the video compression filters are assumed to be in a distinct subgraph in the graph. This is equivalent to wrapping the VIDEOCOMPRESS element in a SUBGRAPH element. If no subgraph attribute is used then the file is loaded into the default namespace.

Remarks

Parent Elements | Child Elements
GRAPH | None

Example

SUBGRAPH Element

Description

The SUBGRAPH element is used create namespace and sectioning behaviors in the filter graph. All Filters defined within the SUBGRAPH element are now referred to with the subgraph name prefixed on to the name in the filter tag. For example, a filter named "Filter" in subgraph "SG1" is referred to by the name "SG1.Filter".

Syntax:

< SUBGRAPH name="subgraph_name"> ... </SUBGRAPH>

Attribute | Required | Description
subgraph_name | Y | Name to be used for this subgraph.

Remarks

Parent Elements | Child Elements
GRAPH | None

FRAGMENT Element

Description

The FRAGMENT element creates a reusable section of XGR code that can be included in numerous places in the graph. When the FRAGMENT element is encountered, all subsequent elements inside the tag are not added to the filter graph. When an INCLUDE tag that references this FRAGMENT is seen, the elements from the fragment are now inserted into the XGR stream as though they were located in the XGR file at the location of the INCLUDE element. You can INCLUDE a FRAGMENT any number of times in the XGR file. A FRAGMENT may contain any other element except GRAPH.

Syntax:

< FRAGMENT name="fragment_name">
...
</FRAGMENT>

Attribute | Required | Description
fragment _name | Y | Name to be used for this fragment

Remarks

Parent Elements | Child Elements
GRAPH | None

Example

FGML Schema

<?xml version="1.0"?>

<Schema xmlns="urn:schemas-microsoft-com:xml-data"

xmlns:dt="urn:schemas-microsoft-com:datatypes">

<!-- Define standard attribute types -->

<AttributeType name="category" dt:type="string" />

<AttributeType name="clsid" dt:type="string" />

<AttributeType name="dest" dt:type="string" />

<AttributeType name="destpin" dt:type="string" />

<AttributeType name="id" dt:type="string" />

<AttributeType name="instance" dt:type="string" />

<AttributeType name="name" dt:type="string" />

<AttributeType name="pin" dt:type="string" />

<AttributeType name="src" dt:type="string" />

<AttributeType name="srcpin" dt:type="string" />

<AttributeType name="url" dt:type="string" />

<AttributeType name="value" dt:type="string" />

<!-- GRAPH element definition -->

<ElementType name="GRAPH" content="eltOnly" model="closed" order="many">

<!-- decide if a version attribute is required -->

<element type="FILTER" />

<element type="CONNECT" />

<element type="SUBGRAPH" />

<element type="PARAM" />

<element type="FILESOURCE" />

</ElementType>

<!-- FILTER element definition -->

<ElementType name="FILTER" content="eltOnly" model="closed" order="many">

<attribute type="id" required="yes" />

<attribute type="clsid" required="no" />

<attribute type="category" required="no" />

<attribute type="instance" required="no" />

<element type="PARAM" />

</ElementType>

<!-- PARAM element definition -->

<ElementType name="PARAM" content="empty" model="closed" order="many">

<attribute type="name" required="yes" />

<attribute type="value" required="yes" />

</ElementType>

<!-- CONNECT element definition -->

<ElementType name="CONNECT" content="empty" model="closed">

<attribute type="src" required="yes" />

<attribute type="srcpin" required="no" />

<attribute type="dest" required="yes" />

<attribute type="destpin" required="no" />

</ElementType>

<!-- RENDER element definition -->

<ElementType name="RENDER" content="empty" model="closed">

<attribute type="id" required="yes" />

<attribute type="pin" required="yes" />

</ElementType>

<!-- FILESOURCE element definition -->

<ElementType name="FILESOURCE" content="empty" model="closed">

<attribute type="id" required="yes" />

<attribute type="url" required="yes" />

</ElementType>

<!-- VIDEOCOMPRESS element definition -->

<!-- AUDIOCOMPRESS element definition -->

<!-- INCLUDE element definition -->

<!-- FRAGMENT element definition -->

<!-- SUBGRAPH element definition -->

</Schema>


International Analog TV Tuning

  • 1 Introduction
  • 2 Frequency Indexes instead of Channel Numbers
  • 3 Frequency Overrides
  • 3.1 Using the Registry to Override Frequencies
  • 3.2 Registry Conversion
  • 4 Using the TV Tuner Filter
  • 4.1 Fine-Tuning Information Collection
  • 4.2 Associating Frequency Tables with Tuning Spaces
  • 5 Tables and Assignments
  • 5.1 Frequency Tables
  • 5.1.1 Australia
  • 5.1.2 China
  • 5.1.3 Czech Republic
  • 5.1.4 Eastern Europe
  • 5.1.5 France
  • 5.1.6 French Overseas Territories
  • 5.1.7 Ireland
  • 5.1.8 Italy
  • 5.1.9 Japan
  • 5.1.10 New Zealand
  • 5.1.11 NTSC (United States)
  • 5.1.12 United Kingdom
  • 5.1.13 Western Europe
  • 5.1.14 Unicable
  • 5.2 Country Assignments

1 Introduction

The TV Tuner support shipped with Windows 98 and Windows 98 SE operating systems was suitable only for TV Tuning in the U.S. market. Although the general framework for International tuning was in place, there were some problems that prevented its use outside the U.S.

Channel Numbers

The TV Tuner filter (kstvtune.ax) includes internal tables for mapping channel numbers to frequencies. Fixed channel numbers are not appropriate for all markets. For instance, the European channel numbers are not actually used by consumers. Instead, the consumer is expecting to choose and assign their own channel numbers for the frequencies used by the broadcast or cable operators in their area.

This problem has been addressed by changing the notion of channel numbers to that of frequency indexes. Ordinal numbers are still used to select frequencies, but they are now treated more as indexes into tables of frequencies, than as channel numbers. In areas where channel numbers make sense (especially the US markets or markets using the US channel lineup), the indexes continue to correspond directly with the channel numbers.

Fixed Frequency Assignments

Since the frequency tables were built into the TV Tuner filter, it wasn't possible to update the frequencies if they were incorrect or had become obsolete. It was also not possible to add new frequencies. This was less of a problem with broadcast frequencies, although errors in these tables could not be fixed without shipping a new binary. However, this was a very big problem with cable frequencies. Most non-US cable operators are free to broadcast on frequencies of their choosing, often mixing frequencies from different standards into the same channel lineup. This problem has been addressed in two ways. One, by providing a "Unicable" frequency table for any country lacking a standard cable channel standards authority; and two, by providing a Windows Registry-based mechanism to override one or more frequencies in the frequency tables.

Erroneous Data

The data encapsulated by the TV Tuner filter includes frequency tables, color standards, and the per-country frequency and color standard assignments. Errors in these tables and assignments could not be corrected without shipping a new TV Tuner filter. This problem has been addressed via a combination of the steps described above, as well as exhaustive research leading to updates to the internal tables and assignments. A significant amount of effort was spent to ensure that the broadcast frequencies and color standard assignments are correct for each country.

This document describes how to use the new features, and includes the frequency tables and country assignments. The new features are being introduced in Windows Millennium Beta 2. As a beta partner, we hope that you will provide feedback on these new features as you apply them to your product plans.

2 Frequency Indexes instead of Channel Numbers

The most significant aspect of the new international tuning support was the simplest to implement... in fact no code changes were necessary. It's simply to not think "Channel Number" anymore; think "Frequency Index". The ramification of this is: the TV viewing application should not expose the frequency index numbers directly to the end-user. Instead, there should be an internal mapping from the Channel Number the user sees to the Frequency Index the app uses to tune to a particular frequency. In some countries, the U.S. being the most obvious, the application can do a one-to-one mapping from channel number to frequency index. But an International Tuning-ready application will allow the end-user (or an agent on behalf of the end-user) to select the channel number to use for each frequency (or index).

The TV Tuner filter continues to use frequency tables, as before, simply because the frequency tables are the end-result of a significant amount of research. There is no point in moving this responsibility up to the TV viewing application.

3 Frequency Overrides

3.1 Using the Registry to Override Frequencies

Despite our best efforts, there will be situations when the frequency tables are not sufficient, or have errors or have become obsolete. To address this problem, the frequencies in the TV Tuner filter's frequency tables may be selectively overridden via the registry.

Figure 1:

[HKEY_LOCAL_MACHINE\Software\Microsoft\TV System Services\TVAutoTune\TS0-1]
"12"=dword:04022750
"AutoTune"=hex:00,00,00,00,50,0c,4b,03,d0,99,a6,03,50,27,02,04,d0,bd,9a,04,50,\
  4b,f6,04,50,1a,72,0a,00,00,00,00,50,35,29,0b,d0,c2,84,0b,50,50,e0,0b,d0,dd,\
  3b,0c,50,6b,97,0c,d0,20,3a,07,50,ae,95,07,d0,3b,f1,07,50,c9,4c,08,d0,56,a8,\
  08,50,e4,03,09,d0,71,5f,09,50,ff,ba,09,d0,8c,16,0a,d0,f8,f2,0c,50,86,4e,0d,\
  d0,13,aa,0d,50,a1,05,0e,d0,2e,61,0e,50,bc,bc,0e,d0,49,18,0f,50,d7,73,0f,d0,\
  64,cf,0f,50,f2,2a,10,d0,7f,86,10,50,0d,e2,10,d0,9a,3d,11,50,28,99,11,d0,b5,\
  f4,11,50,43,50,12,d0,d0,ab,12,50,5e,07,13,d0,eb,62,13,74,6d,bf,13,00,00,00,\
  00,00,00,00,00,d0,21,d1,14,50,af,2c,15,d0,3c,88,15,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,d0,8d,ad,17,50,1b,09,18,d0,a8,64,18,50,\
  36,c0,18,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,f4,e0,fa,20,50,7a,55,21,00,\
  00,00,00,00,00,00,00,d0,22,68,22,00,00,00,00,00,00,00,00,50,cb,7a,23,00,00,\
  00,00,50,e6,31,24,d0,73,8d,24,00,00,00,00,d0,8e,44,25,50,1c,a0,25,d0,a9,fb,\
  25,50,37,57,26,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,74,87,df,06,\
  d0,c4,b2,26,50,52,0e,27,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,00,\
  00,00,00,00,00,00,00,00,00,00,00

Figure 1(and the text version above) shows the registry path where fine-tuning and frequency overrides are stored. In this case, "TS0-1" indicates Tuning Space 0 for cable frequencies (1). There would be a TS0-0 for broadcast frequencies in tuning space 0. The structure of these registry entries has been changed from the previous version, to support the new frequency override mechanism. Previously, the TS*-* keys were binary values consisting of the fine-tuning information for the active frequency table at the time the fine-tuning was performed. In the new format, the fine-tuning information has been moved to the "AutoTune" subkey. All other subkeys are frequency override candidates. To qualify as a frequency override value, the key name must be a valid number within the range of the low and high index values of the currently active frequency table. Additionally, the value of the subkey must be of DWORD type, and must specify a frequency in Hz. Entries that don't qualify as frequency overrides are simply ignored. In the example in Figure 1, the override is for the frequency at index 12 with 67.25MHz.

There may be any number of frequency overrides for a particular tuning space, although there isn't much point in having more overrides than there are frequency indexes. It is not possible to guarantee which of two or more indexes having the same key name will be chosen as the override value.

The IAMTVTuner::put_TuningSpace method allows the application to choose which set of overrides and fine-tuning information to use. It is the application's responsibility to maintain the relationship between the Tuning Space and the frequency table.

3.2 Registry Conversion

Any application that adds frequency overrides to the registry must ensure that the registry location(s) for the tuning space(s) is(are) using the new format. The TV Tuner filter can be utilized to perform the conversion. The old registry format will be converted to the new format whenever the IAMTVTuner::StoreAutoTune method is called. Note that it is not necessary to collect any fine-tuning information before calling the StoreAutoTune method. It is also perfectly reasonable to instantiate a TV Tuner filter as part of a setup process to perform fine-tuning, or simply to do the conversion.

4 Using the TV Tuner Filter

The following sections describe some recommended practices when using the TV Tuner filter (kstvtune.ax).

4.1 Fine-Tuning Information Collection

Fine-tuning Information collection is recommended for broadcast frequencies only. Cable frequencies are generally expected to be exact, while broadcast frequencies may be adjusted up or down several kHz by the broadcast station to reduce potential interference with neighboring channels. Applications may continue to use the IAMTVTuner::AutoTune method to perform fine-tuning for broadcast frequencies. This method lets the application use an index to select a frequency from the currently active table, perform a tune operation, and report the result of the tune operation (whether or not horizontal lock was achieved) in one operation. This method ignores any frequency overrides, so if it is determined that a frequency in the TV Tuner filter's frequency tables is in error, the AutoTune will not give the desired results for that frequency index.

An application will call AutoTune once for each frequency index in the range reported by IAMTVTuner::ChannelMinMax. Once the application is finished, it must call IAMTVTuner::StoreAutoTune to save the fine-tuning information in the registry. Because the AutoTune method does not properly deal with frequency overrides, the StoreAutoTune must be followed by a call to IAMTVTuner::put_TuningSpace to retrieve the overrides again.

An alternative is to mimic the operation of the AutoTune method using the IAMTVTuner::put_Channel and IAMTuner::SignalPresent methods. The put_Channel and AutoTune methods share the same implementation, so the results of calls to put_Channel also are available for IAMTVTuner::StoreAutoTune to save in the registry. The following operations are equivalent to IAMTVTuner::AutoTune:

HRESULT
MyAutoTune(IAMTVTuner *pTuner, long lIndex, long *plFoundSignal)
{
    long SignalStrength = AMTUNER_NOSIGNAL;
    HRESULT hr;

    hr = pTuner->put_Channel(lIndex, AMTUNER_SUBCHAN_DEFAULT, AMTUNER_SUBCHAN_DEFAULT);
    if (NOERROR == hr)
        pTuner->SignalPresent(&SignalStrength);

    // Assume AMTUNER_HASNOSIGNALSTRENGTH means tuned
    *plFoundSignal = (SignalStrength != AMTUNER_NOSIGNAL);

    return hr;
}

The return codes available from the put_Channel and AutoTune methods have been expanded slightly, to compensate for the less reliable characteristics of broadcast reception. With broadcast reception, it is not always possible to get a horizontal lock, although the picture is viewable. In these cases, the tuner hardware will have a frequency lock, but the decoder won't have horizontal lock. This condition can be detected when using put_Channel or AutoTune by examining the return code.

S_OK (or NOERROR)

The tune operation succeeded, the tuner got a frequency lock (and, for AutoTune, the FoundSignal parameter has been updated with the status of the decoder, indicating whether or not horizontal lock was achieved). When performing an AutoTune operation on a broadcast frequency, the application has the option of ignoring the FoundSignal parameter, since the tuner is reporting a frequency lock. Note that there is the possibility of a frequency lock on noise, but this possibility should be weighed against skipping viewable channels.

S_FALSE

There were no errors in during the tune operation, but the tuner was not able to get a frequency lock. It is highly unlikely that there is a viewable channel resulting from this operation.

E_*

Any other return code indicates some error occurred.

4.2 Associating Frequency Tables with Tuning Spaces

The application chooses frequency tables and color standards by selecting the appropriate country code(s) (using the IAMTVTuner::put_CountryCode method). The country codes along with their frequency table and color standard assignments are given in section 5 below.

In order to properly support the use of frequency overrides, it is strongly recommended that the application associate a unique tuning space number with each country code that might be selected. A reasonable approach would be to use the country code value as the tuning space value. Then, every time the application switches to a new country code, it would also switch to the corresponding tuning space (in that order). This will ensure that the frequency overrides and fine-tuning information are correct for the newly-active frequency tables.

5 Tables and Assignments

5.1 Frequency Tables

Worldwide, there is a finite, known set of broadcast frequency standards. These standards have been identified by their country of origin, but in many cases, multiple countries share the same standard. The TV Tuner filter (kstvtune.ax) defines a table for each standard.

Unfortunately, the same cannot be said for cable frequency standards. The cable providers in some countries are free to broadcast programming on frequencies of their choosing. Frequencies from multiple standards are often mixed. In most cases, this practice correlates directly with the country of origin for each of the frequency standards. The TV Tuner filter defines tables for the few cable standards (and countries) that have dependable cable frequency allocations. For all others, the Unicable frequency table must be used.

The frequency tables in the following sections are extracted verbatim from the resource file definitions used to build the tables in the TV Tuner filter. Each table starts with its resource ID. You can use these resource IDs to cross-reference from the Country Code assignments, presented in section 5.2 below, to determine which tables are in use for each country or locale.

5.1.1 Australia

The frequency indexes in the Australia table are not suitable for use as channel numbers. Also note that channels 3, 4, 5, and 5A are being phased out for other uses.

5.1.1.1 Australia Broadcast Assignments

F_OZ__BROAD RCDATA
BEGIN
         1L,            // Lowest index
        53L,            // Highest index

        46250000L,      // 0    (1) VHF Band 1
        57250000L,      // 1    (2)
        64250000L,      // 2    (3) VHF Band 2
        86250000L,      // 3    (4)
        95250000L,      // 4    (5)
       102250000L,      // 5    (6)
       138250000L,      // 5a   (7) VHF Band 3
       175250000L,      // 6    (8)
       182250000L,      // 7    (9)
       189250000L,      // 8    (10)
       196250000L,      // 9    (11)
       209250000L,      // 10   (12)
       216250000L,      // 11   (13)
       223250000L,      // 12   (14)
       527250000L,      // 28   (15) UHF Band 4
       534250000L,      // 29   (16)
       541250000L,      // 30   (17)
       548250000L,      // 31   (18)
       555250000L,      // 32   (19)
       562250000L,      // 33   (20)
       569250000L,      // 34   (21)
       576250000L,      // 35   (22)
       604250000L,      // 39   (23) UHF Band 5
       611250000L,      // 40   (24)
       618250000L,      // 41   (25)
       625250000L,      // 42   (26)
       632250000L,      // 43   (27)
       639250000L,      // 44   (28)
       646250000L,      // 45   (29)
       653250000L,      // 46   (30)
       660250000L,      // 47   (31)
       667250000L,      // 48   (32)
       674250000L,      // 49   (33)
       681250000L,      // 50   (34)
       688250000L,      // 51   (35)
       695250000L,      // 52   (36)
       702250000L,      // 53   (37)
       709250000L,      // 54   (38)
       716250000L,      // 55   (39)
       723250000L,      // 56   (40)
       730250000L,      // 57   (41)
       737250000L,      // 58   (42)
       744250000L,      // 59   (43)
       751250000L,      // 60   (44)
       758250000L,      // 61   (45)
       765250000L,      // 62   (46)
       772250000L,      // 63   (47)
       779250000L,      // 64   (48)
       786250000L,      // 65   (49)
       793250000L,      // 66   (50)
       800250000L,      // 67   (51)
       807250000L,      // 68   (52)
       814250000L,      // 69   (53)
END

5.1.1.2 Australia Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable frequency table will be used.

5.1.2 China

The frequency indexes in the China table are suitable for use as channel numbers.

5.1.2.1 China Broadcast Assignments

F_CHN_BROAD RCDATA
BEGIN
        1L,             // Lowest channel
        36L,            // Highest channel

        49750000L,      // 1
        57750000L,      // 2
        65750000L,      // 3
        77250000L,      // 4
        85250000L,      // 5
       168250000L,      // 6
       176250000L,      // 7
       184250000L,      // 8
       192250000L,      // 9
       200250000L,      // 10
       208250000L,      // 11
       216250000L,      // 12
       471250000L,      // 13
       479250000L,      // 14
       487250000L,      // 15
       495250000L,      // 16
       503250000L,      // 17
       511250000L,      // 18
       519250000L,      // 19
       527250000L,      // 20
       535250000L,      // 21
       543250000L,      // 22
       551250000L,      // 23
       559250000L,      // 24
       605250000L,      // 25
       613250000L,      // 26
       621250000L,      // 27
       629250000L,      // 28
       637250000L,      // 29
       645250000L,      // 30
       653250000L,      // 31
       661250000L,      // 32
       669250000L,      // 33
       677250000L,      // 34
       685250000L,      // 35
       693250000L,      // 36
END

5.1.2.2 China Cable Assignments

F_CHN_CABLE RCDATA
BEGIN
        1L,             // Lowest channel
        52L,            // Highest channel

        49750000L,      // 1
        57750000L,      // 2
        65750000L,      // 3
        77250000L,      // 4
        85250000L,      // 5
       112250000L,      // 6
       120250000L,      // 7
       128250000L,      // 8
       136250000L,      // 9
       144250000L,      // 10
       152250000L,      // 11
       160250000L,      // 12
       168250000L,      // 13
       176250000L,      // 14
       184250000L,      // 15
       192250000L,      // 16
       200250000L,      // 17
       208250000L,      // 18
       216250000L,      // 19
       224250000L,      // 20
       232250000L,      // 21
       240250000L,      // 22
       248250000L,      // 23
       256250000L,      // 24
       264250000L,      // 25
       272250000L,      // 26
       280250000L,      // 27
       288250000L,      // 28
       471250000L,      // 29
       479250000L,      // 30
       487250000L,      // 31
       495250000L,      // 32
       503250000L,      // 33
       511250000L,      // 34
       519250000L,      // 35
       527250000L,      // 36
       535250000L,      // 37
       543250000L,      // 38
       551250000L,      // 39
       559250000L,      // 40
       567250000L,      // 41
       575250000L,      // 42
       583250000L,      // 43
       591250000L,      // 44
       599250000L,      // 45
       607250000L,      // 46
       615250000L,      // 47
       623250000L,      // 48
       631250000L,      // 49
       639250000L,      // 50
       647250000L,      // 51
       655250000L,      // 52
END

5.1.3 Czech Republic

The frequency indexes in the Czech Republic tables are not suitable for use as channel numbers.

5.1.3.1 Czech Republic Broadcast Assignments

F_CZE_BROAD RCDATA
BEGIN
        1L,             // Lowest index
        69L,            // Highest index

        49750000L,      // 1
        57750000L,      // 2
        59250000L,      // 3
        65750000L,      // 4
        77250000L,      // 5
        85250000L,      // 6
        93250000L,      // 7
       175250000L,      // 8
       183250000L,      // 9
       191250000L,      // 10
       199250000L,      // 11
       207250000L,      // 12
       215250000L,      // 13
       223250000L,      // 14

               0L,      // 15 Not used
               0L,      // 16 Not used
               0L,      // 17 Not used
               0L,      // 18 Not used
               0L,      // 19 Not used
               0L,      // 20 Not used

       471250000L,      // 21
       479250000L,      // 22
       487250000L,      // 23
       495250000L,      // 24
       503250000L,      // 25
       511250000L,      // 26
       519250000L,      // 27
       527250000L,      // 28
       535250000L,      // 29
       543250000L,      // 30
       551250000L,      // 31
       559250000L,      // 32
       567250000L,      // 33
       575250000L,      // 34
       583250000L,      // 35
       591250000L,      // 36
       599250000L,      // 37
       607250000L,      // 38
       615250000L,      // 39
       623250000L,      // 40
       631250000L,      // 41
       639250000L,      // 42
       647250000L,      // 43
       655250000L,      // 44
       663250000L,      // 45
       671250000L,      // 46
       679250000L,      // 47
       687250000L,      // 48
       695250000L,      // 49
       703250000L,      // 50
       711250000L,      // 51
       719250000L,      // 52
       727250000L,      // 53
       735250000L,      // 54
       743250000L,      // 55
       751250000L,      // 56
       759250000L,      // 57
       767250000L,      // 58
       775250000L,      // 59
       783250000L,      // 60
       791250000L,      // 61
       799250000L,      // 62
       807250000L,      // 63
       815250000L,      // 64
       823250000L,      // 65
       831250000L,      // 66
       839250000L,      // 67
       847250000L,      // 68
       855250000L,      // 69

END

5.1.3.2 Czech Republic Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable frequency table (see below) will be used.

5.1.4 Eastern Europe

The frequency indexes in the Eastern Europe tables are not suitable for use as channel numbers.

5.1.4.1 Eastern Europe Broadcast Assignments

F_EEU_BROAD RCDATA
BEGIN
        1L,             // Lowest index
        69L,            // Highest index

        49750000L,      // 1
        59250000L,      // 2
        77250000L,      // 3
        85250000L,      // 4
        93250000L,      // 5
       175250000L,      // 6
       183250000L,      // 7
       191250000L,      // 8
       199250000L,      // 9
       207250000L,      // 10
       215250000L,      // 11
       223250000L,      // 12

               0L,      // 13 Not used
               0L,      // 14 Not used
               0L,      // 15 Not used
               0L,      // 16 Not used
               0L,      // 17 Not used
               0L,      // 18 Not used
               0L,      // 19 Not used
               0L,      // 20 Not used

       471250000L,      // 21
       479250000L,      // 22
       487250000L,      // 23
       495250000L,      // 24
       503250000L,      // 25
       511250000L,      // 26
       519250000L,      // 27
       527250000L,      // 28
       535250000L,      // 29
       543250000L,      // 30
       551250000L,      // 31
       559250000L,      // 32
       567250000L,      // 33
       575250000L,      // 34
       583250000L,      // 35
       591250000L,      // 36
       599250000L,      // 37
       607250000L,      // 38
       615250000L,      // 39
       623250000L,      // 40
       631250000L,      // 41
       639250000L,      // 42
       647250000L,      // 43
       655250000L,      // 44
       663250000L,      // 45
       671250000L,      // 46
       679250000L,      // 47
       687250000L,      // 48
       695250000L,      // 49
       703250000L,      // 50
       711250000L,      // 51
       719250000L,      // 52
       727250000L,      // 53
       735250000L,      // 54
       743250000L,      // 55
       751250000L,      // 56
       759250000L,      // 57
       767250000L,      // 58
       775250000L,      // 59
       783250000L,      // 60
       791250000L,      // 61
       799250000L,      // 62
       807250000L,      // 63
       815250000L,      // 64
       823250000L,      // 65
       831250000L,      // 66
       839250000L,      // 67
       847250000L,      // 68
       855250000L,      // 69

END

5.1.4.2 Eastern Europe Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable frequency table (see below) will be used.

5.1.5 France

The frequency indexes in the France tables are not suitable for use as channel numbers.

5.1.5.1 France Broadcast Assignments

F_FRA_BROAD RCDATA
BEGIN
        2L,             // Lowest index
        69L,            // Highest index

        55750000L,      // 2
        60500000L,      // 3
        63750000L,      // 4
       176000000L,      // 5
       184000000L,      // 6
       192000000L,      // 7
       200000000L,      // 8
       208000000L,      // 9
       216000000L,      // 10
               0L,      // 11  Not used
               0L,      // 12  Not used
               0L,      // 13  Not used
               0L,      // 14  Not used
               0L,      // 15  Not used
               0L,      // 16  Not used
               0L,      // 17  Not used
               0L,      // 18  Not used
               0L,      // 19  Not used
               0L,      // 20  Not used
       471250000L,      // 21
       479250000L,      // 22
       487250000L,      // 23
       495250000L,      // 24
       503250000L,      // 25
       511250000L,      // 26
       519250000L,      // 27
       527250000L,      // 28
       535250000L,      // 29
       543250000L,      // 30
       551250000L,      // 31
       559250000L,      // 32
       567250000L,      // 33
       575250000L,      // 34
       583250000L,      // 35
       591250000L,      // 36
       599250000L,      // 37
       607250000L,      // 38
       615250000L,      // 39
       623250000L,      // 40
       631250000L,      // 41
       639250000L,      // 42
       647250000L,      // 43
       655250000L,      // 44
       663250000L,      // 45
       671250000L,      // 46
       679250000L,      // 47
       687250000L,      // 48
       695250000L,      // 49
       703250000L,      // 50
       711250000L,      // 51
       719250000L,      // 52
       727250000L,      // 53
       735250000L,      // 54
       743250000L,      // 55
       751250000L,      // 56
       759250000L,      // 57
       767250000L,      // 58
       775250000L,      // 59
       783250000L,      // 60
       791250000L,      // 61
       799250000L,      // 62
       807250000L,      // 63
       815250000L,      // 64
       823250000L,      // 65
       831250000L,      // 66
       839250000L,      // 67
       847250000L,      // 68
       855250000L,      // 69

END

5.1.5.2 France Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable frequency table (see below) will be used.

5.1.6 French Overseas Territories

The frequency indexes in the French Overseas Territories broadcast table are suitable for use as channel numbers; the cable frequency indexes will not suitable for use as channel numbers.

5.1.6.1 French Overseas Territories Broadcast Assignments

F_FOT_BROAD RCDATA
BEGIN
         4L,            // Lowest channel
         9L,            // Highest channel

       175250000L,      // 4
       183250000L,      // 5
       191250000L,      // 6
       199250000L,      // 7
       207250000L,      // 8
       215250000L,      // 9
END

5.1.6.2 French Overseas Territories Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable frequency table (see below) will be used.

5.1.7 Ireland

The frequency indexes in the Ireland tables are not suitable for use as channel numbers.

5.1.7.1 Ireland Broadcast Assignments

F_IRE_BROAD RCDATA
BEGIN
         1L,            // Lowest index
        10L,            // Highest index

        45750000L,      // A
        53750000L,      // B
        61750000L,      // C
       175250000L,      // D
       183750000L,      // E
       191250000L,      // F
       199250000L,      // G
       207250000L,      // H
       215250000L,      // I
       223250000L,      // J
END

5.1.7.2 Ireland Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable frequency table (see below) will be used.

5.1.8 Italy

The frequency indexes in the Italy tables are not suitable for use as channel numbers.

5.1.8.1 Italy Broadcast Assignments

F_ITA_BROAD RCDATA
BEGIN
         1L,            // Lowest index
        10L,            // Highest index

        53750000L,      // 1    A
        59750000L,      // 2    B
        82750000L,      // 3    C
       175250000L,      // 4    D
       183750000L,      // 5    E
       192250000L,      // 6    F
       201250000L,      // 7    G
       210250000L,      // 8    H
       217250000L,      // 9    H1
       224250000L,      // 10   H2

END

5.1.8.2 Italy Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable frequency table (see below) will be used.

5.1.9 Japan

The frequency indexes in the Japan tables are suitable for use as channel numbers.

5.1.9.1 Japan Broadcast Assignments

F_JAP_BROAD RCDATA
BEGIN
        1L,             // Lowest channel
        62L,            // Highest channel

        91250000L,      // 1
        97250000L,      // 2
       103250000L,      // 3
       171250000L,      // 4
       177250000L,      // 5
       183250000L,      // 6
       189250000L,      // 7
       193250000L,      // 8
       199250000L,      // 9
       205250000L,      // 10
       211250000L,      // 11
       217250000L,      // 12
       471250000L,      // 13
       477250000L,      // 14
       483250000L,      // 15
       489250000L,      // 16
       495250000L,      // 17
       501250000L,      // 18
       507250000L,      // 19
       513250000L,      // 20
       519250000L,      // 21
       525250000L,      // 22
       531250000L,      // 23
       537250000L,      // 24
       543250000L,      // 25
       549250000L,      // 26
       555250000L,      // 27
       561250000L,      // 28
       567250000L,      // 29
       573250000L,      // 30
       579250000L,      // 31
       585250000L,      // 32
       591250000L,      // 33
       597250000L,      // 34
       603250000L,      // 35
       609250000L,      // 36
       615250000L,      // 37
       621250000L,      // 38
       627250000L,      // 39
       633250000L,      // 40
       639250000L,      // 41
       645250000L,      // 42
       651250000L,      // 43
       657250000L,      // 44
       663250000L,      // 45
       669250000L,      // 46
       675250000L,      // 47
       681250000L,      // 48
       687250000L,      // 49
       693250000L,      // 50
       699250000L,      // 51
       705250000L,      // 52
       711250000L,      // 53
       717250000L,      // 54
       723250000L,      // 55
       729250000L,      // 56
       735250000L,      // 57
       741250000L,      // 58
       747250000L,      // 59
       753250000L,      // 60
       759250000L,      // 61
       765250000L,      // 62
END

5.1.9.2 Japan Cable Assignments

F_JAP_CABLE RCDATA
BEGIN
         1L,            // Lowest channel
       113L,            // Highest channel

        91250000L,      //  1
        97250000L,      //  2
       103250000L,      //  3
       109250000L,      //  4
       115250000L,      //  5
       121250000L,      //  6
       127250000L,      //  7
       133250000L,      //  8
       139250000L,      //  9
       145250000L,      // 10
       151250000L,      // 11
       157250000L,      // 12
       165250000L,      // 13
       171250000L,      // 14
       177250000L,      // 15
       183250000L,      // 16
       189250000L,      // 17
       193250000L,      // 18
       199250000L,      // 19
       205250000L,      // 20
       211250000L,      // 21
       217250000L,      // 22
       223250000L,      // 23
       231250000L,      // 24
       237250000L,      // 25
       243250000L,      // 26
       249250000L,      // 27
       253250000L,      // 28
       259250000L,      // 29
       265250000L,      // 30
       271250000L,      // 31
       277250000L,      // 32
       283250000L,      // 33
       289250000L,      // 34
       295250000L,      // 35
       301250000L,      // 36
       307250000L,      // 37
       313250000L,      // 38
       319250000L,      // 39
       325250000L,      // 40
       331250000L,      // 41
       337250000L,      // 42
       343250000L,      // 43
       349250000L,      // 44
       355250000L,      // 45
       361250000L,      // 46
       367250000L,      // 47
       373250000L,      // 48
       379250000L,      // 49
       385250000L,      // 50
       391250000L,      // 51
       397250000L,      // 52
       403250000L,      // 53
       409250000L,      // 54
       415250000L,      // 55
       421250000L,      // 56
       427250000L,      // 57
       433250000L,      // 58
       439250000L,      // 59
       445250000L,      // 60
       451250000L,      // 61
       457250000L,      // 62
       463250000L,      // 63

       471250000L,      // Test
       477250000L,      // Test
       483250000L,      // Test
       489250000L,      // Test
       495250000L,      // Test
       501250000L,      // Test
       507250000L,      // Test
       513250000L,      // Test
       519250000L,      // Test
       525250000L,      // Test
       531250000L,      // Test
       537250000L,      // Test
       543250000L,      // Test
       549250000L,      // Test
       555250000L,      // Test
       561250000L,      // Test
       567250000L,      // Test
       573250000L,      // Test
       579250000L,      // Test
       585250000L,      // Test
       591250000L,      // Test
       597250000L,      // Test
       603250000L,      // Test
       609250000L,      // Test
       615250000L,      // Test
       621250000L,      // Test
       627250000L,      // Test
       633250000L,      // Test
       639250000L,      // Test
       645250000L,      // Test
       651250000L,      // Test
       657250000L,      // Test
       663250000L,      // Test
       669250000L,      // Test
       675250000L,      // Test
       681250000L,      // Test
       687250000L,      // Test
       693250000L,      // Test
       699250000L,      // Test
       705250000L,      // Test
       711250000L,      // Test
       717250000L,      // Test
       723250000L,      // Test
       729250000L,      // Test
       735250000L,      // Test
       741250000L,      // Test
       747250000L,      // Test
       753250000L,      // Test
       759250000L,      // Test
       765250000L,      // Test
END

5.1.10 New Zealand

The frequency indexes in the New Zealand broadcast table are suitable for use as channel numbers; the cable frequency indexes will not suitable for use as channel numbers.

5.1.10.1 New Zealand Broadcast Assignments

F_NZ__BROAD RCDATA
BEGIN
         1L,            // Lowest channel
         11L,           // Highest channel

        45250000L,      // 1
        55250000L,      // 2
        62250000L,      // 3
       175250000L,      // 4
       182250000L,      // 5
       189250000L,      // 6
       196250000L,      // 7
       203250000L,      // 8
       210250000L,      // 9
       217250000L,      // 10
       224250000L,      // 11
END

5.1.10.2 New Zealand Cable Assignments

There was no data supporting a standardized cable lineup, so the Unicable frequency table (see below) will be used.

5.1.11 NTSC (United States)

The NTSC tables are appropriate for any locale using the NTSC standard channel line-ups. Both Broadcast and Cable lineups are standardized and stable. Also, the frequency indexes are suitable for use as channel numbers.

5.1.11.1 NTSC Broadcast Assignments

F_USA_BROAD RCDATA
BEGIN
        2L,             // Lowest channel
        69L,            // Highest channel

        55250000L,      // 2
        61250000L,      // 3
        67250000L,      // 4
        77250000L,      // 5
        83250000L,      // 6
       175250000L,      // 7
       181250000L,      // 8
       187250000L,      // 9
       193250000L,      // 10
       199250000L,      // 11
       205250000L,      // 12
       211250000L,      // 13
       471250000L,      // 14
       477250000L,      // 15
       483250000L,      // 16
       489250000L,      // 17
       495250000L,      // 18
       501250000L,      // 19
       507250000L,      // 20
       513250000L,      // 21
       519250000L,      // 22
       525250000L,      // 23
       531250000L,      // 24
       537250000L,      // 25
       543250000L,      // 26
       549250000L,      // 27
       555250000L,      // 28
       561250000L,      // 29
       567250000L,      // 30
       573250000L,      // 31
       579250000L,      // 32
       585250000L,      // 33
       591250000L,      // 34
       597250000L,      // 35
       603250000L,      // 36
       609250000L,      // 37
       615250000L,      // 38
       621250000L,      // 39
       627250000L,      // 40
       633250000L,      // 41
       639250000L,      // 42
       645250000L,      // 43
       651250000L,      // 44
       657250000L,      // 45
       663250000L,      // 46
       669250000L,      // 47
       675250000L,      // 48
       681250000L,      // 49
       687250000L,      // 50
       693250000L,      // 51
       699250000L,      // 52
       705250000L,      // 53
       711250000L,      // 54
       717250000L,      // 55
       723250000L,      // 56
       729250000L,      // 57
       735250000L,      // 58
       741250000L,      // 59
       747250000L,      // 60
       753250000L,      // 61
       759250000L,      // 62
       765250000L,      // 63
       771250000L,      // 64
       777250000L,      // 65
       783250000L,      // 66
       789250000L,      // 67
       795250000L,      // 68
       801250000L,      // 69
END

5.1.11.2 NTSC Cable Assignments

F_USA_CABLE RCDATA
BEGIN
        1L,             // Lowest channel
        158L,           // Highest channel

        73250000L,      // 1
        55250000L,      // 2
        61250000L,      // 3
        67250000L,      // 4
        77250000L,      // 5
        83250000L,      // 6
       175250000L,      // 7
       181250000L,      // 8
       187250000L,      // 9
       193250000L,      // 10
       199250000L,      // 11
       205250000L,      // 12
       211250000L,      // 13
       121250000L,      // 14
       127250000L,      // 15
       133250000L,      // 16
       139250000L,      // 17
       145250000L,      // 18
       151250000L,      // 19
       157250000L,      // 20
       163250000L,      // 21
       169250000L,      // 22
       217250000L,      // 23
       223250000L,      // 24
       229250000L,      // 25
       235250000L,      // 26
       241250000L,      // 27
       247250000L,      // 28
       253250000L,      // 29
       259250000L,      // 30
       265250000L,      // 31
       271250000L,      // 32
       277250000L,      // 33
       283250000L,      // 34
       289250000L,      // 35
       295250000L,      // 36
       301250000L,      // 37
       307250000L,      // 38
       313250000L,      // 39
       319250000L,      // 40
       325250000L,      // 41
       331250000L,      // 42
       337250000L,      // 43
       343250000L,      // 44
       349250000L,      // 45
       355250000L,      // 46
       361250000L,      // 47
       367250000L,      // 48
       373250000L,      // 49
       379250000L,      // 50
       385250000L,      // 51
       391250000L,      // 52
       397250000L,      // 53
       403250000L,      // 54
       409250000L,      // 55
       415250000L,      // 56
       421250000L,      // 57
       427250000L,      // 58
       433250000L,      // 59
       439250000L,      // 60
       445250000L,      // 61
       451250000L,      // 62
       457250000L,      // 63
       463250000L,      // 64
       469250000L,      // 65
       475250000L,      // 66
       481250000L,      // 67
       487250000L,      // 68
       493250000L,      // 69
       499250000L,      // 70
       505250000L,      // 71
       511250000L,      // 72
       517250000L,      // 73
       523250000L,      // 74
       529250000L,      // 75
       535250000L,      // 76
       541250000L,      // 77
       547250000L,      // 78
       553250000L,      // 79
       559250000L,      // 80
       565250000L,      // 81
       571250000L,      // 82
       577250000L,      // 83
       583250000L,      // 84
       589250000L,      // 85
       595250000L,      // 86
       601250000L,      // 87
       607250000L,      // 88
       613250000L,      // 89
       619250000L,      // 90
       625250000L,      // 91
       631250000L,      // 92
       637250000L,      // 93
       643250000L,      // 94
        91250000L,      // 95
        97250000L,      // 96
       103250000L,      // 97
       109250000L,      // 98
       115250000L,      // 99
       649250000L,      // 100
       655250000L,      // 101
       661250000L,      // 102
       667250000L,      // 103
       673250000L,      // 104
       679250000L,      // 105
       685250000L,      // 106
       691250000L,      // 107
       697250000L,      // 108
       703250000L,      // 109
       709250000L,      // 110
       715250000L,      // 111
       721250000L,      // 112
       727250000L,      // 113
       733250000L,      // 114
       739250000L,      // 115
       745250000L,      // 116
       751250000L,      // 117
       757250000L,      // 118
       763250000L,      // 119
       769250000L,      // 120
       775250000L,      // 121
       781250000L,      // 122
       787250000L,      // 123
       793250000L,      // 124
       799250000L,      // 125
       805250000L,      // 126
       811250000L,      // 127
       817250000L,      // 128
       823250000L,      // 129
       829250000L,      // 130
       835250000L,      // 131
       841250000L,      // 132
       847250000L,      // 133
       853250000L,      // 134
       859250000L,      // 135
       865250000L,      // 136
       871250000L,      // 137
       877250000L,      // 138
       883250000L,      // 139
       889250000L,      // 140
       895250000L,      // 141
       901250000L,      // 142
       907250000L,      // 143
       913250000L,      // 144
       919250000L,      // 145
       925250000L,      // 146
       931250000L,      // 147
       937250000L,      // 148
       943250000L,      // 149
       949250000L,      // 150
       955250000L,      // 151
       961250000L,      // 152
       967250000L,      // 153
       973250000L,      // 154
       979250000L,      // 155
       985250000L,      // 156
       991250000L,      // 157
       997250000L,      // 158
END

5.1.12 United Kingdom

The frequency indexes in the United Kingdom tables are not suitable for use as channel numbers.

5.1.12.1 United Kingdom Broadcast Assignments

F_UK__BROAD RCDATA
BEGIN
        1L,             // Lowest index
        69L,            // Highest index

        45750000L,      // 1
        53750000L,      // 2
        61750000L,      // 3
       175250000L,      // 4
       183250000L,      // 5
       191250000L,      // 6
       199250000L,      // 7
       207250000L,      // 8
       215250000L,      // 9
       223250000L,      // 10
       231250000L,      // 11

               0L,      // 12  not used
               0L,      // 13  not used
               0L,      // 14  not used
               0L,      // 15  not used
               0L,      // 16  not used
               0L,      // 17  not used
               0L,      // 18  not used
               0L,      // 19  not used
               0L,      // 20  not used

       471250000L,      // 21
       479250000L,      // 22
       487250000L,      // 23
       495250000L,      // 24
       503250000L,      // 25
       511250000L,      // 26
       519250000L,      // 27
       527250000L,      // 28
       535250000L,      // 29
       543250000L,      // 30
       551250000L,      // 31
       559250000L,      // 32
       567250000L,      // 33
       575250000L,      // 34
       583250000L,      // 35
       591250000L,      // 36
       599250000L,      // 37
       607250000L,      // 38
       615250000L,      // 39
       623250000L,      // 40
       631250000L,      // 41
       639250000L,      // 42
       647250000L,      // 43
       655250000L,      // 44
       663250000L,      // 45
       671250000L,      // 46
       679250000L,      // 47
       687250000L,      // 48
       695250000L,      // 49
       703250000L,      // 50
       711250000L,      // 51
       719250000L,      // 52
       727250000L,      // 53
       735250000L,      // 54
       743250000L,      // 55
       751250000L,      // 56
       759250000L,      // 57
       767250000L,      // 58
       775250000L,      // 59
       783250000L,      // 60
       791250000L,      // 61
       799250000L,      // 62
       807250000L,      // 63
       815250000L,      // 64
       823250000L,      // 65
       831250000L,      // 66
       839250000L,      // 67
       847250000L,      // 68
       855250000L,      // 69

END

United Kingdom Cable Assignments

F_UK__CABLE RCDATA
BEGIN
         1L,            // Lowest index
       107L,            // Highest index

        48250000L,      // 1    E2
        49750000L,      // 2    E2A
        55250000L,      // 3    E3
        62250000L,      // 4    E4
        69250000L,      // 5    S01
        76250000L,      // 6    S02
        83250000L,      // 7    S03
        90250000L,      // 8    S04
        97250000L,      // 9    S05
       105250000L,      // 10   S1
       112250000L,      // 11   S2
       119250000L,      // 12   S3
       126250000L,      // 13   S4
       133250000L,      // 14   S5
       140250000L,      // 15   S6
       147250000L,      // 16   S7
       154250000L,      // 17   S8
       161250000L,      // 18   S9
       168250000L,      // 19   S10
       175250000L,      // 20   E5
       182250000L,      // 21   E6
       189250000L,      // 22   E7
       196250000L,      // 23   E8
       203250000L,      // 24   E9
       210250000L,      // 25   E10
       217250000L,      // 26   E11
       224250000L,      // 27   E12
       231250000L,      // 28   S11
       238250000L,      // 29   S12
       245250000L,      // 30   S13
       252250000L,      // 31   S14
       259250000L,      // 32   S15
       266250000L,      // 33   S16
       273250000L,      // 34   S17
       280250000L,      // 35   S18
       287250000L,      // 36   S19
       294250000L,      // 37   S20
       303250000L,      // 38   S21
       311250000L,      // 39   S22
       319250000L,      // 40   S23
       327250000L,      // 41   S24
       335250000L,      // 42   S25
       343250000L,      // 43   S26
       351250000L,      // 44   S27
       359250000L,      // 45   S28
       367250000L,      // 46   S29
       375250000L,      // 47   S30
       383250000L,      // 48   S31
       391250000L,      // 49   S32
       399250000L,      // 50   S33
       407250000L,      // 51   S34
       415250000L,      // 52   S35
       423250000L,      // 53   S36
       431250000L,      // 54   S37
       439250000L,      // 55   S38
       447250000L,      // 56   S39
       455250000L,      // 57   S40
       463250000L,      // 58   S41

       471250000L,      // 59
       479250000L,      // 60
       487250000L,      // 61
       495250000L,      // 62
       503250000L,      // 63
       511250000L,      // 64
       519250000L,      // 65
       527250000L,      // 66
       535250000L,      // 67
       543250000L,      // 68
       551250000L,      // 69
       559250000L,      // 70
       567250000L,      // 71
       575250000L,      // 72
       583250000L,      // 73
       591250000L,      // 74
       599250000L,      // 75
       607250000L,      // 76
       615250000L,      // 77
       623250000L,      // 78
       631250000L,      // 79
       639250000L,      // 80
       647250000L,      // 81
       655250000L,      // 82
       663250000L,      // 83
       671250000L,      // 84
       679250000L,      // 85
       687250000L,      // 86
       695250000L,      // 87
       703250000L,      // 88
       711250000L,      // 89
       719250000L,      // 90
       727250000L,      // 91
       735250000L,      // 92
       743250000L,      // 93
       751250000L,      // 94
       759250000L,      // 95
       767250000L,      // 96
       775250000L,      // 97
       783250000L,      // 98
       791250000L,      // 99
       799250000L,      // 100
       807250000L,      // 101
       815250000L,      // 102
       823250000L,      // 103
       831250000L,      // 104
       839250000L,      // 105
       847250000L,      // 106
       855250000L,      // 107

END

5.1.13 Western Europe

The frequency indexes in the Western Europe tables are not suitable for use as channel numbers.

5.1.13.1 Western Europe Broadcast Assignments

F_WEU_BROAD RCDATA
BEGIN
        1L,             // Lowest index
        69L,            // Highest index

        48250000L,      // 2
        49750000L,      // 2A
        55250000L,      // 3
        62250000L,      // 4
       175250000L,      // 5
       182250000L,      // 6
       189250000L,      // 7
       196250000L,      // 8
       203250000L,      // 9
       210250000L,      // 10
       217250000L,      // 11
       224250000L,      // 12

               0L,      // 13 Not used
               0L,      // 14 Not used
               0L,      // 15 Not used
               0L,      // 16 Not used
               0L,      // 17 Not used
               0L,      // 18 Not used
               0L,      // 19 Not used
               0L,      // 20 Not used

       471250000L,      // 21
       479250000L,      // 22
       487250000L,      // 23
       495250000L,      // 24
       503250000L,      // 25
       511250000L,      // 26
       519250000L,      // 27
       527250000L,      // 28
       535250000L,      // 29
       543250000L,      // 30
       551250000L,      // 31
       559250000L,      // 32
       567250000L,      // 33
       575250000L,      // 34
       583250000L,      // 35
       591250000L,      // 36
       599250000L,      // 37
       607250000L,      // 38
       615250000L,      // 39
       623250000L,      // 40
       631250000L,      // 41
       639250000L,      // 42
       647250000L,      // 43
       655250000L,      // 44
       663250000L,      // 45
       671250000L,      // 46
       679250000L,      // 47
       687250000L,      // 48
       695250000L,      // 49
       703250000L,      // 50
       711250000L,      // 51
       719250000L,      // 52
       727250000L,      // 53
       735250000L,      // 54
       743250000L,      // 55
       751250000L,      // 56
       759250000L,      // 57
       767250000L,      // 58
       775250000L,      // 59
       783250000L,      // 60
       791250000L,      // 61
       799250000L,      // 62
       807250000L,      // 63
       815250000L,      // 64
       823250000L,      // 65
       831250000L,      // 66
       839250000L,      // 67
       847250000L,      // 68
       855250000L,      // 69

END

5.1.13.2 Western Europe Cable Assignments

There was data supporting a standardized cable lineup for some countries. However, for those countries not reporting channel lineup data, the Unicable frequency table (see below) will be used.

F_WEU_CABLE RCDATA
BEGIN
         1L,            // Lowest index
       107L,            // Highest index

        48250000L,      // 1    E2
        49750000L,      // 2    E2A
        55250000L,      // 3    E3
        62250000L,      // 4    E4
        69250000L,      // 5    S01
        76250000L,      // 6    S02
        83250000L,      // 7    S03
        90250000L,      // 8    S04
        97250000L,      // 9    S05
       105250000L,      // 10   S1
       112250000L,      // 11   S2
       119250000L,      // 12   S3
       126250000L,      // 13   S4
       133250000L,      // 14   S5
       140250000L,      // 15   S6
       147250000L,      // 16   S7
       154250000L,      // 17   S8
       161250000L,      // 18   S9
       168250000L,      // 19   S10
       175250000L,      // 20   E5
       182250000L,      // 21   E6
       189250000L,      // 22   E7
       196250000L,      // 23   E8
       203250000L,      // 24   E9
       210250000L,      // 25   E10
       217250000L,      // 26   E11
       224250000L,      // 27   E12
       231250000L,      // 28   S11
       238250000L,      // 29   S12
       245250000L,      // 30   S13
       252250000L,      // 31   S14
       259250000L,      // 32   S15
       266250000L,      // 33   S16
       273250000L,      // 34   S17
       280250000L,      // 35   S18
       287250000L,      // 36   S19
       294250000L,      // 37   S20
       303250000L,      // 38   S21
       311250000L,      // 39   S22
       319250000L,      // 40   S23
       327250000L,      // 41   S24
       335250000L,      // 42   S25
       343250000L,      // 43   S26
       351250000L,      // 44   S27
       359250000L,      // 45   S28
       367250000L,      // 46   S29
       375250000L,      // 47   S30
       383250000L,      // 48   S31
       391250000L,      // 49   S32
       399250000L,      // 50   S33
       407250000L,      // 51   S34
       415250000L,      // 52   S35
       423250000L,      // 53   S36
       431250000L,      // 54   S37
       439250000L,      // 55   S38
       447250000L,      // 56   S39
       455250000L,      // 57   S40
       463250000L,      // 58   S41

       471250000L,      // 59
       479250000L,      // 60
       487250000L,      // 61
       495250000L,      // 62
       503250000L,      // 63
       511250000L,      // 64
       519250000L,      // 65
       527250000L,      // 66
       535250000L,      // 67
       543250000L,      // 68
       551250000L,      // 69
       559250000L,      // 70
       567250000L,      // 71
       575250000L,      // 72
       583250000L,      // 73
       591250000L,      // 74
       599250000L,      // 75
       607250000L,      // 76
       615250000L,      // 77
       623250000L,      // 78
       631250000L,      // 79
       639250000L,      // 80
       647250000L,      // 81
       655250000L,      // 82
       663250000L,      // 83
       671250000L,      // 84
       679250000L,      // 85
       687250000L,      // 86
       695250000L,      // 87
       703250000L,      // 88
       711250000L,      // 89
       719250000L,      // 90
       727250000L,      // 91
       735250000L,      // 92
       743250000L,      // 93
       751250000L,      // 94
       759250000L,      // 95
       767250000L,      // 96
       775250000L,      // 97
       783250000L,      // 98
       791250000L,      // 99
       799250000L,      // 100
       807250000L,      // 101
       815250000L,      // 102
       823250000L,      // 103
       831250000L,      // 104
       839250000L,      // 105
       847250000L,      // 106
       855250000L,      // 107
END

5.1.14 Unicable

Due to its length, the Unicable table is not included here. The goal behind the Unicable table is to include a comprehensive set of frequencies (basically all other tables combined, plus some real-world observations) in one table to facilitate an automated channel scan without resorting to a linear search of the entire frequency spectrum. For those frequencies not covered by this table, the consumer will be required to enter a frequency through a custom user interface, resulting in a frequency override entry in the registry (see section 0 above).

5.2 Country Assignments

The number in the first column is the country code, as provided by international telephone dialing standards. This country code number can be passed to the IAMTVTuner::put_CountryCode method to select the color standard, and default frequency mappings.

RCDATA_COUNTRYLIST RCDATA

BEGIN

1,   F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,
                                         // United States of America
                                         // Anguilla
                                         // Antigua
                                         // Bahamas
                                         // Barbados
                                         // Bermuda
                                         // British Virgin Islands
                                         // Canada
                                         // Cayman Islands
                                         // Dominica
                                         // Dominican Republic
                                         // Grenada
                                         // Jamaica
                                         // Montserrat
                                         // Nevis
                                         // St. Kitts
                                         // St. Vincent and the Grenadines
                                         // Trinidad and Tobago
                                         // Turks and Caicos Islands
                                         // Barbuda
                                         // Puerto Rico
                                         // Saint Lucia
                                         // United States Virgin Islands

2,   F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Canada (WIN.INI is bogus for this one country)

20,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,     // Egypt
212, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_SECAM_B,     // Morocco
213, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Algeria
216, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,     // Tunisia
218, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,     // Libya
220, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Gambia
221, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Senegal Republic
222, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_SECAM_B,     // Mauritania
223, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,     // Mali
224, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,     // Guinea
225, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_SECAM_K,     // Ivory Coast
226, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,     // Burkina Faso
227, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Niger
228, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Togo
229, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Benin
230, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,     // Mauritius
231, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Liberia
232, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Sierra Leone
233, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Ghana
234, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Nigeria
235, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Chad
236, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Central African Republic
237, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Cameroon
238, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_FIX___,      // Cape Verde Islands
239, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Sao Tome and Principe
240, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_SECAM_B,     // Equatorial Guinea
241, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Gabon
242, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_D,     // Congo
243, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Zaire
244, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_PAL_I,       // Angola
245, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_FIX___,      // Guinea-Bissau
246, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Diego Garcia
247, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Ascension Island
248, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Seychelle Islands
249, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Sudan
250, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,,      // Rwanda
251, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Ethiopia
252, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Somalia
253, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Djibouti
254, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Kenya
255, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Tanzania
256, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Uganda
257, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_SECAM_K,     // Burundi
258, F_UNI_CABLE, F_FIX_BROAD, AnalogVideo_PAL_B,       // Mozambique
260, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Zambia
261, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Madagascar
262, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Reunion Island
263, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Zimbabwe
264, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_I,       // Namibia
265, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Malawi
266, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_I,       // Lesotho
267, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,     // Botswana
268, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Swaziland
269, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,     // Mayotte Island
269, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Comoros
27,  F_UNI_CABLE, F_UK__BROAD, AnalogVideo_PAL_I,       // South Africa
290, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // St. Helena
291, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Eritrea
297, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Aruba
298, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Faroe Islands
299, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Greenland
30,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,     // Greece
31,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Netherlands
32,  F_WEU_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Belgium
33,  F_UNI_CABLE, F_FRA_BROAD, AnalogVideo_SECAM_L,     // France
34,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Spain
350, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Gibraltar
351, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Portugal
352, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Luxembourg
353, F_UNI_CABLE, F_IRE_BROAD, AnalogVideo_PAL_I,       // Ireland
354, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Iceland
355, F_UNI_CABLE, F_ITA_BROAD, AnalogVideo_PAL_B,       // Albania
356, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Malta
357, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Cyprus
358, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Finland
359, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Bulgaria
36,  F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Hungary
370, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Lithuania
371, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_D,     // Latvia
372, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Estonia
373, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Moldova
374, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Armenia
375, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Belarus
376, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Andorra
377, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_G,     // Monaco
378, F_UNI_CABLE, F_ITA_BROAD, AnalogVideo_PAL_B,       // San Marino
380, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Ukraine
381, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Yugoslavia
385, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Croatia
386, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Slovenia
387, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Bosnia and Herzegovina
389, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // F.Y.R.O.M. (Former Yugoslav Republic of Macedonia)
39,  F_UNI_CABLE, F_ITA_BROAD, AnalogVideo_PAL_B,       // Italy
39,  F_UNI_CABLE, F_ITA_BROAD, AnalogVideo_PAL_B,       // Vatican City
40,  F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_PAL_D,       // Romania
41,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Switzerland
41,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Liechtenstein
420, F_UNI_CABLE, F_CZE_BROAD, AnalogVideo_PAL_D,       // Czech Republic
421, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Slovak Republic
43,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Austria
44,  F_UK__CABLE, F_UK__BROAD, AnalogVideo_PAL_I,       // United Kingdom
45,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Denmark
46,  F_WEU_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Sweden
47,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Norway
48,  F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_PAL_B,       // Poland
49,  F_WEU_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Germany
500, F_UNI_CABLE, F_UK__BROAD, AnalogVideo_PAL_I,       // Falkland Islands
501, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Belize
502, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Guatemala
503, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // El Salvador
504, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Honduras
505, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Nicaragua
506, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Costa Rica
507, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Panama
508, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // St. Pierre and Miquelon
509, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Haiti
51,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Peru
52,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Mexico
53,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Cuba
53,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Guantanamo Bay
54,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_N,       // Argentina
55,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_M,       // Brazil
56,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Chile
57,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Colombia
58,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Venezuela
590, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Guadeloupe
590, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // French Antilles
591, F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_N,       // Bolivia
592, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Guyana
593, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Ecuador
594, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // French Guiana
595, F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_N,       // Paraguay
596, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // Martinique
597, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Suriname
598, F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_N,       // Uruguay
599, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Netherlands Antilles
60,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Malaysia
61,  F_UNI_CABLE, F_OZ__BROAD, AnalogVideo_PAL_B,       // Australia
61,  F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Cocos-Keeling Islands
62,  F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Indonesia
63,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Philippines
64,  F_UNI_CABLE, F_NZ__BROAD, AnalogVideo_PAL_B,       // New Zealand
65,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Singapore
66,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Thailand
670, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Saipan Island
670, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Rota Island
670, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Tinian Island
671, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Guam
672, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Christmas Island
672, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Australian Antarctic Territory
672, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Norfolk Island
673, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Brunei
674, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Nauru
675, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Papua New Guinea
676, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Tonga
677, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Solomon Islands
678, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Vanuatu
679, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Fiji
680, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Palau
681, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_SECAM_K,     // Wallis and Futuna Islands
682, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Cook Islands
683, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Niue
684, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // American Samoa
685, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Western Samoa
686, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Kiribati Republic
687, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // New Caledonia
688, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Tuvalu
689, F_UNI_CABLE, F_FOT_BROAD, AnalogVideo_SECAM_K,     // French Polynesia
690, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Tokelau
691, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Micronesia
692, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Marshall Islands
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Russia
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Kazakhstan
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Kyrgyzstan
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Tajikistan
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Turkmenistan
7,   F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Uzbekistan

81,  F_JAP_CABLE, F_JAP_BROAD, AnalogVideo_NTSC_M_J,       // Japan

82,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Korea (South)
84,  F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Vietnam
850, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Korea (North)
852, F_UNI_CABLE, F_UK__BROAD, AnalogVideo_PAL_I,       // Hong Kong
853, F_UNI_CABLE, F_UK__BROAD, AnalogVideo_PAL_I,       // Macau
855, F_USA_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Cambodia
856, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Laos
86,  F_CHN_CABLE, F_CHN_BROAD, AnalogVideo_PAL_D,       // China
871, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // INMARSAT (Atlantic-East)
872, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // INMARSAT (Pacific)
873, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // INMARSAT (Indian)
874, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // INMARSAT (Atlantic-West)
880, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Bangladesh
886, F_USA_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Taiwan, Republic of China
90,  F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Turkey
91,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // India
92,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Pakistan
93,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Afghanistan
94,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Sri Lanka
95,  F_UNI_CABLE, F_USA_BROAD, AnalogVideo_NTSC_M,      // Myanmar
960, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Maldives
961, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,     // Lebanon
962, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Jordan
963, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,     // Syria
964, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,     // Iraq
965, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Kuwait
966, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,     // Saudi Arabia
967, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Yemen
968, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Oman
971, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // United Arab Emirates
972, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Israel
973, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Bahrain
974, F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_PAL_B,       // Qatar
975, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_FIX___,      // Bhutan
976, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Mongolia
977, F_UNI_CABLE, F_USA_BROAD, AnalogVideo_PAL_B,       // Nepal
98,  F_UNI_CABLE, F_WEU_BROAD, AnalogVideo_SECAM_B,     // Iran
994, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Azerbaijan
995, F_UNI_CABLE, F_EEU_BROAD, AnalogVideo_SECAM_D,     // Georgia

0,   0,           0,           0  // Zero marks the end of the list

END


Multimedia Streaming

This section describes the multimedia streaming interfaces, which automatically negotiate the transfer and conversion of data from a source to an application. It includes reference entries for the multimedia streaming data types, interfaces, and interface methods. It also includes sample code and a description of multimedia streaming component objects along with their CLSIDs and the interfaces they support.

  • About the Multimedia Streaming Architecture
  • List of Multimedia Streaming Interfaces
  • Multimedia Streaming Reference
  • Multimedia Streaming Component Objects
  • Multimedia Streaming Sample Code


About the Multimedia Streaming Architecture

This article describes the architecture of multimedia streaming and how software developers typically use streams in their tools and applications. It also covers the advantages of streaming as a base for data transfer and how to address multimedia programming issues, such as data transfer, performance optimization, and time stamping in streaming applications. Programmers who want to use multimedia streaming should be familiar with COM programming concepts.

This article contains the following sections.

  • Advantages of Multimedia Streaming
  • Object Hierarchy
  • Creating Multimedia Stream Objects and Stream Samples
  • Using Multimedia Streams in Applications
  • Sharing Data Between Streams

Advantages of Multimedia Streaming

When developers use multimedia streaming in their applications, it greatly reduces the amount of format-specific programming needed. Typically, an application that must obtain media data from a file or hardware source must know everything about the data format and the hardware device. The application must handle the connection, transfer of data, any necessary data conversion, and the actual data rendering or file storage. Because each format and device is slightly different, this process is often complex and cumbersome. Multimedia streaming, on the other hand, automatically negotiates the transfer and conversion of data from the source to the application. The streaming interfaces provide a uniform and predictable method of data access and control, which makes it easy for an application to play back the data, regardless of its original source or format.

The following steps show how to implement streaming, from hardware device to rendered playback.

  1. A source of video data, such as Microsoft® DirectShow®, exposes the streaming interfaces.
  2. The application developer uses the multimedia streaming interfaces to handle data format conversion.
  3. The application developer uses the Microsoft DirectDraw® interfaces to render the resulting data.

The specification for multimedia streams comprises several interfaces; each interface includes methods that control a certain aspect of the streaming process or handle a certain type of data. See List of Multimedia Streaming Interfaces for additional information.

Object Hierarchy

The following diagram shows the basic object hierarchy used in multimedia streaming.

There are three basic object types defined in the multimedia streaming architecture:

  1. A multimedia stream, which supports the IMultiMediaStream interface.
  2. Media streams support the IMediaStream interface and are data specific. Every multimedia stream contains one or more of these media streams.
  3. Stream samples support the IStreamSample interface and are created by a media stream. These objects represent a basic unit of work for the stream.

Creating Multimedia Stream Objects and Stream Samples

Objects that support the IMultiMediaStream interface are the basic containers for multimedia data streams. The IMultiMediaStream interface includes methods that enumerate the object's data streams; these streams are typically video and audio data, but can include data of any format, such as closed-captioning, plain text, or SMPTE timecode. The IMultiMediaStream interface is a generic container, however; developers can create other versions of the interface that support specific data formats. Objects that implement the IAMMultiMediaStream interface, for example, can enumerate and control streams of any DirectShow data format. Because individual data streams are format specific, they support at least two different interfaces: one generic and one data-specific. Every stream supports the IMediaStream interface, which provides methods to retrieve its format and a pointer to the stream itself. The IDirectDrawMediaStream interface, on the other hand, has methods that deal specifically with rendering video data. Any interface derived from IMultiMediaStream also supports the creation of stream samples, the basic units of streaming data.

A multimedia sample is a reference to an object containing the media data. For a video image, this is a DirectDraw surface. The sample's exact content varies, depending on the type of media (sound, text, and so on). Because a sample is only a reference to the data object, any number of stream samples can refer to the same object. The IStreamSample interface provides methods that get and set a sample's characteristics, such as its start and stop time, status, and stream association. The IStreamSample::Update method refreshes the sample's data in the case of readable streams. For writable streams, it will write the sample's data to the stream. Typically, you use the Update method in a loop that renders, transfers, or stores streaming data.

Using Multimedia Streams in Applications

The multimedia streaming interfaces greatly simplify the process of manipulating multimedia data by removing the dependency on specific characteristics of the hardware or software source and providing support for all Microsoft DirectX® media formats. Streams abstract the data to a very high level; applications can even move data from one stream to another without knowing anything about the data's format.

Perform the following steps to create a multimedia stream.

  1. Create the multimedia stream. The method of creation and initialization of the stream is architecture specific. DirectShow supports the IAMMultiMediaStream interface, which is used to initialize the stream. Other in-process server implementations of IMultiMediaStream will be created and initialized using different mechanisms.
  2. After the multimedia stream object is initialized, the application will use QueryInterface to retrieve the IMultiMediaStream interface for the object. Use this interface to determine the stream's properties and enumerate the streams themselves. You can retrieve a specific stream by calling the IMultiMediaStream::GetMediaStream method with a specific purpose ID. MSPID_PrimaryVideo and MSPID_PrimaryAudio, which represent the primary video and audio streams, are the most commonly used purpose IDs.
  3. Call IUnknown::QueryInterface for an interface specific to the stream's media type. If you want to render a video stream, for example, retrieve its IDirectDrawMediaStream interface. Media-specific interfaces define additional methods necessary for taking full advantage of a format's capabilities.
  4. Create one or more samples from the stream data. Every media stream supports the IMediaStream::CreateSharedSample method for sample creation. The resulting sample supports the IStreamSample interface, which provides control over the sample and its characteristics. Typically, the media stream supports a format-specific method of sample creation that is more powerful than the aforementioned IStreamSample methods. IDirectDrawMediaStream, for example, can create samples attached to a desired DirectDraw surface and clipping rectangle. In some situations, however, you must handle data without knowing about its data format. If you want to stream data independent of its format, use the IMediaStream::CreateSharedSample method to create the data samples.
  5. After creating all desired stream samples, start the stream by calling the IMultiMediaStream::SetState method and pass in the STREAMSTATE_RUN flag as its parameter.
  6. Call IStreamSample::Update to update the stream sample. When the IStreamSample::Update method exits, you can access the sample's data. If you want a trigger a specific event or function call when the update returns, pass the appropriate pointers to the IStreamSample::Update method.

For more information on the multimedia streaming interfaces, see Multimedia Streaming.

Sharing Data Between Streams

Processing multimedia data typically requires a great deal of system resources; therefore, you should avoid copying data whenever possible. The streaming architecture supports shared stream samples, a mechanism that moves data from one stream to another without copying it. This buffer enables the efficient transportation of data between two streams even if the destination stream doesn't specifically support the underlying data format.

For example, assume that you have a multimedia stream with three data streams: video and audio, and URL data time-stamped to match the video content. You want to write an application that adds a copyright notice on every video frame and writes the data to another stream for storage, but your application doesn't understand any data formats except the video stream. For the video stream, you create a sample attached to the desired DirectDraw surface. You can then create an output stream by calling either the IDirectDrawMediaStream::CreateSample method with that pointer to the same surface, or IMediaStream::CreateSharedSample. In both cases, the input and output streams share the DirectDraw surface. Because you understand the video format, you can access this surface as needed.

To retrieve the other source stream pointers (audio and URL), enumerate the source container stream and grab pointers to the nonvideo streams. Each of these source streams has an associated output stream in the output stream container. Retrieve these output pointers by calling the IMultiMediaStream::GetMediaStream method on the output container with each of the source stream pointers. The following steps describe this process.

  1. Call IMultiMediaStream::EnumMediaStreams to retrieve a pointer to a source stream. Make sure that it's not the video stream, because your application already understands its format.
  2. Call IMultiMediaStream::GetMediaStream on the output container stream with the pointer from step 1. This returns a pointer to the desired output stream.
  3. Call AllocateSample on the source stream.
  4. Call CreateSharedSample on the output stream.
  5. Call Update on the source stream to read the data.
  6. Call Update on the output stream to write the data.

Repeat these steps for each stream whose format you don't support. When both samples finish updating, the output stream has all data from the source stream and you are done.


List of Multimedia Streaming Interfaces

Multimedia streaming comprises a number of interfaces; this article provides a brief description of each interface. For additional information about multimedia streaming, see About the Multimedia Streaming Architecture.

This article contains the following sections.

  • Base Multimedia Streaming Interfaces
  • DirectDraw Streaming Interfaces
  • Audio Streaming Interfaces
  • DirectShow Multimedia Streaming Interfaces

Base Multimedia Streaming Interfaces

The base multimedia streaming interfaces provide a programmatic way to access multimedia streams. However, using a base interface to access a specific type of data can limit the amount of control you have over the data, so media developers should create derived versions of these interfaces that provide more powerful control over the unique capabilities of their media type.

IMultiMediaStream
Defines how to access the highest-level multimedia stream object; this object contains and provides access to other stream objects. IMultiMediaStream has methods that enumerate or retrieve specific streams, as well as checking the stream's total time duration and seeking within the stream.
IMediaStream
Defines a generic stream object. Use its methods to retrieve a pointer to the stream, get information about the stream, and create samples from the stream data. You can also create shared stream samples, which multiple streams can access without duplicating the sample's data.
IStreamSample
Controls the behavior of a specific stream sample. You can retrieve the stream that created the sample, check the sample's start and end times and completion status, and perform a user-defined function on the sample itself (through the Update method). Typically, the Update method processes the sample data in an appropriate manner, such as rendering video data or playing back audio data.

DirectDraw Streaming Interfaces

If you use Microsoft® DirectDraw®-supported video formats in your streams, the following interfaces give you more powerful control over the data than the more generic base interfaces.

IDirectDrawMediaStream
Sets and retrieves the stream format and the DirectDraw object associated with the media stream; this interface derives from IMediaStream. You can also use this interface to create video samples.
IDirectDrawStreamSample
Enables you to attach video samples to DirectDraw surfaces; this interface derives from the IStreamSample interface. Each attached surface includes a clipping rectangle to make rendering easier.

Audio Streaming Interfaces

IAudioMediaStream
Controls audio media streams. This interface inherits from the IMediaStream interface and is used to create one or more IAudioStreamSample objects. It is also used to set and retrieve the current format of the stream data.
IAudioStreamSample
Retrieves information from the underlying IAudioData data objects.
IMemoryData
Contains methods that set and retrieve memory data on audio data objects. Audio data objects provide the underlying data that stream samples access. This interface provides a way to initialize memory buffers and to set actual amounts of audio data in the objects. Additionally, the IMemoryData::GetInfo method can be used to retrieve audio memory data.
IAudioData
Provides methods that enable applications to set and get the underlying audio data that audio streams will reference. The audio data format is set in the WAVEFORMATEX structure.

DirectShow Multimedia Streaming Interfaces

The following interfaces expose Microsoft® DirectShow® functionality to multimedia stream developers. Application developers should implement only the IAMMultiMediaStream interface in their applications; DirectShow uses the other two interfaces internally.

IAMMultiMediaStream
Controls connections between streams and DirectShow filter graphs. It provides methods that instantiate filter graphs, open DirectShow-supported media files, and generate an appropriate filter graph for playback. The CLSID_ActiveMovieMMStream class identifier supports this interface.
IAMMediaStream
Handles the internal negotiation of connections between multimedia streams and DirectShow filter graphs. This interface is a DirectShow-specific derivation of the IMediaStream interface. Application developers should not use or implement this interface.


Multimedia Streaming Reference

This section contains reference entries for all the multimedia streaming interfaces and their methods, including those that Microsoft® DirectShow® supports. It also includes a list of multimedia streaming data types that the interfaces use, and a list of error and success codes that the methods return.

Multimedia Streaming Interfaces

  • IAMMediaStream
  • IAMMediaTypeSample
  • IAMMediaTypeStream
  • IAMMultiMediaStream
  • IAudioData
  • IAudioMediaStream
  • IAudioStreamSample
  • IDirectDrawMediaStream
  • IDirectDrawStreamSample
  • IMediaStream
  • IMemoryData
  • IMultiMediaStream
  • IStreamSample

Data Types and Return Codes

  • Multimedia Streaming Data Types
  • Error and Success Codes for Multimedia Streaming


IAMMediaStream Interface

The IAMMediaStream interface handles the internal connections between Microsoft® DirectShow® filters and filter graphs in applications that use multimedia streaming. This enables applications to automatically negotiate the transfer and conversion of data from the source to the application without having to write code to handle the connection, transfer of data, data conversion, and actual data rendering or file storage. This provides a uniform and predictable method of data access and control.

This interface isn't intended for implementation or use by application developers.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMMediaStream methods | Description
Initialize | Creates and initializes a new media stream with the specified stream type and purpose ID.
SetState | Sets the filter state.
JoinAMMultiMediaStream | The IAMMultiMediaStream::AddMediaStream method calls this method, which adds the specified media stream to the current multimedia stream.
JoinFilter | Connects a media stream to a media stream filter in the underlying filter graph.
JoinFilterGraph | Connects a media stream filter to a filter graph.

IAMMediaStream::Initialize

IAMMediaStream Interface

Creates and initializes a new media stream with the specified stream type and purpose ID.

Syntax

HRESULT Initialize(
    IUnknown *pSourceObject,
    DWORD dwFlags,
    REFMSPID PurposeID,
    STREAM_TYPE StreamType
    );

Parameters

pSourceObject
[in] Pointer to an IUnknown source object.
dwFlags
[in] Value that modifies the media stream's behavior; it is a combination of one or more of the following values.
AMMSF_ADDDEFAULTRENDERER | Add a default renderer.
AMMSF_CREATEPEER | Create a peer stream based on the same object as a pStreamObject.
AMMSF_STOPIFNOSAMPLES | Terminates the stream if no samples were created or if the last sample is deleted.
AMMSF_NOSTALL | Run the stream even if Update is not called.
PurposeID
[in] Purpose ID for the new media stream.
StreamType
[in] STREAM_TYPE enumeration value that specifies the new media stream's media type.

Return Value

Returns S_OK if successful or E_POINTER if one or more of the required parameters are invalid.

Remarks

If dwFlags specifies AMMSF_ADDDEFAULTRENDERER, then the default renderer for the given purpose ID is created, if possible. Currently, the only default renderer supported is for audio using Microsoft® DirectSound®. In this case, the pStreamObject parameter must be NULL and any calls to the IMultiMediaStream::GetMediaStream or IMultiMediaStream::EnumMediaStreams method will not recognize the stream.

If dwFlags specifies AMMSF_CREATEPEER, then a media stream is created using pStreamObject and added to the current multimedia stream. The pStreamObject parameter varies depending on the stream type. In general, pStreamObject can point to an IMediaStream object, in which case a stream with the sample purpose ID and format is created. For IDirectDraw streams, it can also be a pointer to an IDirectDraw object.

If dwFlags specifies AMMSF_STOPIFNOSAMPLES, then the stream is terminated.

If no flags are set, then pStreamObject can be one of the following.
An IAMMediaStream object | This stream is then added to the streams in the multimedia stream.
NULL | In this case a default IMediaStream object is added to the stream with a default underlying object, if required.
A pointer to an underlying object | This is used to construct default streams. For video streams, this can be an IDirectDraw pointer.

IAMMediaStream::JoinAMMultiMediaStream

IAMMediaStream Interface

The IAMMultiMediaStream::AddMediaStream method calls this method, which adds the specified media stream to the current multimedia stream.

Syntax

HRESULT JoinAMMultiMediaStream(
    IAMMultiMediaStream *pAMMultiMediaStream
    );

Parameters

pAMMultiMediaStream
[in] Pointer to the IAMMultiMediaStream object to add the current media stream to.

Return Value

Returns S_OK if successful or MS_E_SAMPLEALLOC if the media stream already has allocated stream samples.

Remarks

Don't increment the reference count of the supplied multimedia stream because it is already accounted for when created.

Applications should not call this method.

IAMMediaStream::JoinFilter

IAMMediaStream Interface

Connects a media stream to a media stream filter in the underlying filter graph.

Syntax

HRESULT JoinFilter( );

Return Value

Returns S_OK if successful.

Remarks

Don't increment the reference count for the specified media stream filter.

Applications should not call this method.

IAMMediaStream::JoinFilterGraph

IAMMediaStream Interface

Connects a media stream filter to a filter graph.

Syntax

HRESULT JoinFilterGraph(
    IFilterGraph *pGraph
    );

Parameters

pGraph
[in] Pointer to the current media stream filter to add to the specified filter graph.

Return Value

Returns S_OK if successful or E_POINTER if pGraph is NULL.

Remarks

Don't increment the reference count of the specified filter graph.

Applications should not call this method.

IAMMediaStream::SetState

IAMMediaStream Interface

Sets the filter state.

Syntax

HRESULT SetState(
    FILTER_STATE State
    );

Parameters

State
[in] Sets the filter's state, as specified by the FILTER_STATE enumerated type.

Return Value

Returns S_OK if successful or E_INVALIDARG if the State parameter is invalid.

Remarks

Applications should not call this method.


IAMMediaTypeSample Interface

This interface contains methods for manipulating stream samples with arbitrary media types. Call the IAMMediaTypeStream::CreateSample method to create a sample that exposes this interface.

This interface inherits from the IStreamSample interface.

The methods in this interface parallel those of the IMediaSample interface, although IAMMediaTypeSample contains a SetPointer method in addition to the GetPointer method.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IStreamSample methods | Description
GetMediaStream | Retrieves a pointer to the media stream object that created the current sample.
GetSampleTimes | Retrieves the current sample's start and end times.
SetSampleTimes | Sets the current sample's start and end times.
Update | Performs a synchronous or an asynchronous update on the current sample.
CompletionStatus | Retrieves the status of the current sample's latest asynchronous update. If the update isn't complete, you can force it to complete.
IAMMediaTypeSample methods | Description
SetPointer | Sets the pointer to the media sample's memory buffer.
GetPointer | Retrieves a read/write pointer to the buffer's memory.
GetSize | Retrieves the size of the buffer data area, in bytes.
GetTime | Retrieves the stream times at which this sample should start and stop.
SetTime | Sets the stream times at which this sample should start and stop.
IsSyncPoint | Determines if the beginning of a sample is a synchronization point.
SetSyncPoint | Specifies whether the beginning of this sample is a synchronization point.
IsPreroll | Determines if this sample is part of the preroll.
SetPreroll | Specifies whether this is a preroll sample.
GetActualDataLength | Retrieves the data length of the sample, in bytes.
SetActualDataLength | Sets the sample's data length.
GetMediaType | Retrieves the media type of the sample.
SetMediaType | Sets the media type for the sample.
IsDiscontinuity | Determines if this sample represents a discontinuity in the data stream.
SetDiscontinuity | Sets the discontinuity property.
GetMediaTime | Retrieves the media time stamps for this sample.
SetMediaTime | Sets the media time stamps for this sample.

IAMMediaTypeSample::GetActualDataLength

IAMMediaTypeSample Interface

Retrieves the data length of the sample, in bytes.

Syntax

long GetActualDataLength(void);

Return Value

Returns the data length of the sample, in bytes.

IAMMediaTypeSample::GetMediaTime

IAMMediaTypeSample Interface

Retrieves the media time stamps for the sample.

Syntax

HRESULT GetMediaTime(
    LONGLONG *pTimeStart,
    LONGLONG *pTimeEnd
);

Parameters

pTimeEnd
[out] Pointer to a variable that receives the media start time.
pTimeStart
[out] Pointer to a variable that receives the media stop time.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_MEDIA_TIME_NOT_SET | No media time stamp was set for this sample.

IAMMediaTypeSample::GetMediaType

IAMMediaTypeSample Interface

Retrieves the media type of the sample. If the format has not changed from the previous sample, the sample might not carry a media type.

Syntax

HRESULT GetMediaType(
    AM_MEDIA_TYPE **ppMediaType
);

Parameters

ppMediaType
Address of a pointer that receives an AM_MEDIA_TYPE structure.

Return Value

Returns one of the following values.

E_OUTOFMEMORY | Insufficient memory.
S_FALSE | The format has not changed from the previous sample.
S_OK | Success.

IAMMediaTypeSample::GetPointer

IAMMediaTypeSample Interface

Retrieves a read/write pointer to the buffer's memory.

Syntax

HRESULT GetPointer(
    BYTE **ppBuffer
);

Parameters

ppBuffer
[out] Address of a pointer to the buffer.

Return Value

Returns S_OK.

IAMMediaTypeSample::GetSize

IAMMediaTypeSample Interface

Retrieves the size of the buffer data area, in bytes.

Syntax

long GetSize(void);

Return Value

Returns the size of the buffer data area, in bytes.

IAMMediaTypeSample::GetTime

IAMMediaTypeSample Interface

Retrieves the stream times at which the sample should start and stop.

Syntax

HRESULT GetTime(
    REFERENCE_TIME *pTimeStart,
    REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart
[out] Pointer to a variable that receives the start time.
pTimeEnd
[out] Pointer to a variable that receives the stop time. If the sample has no stop time, the value is set to the start time plus one.

Return Value

Returns one of the following values.

S_OK | Success.
VFW_E_SAMPLE_TIME_NOT_SET | The sample does not have any time stamps.
VFW_S_NO_STOP_TIME | The sample has a valid start time but no stop time.

IAMMediaTypeSample::IsDiscontinuity

IAMMediaTypeSample Interface

Determines if this sample represents a discontinuity in the data stream.

Syntax

HRESULT IsDiscontinuity(void);

Return Value

Returns S_OK if this sample is a discontinuity, or S_FALSE otherwise.

IAMMediaTypeSample::IsPreroll

IAMMediaTypeSample Interface

Determines if this sample is part of the preroll. A preroll sample should not be displayed.

Syntax

HRESULT IsPreroll(void);

Return Value

Returns S_OK if the sample is a preroll sample, or S_FALSE otherwise.

IAMMediaTypeSample::IsSyncPoint

IAMMediaTypeSample Interface

Determines if the beginning of a sample is a synchronization point.

Syntax

HRESULT IsSyncPoint(void);

Return Value

Returns S_OK if the beginning of the sample is a synchronization point, or S_FALSE otherwise.

IAMMediaTypeSample::SetActualDataLength

IAMMediaTypeSample Interface

Sets the sample's data length.

Syntax

HRESULT SetActualDataLength(
    long lActual
);

Parameters

lActual
Length of the data in the media sample, in bytes.

Return Value

Returns one of the following values.
S_OK | Success.
VFW_E_BUFFER_OVERFLOW | The buffer is not big enough.

IAMMediaTypeSample::SetDiscontinuity

IAMMediaTypeSample Interface

Sets the discontinuity property.

Syntax

HRESULT SetDiscontinuity(
    BOOL bDiscontinuity
);

Parameters

bDiscontinuity
Value that specifies whether this sample is a discontinuity. If the sample is discontinuous with the previous sample, set the value to TRUE. Otherwise, set the value to FALSE.

Return Value

Returns S_OK.

IAMMediaTypeSample::SetMediaTime

IAMMediaTypeSample Interface

Sets the media time stamps for this sample.

Syntax

HRESULT SetMediaTime(
    LONGLONG *pTimeStart,
    LONGLONG *pTimeEnd
);

Parameters

pTimeEnd
[in] Pointer to a variable that contains the media start time.
pTimeStart
[in] Pointer to a variable that contains the media stop time.

Return Value

Returns S_OK.

IAMMediaTypeSample::SetMediaType

IAMMediaTypeSample Interface

Sets the media type for the sample.

Syntax

HRESULT SetMediaType(
    AM_MEDIA_TYPE *pMediaType
);

Parameters

pMediaType
Pointer to an AM_MEDIA_TYPE structure that describes the media type.

Return Value

Returns one of the following values.

E_OUTOFMEMORY | Insufficient memory.
S_OK | Success.

IAMMediaTypeSample::SetPointer

IAMMediaTypeSample Interface

Sets the pointer to the media sample's memory buffer.

Syntax

HRESULT SetPointer(
    BYTE *pBuffer,
    long lSize
);

Parameters

pBuffer
[in] Pointer to a memory buffer allocated by the caller, or NULL.
lSize
[in] Size of the buffer, in bytes.

Return Value

Returns one of the following HRESULT values.

S_OK | Success.
E_OUTOFMEMORY | Insufficient memory.

Remarks

If the value of the pBuffer parameter is NULL, the method allocates a memory block, with a size in bytes equal to the value of the lSize parameter. There is no guarantee that the memory has been initialized.

IAMMediaTypeSample::SetPreroll

IAMMediaTypeSample Interface

Specifies whether this is a preroll sample. A preroll sample should not be displayed.

Syntax

HRESULT SetPreroll(
    BOOL bIsPreroll
);

Parameters

bIsPreroll
Boolean value that specifies whether the sample is a preroll sample. If TRUE, it is for preroll and should not be displayed.

Return Value

Returns S_OK.

IAMMediaTypeSample::SetSyncPoint

IAMMediaTypeSample Interface

Specifies whether the beginning of this sample is a synchronization point.

Syntax

HRESULT SetSyncPoint(
    BOOL bIsSyncPoint
);

Parameters

bIsSyncPoint
Boolean value that specifies whether the beginning of this sample is a synchronization point. If TRUE, the beginning of the sample is a synchronization point.

Return Value

Returns S_OK.

IAMMediaTypeSample::SetTime

IAMMediaTypeSample Interface

Sets the stream times at which the sample should start and stop.

Syntax

HRESULT SetTime(
    REFERENCE_TIME *pTimeStart,
    REFERENCE_TIME *pTimeEnd
);

Parameters

pTimeStart
[in] Pointer to a variable that contains the start time.
pTimeEnd
[in] Pointer to a variable that contains the stop time.

Return Value

Returns S_OK.


IAMMediaTypeStream Interface

This interface contains methods for creating multimedia streams with arbitrary media types. Use this interface if you need to create a multimedia stream with a format that is not supported by the other Microsoft® DirectShow® multimedia streaming interfaces.

This interface inherits from the IMediaStream interface.

Note For video streams, use the IDirectDrawMediaStream interface instead of this interface. For audio streams, use the IAudioMediaStream interface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaStream methods | Description
GetMultiMediaStream | Retrieves a pointer to the multimedia stream that contains the specified media stream.
GetInformation | Retrieves the stream's purpose identifier (ID) and media type.
SetSameFormat | Sets the media stream to the same format as a previous stream.
AllocateSample | Allocates a new stream sample object for the current media stream.
CreateSharedSample | Creates a new stream sample that shares the same backing object as the existing sample.
SendEndOfStream | Forces the current stream to end. If the current stream is not writable, calling this method has no effect.
IAMMediaTypeStream methods | Description
GetFormat | Retrieves the format of the stream.
SetFormat | Sets the format of the stream.
CreateSample | Creates a stream sample and optionally specifies the sample buffer.
GetStreamAllocatorRequirements | Retrieves the allocator requirements for the stream. This method is not currently implemented.
SetStreamAllocatorRequirements | Sets the allocator requirements for the stream. This method is not currently implemented.

IAMMediaTypeStream::CreateSample

IAMMediaTypeStream Interface

Creates a stream sample and optionally specifies the sample buffer.

Syntax

HRESULT CreateSample(
    long lSampleSize,
    BYTE *pbBuffer,
    DWORD dwFlags,
    IUnknown *pUnkOuter,
    IAMMediaTypeSample **ppAMMediaTypeSample
);

Parameters

lSampleSize
[in] Size of the sample.
pbBuffer
[in] [optional] Pointer to an array of bytes that contains the sample data, or NULL.
dwFlags
[in] Reserved.
pUnkOuter
[in] [optional] Pointer to the interface of an object that aggregates the stream sample.
ppAMMediaTypeSample
[in] Address of an IAMMediaTypeSample interface pointer that receives a pointer to the created sample.

Return Value

Returns one of the following values.

E_OUTOFMEMORY | Insufficient memory.
E_POINTER | NULL pointer argument.
S_OK | Success.

Remarks

If pUnkOuter is non-NULL, the new stream sample is aggregated into the specified object. Filters that receive the sample can then query it for interfaces supported by the aggregating object.

IAMMediaTypeStream::GetFormat

IAMMediaTypeStream Interface

Retrieves the format of the stream.

Syntax

HRESULT GetFormat(
    AM_MEDIA_TYPE *pMediaType,
    DWORD dwFlags
);

Parameters

pMediaType
[out] Pointer to an AM_MEDIA_TYPE structure that receives the stream format.
dwFlags
[in] Reserved.

Return Value

Returns one of the following values.

MS_E_NOSTREAM | No stream is associated with this object.
S_OK | Success.

IAMMediaTypeStream::GetStreamAllocatorRequirements

IAMMediaTypeStream Interface

Retrieves the allocator requirements for the stream. This method is not currently implemented.

Syntax

HRESULT GetStreamAllocatorRequirements(
  ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps
[out] Pointer to an ALLOCATOR_PROPERTIES structure that receives the stream allocator requirements.

Return Value

Returns E_FAIL.

IAMMediaTypeStream::SetFormat

IAMMediaTypeStream Interface

Sets the format of the stream.

Syntax

HRESULT SetFormat(
    AM_MEDIA_TYPE *pMediaType,
    DWORD dwFlags
);

Parameters

pMediaType
[in] Pointer to an AM_MEDIA_TYPE structure that contains the stream format.
dwFlags
[in] Reserved.

Return Value

Returns one of the following values.

MS_E_SAMPLEALLOC | The stream has already allocated a sample with another media type.
S_OK | Success.

IAMMediaTypeStream::SetStreamAllocatorRequirements

IAMMediaTypeStream Interface

Sets the allocator requirements for the stream. This method is not currently implemented.

Syntax

HRESULT SetStreamAllocatorRequirements(
  ALLOCATOR_PROPERTIES *pProps
);

Parameters

pProps
[in] Pointer to an ALLOCATOR_PROPERTIES structure that contains the stream allocator requirements.

Return Value

Returns E_FAIL.


IAMMultiMediaStream Interface

The IAMMultiMediaStream interface exposes Microsoft® DirectShow® functionality to multimedia stream developers. You can use its methods to automatically generate filter graphs, open files or monikers for playback or capture of incoming data, and render a given filter graph.

Implement this interface when you want to provide multimedia stream-based support for DirectShow media types in your applications.

Use this interface when you want to control DirectShow-supported media playback in your multimedia streaming applications.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAMMultiMediaStream methods | Description
Initialize | Sets the stream type. If the pFilterGraph parameter is non-NULL the filter graph passed in is used for the stream.
GetFilterGraph | Retrieves the associated filter graph's IGraphBuilder interface.
GetFilter | Retrieves the specified filter from the current filter graph.
AddMediaStream | Adds the specified media stream to the current filter graph.
OpenFile | Opens and automatically creates a filter graph for the specified media file. If DirectShow doesn't support the file format, this method does nothing.
OpenMoniker | Opens a file or device moniker; you can read media data from this moniker if DirectShow supports the media type.
Render | Renders the current filter graph.

IAMMultiMediaStream::AddMediaStream

IAMMultiMediaStream Interface

Adds the specified media stream to the current filter graph.

Syntax

HRESULT AddMediaStream(
    IUnknown *pStreamObject,
    const MSPID *pPurposeID,
    DWORD dwFlags,
    IMediaStream **ppNewStream
    );

Parameters

pStreamObject
[in] Pointer to an IUnknown interface that points to either the media stream or underlying stream object you want to add to the current filter graph.
pPurposeID
[in] Pointer to the purpose ID for the newly added media stream.
dwFlags
[in] Value that modifies the media stream's behavior; it is a combination of one or more of the following values.
AMMSF_ADDDEFAULTRENDERER | Add a default renderer.
AMMSF_CREATEPEER | Create a peer stream based on the same object as a pStreamObject.
AMMSF_STOPIFNOSAMPLES | Terminates the stream if no samples were created or if the last sample is deleted.
AMMSF_NOSTALL | Run the stream even if Update is not called.
ppNewStream
[out] Address of a pointer to an IMediaStream interface that will point to the newly added media stream. This parameter is optional.

Return Value

Returns an HRESULT value, which can include the following values.
MS_E_PURPOSEID | Stream being added has a different purpose ID from the one specified or a stream with the specified purpose ID already exists.
E_POINTER | Null pointer argument.
S_OK | Success.

Remarks

If dwFlags specifies AMMSF_ADDDEFAULTRENDERER then the default renderer for the given purpose ID is created, if possible. Currently the only default renderer supported is for audio using DirectSound. In this case the pStreamObject parameter must be NULL and any calls to the IMultiMediaStream::GetMediaStream or IMultiMediaStream::EnumMediaStreams methods will not recognize the stream.

If dwFlags specifies AMMSF_CREATEPEER then a media stream is created using pStreamObject and added to the current multimedia stream. The pStreamObject parameter varies depending on the stream type. In general, pStreamObject can point to an IMediaStream object, in which case a stream with the sample purpose ID and format is created. For IDirectDraw streams, it can also be a pointer to an IDirectDraw object.

If dwFlags specifies AMMSF_STOPIFNOSAMPLES then the stream is terminated.

If no flags are set, then pStreamObject can be one of the following.
An IAMMediaStream object | This stream is then added to the streams in the multimedia stream.
NULL | In this case, a default IMediaStream object is added to the stream with a default underlying object if required.
A pointer to an underlying object | This is used to construct default streams. For video streams, this can be an IDirectDraw pointer.

IAMMultiMediaStream::GetFilter

IAMMultiMediaStream Interface

Retrieves the specified filter from the current filter graph.

Syntax

HRESULT GetFilter(
    IMediaStreamFilter **ppFilter
    );

Parameters

ppFilter
[out] Address of a pointer to an IMediaStreamFilter interface that will point to the current filter.

Return Value

Returns S_OK if successful or E_POINTER if one or more of the required parameters are NULL.

IAMMultiMediaStream::GetFilterGraph

IAMMultiMediaStream Interface

Retrieves the associated filter graph's IGraphBuilder interface.

Syntax

HRESULT GetFilterGraph(
    IGraphBuilder **ppGraphBuilder
    );

Parameters

ppGraphBuilder
[out] Address of a pointer to an IGraphBuilder interface that will point to the current filter graph.

Return Value

Returns S_OK if successful or E_POINTER if one or more of the required parameters are NULL.

IAMMultiMediaStream::Initialize

IAMMultiMediaStream Interface

Sets the stream type. If the pFilterGraph parameter is non-NULL, the filter graph passed in is used for the stream.

Syntax

HRESULT Initialize(
    STREAM_TYPE StreamType,
    DWORD dwFlags,
    IGraphBuilder *pFilterGraph
    );

Parameters

StreamType
[in] STREAM_TYPE enumeration value that specifies the new filter graph's stream type.
dwFlags
[in] Either contains the AMMSF_NOGRAPHTHREAD flag, which creates a filter graph object on the current thread, or zero.
pFilterGraph
[in] [optional] Pointer to an IGraphBuilder interface that will point to the new filter graph. This parameter is optional; only pass in a valid pointer if you must access the filter graph at a later time.

Return Value

Returns S_OK if successful or E_POINTER if one or more of the required parameters are NULL.

Remarks

Using the AMMSF_NOGRAPHTHREAD flag is safe provided the current thread does not exit before the stream object is released by the application and the current thread processes window messages.

IAMMultiMediaStream::OpenFile

IAMMultiMediaStream Interface

Opens and automatically creates a filter graph for the specified media file. If DirectShow doesn't support the file format, this method does nothing.

Syntax

HRESULT OpenFile(
    LPCWSTR pszFileName,
    DWORD dwFlags
    );

Parameters

pszFileName
[in] Pointer to the name of the file you want to open.
dwFlags
[in] Value that modifies how the filter graph will render the specified file. This value is a combination of one or more of the following flags.
AMMSF_RENDERTOEXISTING | Only render to existing streams
AMMSF_RENDERALLSTREAMS | Render all streams, including those that do not have an existing media stream.
AMMSF_NORENDER | Open the file, but do not render any streams. This flag should always be accompanied with the AMMSF_RUN flag.
AMMSF_NOCLOCK | Run the stream with no clock.
AMMSF_RUN | Set the stream into the run state.

Return Value

Returns one of the following values.
E_INVALIDARG | The dwFlags parameter is invalid.
E_POINTER | This method tried to access an invalid pointer.
S_OK | Success.

Remarks

The AMMSF_RENDERALLSTREAMS flag will create default rendering filters for video and audio if they do not exist. However, these default filters cannot be accessed by the IStreamSample::GetMediaStream method.

IAMMultiMediaStream::OpenMoniker

IAMMultiMediaStream Interface

Opens a file or device moniker; you can read media data from this moniker if DirectShow supports the moniker.

Syntax

HRESULT OpenMoniker(
    IBindCtx *pCtx,
    IMoniker *pMoniker,
    DWORD dwFlags
    );

Parameters

pCtx
[in] Pointer to the bind context associated with the moniker.
pMoniker
[in] Pointer to an IMoniker interface that specifies the moniker you want to open.
dwFlags
[in] Value that modifies how the filter graph will render the specified file. This value is a combination of one or more of the following flags:
AMMSF_RENDERTOEXISTING | Only render to existing streams.
AMMSF_RENDERALLSTREAMS | Render all streams, including those that do not have an existing media stream.
AMMSF_NORENDER | Open the file, but do not render any streams. This flag should always be accompanied with the AMMSF_RUN flag.
AMMSF_NOCLOCK | Run the stream with no clock.
AMMSF_RUN | Set the stream into the run state.

Return Value

Returns S_OK if successful or E_INVALIDARG if the dwFlags parameter is invalid.

IAMMultiMediaStream::Render

IAMMultiMediaStream Interface

Renders the current filter graph.

Syntax

HRESULT Render(
    DWORD dwFlags
    );

Parameters

dwFlags
[in] Value that specifies how the filter graph renders the current multimedia stream. This value currently must be AMMSF_NOCLOCK.

Return Value

Returns S_OK if successful or E_INVALIDARG if the dwFlags parameter is invalid.

Remarks

This method renders each of the source streams for a stream of type STREAMTYPE_WRITE. This can be called several times, for instance, each time a source stream is added, the stream is not set into running mode. Use the IMultiMediaStream::SetState method to set the stream into running mode after calling this method.

The AMMSF_RENDERALLSTREAMS flag will create default rendering streams for video and audio if they do not exist.


IAudioData Interface

The IAudioData interface provides methods that enable applications to set and get the underlying audio data that audio streams will reference. The audio data format is set in the WAVEFORMATEX structure.

Implement this interface on underlying audio data objects that audio stream sample objects will access.

Applications use this interface to set and retrieve information on underlying data objects that an audio stream will reference.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAudioData methods | Description
GetFormat | Retrieves the current data format.
SetFormat | Sets the current data format.

IAudioData::GetFormat

IAudioData Interface

Retrieves the current data format.

Syntax

HRESULT GetFormat(
    WAVEFORMATEX *pWaveFormatCurrent
    );

Parameters

pWaveFormatCurrent
[out] Pointer to a WAVEFORMATEX structure that contains the current data format.

Return Value

Returns S_OK if successful or E_POINTER if pointer is invalid.

Remarks

Currently, Microsoft® DirectShow® supports only PCM wave data.

See Also

IAudioData::SetFormat

IAudioData::SetFormat

IAudioData Interface

Sets the current data format.

Syntax

HRESULT SetFormat(
    const WAVEFORMATEX *lpWaveFormat
    );

Parameters

lpWaveFormat
[in] Pointer to a WAVEFORMATEX structure that will contain the current data format.

Return Value

Returns an HRESULT value, which can include the following values.
E_POINTER | Invalid pointer argument.
E_INVALIDARG | Invalid format.
S_OK | Success.

See Also

IAudioData::GetFormat


IAudioMediaStream Interface

The IAudioMediaStream interface controls audio media streams by providing methods that set and get the stream's format. This interface inherits from the IMediaStream interface and is used to create one or more IAudioStreamSample objects. You can also use it to set and retrieve the stream data's current format.

This interface is currently defined only for PCM format audio data.

For sample code that implements the audio streaming interfaces, see Multimedia Streaming Sample Code.

Like video, audio is contained in a self-describing container object. Implement this interface when an object needs to control streaming audio.

Use this interface when you want to generate audio in your application.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAudioMediaStream methods | Description
GetFormat | Retrieves the stream data's current format.
SetFormat | Sets the format for the stream.
CreateSample | Creates an audio stream sample for use with this stream.

IAudioMediaStream::CreateSample

IAudioMediaStream Interface

Creates an audio stream sample for use with the specified stream.

Syntax

HRESULT CreateSample(
    IAudioData *pAudioData,
    DWORD dwFlags,
    IAudioStreamSample **ppSample
    );

Parameters

pAudioData
[in] Pointer to an IAudioData container. IAudioData objects can be referenced by samples in more than one stream.
dwFlags
[in] Reserved for flag data. Must be zero.
ppSample
[out] Address of a pointer to the new IAudioStreamSample interface.

Return Value

Returns S_OK if successful or E_POINTER if one or more of the required parameters are NULL.

Remarks

The pAudioData object defines the data's format.

IAudioMediaStream::GetFormat

IAudioMediaStream Interface

Retrieves the stream data's current format.

Syntax

HRESULT GetFormat(
    WAVEFORMATEX *pWaveFormatCurrent );

Parameters

pWaveFormatCurrent
[out] Pointer to a WAVEFORMATEX structure that contains the stream data's current format.

Return Value

Returns S_OK if successful or E_POINTER if the required parameter is NULL.

Remarks

Currently, Microsoft® DirectShow® supports only PCM wave data.

IAudioMediaStream::SetFormat

IAudioMediaStream Interface

Sets the format for the stream.

Syntax

HRESULT SetFormat(
    const WAVEFORMATEX *lpWaveFormat
    );

Parameters

lpWaveFormat
[in] Pointer to a WAVEFORMATEX structure that contains stream format information.

Return Value

Returns an HRESULT value, which can include the following values or others not listed.
MS_E_INCOMPATIBLE | Format of the IAudioData object is not compatible with stream.
E_POINTER | Null pointer argument.
E_INVALIDARG | Invalid argument.
S_OK | Success.


IAudioStreamSample Interface

The IAudioStreamSample interface retrieves information from the underlying IAudioData data objects.

For sample code that implements the audio streaming interfaces, see Multimedia Streaming Sample Code.

Implement this interface on audio stream sample objects when they need access to an IAudioData object's data.

Use this interface when your application needs to access an IAudioData object's data for its audio stream.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IAudioStreamSample methods | Description
GetAudioData | Retrieves the address of a pointer to the IAudioData object associated with the sample.

IAudioStreamSample::GetAudioData

IAudioStreamSample Interface

Retrieves the address of a pointer to the IAudioData object associated with the sample.

Syntax

HRESULT GetAudioData(
  IAudioData **ppAudio );

Parameters

ppAudio
[out] Address of a pointer to the IAudioData object.

Return Value

Returns S_OK if successful or E_POINTER if the parameter is NULL.


IDirectDrawMediaStream Interface

The IDirectDrawMediaStream interface controls media streams that appear on Microsoft® DirectDraw® surfaces. To stream to a DirectDraw surface, DirectDraw must support the video stream format.

For sample code that implements the multimedia streaming interfaces, see Multimedia Streaming Sample Code.

This interface isn't intended for implementation by application developers. It is exposed on DirectDraw media streams that can be added to a Microsoft® DirectShow® multimedia stream.

Use this interface when you want to send a video stream to a DirectDraw surface.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDirectDrawMediaStream methods | Description
GetFormat | Retrieves the current media stream's format and, optionally, its desired format.
SetFormat | Sets the current media stream's format. If the stream already has allocated samples and the sample format doesn't match the specified format, this method fails.
GetDirectDraw | Retrieves a pointer to the DirectDraw object used by the current media stream.
SetDirectDraw | Sets the current media stream's DirectDraw object.
CreateSample | Creates a stream sample using the specified DirectDraw surface object.
GetTimePerFrame | Retrieves the average frames per second from a video stream.

IDirectDrawMediaStream::CreateSample

IDirectDrawMediaStream Interface

Creates a stream sample using the specified DirectDraw surface object.

Syntax

HRESULT CreateSample(
    IDirectDrawSurface *pSurface,
    const RECT *pRect,
    DWORD dwFlags,
    IDirectDrawStreamSample **ppSample
    );

Parameters

pSurface
[in] Pointer to an existing DirectDraw surface.
pRect
[in] Pointer to the clipping rectangle you want to use with the specified surface. Set this parameter to NULL if you want to use the entire surface.
dwFlags
[in] Flag that specifies whether the render should be progressive. To perform a progressive render, set this value to DDSFF_PROGRESSIVERENDER. If you don't set this flag, sample updates will copy the sample data to the surface.
ppSample
[out] Address of a pointer to an IDirectDrawStreamSample interface that will point to the newly created sample.

Return Value

Returns one of the following values.
DDERR_INVALIDPIXELFORMAT | The specified pixel format is incompatible with the stream format.
DDERR_INVALIDRECT | The specified clipping rectangle is invalid.
DDERR_INVALIDSURFACETYPE | The specified surface is incompatible with the stream format.
E_POINTER | One or more of the required parameters is invalid.
MS_E_SAMPLEALLOC | The stream already has allocated samples and the surface doesn't match the sample format.
S_OK | Success.

Remarks

This method creates a sample from the current stream and attaches the sample to this surface.

If the stream doesn't have an allocated surface and the specified surface doesn't match the stream's format, this method calls the IDirectDrawMediaStream::SetFormat method on the stream so the two will match.

To perform a progressive render, create a single sample and repeatedly use that sample for successive frames of video. Video decompressors use this technique to do partial updates to the previous frame.

The pRect parameter should match the format of the stream (see IDirectDrawMediaStream::GetFormat). If the wrong clip rectangle is set or no clip rectangle is set, and the surface size does not match the movie size, the movie might not play. If a primary surface is used, it is advisable to use a clipping rectangle because the primary surface size can change if the user changes display settings.

IDirectDrawMediaStream::GetDirectDraw

IDirectDrawMediaStream Interface

Retrieves a pointer to the DirectDraw object used by the current media stream.

Syntax

HRESULT GetDirectDraw(
    IDirectDraw **ppDirectDraw
    );

Parameters

ppDirectDraw
[out] Address of a pointer to an IDirectDraw interface that will contain the current media stream's associated DirectDraw object.

Return Value

Returns S_OK if successful or E_POINTER if the parameter is invalid.

Remarks

If you haven't initialized the stream yet, the retrieved pointer will be NULL and the method will return S_OK. If you have initialized the stream, this method increments the retrieved pointer's reference count.

IDirectDrawMediaStream::GetFormat

IDirectDrawMediaStream Interface

Retrieves the current media stream's format and, optionally, its desired format.

Syntax

HRESULT GetFormat(
    DDSURFACEDESC *pDDSDCurrent,
    IDirectDrawPalette **ppDirectDrawPalette,
    DDSURFACEDESC *pDDSDDesired,
    DWORD *pdwFlags
    );

Parameters

pDDSDCurrent
[out] Pointer to a DirectDraw surface description that will contain the current media stream's format.
ppDirectDrawPalette
[out] Address of a pointer to an IDirectDrawPalette interface if one exists.
pDDSDDesired
[out] Pointer to a DirectDraw surface description that will contain the current media stream's desired format.
pdwFlags
[out] Pointer to the flags set in a DDSURFACEDESC structure. Fields of interest include:
DDSD_HEIGHT | Indicates that the height member of the structure is valid.
DDSD_WIDTH | Indicates that the width member of the structure is valid.
DDSD_PIXELFORMAT | Indicates that the pixel format member of the structure is valid.
DDSD_CAPS | Indicates that the surface capability member of the structure is valid.

Return Value

Returns one of the following values.
DDERR_INVALIDPARAMS | One of the DirectDraw surface parameters is invalid.
E_POINTER | One or more of the required parameters is invalid.
S_OK | Success.

Remarks

After you call this method, you can either conform to the current format or attempt to change the format by calling the IDirectDrawMediaStream::SetFormat method.

All of this method's parameters are optional; set any of them to NULL to indicate that you don't want to retrieve that information.

To perform a progressive render, create a single sample and repeatedly use that sample for successive frames of video. Video decompressors use this technique to do partial updates to the previous frame.

You must initialize the dwSize member of the DDSURFACEDESC structure before calling this method.

The DDSD_CAPS flag will return one of the values listed in the DDSCAPS structure or DDSCAPS_DATAEXCHANGE, which is defined as DDSCAPS_SYSTEMMEMORY|DDSCAPS_VIDEOMEMORY in Ddrawex.h.

IDirectDrawMediaStream::GetTimePerFrame

IDirectDrawMediaStream Interface

Retrieves the average frames per second from a video stream.

Syntax

HRESULT GetTimePerFrame(
    STREAM_TIME *pFrameTime
    );

Parameters

pFrameTime
[out] Pointer to a STREAM_TIME value that indicates the average time per frame in 100-nanosecond units.

Return Value

Returns S_OK if successful or E_POINTER if the pointer is invalid.

IDirectDrawMediaStream::SetDirectDraw

IDirectDrawMediaStream Interface

Sets the current media stream's DirectDraw object.

Syntax

HRESULT SetDirectDraw(
    IDirectDraw *pDirectDraw
    );

Parameters

pDirectDraw
[in] Pointer to an IDirectDraw interface that contains the media stream's new DirectDraw object.

Return Value

Returns S_OK if successful or E_POINTER if the pointer is invalid.

Remarks

This method fails if the current stream already has allocated samples and its DirectDraw object differs from the specified one. It will always succeed if the specified DirectDraw object matches the stream's current object.

If this stream has no allocated samples, you can set pDirectDraw to NULL. This forces the stream to release its reference to the current DirectDraw object.

IDirectDrawMediaStream::SetFormat

IDirectDrawMediaStream Interface

Sets the format of the current media stream.

Syntax

HRESULT SetFormat(
    const DDSURFACEDESC *pDDSurfaceDesc,
    IDirectDrawPalette *pDirectDrawPalette
    );

Parameters

pDDSurfaceDesc
[in] Pointer to a DirectDraw surface description that contains the new format.
pDirectDrawPalette
[in] Optional parameter that is a pointer to an IDirectDrawPalette interface.

Return Value

Returns one of the following values.
S_OK | Success.
DDERR_INVALIDSURFACETYPE | The specified format is incompatible with the current stream.
MS_E_SAMPLEALLOC | Can't change the format because one or more stream samples are already allocated for this stream.

Remarks

If the stream already has allocated samples and the sample format doesn't match the specified format, this method fails. This method always succeeds if the specified format matches the current format.


IDirectDrawStreamSample Interface

The IDirectDrawStreamSample interface provides methods that set and retrieve pointers to the Microsoft® DirectDraw® surface associated with the current stream sample.

This interface isn't intended for implementation by application developers. It is exposed by sample objects created by the DirectDraw stream.

Use this interface when applications need to set clipping rectangles and retrieve the rendering surface for DirectDraw stream samples.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IDirectDrawStreamSample methods | Description
GetSurface | Retrieves pointers to the current sample's DirectDraw surface and associated clipping rectangle.
SetRect | Changes the clipping rectangle for a sample.

IDirectDrawStreamSample::GetSurface

IDirectDrawStreamSample Interface

Retrieves pointers to the current sample's DirectDraw surface and associated clipping rectangle.

Syntax

HRESULT GetSurface(

  IDirectDrawSurface **ppDirectDrawSurface,

  RECT *pRect

  );

Parameters

ppDirectDrawSurface
[out] Address of a pointer to an IDirectDrawSurface interface that specifies the sample's new surface. Set this parameter to NULL if you don't want to specify a new surface.
pRect
[out] Pointer to a RECT structure that will contain the current sample's clipping rectangle. Set this parameter to NULL if you don't want to retrieve the clipping rectangle.

Return Value

Returns an HRESULT value.

Remarks

Both parameters are optional. All implementations of this interface must support null values as valid parameters. If you retrieve a surface pointer, this method increments its reference count, so you must release the reference.

IDirectDrawStreamSample::SetRect

IDirectDrawStreamSample Interface

Changes the clipping rectangle for a sample.

Syntax

HRESULT SetRect (

  const RECT *pRect

  );

Parameters

pRect
[in] Pointer to a RECT structure that specifies the stream's new clipping rectangle.

Return Value

Returns one of the following values.
DDERR_INVALIDPIXELFORMAT | The stream isn't compatible with the pixel format.
DDERR_INVALIDRECT | The specified rectangle is invalid.
DDERR_INVALIDSURFACETYPE | The stream isn't compatible with the surface.
E_POINTER | One of the pointers is invalid.
MS_E_SAMPLEALLOC | The stream format doesn't match the surface and samples are currently allocated to the stream.
S_OK | Success.

Remarks

Both parameters are optional; set either to NULL to avoid changing that value. If the surface format doesn't match the stream format, this method fails.

If the new rectangle's size isn't the same as the current rectangle, a call to this method will fail.


IMediaStream Interface

The IMediaStream interface provides access to the characteristics of a media stream, such as the stream's media type and purpose ID. It also has methods that create data samples.

For sample code that implements the multimedia streaming interfaces, see Multimedia Streaming Sample Code.

Implement this interface when you want to add media type-specific functionality to your media stream. This interface is implemented on multimedia stream objects. IMediaStream provides generic sample-creation methods, but you usually want to write a more powerful version of these methods that will take advantage of your media type's specific characteristics.

Use this interface when your application needs to access a stream's media type information and create data samples.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMediaStream methods | Description
GetMultiMediaStream | Retrieves a pointer to the multimedia stream that contains the specified media stream.
GetInformation | Retrieves the stream's purpose ID and media type.
SetSameFormat | Sets the media stream to the same format as a previous stream.
AllocateSample | Allocates a new stream sample object for the current media stream.
CreateSharedSample | Creates a new stream sample that shares the same backing object as the existing sample.
SendEndOfStream | Forces the current stream to end. If the current stream isn't writable, this method does nothing.

IMediaStream::AllocateSample

IMediaStream Interface

Allocates a new stream sample object for the current media stream.

Syntax

HRESULT AllocateSample(
  DWORD dwFlags,
  IStreamSample **ppSample
  );

Parameters

dwFlags
[in] Flags. Must be zero.
ppSample
[out] Address of a pointer to the newly created stream sample's IStreamSample interface.

Return Value

Returns one of the following values.
E_OUTOFMEMORY | There isn't enough memory available to create a stream sample.
E_POINTER | A parameter is invalid.
S_OK | Success.

Remarks

This method allocates the sample and its associated backing object or buffer. The backing object is either the DirectDraw surface for video or the IAudioData object for audio.

IMediaStream::CreateSharedSample

IMediaStream Interface

Creates a new stream sample that shares the same backing object as the existing sample.

Syntax

HRESULT CreateSharedSample(

  IStreamSample *pExistingSample,

  DWORD dwFlags ,

  IStreamSample **ppNewSample

  );

Parameters

pExistingSample
[in] Pointer to the existing sample.
dwFlags
[in] Reserved for flag data. Must be zero.
ppNewSample
[out] Address of a pointer to an IStreamSample interface that will point to the newly created shared sample.

Return Value

Returns one of the following values.
E_OUTOFMEMORY | There isn't enough memory available to create the sample.
E_POINTER | One of the parameters is invalid.
MS_E_INCOMPATIBLE | The existing sample isn't compatible with the specified media stream.
S_OK | Success; ppNewSample points to the newly created sample.

Remarks

This method calls IUnknown::QueryInterface on the existing sample to retrieve the media type-specific information, which it uses to create the shared sample.

IMediaStream::GetInformation

IMediaStream Interface

Retrieves the stream's purpose ID and media type.

Syntax

HRESULT GetInformation(

  MSPID *pPurposeId,

  STREAM_TYPE *pType

  );

Parameters

pPurposeId
[out] Pointer to an MSPID value that will contain the stream's purpose ID. If this parameter is NULL on entry, the method won't retrieve the purpose ID.
pType
[out] Pointer to a STREAM_TYPE enumerated data type value that will contain the stream's media type. If this parameter is NULL on entry, the method won't retrieve the media type.

Return Value

Returns S_OK if successful or E_POINTER if one of the parameters is invalid.

Remarks

The value retrieved in the pPurposeId parameter will usually be either MSPID_PrimaryVideo, which identifies the primary video stream, or MSPID_PrimaryAudio, which identifies the primary audio stream; however, you can define other values if necessary.

IMediaStream::GetMultiMediaStream

IMediaStream Interface

Retrieves a pointer to the multimedia stream that contains the specified media stream.

Syntax

HRESULT GetMultiMediaStream(

  IMultiMediaStream **ppMultiMediaStream

  );

Parameters

ppMultiMediaStream
[out] Address of a pointer to an IMultiMediaStream interface object that will point to the multimedia stream from which the current media stream was created.

Return Value

Returns S_OK if successful or E_POINTER if ppMultiMediaStream is invalid.

Remarks

This method increments the reference count of the retrieved object pointer.

IMediaStream::SendEndOfStream

IMediaStream Interface

Forces the current stream to end. If the current stream isn't writable, this method does nothing.

Syntax

HRESULT SendEndOfStream(

  DWORD dwFlags

  );

Parameters

dwFlags
[in] Reserved for flag data. Must be zero.

Return Value

Returns S_OK if successful or MS_E_INCOMPATIBLE if the existing sample isn't compatible with the current media stream.

Remarks

Applications do not call this internal method.

IMediaStream::SetSameFormat

IMediaStream Interface

Sets the media stream to the same format as a previous stream.

Syntax

HRESULT SetSameFormat(

  IMediaStream *pStreamThatHasDesiredFormat,

  DWORD dwFlags

  );

Parameters

pStreamThatHasDesiredFormat
[in] Pointer to a media stream object that has the same format.
dwFlags
[in] Reserved for flag data. Must be zero.

Return Value

Returns S_OK if successful or E_POINTER if one of the parameters is invalid.


IMemoryData Interface

The IMemoryData interface contains methods that set and retrieve memory data on audio data objects. Audio data objects provide the underlying data which stream samples access. This interface provides a way to initialize memory buffers and to set actual amounts of audio data in the objects. Additionally, the GetInfo method can be used to retrieve audio memory data.

Implement this interface on underlying audio data objects that audio stream sample objects will access.

Typically these methods are called by the IAudioMediaStream or IAudioStreamSample object, rather than by the application.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMemoryData methods | Description
SetBuffer | Initializes a memory buffer with a pointer to memory and length.
GetInfo | Retrieves information describing an audio data object.
SetActual | Sets the amount of audio data currently in the object, in bytes.

IMemoryData::GetInfo

IMemoryData Interface

Retrieves information describing an audio data object.

Syntax

HRESULT GetInfo(
  DWORD *pdwLength,
  BYTE **ppbData,
  DWORD *pcbActualData );

Parameters

pdwLength
[out] Length of memory in bytes, if non-NULL.
ppbData
[out] Pointer to the memory, if non-NULL.
pcbActualData
[out] Length of data in bytes, if non-NULL.

Return Value

Returns an HRESULT value.

Remarks

This method determines how much data the object currently contains as last set by SetActual.

IMemoryData::SetActual

IMemoryData Interface

Sets the amount of audio data currently in the object.

Syntax

HRESULT SetActual(
  DWORD cbDataValid
  );

Parameters

cbDataValid
[in] Amount of data, in bytes.

Return Value

Returns S_OK if successful or E_POINTER if the required parameter is NULL.

Remarks

This method is usually called by the IAudioMediaStream or IAudioStreamSample object, rather than by the application.

IMemoryData::SetBuffer

IMemoryData Interface

Initializes a memory buffer with a pointer to memory and length.

Syntax

HRESULT SetBuffer(
  DWORD cbSize,
  BYTE *pbData,
  DWORD dwFlags );

Parameters

cbSize
[in] Size of memory pointed to by pbData, in bytes.
pbData
[in] Pointer to memory that this object will use.
dwFlags
[in] Reserved for flag data. Must be zero.

Return Value

Returns S_OK if successful or E_INVALIDARG if cbSize is zero or pbData is NULL.

Remarks

This method can be called as often as needed. When using IStreamSample::Update to update samples asynchronously, make sure that SetBuffer is never called before an update is completed.


IMultiMediaStream Interface

The IMultiMediaStream interface provides methods that control a multimedia stream and provide access to its underlying media streams. A multimedia stream is the highest-level streaming object and can contain one or more media streams. While each media stream is media-type specific (audio, video, and so on), multimedia streams are generic across all types because they must provide access to a number of streams that can have different media types. IMultiMediaStream interface methods enable you to enumerate and retrieve pointers to the specific streams; IMediaStream interface methods provide specific control over the media stream behavior.

For sample code that implements the multimedia streaming interfaces, see Multimedia Streaming Sample Code.

Implement this interface when you want to create containers for a specific type of media stream.

Use this interface when your application must enumerate and control a multimedia stream's underlying, type-specific streams.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IMultiMediaStream methods | Description
GetInformation | Retrieves the capabilities and stream type of a multimedia stream.
GetMediaStream | Retrieves a media stream that has the specified purpose ID.
EnumMediaStreams | Retrieves a media stream from a multimedia stream by zero-based index.
GetState | Retrieves the multimedia stream's current state.
SetState | Sets the media stream to either a running or stopped state.
GetTime | Retrieves the current time from the multimedia stream's clock, if it has a clock.
GetDuration | Retrieves the media stream's duration.
Seek | Sets the seek location of all derived media streams to the specified time.
GetEndOfStreamEventHandle | Retrieves the handle for the event triggered when the stream completes playback.

IMultiMediaStream::EnumMediaStreams

IMultiMediaStream Interface

Retrieves a media stream from a multimedia stream by zero-based index.

Syntax

HRESULT EnumMediaStreams(

  long Index,

  IMediaStream **ppMediaStream

  );

Parameters

Index
[in] Index of the stream array to check.
ppMediaStream
[out] Address of a pointer to an IMediaStream interface object. On return, it contains a pointer to the stream at the specified index.

Return Value

Returns one of the following values.
E_POINTER | The ppMediaStream pointer is invalid.
S_FALSE | Index is out of range; no streams are left to enumerate. When the method returns this value, it also sets ppMediaStream to NULL.
S_OK | Success.

Remarks

You should call this method until it returns S_FALSE, which indicates that the stream enumeration is complete.

IMultiMediaStream::GetDuration

IMultiMediaStream Interface

Returns the media stream's duration.

Syntax

HRESULT GetDuration(
  STREAM_TIME *pDuration
  );

Parameters

pDuration
[out] Pointer to a STREAM_TIME value that will contain the media duration.

Return Value

Returns one of the following values.
E_POINTER | The value of pDuration is invalid.
MS_E_WRITESTREAM | The media stream is writable and therefore has no duration.
S_FALSE | Stream contains live data or this method couldn't determine the duration. On return, this method sets pDuration to zero.
S_OK | Stream contains recorded media. On return, pDuration contains duration of media.

IMultiMediaStream::GetEndOfStreamEventHandle

IMultiMediaStream Interface

Retrieves the handle for the event triggered when the stream completes playback.

Syntax

HRESULT GetEndOfStreamEventHandle(

  HANDLE *phEOS

  );

Parameters

phEOS
[out] Pointer to an event HANDLE returned by the current object when it completes playback. If no HANDLE is associated with the object, this value will be NULL.

Return Value

Returns S_OK if successful or E_POINTER if one or more of the required parameters are NULL.

Remarks

The Microsoft® Win32® WaitForSingleObject and WaitForMultipleObjects functions use the retrieved handle to watch for completion of playback.

IMultiMediaStream::GetInformation

IMultiMediaStream Interface

Retrieves the capabilities of a media stream that matches the specified media type.

Syntax

HRESULT GetInformation(
  DWORD *pdwFlags,
  STREAM_TYPE *pStreamType

  );

Parameters

pdwFlags
[out] Pointer to a value that will contain a combination of one or more of the following flags. Can be NULL.
MMSSF_ASYNCHRONOUS | The stream supports asynchronous sample updates. All implementations of IMultiMediaStream will support the asynchronous updates; this flag confirms it.
MMSSF_HASCLOCK | The stream has a clock.
MMSSF_SUPPORTSEEK | The stream supports seeking.
pStreamType
[out] Pointer to a STREAM_TYPE enumeration type that will contain the media type information for the derived media streams. Can be NULL.

Return Value

Returns an HRESULT value.

Remarks

A stream's capabilities include whether it has a clock, if it supports seeking, and whether it supports asynchronous updating.

IMultiMediaStream::GetMediaStream

IMultiMediaStream Interface

Retrieves a media stream that has the specified purpose ID.

Syntax

HRESULT GetMediaStream(
  REFMSPID idPurpose,
  IMediaStream **ppMediaStream

  );

Parameters

idPurpose
Value that specifies the desired stream.
ppMediaStream
Address of a pointer to an IMediaStream interface that will point to the desired media stream.

Return Value

Returns one of the following values.
E_POINTER | The ppMediaStream pointer is invalid.
MS_E_NOSTREAM | No stream has the specified purpose ID.
S_OK | Success.

Remarks

If a stream exists that matches the purpose ID in idPurpose, the ppMediaStream parameter points to the stream and increments its reference count.

MSPID_PrimaryVideo and MSPID_PrimaryAudio, which represent the primary video and audio streams, are the most commonly used purpose IDs.

IMultiMediaStream::GetState

IMultiMediaStream Interface

Retrieves the multimedia stream's current state.

Syntax

HRESULT GetState(

  STREAM_STATE *pCurrentState

  );

Parameters

pCurrentState
[out] Pointer to the STREAM_STATE enumerated type that will contain the current multimedia stream's state.

Return Value

Returns S_OK if successful or E_POINTER if pCurrentState is invalid.

IMultiMediaStream::GetTime

IMultiMediaStream Interface

Retrieves the current time from the multimedia stream's clock, if it has a clock.

Syntax

HRESULT GetTime(

  STREAM_TIME *pCurrentTime

  );

Parameters

pCurrentTime
[out] Pointer to a STREAM_TIME value that will contain the current time, if the media stream has a clock.

Return Value

Returns one of the following values.
E_POINTER | The pCurrentTime pointer is invalid.
S_FALSE | Stream doesn't have a clock; *pCurrentTime is zero.
S_OK | Stream has a clock and the method succeeded; pCurrentTime contains the current time.

Remarks

If the stream doesn't have a clock, this method sets *pCurrentTime to zero and returns S_FALSE. If a stream has a clock, the stream sample times are relative to the stream's clock.

STREAM_TIME is defined as a LONGLONG value.

IMultiMediaStream::Seek

IMultiMediaStream Interface

Sets the seek location of all contained media streams to the specified time.

Syntax

HRESULT Seek(
  STREAM_TIME SeekTime
  );

Parameters

SeekTime
[in] STREAM_TIME value that specifies the seek time.

Return Value

Returns one of the following values.
E_POINTER | One of the pointers is invalid.
MS_E_NOSEEKING | One or more media streams don't support seeking.
MS_E_WRITESTREAM | The streams are writable and therefore don't support seeking.
S_OK | Success.

Remarks

This method won't work on streams that don't support seeking. Before calling this method, retrieve the stream's capabilities by calling IMultiMediaStream::GetInformation; if the retrieved value includes the MMSSF_SUPPORTSEEK flag, you can call this method.

When seeking a stream that has a clock, the current time can change to an unpredictable value, including a time before the desired seek time. This causes the method to fail.

This method seeks to the specified time in all the media streams derived from the multimedia stream object.

IMultiMediaStream::SetState

IMultiMediaStream Interface

Sets the media stream to either a running or stopped state.

Syntax

HRESULT SetState(
  STREAM_STATE NewState
  );

Parameters

NewState
[in] A STREAM_STATE enumeration value that specifies the new media stream state.

Return Value

Returns S_OK.

Remarks

When you set the stream to STREAMSTATE_STOP, this method deletes all data still pending.


IStreamSample Interface

The IStreamSample interface provides control over the behavior of stream samples. You can retrieve the media stream that created the sample, set or retrieve sample start and stop times, check the sample's completion status, and perform a developer-specified function on the sample itself.

Implement this interface when you implement a media stream for a new media type. The interface is exposed on sample objects created by media streams.

Use this interface when you want to control data samples created by IMediaStream or its derived interfaces.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IStreamSample methods | Description
GetMediaStream | Retrieves a pointer to the media stream object that created the current sample.
GetSampleTimes | Retrieves the current sample's start and end times.
SetSampleTimes | Sets the current sample's start and end times.
Update | Performs a synchronous or an asynchronous update on the current sample.
CompletionStatus | Retrieves the status of the current sample's latest asynchronous update. If the update isn't complete, you can force it to complete.

IStreamSample::CompletionStatus

IStreamSample Interface

Retrieves the status of the current sample's latest asynchronous update. If the update isn't complete, you can force it to complete.

Syntax

HRESULT CompletionStatus(
  DWORD dwFlags,
  DWORD dwMilliseconds
  );

Parameters

dwFlags
[in] Value that specifies whether to forcibly complete the update. This value is a combination of one or more of the following flags.
COMPSTAT_NOUPDATEOK (0x01) | Force the update to complete as soon as possible, even if the sample update isn't yet complete. If the sample is updating and you didn't set the COMPSTAT_WAIT flag, the method returns MS_S_PENDING. If the sample is waiting to be updated, this method removes it from the queue and returns MS_S_NOTUPDATED.
COMPSTAT_WAIT (0x02) | Wait until the sample finishes updating before returning from this method.
COMPSTAT_ABORT (0x04) | Forces the update to complete, even if it's currently updating. This leaves the sample data in an undefined state. Combine this value with the COMPSTAT_WAITFORCOMPLETION flag to ensure that the update canceled.
dwMilliseconds
[in] If the dwFlags parameter is COMPSTAT_WAIT, this value is the number of milliseconds to wait for the update to complete. Specify INFINITE to indicate that you want to wait until the sample updates before this call returns.

Return Value

Returns one of the following values.
E_ABORT | The update aborted.
MS_S_ENDOFSTREAM | The sample wasn't updated because it reached the end of the stream.
MS_S_NOUPDATE | The update was forcibly completed; the sample was not updated by the stream.
MS_S_PENDING | An asynchronous update is pending.
S_OK | Success.

IStreamSample::GetMediaStream

IStreamSample Interface

Retrieves a pointer to the media stream object that created the current sample.

Syntax

HRESULT GetMediaStream(

  IMediaStream **ppMediaStream

  );

Parameters

ppMediaStream
[in] Address of a pointer to an IMediaStream interface that will point to the media stream that created the current sample.

Return Value

Returns S_OK if successful or E_POINTER if ppMediaStream is invalid.

Remarks

If successful, this method increments the reference count of the media stream specified by ppMediaStream.

IStreamSample::GetSampleTimes

IStreamSample Interface

Retrieves the current sample's start and end times. If the sample is updating, this method returns the times after the update completes.

Syntax

HRESULT GetSampleTimes(

  STREAM_TIME *pStartTime,

  STREAM_TIME *pEndTime,

  STREAM_TIME *pCurrentTime

  );

Parameters

pStartTime
[out] Pointer to a STREAM_TIME value that will contain the sample's start time.
pEndTime
[out] Pointer to a STREAM_TIME value that will contain the sample's end time.
pCurrentTime
[out] Pointer to a STREAM_TIME value that will contain the media stream's current media time.

Return Value

Returns S_OK if successful or E_POINTER if one of the parameters is invalid.

Remarks

For streams that have a clock, the start and end times will be relative to the stream's current time. If the stream doesn't have a clock, the times are media-relative and the current time will be zero.

The pCurrentTime parameter enables you to conveniently track the media stream's current time, so you don't have to call IMultiMediaStream::GetTime. Unlike GetTime, however, this method returns S_OK if the stream doesn't have a clock; GetTime returns S_FALSE. The value assigned to pCurrentTime is the same as the value produced by the following code fragment.

pSample->GetMediaStream(&pMediaStream);
pMediaStream->GetMultiMediaStream(&pMultiMediaStream);
pMediaStream->Release();
pMultiMediaStream->GetTime(&pCurrentTime);
pMultiMediaStream->Release();

IStreamSample::SetSampleTimes

IStreamSample Interface

Sets the current sample's start and end times. You can call this method prior to updating the sample.

Syntax

HRESULT SetSampleTimes(

  const STREAM_TIME *pStartTime,

  const STREAM_TIME *pEndTime

  );

Parameters

pStartTime
[in] Pointer to a STREAM_TIME value that contains the sample's new start time.
pEndTime
[in] Pointer to a STREAM_TIME value that contains the sample's new end time.

Return Value

Returns S_OK if successful or E_POINTER if one of the parameters is NULL.

Remarks

For streams that have a clock, the times must be relative to the stream's current time. If the stream doesn't have a clock, the times should be relative to the media.

This method applies only to writable streams.

IStreamSample::Update

IStreamSample Interface

Performs a synchronous or an asynchronous update on the current sample.

Syntax

HRESULT Update(
  DWORD dwFlags,
  HANDLE hEvent,
  PAPCFUNC pfnAPC,
  DWORD dwAPCData
  );

Parameters

dwFlags
[in] Flag that specifies whether the update is synchronous or asynchronous. The SSUPDATE_ASYNC flag specifies an asynchronous update, which you can set if both hEvent and pfnAPC are NULL. Use SSUPDATE_CONTINUOUS to continuously update the sample until you call the IStreamSample::CompletionStatus method.
hEvent
[in] Handle to an event that this method will trigger when the update is complete.
pfnAPC
[in] Pointer to a Win32 asynchronous procedure call (APC) function that this method will call after it completes the sample update.
dwAPCData
[in] Value that this method passes to the function specified by the pfnAPC parameter.

Return Value

Returns one of the following values.
E_ABORT | The update aborted.
E_INVALIDARG | One of the parameters is invalid.
E_POINTER | One of the parameters is invalid.
MS_E_BUSY | This sample already has a pending update.
MS_S_ENDOFSTREAM | Reached the end of the stream; the sample wasn't updated.
MS_S_PENDING | The asynchronous update is pending.
S_OK | Success.

Remarks

This method can be used to perform a synchronous or asynchronous update of a sample. If both hEvent and pfnAPC are NULL then the update will be synchronous unless either of the SSUPDATE_ASYNC or SSUPDATE_CONTINUOUS flags is specified. When a synchronous update returns, the result of the function contains the I/O completion status.

You can't specify values for both hEvent and pfnAPC; the method will fail.

Asynchronous updates might complete before the update returns; in that case, the return value is S_OK. If you specify an event and the update returns S_OK, this method sets the event on return. If you specify an APC function and the update returns S_OK, the APC will not be queued and the function will not be called.

Asynchronous updates that don't complete prior to returning will return a value of MS_S_PENDING.

If an application creates multiple streams, it must perform an asynchronous update on each stream. Call WaitForMultipleObjects to wait for each stream update to complete, before making the next update. Otherwise, the application might block.


Multimedia Streaming Data Types

This article describes the Microsoft® DirectShow® multimedia streaming data types.
Data type | Description
MSPID | Media stream purpose IDs define the purpose of a media stream. You declare a purpose ID as a GUID with a typedef.
STREAM_STATE | Describes the state of the stream.
STREAM_TIME | Stream time measured in 100-nanosecond increments. This type is defined to be a 64-bit integer (LONGLONG).
STREAM_TYPE | Defines the direction of data flow for the stream.

STREAM_STATE

Multimedia Streaming Data Types

Describes the state of the stream.

Syntax

typedef enum {
    STREAMSTATE_STOP        = 0,
    STREAMSTATE_RUN         = 1
} STREAM_STATE;

Elements

STREAMSTATE_STOP
Stop state.
STREAMSTATE_RUN
Run state.

Remarks

Change the state by calling the IMultiMediaStream::SetState method.

STREAM_TYPE

Multimedia Streaming Data Types

Defines the direction of data flow for the stream.

Syntax

typedef enum {
    STREAMTYPE_READ         = 0,
    STREAMTYPE_WRITE        = 1,
    STREAMTYPE_TRANSFORM    = 2
} STREAM_TYPE;

Elements

STREAMTYPE_READ
Application can read the stream.
STREAMTYPE_WRITE
Application can write to the stream.
STREAMTYPE_TRANSFORM
Application reads and writes to the stream.

Remarks

Transform streams are read/write where the sample is updated in place.


Error and Success Codes for Multimedia Streaming

The following list contains error messages and success notifications for applications that use the multimedia streaming interfaces. This list does not contain all possible errors; the errors shown apply specifically to the Microsoft® DirectShow® implementation of the multimedia streaming interfaces. Note that success codes start with MS_S and return TRUE from the SUCCEEDED macro and FALSE from the FAILED macro.
Message | Hexadecimal code | Meaning
MS_S_PENDING | 0x00040001 | Sample update is not yet complete.
MS_S_NOUPDATE | 0x00040002 | Sample was not updated after forced completion.
MS_S_ENDOFSTREAM | 0x00040003 | End of stream. Sample not updated.
MS_E_SAMPLEALLOC | 0x80040401 | An IMediaStream object could not be removed from an IMultiMediaStream object because it still contains at least one allocated sample.
MS_E_PURPOSEID | 0x80040402 | The specified purpose ID can't be used for the call.
MS_E_NOSTREAM | 0x80040403 | No stream can be found with the specified attributes.
MS_E_NOSEEKING | 0x80040404 | Seeking not supported for this IMultiMediaStream object.
MS_E_INCOMPATIBLE | 0x80040405 | The stream formats are not compatible.
MS_E_BUSY | 0x80040406 | The sample is busy.
MS_E_NOTINIT | 0x80040407 | The object can't accept the call because its initialize function or equivalent has not been called.
MS_E_SOURCEALREADYDEFINED | 0x80040408 | Source already defined.
MS_E_INVALIDSTREAMTYPE | 0x80040409 | The stream type is not valid for this operation.
MS_E_NOTRUNNING | 0x8004040A | The IMultiMediaStream object is not in running state.


Multimedia Streaming Component Objects

This article provides a table that describes the various components that Microsoft® DirectShow® supports. These objects support the multimedia streaming interfaces. This article also includes a diagram that shows the hierarchy of component objects.

This article contains the following sections.

  • Component Objects Table
  • Object References Diagram

Component Objects Table

This section describes the various components that are supported by DirectShow.
Object | Description | Interfaces supported
CLSID_AMMultiMediaStream | DirectShow implementation of multimedia stream. | IAMMultiMediaStream, IMultiMediaStream
CLSID_MediaStreamFilter | Provides multimedia streaming functionality for the CLSID_AMMultiMediaStream object through the IAMMultiMediaStream interface. | IBaseFilter
CLSID_AMDirectDrawStream | Microsoft® DirectDraw® media stream that can be added to a DirectShow multimedia stream. | IAMMediaStream, IMediaStream, IDirectDrawMediaStream, IPin, IMemInputPin
Samples created by the DirectDraw stream. |  | IStreamSample, IDirectDrawStreamSample, IMediaSample
CLSID_ AMMediaTypeStream | Can create media samples for any DirectShow-supported data type | IAMMediaStream, IMediaStream, IPin, IMemInputPin
Samples created by the CLSID_ AMMediaTypeStream object |  | IStreamSample, IMediaSample, IMediaSample2
CLSID_AMAudioData | Implementation of IAudioData audio container object | IAudioData

Object References Diagram

The hierarchy of objects creates some interesting circular references between the DirectShow objects. The following diagram shows all the objects and their references. Strong references (those that increment the referenced object) are indicated by solid lines. Weak references (those that do not AddRef the referenced object) are indicated by a dotted line.

Object references diagram

Samples hold strong references to the multimedia stream object, while the media streams do not.


Multimedia Streaming Sample Code

This article provides sample code that implements the multimedia streaming interfaces. The video streaming sample code demonstrates how to read a file and render it to a primary Microsoft® DirectDraw® surface. For brevity, this code contains no error checking.

The second code sample demonstrates how to use the audio streaming interfaces to stream audio data.

This article contains the following sections.

  • Video Streaming Sample Code
  • Audio Streaming Sample Code

Video Streaming Sample Code

This sample code reads a file and renders it to a primary DirectDraw surface.

#include <stdio.h>
#include "ddraw.h"       // DirectDraw interfaces
#include "mmstream.h"    // multimedia stream interfaces
#include "amstream.h"    // DirectShow multimedia stream interfaces
#include "ddstream.h"    // DirectDraw multimedia stream interfaces

void RenderStreamToSurface(IDirectDrawSurface *pSurface,
    IMultiMediaStream *pMMStream)
{
    IMediaStream *pPrimaryVidStream;
    IDirectDrawMediaStream *pDDStream;
    IDirectDrawStreamSample *pSample;
    RECT rect;
    DDSURFACEDESC ddsd;

    pMMStream->GetMediaStream(MSPID_PrimaryVideo, &pPrimaryVidStream);
    pPrimaryVidStream->QueryInterface(IID_IDirectDrawMediaStream, (void **)&pDDStream);
    ddsd.dwSize = sizeof(ddsd);
    pDDStream->GetFormat(&ddsd, NULL, NULL, NULL);
    rect.top = rect.left = 0;
    rect.bottom = ddsd.dwHeight;
    rect.right = ddsd.dwWidth;
    pDDStream->CreateSample(pSurface, &rect, 0, &pSample);

    pMMStream->SetState(STREAMSTATE_RUN);
    while (pSample->Update(0, NULL, NULL, NULL) == S_OK);
    pMMStream->SetState(STREAMSTATE_STOP);

    pSample->Release();
    pDDStream->Release();
    pPrimaryVidStream->Release();
}

void RenderFileToMMStream(const char * szFileName,
    IMultiMediaStream **ppMMStream,
    IDirectDraw *pDD)
{
    IAMMultiMediaStream *pAMStream;
    CoCreateInstance(CLSID_AMMultiMediaStream, NULL, CLSCTX_INPROC_SERVER,
        IID_IAMMultiMediaStream, (void **)&pAMStream);
    WCHAR    wPath[MAX_PATH];        // wide (32-bit) string name
    MultiByteToWideChar(CP_ACP, 0, szFileName, -1, wPath,
        sizeof(wPath)/sizeof(wPath[0]));

    pAMStream->Initialize(STREAMTYPE_READ, AMMSF_NOGRAPHTHREAD, NULL);
    pAMStream->AddMediaStream(pDD, &MSPID_PrimaryVideo, 0, NULL);
    pAMStream->AddMediaStream(NULL, &MSPID_PrimaryAudio, AMMSF_ADDDEFAULTRENDERER, NULL);
    pAMStream->OpenFile(wPath, 0);
    *ppMMStream = pAMStream;
}

int _CRTAPI1 main(int argc, char *argv[])
{
    if (argc < 2) {
    printf("Usage : showstrm movie.ext\n");
    exit(0);}

    DDSURFACEDESC ddsd;
    IDirectDraw *pDD;
    IDirectDrawSurface *pPrimarySurface;
    IMultiMediaStream *pMMStream;

    CoInitialize(NULL);

    DirectDrawCreate(NULL, &pDD, NULL);
    pDD->SetCooperativeLevel(GetDesktopWindow(), DDSCL_NORMAL);
    ddsd.dwSize = sizeof(ddsd);
    ddsd.dwFlags = DDSD_CAPS;
    ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
    pDD->CreateSurface(&ddsd, &pPrimarySurface, NULL);
    RenderFileToMMStream(argv[1], &pMMStream, pDD);
    RenderStreamToSurface(pPrimarySurface, pMMStream);
    pMMStream->Release();
    pPrimarySurface->Release();
    pDD->Release();

    CoUninitialize();
    return 0;
}

Audio Streaming Sample Code

The following code sample demonstrates how to stream audio data using the IAudioMediaStream, IAudioStreamSample, IMemoryData, and IAudioData interfaces.

#include <windows.h>
#include <mmsystem.h>
#include <amstream.h>

/********************************************************************

   Trivial wave player stuff

 ********************************************************************/

class CWaveBuffer;

class CWaveBuffer {
    public:
        CWaveBuffer();
        ~CWaveBuffer();
        BOOL Init(HWAVEOUT hWave, int Size);
        void Done();
        BOOL Write(PBYTE pData, int nBytes, int& BytesWritten);
        void Flush();

    private:
        WAVEHDR      m_Hdr;
        HWAVEOUT     m_hWave;
        int          m_nBytes;
};

class CWaveOut {
    public:
        CWaveOut(LPCWAVEFORMATEX Format, int nBuffers, int BufferSize);
        ~CWaveOut();
        void Write(PBYTE Data, int nBytes);
        void Flush();
        void Wait();
        void Reset();
    private:
        const HANDLE   m_hSem;
        const int      m_nBuffers;
        int            m_CurrentBuffer;
        BOOL           m_NoBuffer;
        CWaveBuffer   *m_Hdrs;
        HWAVEOUT       m_hWave;
};

/*
    CWaveBuffer
*/

CWaveBuffer::CWaveBuffer()
{
}

BOOL CWaveBuffer::Init(HWAVEOUT hWave, int Size)
{
    m_hWave  = hWave;
    m_nBytes = 0;

    /*  Allocate a buffer and initialize the header. */
    m_Hdr.lpData = (LPSTR)LocalAlloc(LMEM_FIXED, Size);
    if (m_Hdr.lpData == NULL) {
        return FALSE;
    }
    m_Hdr.dwBufferLength  = Size;
    m_Hdr.dwBytesRecorded = 0;
    m_Hdr.dwUser = 0;
    m_Hdr.dwFlags = 0;
    m_Hdr.dwLoops = 0;
    m_Hdr.lpNext = 0;
    m_Hdr.reserved = 0;

    /*  Prepare it. */
    waveOutPrepareHeader(hWave, &m_Hdr, sizeof(WAVEHDR));

    return TRUE;
}

CWaveBuffer::~CWaveBuffer() {
    if (m_Hdr.lpData) {
        waveOutUnprepareHeader(m_hWave, &m_Hdr, sizeof(WAVEHDR));
        LocalFree(m_Hdr.lpData);
    }
}

void CWaveBuffer::Flush()
{
    // ASSERT(m_nBytes != 0);
    m_nBytes = 0;
    waveOutWrite(m_hWave, &m_Hdr, sizeof(WAVEHDR));
}

BOOL CWaveBuffer::Write(PBYTE pData, int nBytes, int& BytesWritten)
{
    // ASSERT((DWORD)m_nBytes != m_Hdr.dwBufferLength);
    BytesWritten = min((int)m_Hdr.dwBufferLength - m_nBytes, nBytes);
    CopyMemory((PVOID)(m_Hdr.lpData + m_nBytes), (PVOID)pData, BytesWritten);
    m_nBytes += BytesWritten;
    if (m_nBytes == (int)m_Hdr.dwBufferLength) {
        /*  Write it! */
        m_nBytes = 0;
        waveOutWrite(m_hWave, &m_Hdr, sizeof(WAVEHDR));
        return TRUE;
    }
    return FALSE;
}

void CALLBACK WaveCallback(HWAVEOUT hWave, UINT uMsg, DWORD dwUser,
                           DWORD dw1, DWORD dw2)
{
    if (uMsg == WOM_DONE) {
        ReleaseSemaphore((HANDLE)dwUser, 1, NULL);
    }
}

/*
    CWaveOut
*/

CWaveOut::CWaveOut(LPCWAVEFORMATEX Format, int nBuffers, int BufferSize) :
    m_nBuffers(nBuffers),
    m_CurrentBuffer(0),
    m_NoBuffer(TRUE),
    m_hSem(CreateSemaphore(NULL, nBuffers, nBuffers, NULL)),
    m_Hdrs(new CWaveBuffer[nBuffers]),
    m_hWave(NULL)
{
    /*  Create wave device. */
    waveOutOpen(&m_hWave,
                WAVE_MAPPER,
                Format,
                (DWORD)WaveCallback,
                (DWORD)m_hSem,
                CALLBACK_FUNCTION);

    /*  Initialize the wave buffers. */
    for (int i = 0; i < nBuffers; i++) {
        m_Hdrs[i].Init(m_hWave, BufferSize);
    }
}

CWaveOut::~CWaveOut()
{
    /*  First, get the buffers back. */
    waveOutReset(m_hWave);

    /*  Free the buffers. */
    delete [] m_Hdrs;

    /*  Close the wave device. */
    waveOutClose(m_hWave);

    /*  Free the semaphore. */
    CloseHandle(m_hSem);
}

void CWaveOut::Flush()
{
    if (!m_NoBuffer) {
        m_Hdrs[m_CurrentBuffer].Flush();
        m_NoBuffer = TRUE;
        m_CurrentBuffer = (m_CurrentBuffer + 1) % m_nBuffers;
    }
}

void CWaveOut::Reset()
{
    waveOutReset(m_hWave);
}

void CWaveOut::Write(PBYTE pData, int nBytes)
{
    while (nBytes != 0) {
        /*  Get a buffer if necessary. */
        if (m_NoBuffer) {
            WaitForSingleObject(m_hSem, INFINITE);
            m_NoBuffer = FALSE;
        }

        /*  Write into a buffer. */
        int nWritten;
        if (m_Hdrs[m_CurrentBuffer].Write(pData, nBytes, nWritten)) {
            m_NoBuffer = TRUE;
            m_CurrentBuffer = (m_CurrentBuffer + 1) % m_nBuffers;
            nBytes -= nWritten;
            pData += nWritten;
        } else {
            // ASSERT(nWritten == nBytes);
            break;
        }
    }
}

void CWaveOut::Wait()
{
    /*  Send any remaining buffers. */
    Flush();

    /*  Wait for the buffers back. */
    for (int i = 0; i < m_nBuffers; i++) {
        WaitForSingleObject(m_hSem, INFINITE);
    }
    LONG lPrevCount;
    ReleaseSemaphore(m_hSem, m_nBuffers, &lPrevCount);
}

/************************************************************

  End of wave player stuff

 ************************************************************/

HRESULT RenderStreamToDevice(IMultiMediaStream *pMMStream)
{
    WAVEFORMATEX wfx;
    #define DATA_SIZE 5000
    PBYTE pBuffer = (PBYTE)LocalAlloc(LMEM_FIXED, DATA_SIZE);

    IMediaStream *pStream;
    IAudioStreamSample *pSample;
    IAudioMediaStream *pAudioStream;
    IAudioData *pAudioData;

    pMMStream->GetMediaStream(MSPID_PrimaryAudio, &pStream);
    pStream->QueryInterface(IID_IAudioMediaStream, (void **)&pAudioStream);
    pAudioStream->GetFormat(&wfx);
    CoCreateInstance(CLSID_AMAudioData, NULL, CLSCTX_INPROC_SERVER,
                                    IID_IAudioData, (void **)&pAudioData);
    pAudioData->SetBuffer(DATA_SIZE, pBuffer, 0);
    pAudioData->SetFormat(&wfx);
    pAudioStream->CreateSample(pAudioData, 0, &pSample);
    HANDLE hEvent = CreateEvent(FALSE, NULL, NULL, FALSE);
    CWaveOut WaveOut(&wfx, 4, 2048);
    int iTimes;
    for (iTimes = 0; iTimes < 3; iTimes++) {
        DWORD dwStart = timeGetTime();
        for (; ; ) {
            HRESULT hr = pSample->Update(0, hEvent, NULL, 0);
            if (FAILED(hr) || MS_S_ENDOFSTREAM == hr) {
                break;
            }
            WaitForSingleObject(hEvent, INFINITE);
            DWORD dwTimeDiff = timeGetTime() - dwStart;
            // Limit to 10 seconds
            if (dwTimeDiff > 10000) {
                break;
            }
            DWORD dwLength;
            pAudioData->GetInfo(NULL, NULL, &dwLength);
            WaveOut.Write(pBuffer, dwLength);
        }
        pMMStream->Seek(0);
    }

    pAudioData->Release();
    pSample->Release();
    pStream->Release();
    pAudioStream->Release();
    LocalFree((HLOCAL)pBuffer);

    return S_OK;
}

HRESULT RenderFileToMMStream(
    WCHAR * pszFileName, IMultiMediaStream **ppMMStream)
{
    IAMMultiMediaStream *pAMStream;
    CoCreateInstance(CLSID_AMMultiMediaStream, NULL, CLSCTX_INPROC_SERVER,
              IID_IAMMultiMediaStream, (void **)&pAMStream);
    pAMStream->Initialize(STREAMTYPE_READ, AMMSF_NOGRAPHTHREAD, NULL);
    pAMStream->AddMediaStream(NULL, &MSPID_PrimaryAudio, 0, NULL);
    pAMStream->OpenFile(pszFileName, AMMSF_RUN);
    *ppMMStream = pAMStream;
    return S_OK;
}

int _CRTAPI1 main(int argc, char *argv[])
{
    IMultiMediaStream *pMMStream;
    CoInitialize(NULL);
    WCHAR wszName[1000];
    MultiByteToWideChar(CP_ACP, 0, argv[1], -1, wszName,
        sizeof(wszName) / sizeof(wszName[0]));
    RenderFileToMMStream(wszName, &pMMStream);
    RenderStreamToDevice(pMMStream);
    pMMStream->Release();
    CoUninitialize();
    return 0;
}


SMPTE Timecode

This article describes SMPTE (Society of Motion Picture and Television Engineers) timecode. It also discusses how timecode is used in the production environment and lists some typical applications that rely on external devices. Finally, it describes how external device control is implemented in Microsoft® DirectShow® and provides links to the interfaces available to build VCR control- and timecode-enabled filters in DirectShow.

This article contains the following sections:

  • Understanding SMPTE Timecode
  • Typical Uses of Timecode
  • Capturing Timecode
  • External Device Control
  • References and Suggested Reading

Understanding SMPTE Timecode

SMPTE timecode is the glue that holds the post-production process together. It identifies video and audio sources, makes automatic track synchronization possible, and provides a container for ancillary data related to the production. You will need to understand this data stream and its application to media production, tool development, or system design.

SMPTE timecode, more properly known as SMPTE time and control code, is a series of digital frame address values, flags and additional data applied to a video or audio stream, and is defined in ANSI/SMPTE 12-1986. Its purpose is to provide a machine-readable address for video and audio.

The most common form of an SMPTE timecode data structure is an 80-bit frame that contains the following information:

  • A time stamp in hh:mm:ss:ff (hours:minutes:seconds:frames) format
  • Eight 4-bit binary groups commonly known as userbits
  • Various flag bits
  • Synchronization sequence
  • Checksum

The DirectShow TIMECODE_SAMPLE structure is an example of a timecode data structure that contains timecode information for video or audio data.

SMPTE timecode comes in one of two types. Timecode recorded on an analog audio track as a bi-phase mark encoded signal is known as LTC, or Linear TimeCode (formerly known as Longitudinal TimeCode). Each timecode frame is one video frame time in duration. The other common type of timecode is known as VITC, or Vertical TimeCode. VITC is usually stored on two lines of a video signal's vertical blanking interval, somewhere between lines 10 and 20.

LTC timecode is easy to add to a prerecorded tape, because it is encoded in a separate audio signal. However, it cannot be read when the tape is paused, moving very slowly, or moving very quickly. In addition, it consumes one audio channel on nonprofessional VCRs.

VITC timecode, on the other hand, can be read from speeds of zero to 15 times normal speed. It can contain field-dependent data and can be read from video capture cards. However, it is not easily added to a prerecorded tape and often requires expensive hardware.

SMPTE timecode also comes in one of two modes, nondrop frame and drop frame. Nondrop frame is timecode that is consistently increasing and sequential. It can act as a real-time clock and works fine for monochrome video that runs at a frame rate of exactly 30 frames per second.

However, NTSC color video actually runs at a frame rate of 29.97 Hz (frames per second) because of some compatibility issues with monochrome television. This causes a problem with nondrop frame timecode because it gets out of step with real time at the rate of 108 frames (or 3.6 seconds) per hour. This means that after 1 hour of playback, the timecode would read 00:59:56:12, assuming a start point of 00:00:00:00. This causes problems when trying to calculate show duration or using "time-of-day" referencing.

A solution to this problem is to skip some frames in the count every so often so the error is reduced to something tolerable. This compensation method is called "drop frame" and is implemented by skipping the first two frames from the count at the start of each minute except minutes 00, 10, 20, 30, 40 and 50. The net result is an error of less than 1 frame per hour, or about 3 frames per 24 hour period.

Drop frame is used more commonly in today's productions, although any implementation should support mixing both modes.

Typical Uses of Timecode

Applications that provide video capture and editing functionality will typically require control of external devices. These applications need to identify and index video and audio frames through references to SMPTE timecode. Linear editing system computers generally control three or more tape machines, as well as a video switcher and possibly a digital disk recorder. The controlling computer must execute commands at precise times and therefore must get videotapes cued to specific places at specific points in time.

Applications typically use timecode in a number of different ways including, but not limited to the following:

  • Tracking of video and audio sources throughout the editorial process so an edit decision list, or EDL, can be generated for archival or export to another system. To create an EDL, perform the following steps:
    1. Shoot the video.
    2. Capture into a nonlinear offline system that uses some form of intraframe-only compression (MJPEG, DV, and so on).
    3. Edit the material and generate an EDL and offline edited master.
    4. Import the EDL to an online system and do an "auto-assembly" using the original source material to generate the final master, adding titles and effects where required.
  • Synchronizing audio to video. In feature film production, audio is usually recorded on a separate tape recorder along with timecode. Specially equipped film cameras can also record timecode on the film in-between the sprocket holes. After the filmed image is electronically transferred to videotape, the timecode is used to align the audio with the picture in a process known as "synching the dailies". If the audio and video timecodes are different, VITC and LTC can sometimes be used together, one for video timecode and the other for audio timecode.
  • Synchronization and triggering of multiple devices such as ATRs, digital disk recorder or players, VCRs, or other similar devices. This is a much broader class of synchronization than previously described, and is most commonly seen in linear editing and nonlinear editing systems, closed-captioning systems, and subtitling systems.
  • Using the undefined bits in the timecode, called userbits. Often information such as dates, ASCII codes, or film industry information is contained in the userbits; however, use of userbits is limited only to the ingenuity of the user.

It quickly becomes apparent that timecode makes many things possible when properly handled. Unfortunately, there is also a lot that can go wrong, either because of poor technique or hardware malfunctions. Some things to look out for on timecoded tapes are:

  • Unstable or drifting timecode relative to video or audio.
  • Poor timecode field integrity. This means an LTC word begins in the middle of a frame rather than at the beginning, or VITC is not updated on a true frame boundary. The net result is an ambiguous reference.
  • Unintentional VITC/LTC mismatch.
  • Intermittent dropouts.
  • Missing timecode.
  • Poor timecode signal quality.
  • Incremental frame offset from incorrectly made copies.

Capturing Timecode

Timecode can be generated either by an external timecode generator, by a capture card capable of generating timecode, by the device control filter itself, or by an external device such as a VCR that has a built-in timecode reader. An RS-422 connection is generally necessary if an external device sends the timecode to the host.

After timecode is generated, it needs to be captured either in tabular or stream format concurrently with the video or audio, so that it can later be accessed during editing. This is handled in one of two ways:

1. Build a table that lists the timecode discontinuities indexed to frame position within the stream, and write the table to the end of the file after capture is complete. The list might be an array of structures that look like this (note that the following structure is a simplification of the DirectShow TIMECODE_SAMPLE structure and is intended as an example only):

struct {
    DWORD dwOffset;   // Offset into stream in frames
    char[11] szTC;    // Timecode value at offset
                      // (hh:mm:ss:ff for nondrop, hh:mm:ss;ff for drop frame)
} TIMECODE;

For example, given a captured video stream with one timecode break in it, the list might look like this:

{0, 02:00:00:02},
{16305, 15:21:13:29}        // Timecode jumps at frame 16305.

Using this table, any frame's timecode can be easily calculated.

2. Treat the data as a stream and write it to the file just as video and audio are written. This is useful for rapidly changing data or even non-timecode data in the vertical blanking interval (VBI) such as closed-captioned data.

After the timecode data is properly stored with its associated frame data, applications that edit, composite, synchronize, or trigger can access and use a familiar and standard indexing system.

External Device Control

You can control an external device in DirectShow by implementing device control filters. These filters control devices or streams of data that are entirely external to the computer and expose interfaces such as IAMExtDevice, IAMExtTransport, IAMTimecodeGenerator, and IAMTimecodeReader. Generally, external device control filters do not need to expose pins. However, an example of a device control filter that does expose pins might be a filter representing a source of data such as a VCR. A pin-to-pin connection representing the data flowing from the VCR to the capture board enables the device control filter and the video capture filter to communicate with each other and negotiate data types, although they do not use the standard transport and no data would flow between the filters themselves, other than control information. Applications can instantiate and directly control an external device filter, but it is strongly recommended that they are always instantiated within the context of a filter graph, even if they are the only filter in the graph.

External devices can include VCRs, video editing stations, audio tape recorders (ATRs), mixers, or any other device used in the video capture and editing process. Capture and editing requires DirectShow external device control filters to provide audio and video synchronization and precise control. You can accomplish synchronization of audio and video during playback, edit, and capture with external clocks or SMPTE timecode.

To understand external device control, it is necessary to understand timecode. The key things to remember about timecode are:

  • SMPTE timecode is a frame-addressing system that identifies video and audio frames. It comes in many types and modes, such as LTC, VITC, drop frame, and nondrop frame. It operates at various frame rates: 24, 25, 29.97, and 30 frames per second.
  • SMPTE timecode is used in edit decision lists (EDLs), which are generated for offline editing and online editing, as a timing reference for synchronizing hardware devices and as a vehicle for additional data such as production source or film-reference information.
  • SMPTE timecode can be stored as a stream or table of discontinuities.
  • Timelines are necessary for synchronization, and can be local to the controlling computer, external synchronizer, or the controlled device itself.

Given this background, two fundamental problems exist with device control. First, hundreds of different communication protocols exist for all the various devices from all the various manufacturers. Although some devices are more widely used than others, such as VCRs and laser disc players, almost all have a different remote control interface. As more sophisticated professional video and audio applications continue to move to the desktop, this problem gets worse. Due to these myriad protocols, you must implement separate DirectShow filters for each external device you want to control.

Second, the fundamental problem in the design of professional video and audio systems is that events must occur at precise points in time. Taking a systems view of this issue, consider the following timing diagram.

Basic Video Production System Timing Diagram

The horizontal axis denotes time in video fields, or roughly 1/60 of a second for NTSC video. The key point here is that all signals line up in time; that is, timecode starts at the beginning of a frame (System Frame Pulse). External devices, such as tape machines, are aligned with the system reference, as well as digital video playback such as an AVI file run from an AVI-enabled application.

Conformance to this timing requirement is achieved by various means, the most common of which is a master reference signal distributed to all components in the system. This reference is known as blackburst in the video world, so named because it is a composite video signal containing no active video above black level. The "burst" portion of the name refers to the color burst portion of the video signal. Each device connected to the reference must maintain its own synchronization. This means, for example, that a digital video player must switch frames during the vertical blanking interval, a tape machine must switch into record mode during the vertical blanking interval, commands sent to external devices through a serial port must be timed to the frame pulse, and all of these and other synchronized events must occur when the SMPTE timecode hits a predetermined value. Failure to conform to these rules results in tearing of a video image or edits occurring at the wrong point in time.

Accomplishing all this in the professional video world is relatively straightforward, but in the hybrid world of desktop video, it is very difficult.

Building on the concepts presented so far, the two design examples in the following diagrams illustrate a potential configuration of external devices.

Basic Single VCR Digital Video Editing System Block Diagram

Basic Multi-VCR Video Editing System Block Diagram

The block diagrams show that it is relatively simple to distribute the reference signal to all of the boxes. For example, to deal with synchronization that takes place within the computer between the timecode reader and digital video player, it is recommended that either a "vertical drive" hardware interrupt, specialized operating system services, or some other custom solution be used.

Finally, if you intend to write a filter that controls an external device, you should implement the IAMExtDevice and IAMExtTransport interfaces. If your filter reads or generates timecode, you should also implement IAMTimecodeReader, IAMTimecodeGenerator, and IAMTimecodeDisplay interfaces provided by DirectShow. Additionally, if you need to move binary messages to and from an external device—for example, to download executable code for the external device's microprocessor to execute—you should do this by implementing the COM IDataObject interface, which has a complete set of methods for handling binary data transfers. Use this interface for whatever custom data transfer purposes your filter needs.

References and Suggested Reading

For additional information on SMPTE timecode and external device control, refer to the following documentation:

  • Proposed revision to ANSI/SMPTE 12M-1986, SMPTE Standard for Television, Audio and Film Time and Control Code, SMPTE Journal, February 1995.
  • SMPTE RP 135-1990 "Use of Binary User Groups in Motion-Picture Time and Control Codes"
  • SMPTE RP 169 "Television, Audio and Film Time and Control Code—Auxiliary Time Address Data in Binary Groups—Dialect Specification of Directory Index Locations"
  • SMPTE RP 179-1994 "Dialect Specification of Page-Line Directory Index for Television, Audio and Film Time and Control Code for Video-Assisted Film Editing"
  • "Touring the Vertical Interval", Warner Johnston, TV Technology, August 1991
  • "Closed Captioning in Real Time", Marc Oakrand, SMPTE Journal, June 1991
  • Timecode Handbook, 3rd. Edition, Cipher Digital, Inc. (available from Mix Bookshelf)
  • Timecode: A User's Guide, John Ratcliffe (available from Mix Bookshelf)
  • SMPTE RP 138—Control Message Architecture
  • SMPTE RP 139—Tributary Interconnection
  • SMPTE RP 163—System Service Messages
  • SMPTE RP 170—Video Tape Recorder Type Specific Messages for Digital Control Interface
  • SMPTE RP 171—Type-Specific Messages for Digital Control Interface of Analog Audio Tape Recorders
  • SMPTE RP 172—Common Messages for Digital Control Interface
  • SMPTE 275M—ESlan-1 Remote Control System

SMPTE standards and reprints are available from SMPTE by calling (914) 761-1100.


Using DirectShow with Visual Basic

This section describes how to write Microsoft® DirectShow® applications using Microsoft® Visual Basic®. It contains the following articles.

  • Constructing Filter Graphs Using Visual Basic
  • Controlling Filter Graphs Using Visual Basic
  • Visual Basic Objects


Constructing Filter Graphs Using Visual Basic

This article describes how to use Microsoft® Visual Basic® to manage the components of a filter graph.

This article is written for the Visual Basic developer who is already familiar with application programming in Microsoft® Windows®, Windows-based multimedia programming, and Automation features of the Visual Basic programming system.

This article contains the following sections.

  • About the DirectShow Quartz.dll Objects
  • Creating a Filter Graph
  • Generating the Complete Filter Graph
  • Creating a New Filter Graph and Adding Filters
  • Connecting Filter Pins
  • Viewing Pin Connection Information
  • Summary

About the DirectShow Quartz.dll Objects

Quartz.dll provides objects that you can use in your Visual Basic-based applications to manage filters and pins. There is an implicit hierarchy among these objects; that is, you must often access the properties of one object to obtain another object. In the following example, an object that appears indented below another indicates that you obtain that lower-level object from a property or method of the higher-level object.

Filter graph object (IMediaControl)
  Filter collection (RegFilterCollection, FilterCollection properties)
    Filter Info object (IFilterInfo or IRegFilterInfo in filter collection)
      Pin collection (Pins property)
        Pin Info object (IPinInfo item in pins collection)

The top-level object in the hierarchy is the filter graph object, or the IMediaControl object, which represents the entire filter graph. You can access two properties of the IMediaControl object to obtain collections of filter objects. The RegFilterCollection property represents the filters registered with the system. The FilterCollection property represents the filters that are part of the filter graph.

As with other collections accessible to Visual Basic, you can access individual items in the collections by using the Visual Basic for each...next statement. The number of items in the collection is indicated by the Count property of the collection.

The filter collection contains IFilterInfo objects. Each IFilterInfo object has a Pins property that represents a collection of pins defined for that filter.

The pins collection contains IPinInfo objects. Each IPinInfo object includes detailed information about that pin, including its media type and its connection to another pin.

To examine a specific pin on a filter in the filter graph, use the following procedure.

  1. Obtain the filter graph object.
  2. Use the IMediaControl.FilterCollection property of the filter graph object to obtain the collection of filters present in the filter graph.
  3. Search through the filter collection for the specific filter.
  4. Use the IFilterInfo.Pins property of the filter object to obtain the collection of pins defined for the filter.
  5. Search through the pins collection for the specific pin.
  6. Examine the properties of the pin object to find connection information and other information for the pin.

Creating a Filter Graph

There are three distinct ways to use Quartz.dll to create a filter graph; each way offers a different amount of control over the filter graph. These range from automatically generating the entire filter graph to specifying every filter and pin connection. The three approaches are as follows:

  • Automatic: Generate the complete filter graph from either a multimedia source or a stored filter graph file.
  • Semi-automatic: Create a new (empty) filter graph, add one or more filters, then automatically generate all filters and connections needed to render a specific pin.
  • Manual: Create a new (empty) filter graph, add individual filters to the graph, and explicitly add connections between pins.

Generating the Complete Filter Graph

The following code fragment demonstrates how to generate the complete filter graph based on the multimedia source or stored filter graph. After creating an IMediaControl object that is initially "empty," the application calls the IMediaControl.RenderFile method to build up the complete graph.

    ' start by creating a new, empty filter graph;
    Dim g_objMC as IMediaControl  ' from the General Declarations section
    ...
    Set g_objMC = New FilgraphManager  ' create the new filter graph
    ' ...
    ' Use the common File Open dialog to let the user select the input file
    CommonDialog1.ShowOpen  ' user selects a source or filter graph
    ' call IMediaControl.RenderFile to add all filters and connect all pins
    g_objMC.RenderFile CommonDialog1.filename  ' generates the complete graph

Creating a New Filter Graph and Adding Filters

The following code fragment demonstrates how to create the new (empty) filter graph object.

    Dim g_objMC as IMediaControl  ' from the General Declarations section
    ...
    Set g_objMC = New FilgraphManager  ' create the new filter graph

When you choose to create an empty filter graph and add individual filters, you must know the filter type. In general, there are three categories of filters: source filters, transform filters, and renderer filters. The procedure for adding source filters uses a different method than the procedure for adding transform and renderer filters.

Add source filters to the filter graph by calling the IMediaControl.AddSourceFilter method and supplying the name of a file of the specified source type or stored filter graph.

Dim objFilter As Object  ' temporary object for valid syntax; not used

    CommonDialog1.ShowOpen  ' get the name of the source or filter graph file
    g_objMC.AddSourceFilter CommonDialog1.filename, objFilter

Add transform and renderer filters to the filter graph by calling the IRegFilterInfo.Filter method. The IRegFilterInfo object can be obtained from the IMediaControl.RegFilterCollection property, which represents the collection of filter objects registered with the system and available for use.

After creating the filter graph and obtaining the IMediaControl object, use the following procedure to add filters.

  1. Obtain the list of registered filters by getting the IMediaControl.RegFilterCollection property.
  2. Search through the collection for the desired filter. Each element in the collection is an IRegFilterInfo object.
  3. Add the filter to the filter graph by calling the IRegFilterInfo.Filter method.

The following code fragment illustrates steps 1 and 2 in the previous procedure.

 ' code fragment that populates the registered filter list box
' global variable g_objRegFilters is set to IMediaControl.RegFilterCollection
' Set g_objRegFilters = g_objMC.RegFilterCollection
Dim filter As IRegFilterInfo
    listRegFilters.Clear
    If Not g_objRegFilters Is Nothing Then
        For Each filter In g_objRegFilters  ' for each filter in collection
            listRegFilters.AddItem filter.Name ' add name to the list box
        Next filter
    End If

The following code fragment illustrates step 3 in the previous procedure.

Dim filter As IRegFilterInfo
' find the selected filter and add it to the graph
' g_objRegFilters is the IMediaControl object RegFilterCollection property
For Each filter In g_objRegFilters
    If filter.Name = listRegFilters.Text Then  ' the selected filter?
        Dim f As IFilterInfo  ' yes
        filter.filter f  ' add to the filter graph, return IFilterInfo f
        If f.IsFileSource Then
            CommonDialog1.ShowOpen
            f.filename = CommonDialog1.filename
        End If
        Exit For
    End If
Next filter

Connecting Filter Pins

After adding individual filters to the filter graph, you can establish connections between the filters by explicitly connecting each pin, or by automatically generating all connections that are needed downstream from a specific pin.

In both cases, you must traverse the hierarchy of Microsoft® DirectShow® objects to obtain the IPinInfo object that represents a pin of the filter object. This involves finding the desired filter in the filter collection of the filter graph object, then finding the desired pin in the pin collection of the filter object.

This section contains the following topics.

  • Listing Filters in the Filter Graph
  • Listing Pins Defined for a Filter
  • Explicitly Connecting Two Pins
  • Automatically Connecting Pins

Listing Filters in the Filter Graph

All filters in the filter graph are available in a collection that you can access using the IMediaControl.FilterCollection property.

' refresh a list box that contains the current filters in the graph
    listFilters.Clear
    For Each objFI In g_objMC.FilterCollection
        listFilters.AddItem objFI.Name ' add to list box
    Next objFI

Listing Pins Defined for a Filter

You can access the pins defined for a filter object through the IFilterInfo.Pins property. The Pins property is a collection of individual IPinInfo objects.

After you obtain an individual IPinInfo object from the collection, you can access its properties and call its methods, as shown in the following code fragment.

For Each objPin In g_objSelFilter.Pins
    If objPin.Name = listPins.Text Then  ' selected pin?
        Set g_objSelPin = objPin ' yes, update information
        ' ... perform operations using that pin
    End If
Next objPin

After you have obtained the pin object, you can explicitly connect to one other pin or automatically generate all subsequent pin connections needed to render the pin.

Explicitly Connecting Two Pins

The IPinInfo object provides three methods to connect pins: Connect, ConnectDirect, and ConnectWithType. Connect adds other transform filters as needed, ConnectDirect does not add transform filters, and ConnectWithType performs the connection only if the specified pin matches the specified media type.

    frmSelectPin.OtherDir = g_objSelPin.Direction
    Set frmSelectPin.Graph = g_objMC  ' give that form a copy of the graph
    Set frmSelectPin.SelFilter = g_objSelFilter  ' and the current filter
    frmSelectPin.RefreshFilters  ' display available filters to connect
    frmSelectPin.Show 1  ' display the form
    If frmSelectPin.bOK Then ' user has selected one--used OK button
        Dim objPI As IPinInfo
        Set objPI = frmSelectPin.SelPin ' get the new pin from the form
        g_objSelPin.Connect objPI  ' connect the two pins
        RefreshFilters  ' display the latest pin information
    End If

Automatically Connecting Pins

Call the IPinInfo.Render method to automatically generate all portions of the filter graph that are needed downstream from that pin.

The term downstream refers to all connections needed to construct a complete path from that pin to a renderer filter. For example, consider the representation of the filter graph by the GraphEdit utility, which shows connections as moving from the source filter at the left to the renderer filter at the right. The Render method adds all required filters and connections to the right of the specified pin.

' call IPinInfo.Render
' complete the graph downstream from this pin
' g_objSelPin refers to the pin selected in the list box labeled 'Pins'
    g_objSelPin.Render

Viewing Pin Connection Information

When you have obtained a pin object from the collection available from the IFilterInfo.Pins property of the filter object, you can list its connection and other information.

  Dim strTemp As String
  On Error Resume Next
  Dim objPin As IPinInfo
  For Each objPin In g_objSelFilter.Pins
    If objPin.Name = listPins.Text Then ' selected in list box?
      Set g_objSelPin = objPin  'yes, get all information
      strTemp = ""  ' clear existing displayed pin information
      Dim objPinOther As IPinInfo
      Set objPinOther = objPin.ConnectedTo
      If Err.Number = 0 Then  ' yes, there is a connection
        strTemp = "Connected to pin: " + objPinOther.Name + " "
        Dim objPeer As IFilterInfo
        Set objPeer = objPinOther.FilterInfo
        strTemp = strTemp + " on filter: " + objPeer.Name + " "
        Dim objMTI As IMediaTypeInfo
        Set objMTI = objPin.ConnectionMediaType
        strTemp = strTemp + vbCrLf + "Media Type: " + objMTI.Type
      End If
      If objPin.Direction = 0 Then
        strTemp = strTemp + " " + vbCrLf + "Direction: Input"
      Else
        strTemp = strTemp + " " + vbCrLf + "Direction: Output"
      End If
    txtPinInfo.Text = strTemp
    End If
  Next objPin

Summary

In summary, this article discussed the use of the following DirectShow objects, properties, and methods.
Task | DirectShow properties or methods
Create a new, empty filter graph. | Set objMediaControl = New FilgraphManager.
Generate the complete filter graph for a specific file. | Call the IMediaControl.RenderFile method.
Add a source filter. | Call the IMediaControl.AddSourceFilter method.
Add a renderer or transform filter. | Get the IRegFilterInfo objects using the IMediaControl.RegFilterCollection property; call the IRegFilterInfo.Filter method.
List the pins of a filter object. | Get the IPinInfo objects using the IFilterInfo.Pins property.
Explicitly connect two pins. | Call the IPinInfo.Connect method.
Create all connections from the pin to the renderer filter. | Call the IPinInfo.Render method.


Controlling Filter Graphs Using Visual Basic

This article describes how to use the methods, events, and properties exposed by the Microsoft® DirectShow® dynamic-link library, Quartz.dll, to render a stream of time-stamped video data in applications based in Microsoft® Visual Basic®. This article is written for the Visual Basic developer who is already familiar with Microsoft® Windows®-based application programming, Windows-based multimedia programming, and Automation features of the Visual Basic programming system version 5.x.

This article contains the following sections.

  • DirectShow Filters and Filter Graphs
  • How to Register Quartz.dll to Access DirectShow Interfaces
  • Controlling the Filter Graph in Visual Basic

DirectShow Filters and Filter Graphs

When multimedia is displayed in an application by using Quartz.dll, the application is using a collection of objects called filters; this collection is sometimes called a filter graph. The following diagram depicts a filter graph that can render an Audio-Video Interleaved (AVI) file.

AVI filter graph

In this diagram, the AVI source filter reads the file from disk. The AVI decompressor filter (codec) decompresses the video data as it is passed from the source filter. The codec filter then passes this data to the video renderer. The video renderer, in turn, passes the data to the device in a format that the device understands. The AVI source filter passes the audio data directly to the audio renderer, which, in turn, passes the data to the audio device.

In addition to filters, DirectShow supports an Automation object called the filter graph manager. This object knows about the available filters and understands which filter types are required to render which file formats. The filter graph manager exposes the methods, events, and properties supported by the filters in a given graph. The filter graph manager also exposes its own set of methods, events, and properties. These are exposed by using interfaces, which are simply collections of related methods, events, and properties.

The following table identifies the DirectShow interfaces available in Quartz.dll for use with Visual Basic-based applications, and describes the purpose of each interface.
Interface | Description
IAMCollection | Accesses pin and filter collections.
IBasicAudio | Controls and retrieves current volume setting.
IBasicVideo | Controls a generic video renderer.
IFilterInfo | Retrieves information about a filter and about pin objects in the filter.
IMediaControl | Instantiates the filter graph and controls media flow (running, paused, stopped).
IMediaEvent | Allows customized event handling for events such as repainting, user termination, completion, and so on.
IMediaPosition | Controls and retrieves start time, stop time, rate, and current position.
IMediaTypeInfo | Retrieves the media type and subtype.
IPinInfo | Accesses pin information, such as pin direction and media type, and controls pin connection, disconnection, and rendering.
IRegFilterInfo | Contains information about registered (transform and render) filters.
IVideoWindow | Controls window aspects of a video renderer.

How to Register Quartz.dll to Access DirectShow Interfaces

To use the DirectShow interfaces in your Microsoft Visual Basic-based application, you must register the Microsoft® ActiveMovie® control type library in your Visual Basic project. You can do this by choosing References from the Project menu, and then selecting the check box next to ActiveMovie control type library.

When you register the ActiveMovie control type library by using the Visual Basic References dialog box, you are identifying the type library that contains the Automation information that Visual Basic requires. The following illustration shows the References dialog box.

Visual Basic References dialog box

After the type library is registered, you can use the Object Browser dialog box to view the list of methods, events, and properties associated with a given interface. Choose Object Browser from the View menu, and then choose QuartzTypeLib from the drop-down list of libraries at the top left of the Object Browser dialog box.

Note The type information in the QuartzTypeLib is organized by interface, rather than object.

Controlling the Filter Graph in Visual Basic

This section contains the following topics.

  • Installing the Files
  • Registering Quartz.dll with Visual Basic
  • Preparing to Use the DirectShow Objects
  • Instantiating the Filter Graph
  • Rendering Video
  • Controlling Audio
  • Scaling and Translating the Video Output
  • Tracking Status
  • Getting and Setting the Start Position
  • Getting and Setting the Rate
  • Cleaning Up

Installing the Files

Before using the DirectShow objects in your Visual Basic-based application, you must install Quartz.dll in the Windows\System directory and ensure that the appropriate entries are made in your system's registry database. Currently, the Microsoft® DirectX® Software Development Kit (SDK) Setup program automates this process. To install, start Setup.exe and choose the Runtime option. The dynamic-link library (DLL) will be copied to the correct location, and the registry will be automatically updated.

Registering Quartz.dll with Visual Basic

To verify that the files were installed successfully, open the Visual Basic application and choose the References command from the View menu. (At startup, Visual Basic examines the registry database for registered automation controls and adds their names to the list that appears in this dialog box.) To use the filter graph manager, select the ActiveMovie control type library box.

After Visual Basic registers the type information, you can use the filter graph manager and its associated interfaces in your application.

Preparing to Use the DirectShow Objects

Visual Basic initializes all objects using the FilgraphManager object, which implements the following interfaces.

  • IBasicAudio
  • IBasicVideo
  • IMediaControl
  • IMediaEvent
  • IMediaPosition
  • IVideoWindow

Each of the interfaces is accessed by a Visual Basic programmable object defined to be of that interface type. You can define the objects as global variables in the general declarations section, as shown in the following example.

Dim g_objVideoWindow As IVideoWindow            'VideoWindow Object
Dim g_objMediaControl As IMediaControl          'MediaControl Object
Dim g_objMediaPosition As IMediaPosition        'MediaPosition Object
Dim g_objBasicAudio  As IBasicAudio             'Basic Audio Object
Dim g_objBasicVideo As IBasicVideo              'Basic Video Object

Initialize all the programmable objects using FilgraphManager, as shown in the following example.

     Set g_objMediaControl = New FilgraphManager
    g_objMediaControl.RenderFile (g_strFileName)    ' name of input file
    ...
    Set g_objBasicAudio = g_objMediaControl
    Set g_objVideoWindow = g_objMediaControl
    Set g_objMediaEvent = g_objMediaControl
    Set g_objMediaPosition = g_objMediaControl

Obtain the other interfaces by calling methods that explicitly return the desired interface. The following table summarizes how to obtain these interfaces.
Interface | Methods that return the interface pointer
IAMCollection | IPinInfo.MediaTypes, IFilterInfo.Pins, IMediaControl.FilterCollection, IMediaControl.RegFilterCollection
IFilterInfo | First IMediaControl.FilterCollection, then IAMCollection.Item or IPinInfo.FilterInfo
IMediaTypeInfo | IPinInfo.ConnectionMediaType
IPinInfo | IFilterInfo.FindPin, IAMCollection.Item
IRegFilterInfo | First IMediaControl.RegFilterCollection, then IAMCollection.Item

For a sample that shows how to manipulate these filter and pin interfaces, see Constructing Filter Graphs Using Visual Basic.

Instantiating the Filter Graph

You can use the filter graph manager to render existing files of the following types.

  • .avi (Audio-Video Interleaved)
  • .mov (Apple® QuickTime®)
  • .mpg (Motion Picture Experts Group)

In addition, you can use the filter graph manager to render an existing filter graph by specifying the file that contains that graph as a parameter to the RenderFile method.

Because the filters in a filter graph are dependent on the type of file being rendered, do not instantiate a filter graph until the user selects a file. The filter graph manager is instantiated when the Visual Basic keyword New is used to create the AUTOMATION object. The filter graph object is created when the IMediaControl::RenderFile method is called, as shown in the following example.

    'Instantiate a filter graph for the requested
    'file format.

    Set g_objMediaControl = New FileGraphManager
    g_objMediaControl.RenderFile (g_strFileName)

Rendering Video

The IMediaControl interface supports three methods (Run, Pause, and Stop) that an application can call to render, pause, or stop a video stream. After the filter graph object is instantiated, your application can call these methods.

The following code example activates the Run, Pause, and Stop methods in response to the user clicking a button.

Private Sub Toolbar1_ButtonClick(ByVal Button As Button)
' handle buttons on the toolbar

    ' if the objects aren't defined, avoid errors
    If g_objMediaControl Is Nothing Then
        Exit Sub
    End If

    If Button.Index = 1 Then 'PLAY
        'Invoke the MediaControl Run() method
        'and play the video through the predefined
        'filter graph.

        g_objMediaControl.Run
        g_fVideoRun = True

    ElseIf Button.Index = 2 Then  'PAUSE
        'Invoke the MediaControl Pause() method
        'and pause the video that is being
        'displayed through the predefined
        'filter graph.

        g_objMediaControl.Pause
        g_fVideoRun = False

    ElseIf Button.Index = 3 Then  'STOP

        'Invoke the MediaControl Stop() method
        'and stop the video that is being
        'displayed through the predefined
        'filter graph.

        g_objMediaControl.Stop
        g_fVideoRun = False
        ' reset to the beginning of the video
        g_objMediaPosition.CurrentPosition = 0
        txtElapsed.Text = "0.0"

Controlling Audio

The IBasicAudio interface supports two properties: the Volume property and the Balance property. The Volume property retrieves or sets the volume. In the sample application, this property is bound to the slider control slVolume. The Balance property retrieves or sets the stereo balance. In the sample application, this property is bound to the slider control slBalance.

Note The volume is a linear volume scale, so only the far right side of the slider is useful.

The following example adjusts the volume by setting the g_objBasicAudio.Volume property.

Private Sub slVolume_Change()

    'Set the volume on the slider

    If Not g_objMediaControl Is Nothing Then
    'if g_objMediaControl has been assigned

       g_objBasicAudio.Volume = slVolume.Value

    End If

End Sub

Scaling and Translating the Video Output

The IVideoWindow interface supports the methods and properties you can use to alter the size, state, owner, palette, visibility, and so on, for the destination window. If you are not concerned with the location or appearance of the destination window, you can render output in the default window (which appears in the upper-left corner of the desktop) without calling any of these methods or properties.

You can also change the window style by removing the caption, border, and dialog box frame. To do this, set the g_objVideoWindow.WindowStyle property to 0x06000000. This corresponds to the logical OR operation of the values WS_DLGFRAME (0x04000000) and WS_VSCROLL (0x02000000). For a complete list of window styles and corresponding values, see the Winuser.h file in the Microsoft® Platform SDK.

To move the destination window onto the form, specify a new position by setting the Top and Left properties of g_objVideoWindow. The Top and Left properties are set to correspond to the upper-left corner of a blank control with a rectangular shape, a placeholder of sorts, that appears on the form. The ScaleMode property for the form was set to 3, which specifies units of pixels. This allows the form properties and DirectShow object properties to be used without conversion. The DirectShow object properties are also expressed in pixels. The default units for a Visual Basic form are twips.

Determine the required size of the rectangle by retrieving the source video width and height. These values correspond to the VideoWidth and VideoHeight properties of the IBasicVideo object.

In addition to setting the Top and Left properties, it is necessary to identify the form of the application as the new parent window by passing the window handle of the form, hWnd, to the object's Owner property. If the handle is not passed, the destination window will appear relative to the desktop and not the form.

The following example shows these tasks.

    Set g_objVideoWindow = g_objMediaControl
    g_objVideoWindow.WindowStyle = CLng(&H6000000)   ' WS_DLGFRAME | WS_VSCROLL
    g_objVideoWindow.Left = CLng(Shape1.Left)   ' shape is a placeholder on the form
    g_objVideoWindow.Top = CLng(Shape1.Top)
    Shape1.Width = g_objVideoWindow.Width    ' resize the shape given the input video
    Shape1.Height = g_objVideoWindow.Height
    g_objVideoWindow.Owner = frmMain.hWnd    ' set the form as the parent

The following example shows how to initialize the ScaleMode property.

' ...
    frmMain.ScaleMode = 3    ' pixels
' ...

Avoid attempting to scale the destination window by setting the Width and Height properties for the IVideoWindow object, because performance suffers considerably.

Tracking Status

The IMediaPosition object exposes a number of properties that you can use to retrieve or set the current position, stop point, duration, and rate. The following code examples shows how to do this.

    Set g_objMediaPosition = g_objMediaControl
    g_dblRunLength = g_objMediaPosition.Duration
    txtDuration.Text = CStr(g_dblRunLength)   ' display the duration
    g_dblStartPosition = 0.0
    txtStart.Text = CDbl(g_dblStartPosition)   ' display the start time
    g_dblRate = g_objMediaPosition.Rate
    txtRate.Text = CStr(g_dblRate)

Getting and Setting the Start Position

Use the IMediaPosition.CurrentPosition property to let the user adjust the point at which the video begins rendering. The following code example changes the current position in response to the user pressing a key.

 Private Sub txtStart_KeyDown(KeyCode As Integer, Shift As Integer)
' handle user input to change the start position
If KeyCode = vbKeyReturn Then
    If g_objMediaPosition Is Nothing Then
        Exit Sub
    ElseIf CDbl(txtStart.Text) > g_dblRunLength Then
        MsgBox "Specified position invalid: re-enter new position."
    ElseIf CDbl(txtStart.Text) < 0 Then
        MsgBox "Specified position invalid: re-enter new position."
    ElseIf CDbl(txtStart.Text) <> "" Then
        g_dblStartPosition = CDbl(txtStart.Text)
        g_objMediaPosition.CurrentPosition = g_dblStartPosition
    End If
End If
End Sub

Getting and Setting the Rate

Use the IMediaPosition.Rate property to let the user adjust the rate at which the video is rendered. This rate is a ratio with respect to typical playback speed. For example, a rate of 0.5 causes the video to be rendered at one-half its typical speed, and a rate of 2.0 causes the video to be rendered at twice its typical speed.

Unlike the CurrentPosition property, which can be set while the video is being rendered, the Rate property must be set prior to rendering.

Note The sound track can be disabled for some videos when the rate is less than 1.0.

The following code example changes the rate in response to the user pressing a key.

Private Sub txtRate_KeyDown(KeyCode As Integer, Shift As Integer)
' DirectShow VB sample
' handle user updates to the Rate value
If KeyCode = vbKeyReturn Then
    If g_objMediaPosition Is Nothing Then
        Exit Sub
    ElseIf CDbl(txtRate.Text) < 0# Then
        MsgBox "Negative values invalid: re-enter value between 0 and 2.0"
    ElseIf CStr(txtRate.Text) <> "" Then
        g_dblRate = CDbl(txtRate.Text)
        g_objMediaPosition.Rate = g_dblRate
    End If
End If
End Sub

Cleaning Up

Each time your application uses the Visual Basic Set statement to create an instance of a new DirectShow object, it must include a corresponding Set statement to remove that object (and its corresponding resources) from memory prior to shutdown, as shown in the following code.

Set g_objBasicAudio = Nothing


Visual Basic Objects

Microsoft® DirectShow® exposes a subset of its functionality to Microsoft® Visual Basic® applications.

Use the following objects to build and control filter graphs:

  • IAMCollection Object
  • IBasicAudio Object
  • IBasicVideo Object
  • IFilterInfo Object
  • IMediaControl Object
  • IMediaEvent Object
  • IMediaPosition Object
  • IMediaTypeInfo Object
  • IPinInfo Object
  • IRegFilterInfo Object
  • IVideoWindow Object

DirectShow Editing Services (DES) supports the following objects for video editing:

  • AMTimeline
  • AMTimelineComp
  • AMTimelineEffect
  • AMTimelineGroup
  • AMTimelineObj
  • AMTimelineSrc
  • AMTimelineTrack
  • AMTimelineTrans
  • IAMTimelineEffectable
  • IAMTimelineSplittable
  • IAMTimelineTransable
  • IAMTimelineVirtualTrack
  • MediaDet
  • MediaLocator
  • RenderEngine
  • Xml2Dex


AMTimeline Object

Provides methods for manipulating the timeline, the central object in Microsoft® DirectShow® Editing Services (DES). A timeline is a collection of time-ordered elements, such as video clips, audio clips, effects, and transitions between clips. The render engine uses the timeline to create a filter graph, from which the application can generate the rendered output.

The AMTimeline object performs three basic services:

  • Creates the objects in the timeline.
  • Acts as a container for those objects.
  • Sets and retrieves general parameters of the timeline.

Methods

AddGroup | Adds a group to the timeline.
ClearAllGroups | Removes all groups from the timeline, along with all objects contained in those groups.
CreateEmptyNode | Creates a new timeline object.
EffectsEnabled | Determines whether effects are enabled.
EnableEffects | Enables or disables all effects in the timeline.
EnableTransitions | Enables or disables all transitions in the timeline.
GetCountOfType | Retrieves the number of objects of the specified type that are contained in a specified group and all of its children.
GetDefaultEffect | Not supported for Visual Basic.
GetDefaultEffectB | Retrieves the default effect.
GetDefaultFPS | Retrieves the default output frame rate, in frames per second.
GetDefaultTransition | Not supported for Visual Basic.
GetDefaultTransitionB | Retrieves the default transition.
GetDirtyRange | Not supported for Visual Basic.
GetDuration | Not supported for Visual Basic.
GetDuration2 | Retrieves the duration of the timeline.
GetGroup | Retrieves a specified group.
GetGroupCount | Retrieves the number of groups that are contained in the timeline.
GetInsertMode | Not supported for Visual Basic.
IsDirty | Not supported for Visual Basic.
RemGroupFromList | Not supported for Visual Basic.
SetDefaultEffect | Not supported for Visual Basic.
SetDefaultEffectB | Sets the default effect.
SetDefaultFPS | Sets the default output frame rate, in frames per second.
SetDefaultTransition | Not supported for Visual Basic.
SetDefaultTransitionB | Sets the default transition.
SetInsertMode | Not supported for Visual Basic.
SetInterestRange | Not supported for Visual Basic.
TransitionsEnabled | Determines whether transitions are enabled.
ValidateSourceNames | Validates source names in the timeline.

AddGroup Method (AMTimeline Object)

AMTimeline Object

Adds a group to the timeline.

Syntax

object.AddGroup(
    pGroup As IAMTimelineObj
)

Parts

object
Object expression that evaluates to an AMTimeline object.
pGroup
AMTimelineObj object that specifies the group.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Maximum number of groups exceeded.
E_NOINTERFACE | The object is not a group.

Remarks

Currently, timelines support a maximum of 32 groups.

ClearAllGroups Method (AMTimeline Object)

AMTimeline Object

Removes all groups from the timeline, along with all objects contained in those groups.

Syntax

object.ClearAllGroups()

Parts

object
Object expression that evaluates to an AMTimeline object.

Error Codes

If the method fails, an error is raised.

CreateEmptyNode Method (AMTimeline Object)

AMTimeline Object

Creates a new timeline object.

Use this method to create timeline objects, rather than the New keyword, because this method performs important initialization routines.

Syntax

object.CreateEmptyNode(
    ppObj As AMTimelineObj,
    Type As TIMELINE_MAJOR_TYPE
)

Parts

object
Object expression that evaluates to an AMTimeline object.
ppObj
AMTimelineObj object that receives the new object.
Type
Member of the TIMELINE_MAJOR_TYPE enumerated type that specifies the type of object to create.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Object type is not valid.
E_OUTOFMEMORY | Insufficient memory.

EffectsEnabled Method (AMTimeline Object)

AMTimeline Object

Determines whether effects are enabled. If effects are disabled, they remain in the timeline but are not rendered.

Syntax

object.EffectsEnabled(
    pfEnabled As Long
)

Parts

object
Object expression that evaluates to an AMTimeline object.
pfEnabled
Variable that receives a value indicating whether effects are enabled. If the value is zero, effects are disabled. If the value is non-zero, effects are enabled.

Error Codes

If the method fails, an error is raised.

EnableEffects Method (AMTimeline Object)

AMTimeline Object

Enables or disables all effects in the timeline. If effects are disabled, they remain in the timeline but are not rendered.

Syntax

object.EnableEffects(
    fEnabled As Long
)

Parts

object
Object expression that evaluates to an AMTimeline object.
fEnabled
Value that specifies whether to enable or disable effects. If zero, effects are disabled. If non-zero, effects are enabled.

Error Codes

If the method fails, an error is raised.

EnableTransitions Method (AMTimeline Object)

AMTimeline Object

Enables or disables all transitions in the timeline. If transitions are disabled, the render engine treats them as cuts; that is, the rendered output jumps instantly from one track to the next. The default cut point is halfway through the duration of the transition. You can change the cut point by calling the IAMTimelineTrans.SetCutPoint method on the transition. Disabled transitions remain in the timeline.

Syntax

object.EnableTransitions(
    fEnabled As Long
)

Parts

object
Object expression that evaluates to an AMTimeline object.
fEnabled
Value that specifies whether to enable or disable transitions. If zero, transitions are disabled. If non-zero, transitions are enabled.

Error Codes

If the method fails, an error is raised.

GetCountOfType Method (AMTimeline Object)

AMTimeline Object

Retrieves the number of objects of the specified type that are contained in a specified group and all of its children.

Syntax

object.GetCountOfType(
    Group As Long,
    pVal As Long,
    pValWithComps As Long,
    MajorType As TIMELINE_MAJOR_TYPE
)

Parts

object
Object expression that evaluates to an AMTimeline object.
Group
Index number of the group for which to retrieve the count.
pVal
Variable that receives the number of objects of the specified type contained in the group and all of its virtual tracks, recursively.
pValWithComps
Variable that receives the count returned in pVal plus the number of compositions searched, including this one.
MajorType
Member of the TIMELINE_MAJOR_TYPE enumerated type, specifying the type of object to count.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_INVALIDARG Invalid group number.

Remarks

Calling this method is equivalent to calling AMTimelineComp.GetCountOfType on the specified group. See the Remarks section of that method for more information.

Typically, an application will not call this method. It is called internally by the render engine.

GetDefaultEffect Method (AMTimeline Object)

AMTimeline Object

Not supported for Visual Basic.

Syntax

object.GetDefaultEffect(
    pGuid As GUID
)

GetDefaultEffectB Method (AMTimeline Object)

AMTimeline Object

Retrieves the default effect. If the render engine cannot render an effect, it substitutes the default effect.

Syntax

object.GetDefaultEffectB() As String

Parts

object
Object expression that evaluates to an AMTimeline object.

Return Value

Returns a string that contains the GUID of the default effect.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_OUTOFMEMORY Insufficient memory.

GetDefaultFPS Method (AMTimeline Object)

AMTimeline Object

Retrieves the default output frame rate, in frames per second (FPS). Groups use this value as their default frame rate. To set a group's frame rate, call the AMTimelineGroup.SetOutputFPS method on the group.

Syntax

object.GetDefaultFPS(
    pFPS As Double
)

Parts

object
Object expression that evaluates to an AMTimeline object.
pFPS
Variable that receives the default frame rate, in frames per second.

Error Codes

If the method fails, an error is raised.

GetDefaultTransition Method (AMTimeline Object)

AMTimeline Object

Not supported for Visual Basic.

Syntax

object.GetDefaultTransition(
    pGuid As GUID
)

GetDefaultTransitionB Method (AMTimeline Object)

AMTimeline Object

Retrieves the default transition. If the render engine cannot render a transition, it substitutes the default transition.

Syntax

object.GetDefaultTransitionB() As *pGuid

Parts

object
Object expression that evaluates to an AMTimeline object.

Return Value

Returns a string that contains the GUID of the default transition.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_OUTOFMEMORY Insufficient memory.

GetDirtyRange Method (AMTimeline Object)

AMTimeline Object

Not supported for Visual Basic.

Syntax

object.GetDirtyRange(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

GetDuration Method (AMTimeline Object)

AMTimeline Object

Not supported for Visual Basic.

Syntax

object.GetDuration(
    pDuration As <Unsupported variant type>
)

GetDuration2 Method (AMTimeline Object)

AMTimeline Object

Retrieves the duration of the timeline.

Syntax

object.GetDuration2(
    pDuration As Double
)

Parts

object
Object expression that evaluates to an AMTimeline object.
pDuration
Variable that receives the duration of the timeline, in seconds.

Error Codes

If the method fails, an error is raised.

GetGroup Method (AMTimeline Object)

AMTimeline Object

Retrieves a specified group.

Syntax

object.GetGroup(
    ppGroup As AMTimelineObj,
    WhichGroup As Long
)

Parts

object
Object expression that evaluates to an AMTimeline object.
ppGroup
AMTimelineObj object that receives the specified group.
WhichGroup
Index of the group to retrieve, based on the order in which the groups were added to the timeline. The first group added to the timeline has an index of 0.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_INVALIDARG Invalid argument.

GetGroupCount Method (AMTimeline Object)

AMTimeline Object

Retrieves the number of groups that are contained in the timeline.

Syntax

object.GetGroupCount(
    pCount As Long
)

Parts

object
Object expression that evaluates to an AMTimeline object.
pCount
Variable that receives the number of groups in the timeline.

Error Codes

If the method fails, an error is raised.

GetInsertMode Method (AMTimeline Object)

AMTimeline Object

Not supported for Visual Basic.

Syntax

object.GetInsertMode(
    pMode As Long
)

IsDirty Method (AMTimeline Object)

AMTimeline Object

Not supported for Visual Basic.

Syntax

object.IsDirty(
    pDirty As Long
);

RemGroupFromList Method (AMTimeline Object)

AMTimeline Object

Not supported for Visual Basic.

Syntax

object.RemGroupFromList(
    pGroup As AMTimelineObj
);

SetDefaultEffect Method (AMTimeline Object)

AMTimeline Object

Not supported for Visual Basic.

Syntax

object.SetDefaultEffect(
    pGuid As GUID
)

SetDefaultEffectB Method (AMTimeline Object)

AMTimeline Object

Sets the default effect. If the render engine cannot render an effect, it substitutes the default effect.

Syntax

object.SetDefaultEffectB(
    pGuid As String
)

Parts

object
Object expression that evaluates to an AMTimeline object.
pGuid
String that contains the GUID of the default effect.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_OUTOFMEMORY Insufficient memory.

Remarks

If you do not set a default effect, or if the effect that you specify as a default causes an error, DES uses its own default effect.

SetDefaultFPS Method (AMTimeline Object)

AMTimeline Object

Sets the default output frame rate, in frames per second. Groups use this value as their default frame rate. To set a group's frame rate, call the AMTimelineGroup.SetOutputFPS method on the group.

Syntax

object.SetDefaultFPS(
    FPS As Double
)

Parts

object
Object expression that evaluates to an AMTimeline object.
FPS
Default frame rate, in frames per second.

Error Codes

If the method fails, an error is raised.

SetDefaultTransition Method (AMTimeline Object)

AMTimeline Object

Not supported for Visual Basic.

Syntax

object.SetDefaultTransition(
    pGuid As GUID
)

SetDefaultTransitionB Method (AMTimeline Object)

AMTimeline Object

Sets the default transition. If the render engine cannot render a transition, it substitutes the default transition.

Syntax

object.SetDefaultTransitionB(
    pGuid As String
)

Parts

object
Object expression that evaluates to an AMTimeline object.
pGuid
String that contains the GUID of the default transition.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_OUTOFMEMORY Insufficient memory.

Remarks

If you do not set a default transition, or if the transition that you specify as a default causes an error, DES uses its own default transition.

SetInsertMode Method (AMTimeline Object)

AMTimeline Object

Not supported for Visual Basic.

Syntax

object.SetInsertMode(
    Mode As Long
)

SetInterestRange Method (AMTimeline Object)

AMTimeline Object

Not supported for Visual Basic.

Syntax

object.SetInterestRange(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

TransitionsEnabled Method (AMTimeline Object)

AMTimeline Object

Determines whether transitions are enabled.

Syntax

object.TransitionsEnabled(
    pfEnabled As Long
)

Parts

object
Object expression that evaluates to an AMTimeline object.
pfEnabled
Value that specifies whether transitions are enabled. If zero, transitions are disabled. If non-zero, transitions are enabled.

Error Codes

If the method fails, an error is raised.

See Also

EnableTransitions

ValidateSourceNames Method (AMTimeline Object)

AMTimeline Object

Validates source names in the timeline, using the media locator. Optionally, this method also updates any source object for which it locates a file.

Syntax

object.ValidateSourceNames(
    ValidateFlags As Long,
    pOverride As MediaLocator,
    NotifyEventHandle As LONG_PTR
)

Parts

object
Object expression that evaluates to an AMTimeline object.
ValidateFlags
Bitwise combination of validation flags, specifying the behavior of the media locator. The SFN_VALIDATEF_REPLACE and SFN_VALIDATEF_CHECK flags must be present, or the method returns E_INVALIDARG.
pOverride
Optional MediaLocator object to use in place of the default. To use the default media locator, set the value of this parameter to Nothing.
NotifyEventHandle
Variable of type LONG_PTR. This parameter is ignored and can be zero.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_INVALIDARG Invalid argument.


AMTimelineComp Object

Inserts or retrieves virtual tracks on a composition in Microsoft® DirectShow® Editing Services (DES).

A composition is a collection of layers that acts as a composited track. For example, a composition that contains two tracks with a transition between them acts as a single track with the transition precomposited. A composition should contain media of only one type (such as audio or video), but this limitation is not enforced. A virtual track is any object that can reside in a composition, including tracks and other compositions.

The topmost nodes in the timeline are groups. Groups support both AMTimelineComp and AMTimelineGroup.

For more information, see The Timeline Model.

Methods

GetCountOfType | Retrieves the number of objects of a given type contained in this composition and all of its virtual tracks, recursively.
GetNextVTrack | Retrieves the next virtual track after a specified virtual track.
GetRecursiveLayerOfType | Performs a depth-first ordering of the virtual tracks contained in this composition, and retrieves the nth virtual track from that ordering.
GetRecursiveLayerOfTypeI | Not supported for Visual Basic.
GetVTrack | Retrieves the virtual track at the specified priority.
VTrackGetCount | Retrieves the number of virtual tracks contained in the composition.
VTrackInsBefore | Inserts a virtual track into the composition at the specified priority.
VTrackSwapPriorities | Switches the priority levels of two tracks.

GetCountOfType Method (AMTimelineComp Object)

AMTimelineComp Object

Retrieves the number of objects of a given type contained in this composition and all its virtual tracks, recursively.

Syntax

object.GetCountOfType(
    pVal As Long,
    pValWithComps As Long,
    MajorType As TIMELINE_MAJOR_TYPE
)

Parts

object
Object expression that evaluates to an AMTimelineComp object.
pVal
Variable that receives the number of objects of the specified type contained in this composition and all its virtual tracks, recursively.
pValWithComps
Variable that receives the count returned in pVal plus the number of compositions searched, including this one.
MajorType
Member of the TIMELINE_MAJOR_TYPE enumerated type, specifying the type of object to count.

Error Codes

If the method fails, an error is raised.

Remarks

Typically, an application will not call this method. It is called by the render engine.

If you count compositions, the value returned in pVal is zero and the value returned in pValWithComps is the number of compositions. The value of pValWithComps includes the composition on which you call the method. For example, if you call this method on an empty composition, pValWithComps equals 1.

Groups cannot reside inside compositions, so you cannot use this method to count groups (the returned count will always be zero). To count groups, call the AMTimeline.GetGroupCount method.

GetNextVTrack Method (AMTimelineComp Object)

AMTimelineComp Object

Retrieves the next virtual track after a specified virtual track.

Syntax

object.GetNextVTrack(
    pVirtualTrack As AMTimelineObj,
    ppNextVirtualTrack As AMTimelineObj
)

Parts

object
Object expression that evaluates to an AMTimelineComp object.
pVirtualTrack
AMTimelineObj object that specifies the previous virtual track, or Nothing to retrieve the first virtual track in the composition.
ppNextVirtualTrack
AMTimelineObj object that receives the next virtual track, in order of priority.

Error Codes

If the method fails, an error is raised.

GetRecursiveLayerOfType Method (AMTimelineComp Object)

AMTimelineComp Object

Performs a depth-first ordering of the virtual tracks contained in this composition, and retrieves the nth virtual track from that ordering.

Syntax

object.GetRecursiveLayerOfType(
    ppVirtualTrack As AMTimelineObj,
    WhichLayer As Long,
    Type As TIMELINE_MAJOR_TYPE
)

Parts

object
Object expression that evaluates to an AMTimelineComp object.
ppVirtualTrack
AMTimelineObj object that receives the virtual track.
WhichLayer
Value that specifies which virtual track to retrieve, indexed from zero.
Type
Member of the TIMELINE_MAJOR_TYPE enumerated type that specifies whether to include tracks in the search.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_INVALIDARG No object of the specified type.

Remarks

Typically, an application will not need to call this method.

If the Type parameter is TIMELINE_MAJOR_TYPE_TRACK, the depth-first ordering includes tracks. If not, it includes only compositions and groups. The object itself is included in the ordering.

For example, in the following arrangement, starting from Composition A, the ordering would be B, C, F, D, E, A.

GetRecursiveLayerOfTypeI Method (AMTimelineComp Object)

AMTimelineComp Object

Not supported for Visual Basic. Call the GetRecursiveLayerOfType method instead.

Syntax

object.GetRecursiveLayerOfTypeI(
    ppVirtualTrack As AMTimelineObj,
    pWhichLayer As Long,
    Type As TIMELINE_MAJOR_TYPE
)

GetVTrack Method (AMTimelineComp Object)

AMTimelineComp Object

Retrieves the virtual track at the specified priority.

Syntax

object.GetVTrack(
    ppVirtualTrack As AMTimelineObj,
    Which As Long
)

Parts

object
Object expression that evaluates to an AMTimelineComp object.
ppVirtualTrack
AMTimelineObj object that receives the virtual track.
Which
Priority of the virtual track to retrieve.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG No virtual track with the specified priority.

VTrackGetCount Method (AMTimelineComp Object)

AMTimelineComp Object

Retrieves the number of virtual tracks contained in the composition.

Syntax

object.VTrackGetCount(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineComp object.
pVal
Variable that receives the number of virtual tracks.

Error Codes

If the method fails, an error is raised.

VTrackInsBefore Method (AMTimelineComp Object)

AMTimelineComp Object

Inserts a virtual track into the composition at the specified priority.

Syntax

object.VTrackInsBefore(
    pVirtualTrack As AMTimelineObj,
    Priority As Long
)

Parts

object
Object expression that evaluates to an AMTimelineComp object.
pVirtualTrack
AMTimelineObj object that specifies the virtual track.
Priority
Priority at which to insert the virtual track, or –1 to insert the virtual track at the end of the priority list.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Invalid argument.
E_NOINTERFACE | Object specified by pVirtualTrack is not a virtual track.

Remarks

Priority levels start at zero. If the timeline already contains a virtual track at the specified priority level, everything from that point on moves down the priority list to make room for the inserted track. This method fails if the specified priority is greater than the current number of tracks.

VTrackSwapPriorities Method (AMTimelineComp Object)

AMTimelineComp Object

Switches the priority levels of two tracks.

Given two priority levels, this method switches the virtual tracks at those priorities. When the method returns, the track that was at the first priority level is now at the second priority level, and vice versa.

Syntax

object.VTrackSwapPriorities(
    VirtualTrackA As Long,
    VirtualTrackB As Long
)

Parts

object
Object expression that evaluates to an AMTimelineComp object.
VirtualTrackA
First priority level at which to swap virtual tracks.
VirtualTrackB
Second priority level at which to swap virtual tracks.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG Invalid argument.


AMTimelineEffect Object

Provides methods for manipulating effects in Microsoft® DirectShow® Editing Services (DES).

The AMTimelineEffect object is a wrapper object for any type of one-input effect that DES supports. To specify which effect to use, call the AMTimelineObj.SetSubObjectGUID method on the effect.

Methods

EffectGetPriority Retrieves the effect's priority level.

EffectGetPriority Method (AMTimelineEffect Object)

AMTimelineEffect Object

Retrieves the effect's priority level. For each timeline object with effects, the render engine applies that object's effects in the order of their priority, starting with priority level zero.

Syntax

object.EffectGetPriority(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineEffect object.
pVal
Variable that receives the priority level.

Error Codes

If the method fails, an error is raised.


AMTimelineGroup Object

Sets and retrieves properties on groups in Microsoft® DirectShow® Editing Services (DES).

A group contains one or more tracks, and possibly one or more compositions, which in turn contain source clips of a uniform type, such as video or audio. Groups are the topmost compositions in a timeline, and also support the AMTimelineComp object. A timeline can contain multiple groups.

Each group has the following attributes:

  • An associated media type.
  • The frame rate at which the group renders, in frames per second (FPS). All edits occur at a time rounded to the nearest frame boundary, as defined by the group's FPS setting.
  • A priority level, for writing files with multiple streams of the same media type (for example, a two-video-stream AVI file).

Methods

ClearRecompressFormatDirty | Not supported for Visual Basic.
GetGroupName | Retrieves the application-defined name of the group.
GetMediaType | Not supported for Visual Basic.
GetOutputBuffering | Retrieves the number of frames rendered in advance during preview.
GetOutputFPS | Retrieves the output frame rate of this group.
GetPreviewMode | Retrieves the preview mode for the group.
GetPriority | Retrieves the group's priority.
GetSmartRecompressFormat | Not supported for Visual Basic.
GetTimeline | Retrieves the timeline to which this group belongs.
IsRecompressFormatDirty | Not supported for Visual Basic.
IsSmartRecompressFormatSet | Not supported for Visual Basic.
SetGroupName | Sets the application-defined name of the group.
SetMediaType | Not supported for Visual Basic.
SetMediaTypeForVB | Specifies the media type for the group.
SetOutputBuffering | Specifies the number of frames rendered in advance during preview.
SetOutputFPS | Sets the uncompressed output frame rate for this group.
SetPreviewMode | Sets the preview mode for the group.
SetRecompFormatFromSource | Sets the video recompression format using the compression format from a source file.
SetSmartRecompressFormat | Not supported for Visual Basic.
SetTimeline | Not supported for Visual Basic.

ClearRecompressFormatDirty Method (AMTimelineGroup Object)

AMTimelineGroup Object

Not supported for Visual Basic.

Syntax

object.ClearRecompressFormatDirty()

GetGroupName Method (AMTimelineGroup Object)

AMTimelineGroup Object

Retrieves the application-defined name of the group.

Syntax

object.GetGroupName() As String

Parts

object
Object expression that evaluates to an AMTimelineGroup object.

Return Value

Returns the application-defined name of the group.

Error Codes

If the method fails, an error is raised.

GetMediaType Method (AMTimelineGroup Object)

AMTimelineGroup Object

Not supported for Visual Basic.

Syntax

object.GetMediaType(
    pmt As _AMMediaType
)

GetOutputBuffering Method (AMTimelineGroup Object)

AMTimelineGroup Object

Retrieves the number of frames rendered in advance during preview.

Syntax

object.GetOutputBuffering(
    pnBuffer As Long
)

Parts

object
Object expression that evaluates to an AMTimelineGroup object.
pnBuffer
Variable that receives the number of buffered frames.

Error Codes

If the method fails, an error is raised.

GetOutputFPS Method (AMTimelineGroup Object)

AMTimelineGroup Object

Retrieves the output frame rate of this group.

Syntax

object.GetOutputFPS(
    pFPS As Double
)

Parts

object
Object expression that evaluates to an AMTimelineGroup object.
pFPS
Variable that receives the output frame rate, in frames per second.

Error Codes

If the method fails, an error is raised.

GetPreviewMode Method (AMTimelineGroup Object)

AMTimelineGroup Object

Retrieves the preview mode for the group.

Syntax

object.GetPreviewMode(
    pfPreview As Long
)

Parts

object
Object expression that evaluates to an AMTimelineGroup object.
pfPreview
Variable that receives a value indicating the preview mode. If zero, the group is in authoring mode. If non-zero, the group is in preview mode.

Error Codes

If the method fails, an error is raised.

Remarks

In preview mode, frames are dropped during slow effects or transitions to keep the video synchronized with the audio. The video might look choppy as a result. In authoring mode, every frame is rendered. Authoring mode is appropriate for writing files; for on-screen preview, the video might become out of sync with the audio.

GetPriority Method (AMTimelineGroup Object)

AMTimelineGroup Object

Retrieves the group's priority.

Syntax

object.GetPriority(
    pPriority As Long
)

Parts

object
Object expression that evaluates to an AMTimelineGroup object.
pPriority
Variable that receives the group's priority.

Error Codes

If the method fails, an error is raised.

GetSmartRecompressFormat Method (AMTimelineGroup Object)

AMTimelineGroup Object

Not supported for Visual Basic.

Syntax

object.GetSmartRecompressFormat(
   ppFormat As Long
)

GetTimeline Method (AMTimelineGroup Object)

AMTimelineGroup Object

Retrieves the timeline to which this group belongs.

Syntax

object.GetTimeline(
    ppTimeline As AMTimeline
)

Parts

object
Object expression that evaluates to an AMTimeline object.
ppTimeline
AMTimeline object that receives the timeline. If the group is not part of a timeline, the object is set to Nothing.

Error Codes

If the method fails, an error is raised.

IsRecompressFormatDirty Method (AMTimelineGroup Object)

AMTimelineGroup Object

Not supported for Visual Basic.

Syntax

object.IsRecompressFormatDirty(
    pVal As Long
)

IsSmartRecompressFormatSet Method (AMTimelineGroup Object)

AMTimelineGroup Object

Not supported for Visual Basic.

Syntax

object.IsSmartRecompressFormatSet(
    pVal As Long
)

SetGroupName Method (AMTimelineGroup Object)

AMTimelineGroup Object

Sets the application-defined name of the group.

Syntax

object.SetGroupName(
    pGroupName As String
)

Parts

object
Object expression that evaluates to an AMTimelineGroup object.
pGroupName
Name of the group.

Error Codes

If the method fails, an error is raised.

SetMediaType Method (AMTimelineGroup Object)

AMTimelineGroup Object

Not supported for Visual Basic. Use the SetMediaTypeForVB method instead.

Syntax

object.SetMediaType(
    pmt As _AMMediaType
)

SetMediaTypeForVB Method (AMTimelineGroup Object)

AMTimelineGroup Object

Specifies the media type for the group.

Syntax

object.SetMediaTypeForVB(
    Val As Long
)

Parts

object
Object expression that evaluates to an AMTimelineGroup object.
Val
Value that specifies the media type:
Zero | Video
Non-zero | Audio

Error Codes

If the method fails, an error is raised.

Remarks

This method supports the following formats.

  • Video: 320 × 240 16-bit RGB, 555 format (MEDIASUBTYPE_RGB555).
  • Audio: 44.1-kHz stereo PCM, 16 bits per sample (MEDIASUBTYPE_PCM).

SetOutputBuffering Method (AMTimelineGroup Object)

AMTimelineGroup Object

Specifies the number of frames rendered in advance during preview.

Syntax

object.SetOutputBuffering(
    nBuffer As Long
)

Parts

object
Object expression that evaluates to an AMTimelineGroup object.
nBuffer
Number of frames to buffer during preview. Must be two or greater.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG Invalid argument.

Remarks

A larger buffer requires more memory but can result in smoother previewing, especially during effects or transitions that require more time to render. The default buffer is 30 frames.

SetOutputFPS Method (AMTimelineGroup Object)

AMTimelineGroup Object

Sets the uncompressed output frame rate for this group.

Syntax

object.SetOutputFPS(
    FPS As Double
)

Parts

object
Object expression that evaluates to an AMTimelineGroup object.
FPS
Output frame rate for this group, in frames per second. The value cannot equal zero, and cannot have more than seven digits after the decimal place.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG Invalid argument.

Remarks

Rendered output from this group runs at the specified frame rate, and all edits on the source material are rounded to the nearest frame boundary, as defined by the frame rate.

SetPreviewMode Method (AMTimelineGroup Object)

AMTimelineGroup Object

Sets the preview mode for the group.

Syntax

object.SetPreviewMode(
    fPreview As Long
)

Parts

object
Object expression that evaluates to an AMTimelineGroup object.
fPreview
Value that specifies the preview mode. If zero, the group is in authoring mode. If non-zero, the group is in preview mode.

Error Codes

If the method fails, an error is raised.

Remarks

In preview mode, frames are dropped during slow effects or transitions to keep the video synchronized with the audio. The video might look choppy as a result. In authoring mode, every frame is rendered. Authoring mode is appropriate for writing files; for on-screen preview, the video might be out of sync with the audio.

SetRecompFormatFromSource (AMTimelineGroup Object)

AMTimelineGroup Object

Sets the video recompression format using the compression format from a source file.

Syntax

object.SetRecompFormatFromSource(
    pSource As AMTimelineSrc
)

Parts

object
Object expression that evaluates to an AMTimelineGroup object.
pSource
IAMTimelineSrc object.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_NO_TIMELINE | The group is not within a timeline.
E_OUTOFMEMORY | Insufficient memory.
VFW_E_INVALIDMEDIATYPE | Source file has no video stream.

Remarks

This method finds the source file associated with pSource, retrieves the media type of the first video stream in the file, and sets the group compression format using that type.

SetSmartRecompressFormat Method (AMTimelineGroup Object)

AMTimelineGroup Object

Not supported for Visual Basic.

Syntax

object.SetSmartRecompressFormat(
    pFormat As Long
)

SetTimeline Method (AMTimelineGroup Object)

AMTimelineGroup Object

Not supported for Visual Basic.

Syntax

object.SetTimeline(
    pTimeline As AMTimeline
)


AMTimelineObj Object

Provides methods for manipulating timeline objects in Microsoft® DirectShow® Editing Services (DES). All timeline objects support AMTimelienObj, including source, effect, transition, track, group, and composition objects. Create a timeline object by calling the AMTimeline.CreateEmptyNode method.

Methods

ClearDirty | Not supported for Visual Basic.
FixTimes | Not supported for Visual Basic.
FixTimes2 | Rounds the specified start and stop times to the nearest frame boundaries, as defined by the parent group's frame rate setting.
GetDirtyRange | Not supported for Visual Basic.
GetDirtyRange2 | Not supported for Visual Basic.
GetEmbedDepth | Not supported for Visual Basic.
GetGenID | Retrieves the object's generated identifier.
GetGroupIBelongTo | Not supported for Visual Basic.
GetLocked | Retrieves the object's editing state (locked or unlocked).
GetMuted | Retrieves the object's muted state.
GetPropertySetter | Not supported for Visual Basic.
GetStartStop | Not supported for Visual Basic.
GetStartStop2 | Retrieves the object's start and stop times, relative to the object's parent.
GetSubObject | Not supported for Visual Basic.
GetSubObjectGUID | Not supported for Visual Basic.
GetSubObjectGUIDB | Retrieves the GUID of the subobject associated with this object.
GetSubObjectLoaded | Determines whether a subobject has been created for the object.
GetTimelineNoRef | Not supported for Visual Basic.
GetTimelineType | Retrieves the object's type.
GetUserData | Retrieves application-defined persistent data.
GetUserID | Retrieves the object's application-defined identifier.
GetUserName | Retrieves the object's application-defined name.
Remove | Removes this object from the timeline, for reinsertion elsewhere.
RemoveAll | Permanently removes this object from the timeline, including subobjects and children.
SetDirtyRange | Not supported for Visual Basic.
SetDirtyRange2 | Not supported for Visual Basic.
SetLocked | Sets the object's editing state to locked or unlocked.
SetMuted | Sets the object's muted state.
SetPropertySetter | Not supported for Visual Basic.
SetStartStop | Not supported for Visual Basic.
SetStartStop2 | Sets the object's start and stop times, relative to the object's parent.
SetSubObject | Not supported for Visual Basic.
SetSubObjectGUID | Not supported for Visual Basic.
SetSubObjectGUIDB | Specifies the GUID of the subobject associated with this object.
SetTimelineType | Not supported for Visual Basic.
SetUserData | Sets application-defined persistent data.
SetUserID | Sets an application-defined identifier for the object.
SetUserName | Sets an application-defined name for the object.

ClearDirty Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.ClearDirty()

FixTimes Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.FixTimes(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

FixTimes2 Method (AMTimelineObj Object)

AMTimelineObj Object

Rounds the specified start and stop times to the nearest frame boundaries, as defined by the parent group's frame rate setting.

Syntax

object.FixTimes2(
    pStart As Double,
    REFTIME As Double*pStop
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
pStart
Variable that contains the start time, in seconds. If the call succeeds, the value is set to the rounded time.
pStop
Variable that contains the stop time, in seconds. If the call succeeds, the value is set to the rounded time.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_NOTINTREE The object is not in the timeline.

Remarks

During rendering, DES rounds the object's start and stop times to the nearest frame boundary. However, DES does not overwrite the object's times. If you change the group frame rate, the rounded times are always calculated from the original times. For more information, see Frame Rates.

Use this method to determine accurate start and stop times in the rendered project. For example, if you seek within the project, seek to the rounded times and not the original times. Call GetStartStop2 to obtain the original times, and pass those values to FixTimes2.

GetDirtyRange Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.GetDirtyRange(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

GetDirtyRange2 Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.GetDirtyRange2(
    pStart As Double,
    pStop As Double
)

GetEmbedDepth Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.GetEmbedDepth(
    pVal As Long
)

GetGenID Method (AMTimelineObj Object)

AMTimelineObj Object

Retrieves the object's generated identifier. The identifier is a reserved number. Applications should not use it.

Syntax

object.GetGenID(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
pVal
Variable that receives the generated identifier.

Error Codes

If the method fails, an error is raised.

GetGroupIBelongTo Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.GetGroupIBelongTo(
    ppGroup As AMTimelineGroup
)

GetLocked Method (AMTimelineObj Object)

AMTimelineObj Object

Retrieves the object's editing state (locked or unlocked). A locked state indicates that the object should not be edited; an unlocked state indicates that the object can be edited. The timeline does not enforce the lock. The locked setting exists only for the convenience of the application.

Syntax

GetLocked(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
pVal
Variable that receives the object's editing state. If the value is zero, the object is unlocked and can be edited. If the value is non-zero, the object is locked and should not be edited.

Error Codes

If the method fails, an error is raised.

GetMuted Method (AMTimelineObj Object)

AMTimelineObj Object

Retrieves the object's muted state. A muted object is not rendered, but it remains in the timeline.

Syntax

object.GetMuted(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
pVal
Variable that receives a value indicating the muted state. If the value is zero, the object is not muted. If the value is non-zero, the object and its children are muted.

Error Codes

If the method fails, an error is raised.

Remarks

If an object's parent is muted, the object is muted regardless of its muted state. When the parent is no longer muted, the object's previous muted state is restored.

GetPropertySetter Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic..

Syntax

object.GetPropertySetter() As PropertySetter

GetStartStop Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.GetStartStop(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

GetStartStop2 Method (AMTimelineObj Object)

AMTimelineObj Object

Retrieves the object's start and stop times, relative to the object's parent.

Syntax

object.GetStartStop2(
    pStart As Double,
    pStop As Double
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
pStart
Variable that receives the start time, in seconds.
pStop
Variable that receives the stop time, in seconds.

Error Codes

If the method fails, an error is raised.

Remarks

Compositions, groups, and tracks always have a start time of 0.

During rendering, DES rounds an object's start and stop times to the nearest frame boundary. However, it does not overwrite the object's times. If you change the group frame rate, the rounded times are always calculated from the original times. For more information, see Frame Rates. To determine the start and stop times in the rendered project, pass the values returned by GetStartStop2 to the FixTimes2 method.

GetSubObject Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.GetSubObject(
    pVal As Unknown
)

GetSubObjectGUID Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.GetSubObjectGUID(
    pVal As GUID
)

GetSubObjectGUIDB Method (AMTimelineObj Object)

AMTimelineObj Object

Retrieves the GUID of the subobject associated with this timeline object.

Syntax

object.GetSubObjectGUIDB() As String

Parts

object
Object expression that evaluates to an AMTimelineObj object.

Return Value

Returns a string that contains the GUID of the subobject. If the object has no subobject, the return value is {00000000-0000-0000-0000-000000000000}.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_OUTOFMEMORY Insufficient memory.

GetSubObjectLoaded Method (AMTimelineObj Object)

AMTimelineObj Object

Determines whether a subobject has been created for the object.

Syntax

object.GetSubObjectLoaded(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
pVal
Variable that receives a value indicating whether a subobject has been created. If zero, a subobject has been not created. If non-zero, a subobject has been created.

Error Codes

If the method fails, an error is raised.

GetTimelineNoRef Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.GetTimelineNoRef(
    ppResult As AMTimeline
)

GetTimelineType Method (AMTimelineObj Object)

AMTimelineObj Object

Retrieves the object's type.

Syntax

object.GetTimelineType(
    pVal As TIMELINE_MAJOR_TYPE
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
pVal
Variable that receives a member of the TIMELINE_MAJOR_TYPE enumerated type, indicating the type of object.

Error Codes

If the method fails, an error is raised.

GetUserData Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.GetUserData(
    pData As Byte,
    pSize As Long
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
pData
Reference to an array of bytes that contains the data.
pSize
Size of the array, in bytes. When the method returns, the value is set to the required size. See Remarks.

Error Codes

If the method fails, an error is raised.

Error Codes

This method sets the value of pSize equal to the array size needed for the user data. Use the ReDim statement to resize the array and call the method again. Pass the pData parameter by reference, using the first element of the array as the parameter value.

Dim UserData(0) As Byte
Dim Size As Long

' Find the required size.
ReDim UserData(1)
objTimelineObject.GetUserData UserData(0), Size

' Resize the array and get all the data.
If Size <> 0 Then
    ReDim UserData(Size)
    objTimelineObject.GetUserData UserData(0), Size
End If

GetUserID Method (AMTimelineObj Object)

AMTimelineObj Object

Retrieves the object's application-defined identifier.

Syntax

object.GetUserID(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
pVal
Variable that receives the application-defined identifier.

Error Codes

If the method fails, an error is raised.

GetUserName Method (AMTimelineObj Object)

AMTimelineObj Object

Retrieves the object's application-defined name.

Syntax

object.GetUserName() As String

Parts

object
Object expression that evaluates to an AMTimelineObj object.

Return Value

Returns a string that contains the application-defined name.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_OUTOFMEMORY Insufficient memory.

Remove Method (AMTimelineObj Object)

AMTimelineObj Object

Removes this object from the timeline (including subobjects but not children), for reinsertion elsewhere.

Syntax

object.Remove()

Error Codes

If the method fails, an error is raised.

Remarks

Call this method only if the application will immediately insert the object back into the timeline. It is an invalid operation to call this method without then reinserting the object. To remove an object permanently, call RemoveAll.

RemoveAll Method (AMTimelineObj Object)

AMTimelineObj Object

Permanently removes this object from the timeline, including subobjects and children.

Syntax

object.RemoveAll()

Error Codes

If the method fails, an error is raised.

Remarks

To remove an object for the purpose of reinserting it elsewhere in the timeline, call Remove.

SetDirtyRange Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.SetDirtyRange(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

SetDirtyRange2 Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.SetDirtyRange2(
    Start As Double,
    Stop As Double
)

SetLocked Method (AMTimelineObj Object)

AMTimelineObj Object

Sets the object's editing state to locked or unlocked. A locked state indicates that the object should not be edited; an unlocked state indicates that the object can be edited. The timeline does not enforce the lock. The locked setting exists only for the convenience of the application.

Syntax

object.SetLocked(
    newVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
newVal
Value that specifies the object's editing state. If zero, the object is unlocked and can be edited. If non-zero, the object is locked and should not be edited.

Error Codes

If the method fails, an error is raised.

SetMuted Method (AMTimelineObj Object)

AMTimelineObj Object

Sets the object's muted state. A muted object is not rendered, but it remains in the timeline.

Syntax

object.SetMuted(
    newVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
newVal
Value that specifies the muted state. If zero, the object is non muted. If non-zero, the object and all its children are muted.

Error Codes

If the method fails, an error is raised.

Remarks

Muting an object also mutes any children contained in the object. For example, if you mute a track, the transitions, sources, and effects in that track are also muted. Once the object is no longer muted, its children revert to their previous state, which might be muted or unmuted.

SetPropertySetter Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.SetPropertySetter(
    newVal As PropertySetter
)

SetStartStop Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.SetStartStop(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

SetStartStop2 Method (AMTimelineObj Object)

AMTimelineObj Object

Sets the object's start and stop times, relative to the object's parent.

Syntax

object.SetStartStop2(
    Start As Double,
    Stop As Double
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
Start
New start time, in seconds, or –1 to keep the existing start time.
Stop
New stop time, in seconds, or –1 to keep the existing stop time.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Invalid argument.
E_NOTIMPL | Not implemented.

Remarks

Tracks, compositions, and groups do not implement this method. For these objects, the start time is always zero, and the stop time is the maximum stop time of the objects they contain.

Do not set overlapping times on source objects within the same track. Doing so can cause undefined behaviors.

For source objects, the start and stop times are independent of the media start and media stop times. Changing one pair of values does not change the other. To set the media start and stop times, call the AMTimelineSrc.SetMediaTimes2 method. For more information, see Time in DirectShow Editing Services.

SetSubObject Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.SetSubObject(
    newVal As Unknown
)

SetSubObjectGUID Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic.

Syntax

object.SetSubObjectGUID(
    newVal As GUID
)

SetSubObjectGUIDB Method (AMTimelineObj Object)

AMTimelineObj Object

Specifies the GUID of the subobject associated with this object.

Syntax

object.SetSubObjectGUIDB(
    newVal As String
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
newVal
String that contains the GUID of the subobject.

Error Codes

If the method fails, an error is raised.

Remarks

The render engine creates an instance of the subobject as needed.

SetTimelineType Method (AMTimelineObj Object)

AMTimelineObj Object

Not supported for Visual Basic. To create a new timeline object, call the AMTimeline.CreateEmptyNode method. Once an object is created, you cannot change its type.

Syntax

object.SetTimelineType(
    newVal As TIMELINE_MAJOR_TYPE
)

SetUserData Method (AMTimelineObj Object)

AMTimelineObj Object

Sets application-defined persistent data.

Syntax

object.SetUserData(
    pData As Byte,
    Size As Long
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
pData
Reference to an array of bytes that contains the data.
Size
Size of the array, in bytes.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_OUTOFMEMORY Insufficient memory.

Remarks

Pass the pData parameter by reference, using the first element of the array as the parameter value:

Dim UserData(100) As Byte
' Initialize the array (not shown).
objTimelineObject.SetUserData UserData(0), 100

SetUserID Method (AMTimelineObj Object)

AMTimelineObj Object

Sets an application-defined identifier for the object.

Syntax

object.SetUserID(
    newVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
newVal
Value that specifies the identifier. This identifier is used only by the application and can be any value.

Error Codes

If the method fails, an error is raised.

SetUserName Method (AMTimelineObj Object)

AMTimelineObj Object

Sets an application-defined name for the object.

Syntax

object.SetUserName(
    newVal As String
)

Parts

object
Object expression that evaluates to an AMTimelineObj object.
newVal
String that contains the name. Strings longer than 256 characters might be truncated.

Error Codes

If the method fails, an error is raised.


AMTimelineSrc Object

Provides methods for manipulating and setting properties on sources in Microsoft® DirectShow® Editing Services (DES). An AMTimelineSrc object represents a clip taken from one stream in a media source.

You can use a portion of the data within a source file by setting the media start and media stop times. These values specify the beginning and end of the AMTimelineSrc object, relative to the original media source. The media times can differ from the object's start and stop times on the timeline, allowing for fast- or slow-motion playback (with audio sources, the pitch shifts).

Methods

FixMediaTimes | Not supported for Visual Basic.
FixMediaTimes2 | Rounds the specified time values to the nearest frame boundary, as defined by the output frame rate.
GetDefaultFPS | Retrieves the source object's default frame rate.
GetMediaLength | Not supported for Visual Basic.
GetMediaLength2 | Retrieves the media length of this object.
GetMediaName | Retrieves the name of the source file represented by this object.
GetMediaTimes | Not supported for Visual Basic.
GetMediaTimes2 | Retrieves the media start and stop times.
GetStreamNumber | Retrieves the current stream number for the source object.
GetStretchMode | Retrieves the stretch mode.
IsNormalRate | Indicates whether the clip will play at the authored playback rate.
ModifyStopTime | Not supported for Visual Basic.
ModifyStopTime2 | Sets the stop time.
SetDefaultFPS | Sets the source object's default frame rate.
SetMediaLength | Not supported for Visual Basic.
SetMediaLength2 | Specifies the duration of the source file.
SetMediaName | Specifies the name of the source file.
SetMediaTimes | Not supported for Visual Basic.
SetMediaTimes2 | Sets the media stop and start times.
SetStretchMode | Sets the stretch mode.
SetStreamNumber | Specifies which stream to read from the source file.
SpliceWithNext | Joins the AMTimelineSrc object to another AMTimelineSrc object.

FixMediaTimes Method (AMTimelineSrc Object)

AMTimelineSrc Object

Not supported for Visual Basic.

Syntax

object.FixMediaTimes(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

FixMediaTimes2 Method (AMTimelineSrc Object)

AMTimelineSrc Object

Rounds the specified time values to the nearest frame boundary, as defined by the output frame rate. In general, applications do not need to call this method.

Syntax

object.FixMediaTimes2(
    pStart As Double,
    pStop As Double
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
pStart
Start time, in seconds. If the call succeeds, this variable is set to the rounded time.
pStop
Stop time, in seconds. If the call succeeds, this variable is set to the rounded time.

Error Codes

If the method fails, an error is raised.

Remarks

This method is similar to the AMTimelineObj.FixTimes2 method, but it preserves the original ratio of media times and timeline times. Just rounding the times to the nearest frame boundary could distort this ratio.

GetDefaultFPS Method (AMTimelineSrc Object)

AMTimelineSrc Object

Retrieves the source object's default frame rate. The render engine uses this value if it cannot determine the frame rate from the original source.

Syntax

object.GetDefaultFPS(
    pFPS As Double
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
pFPS
Variable that receives the default frame rate, in frames per second.

Error Codes

If the method fails, an error is raised.

Remarks

The default frame rate is not required if the file format specifies the frame rate. This is the case for audio and video formats.

If the source is a bitmap or JPEG image, the render engine uses it as the first image in a device-independent bitmap (DIB) sequence, with a frame rate equal to the default frame rate. To render a static image, rather than a DIB sequence, set the default frame rate to 0.

If the source is a GIF, do not set the frame rate. For animated GIFs, the GIF file specifies the delay between each image.

GetMediaLength Method (AMTimelineSrc Object)

AMTimelineSrc Object

Not supported for Visual Basic.

Syntax

object.GetMediaLength(
    pLength As <Unsupported variant type>
)

GetMediaLength2 Method (AMTimelineSrc Object)

AMTimelineSrc Object

Retrieves the media length of this object.

Syntax

object.GetMediaLength2(
    pLength As Double
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
pLength
Variable that receives the media length in seconds.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_NOTDETERMINED Media times are not set on this object.

See Also

SetMediaLength2

GetMediaName Method (AMTimelineSrc Object)

AMTimelineSrc Object

Retrieves the name of the source file represented by this object.

Syntax

object.GetMediaName() As String

Parts

object
Object expression that evaluates to an AMTimelineSrc object.

Return Value

Returns the name of the source file.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_OUTOFMEMORY Insufficient memory.

GetMediaTimes Method (AMTimelineSrc Object)

AMTimelineSrc Object

Not supported for Visual Basic.

Syntax

object.GetMediaTimes(
    pStart As <Unsupported variant type>,
    pStop As <Unsupported variant type>
)

GetMediaTimes2 Method (AMTimelineSrc Object)

AMTimelineSrc Object

Retrieves the media start and stop times.

Syntax

object.GetMediaTimes2(
    pStart As Double,
    pStop As Double
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
pStart
Variable that receives the media start time, in seconds.
pStop
Variable that receives the media stop time, in seconds.

Error Codes

If the method fails, an error is raised.

Remarks

The media times are relative to the original media file. For more information, see Time in DirectShow Editing Services.

GetStreamNumber Method (AMTimelineSrc Object)

AMTimelineSrc Object

Retrieves the current stream number for the source object.

Syntax

object.GetStreamNumber(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
pVal
Variable that receives the stream number.

Error Codes

If the method fails, an error is raised.

GetStretchMode Method (AMTimelineSrc Object)

AMTimelineSrc Object

Retrieves the stretch mode. The stretch mode determines how a video source is rendered if its size does not match the output dimensions.

Syntax

object.GetStretchMode(
    pnStretchMode As Long
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
pnStretchMode
Variable that receives one of the following values:
  • RESIZEF_STRETCH
  • RESIZEF_CROP
  • RESIZEF_PRESERVEASPECTRATIO
  • RESIZEF_PRESERVEASPECTRATIO_NOLETTERBOX

Error Codes

If the method fails, an error is raised.

IsNormalRate Method (AMTimelineSrc Object)

AMTimelineSrc Object

Indicates whether the clip will play at the authored playback rate.

Syntax

object.IsNormalRate(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
pVal
Variable that receives a value indicating how the clip will render. If non-zero, the clip will play at the normal rate. If zero, it will play faster or slower than normal.

Error Codes

If the method fails, an error is raised.

Remarks

A clip's playback rate is determined by its media start and stop times, relative to its timeline times:

Playback rate = (Media Stop — Media Start) / (Timeline Stop — Timeline Start)

If this ratio is equal to 1, the clip plays at the authored speed. Otherwise, it plays faster or slower. For more information, see Time in DirectShow Editing Services.

ModifyStopTime Method (AMTimelineSrc Object)

AMTimelineSrc Object

Not supported for Visual Basic.

Syntax

object.ModifyStopTime(
    Stop As <Unsupported variant type>
)

ModifyStopTime2 Method (AMTimelineSrc Object)

AMTimelineSrc Object

Sets the stop time.

Syntax

object.ModifyStopTime2(
    Stop As Double
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
Stop
New stop time, in seconds.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_INVALIDARG The specified time is invalid.

SetDefaultFPS Method (AMTimelineSrc Object)

AMTimelineSrc Object

Sets the source object's default frame rate.

Syntax

object.SetDefaultFPS(
    FPS As Double
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
FPS
Default frame rate, in frames per second.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_INVALIDARG The specified frame rate is less than zero.

Remarks

The render engine uses this value if it cannot determine the frame rate from the original source file.

Call this method only for source files without a predefined frame rate. For bitmap and JPEG files, the default frame rate is zero, which causes the source to be rendered as a still image. To use the image as the first frame in a DIB sequence, set the frame rate to a value greater than zero.

SetMediaLength Method (AMTimelineSrc Object)

AMTimelineSrc Object

Not supported for Visual Basic.

Syntax

object.SetMediaLength(
    Length As <Unsupported variant type>
)

SetMediaLength2 Method (AMTimelineSrc Object)

AMTimelineSrc Object

Specifies the duration of the source file. This method is equivalent to the SetMediaLength method, but takes a REFTIME value.

Syntax

object.SetMediaLength2(
    Length As Double
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
Length
Media length, in seconds.

Error Codes

If the method fails, an error is raised.

Remarks

You can avoid potential rendering errors by setting the media length before you set the media stop time. When you set the media stop time, DES checks it against the media length.

This method does not validate the Length parameter, but the value must equal the actual duration of the source file. Obtain the source file duration by retrieving the IMediaDet.StreamLength property.

SetMediaName Method (AMTimelineSrc Object)

AMTimelineSrc Object

Specifies the name of the source file.

Syntax

object.SetMediaName(
    newVal As String
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
newVal
String that specifies the name of the media file.

Error Codes

If the method fails, an error is raised.

SetMediaTimes Method (AMTimelineSrc Object)

AMTimelineSrc Object

Not supported for Visual Basic.

Syntax

object.SetMediaTimes(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

SetMediaTimes2 Method (AMTimelineSrc Object)

AMTimelineSrc Object

Sets the media stop and start times.

Syntax

object.SetMediaTimes2(
    Start As Double,
    Stop As Double
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
Start
Media start time, in seconds.
Stop
Media stop time, in seconds.

Error Codes

If the method fails, an error is raised.

Remarks

The media times are the stop and start times relative to the original media file. Always set the media times when you add a video or audio source to the timeline. Otherwise, rendering problems might occur. The stop time must be greater than the start time.

To use a still frame from a video source, set the stop time to a fractional amount more than the start time, such as 100 nanoseconds. Setting them to the same value causes a rendering error.

If the timeline duration does not match the media duration, the source stretches or shrinks accordingly. This causes the clip to play slower or faster than the authored rate (pitch shifting will occur in an audio source). For more information, see Time in DirectShow Editing Services.

You can specify the duration of the source file by calling the SetMediaLength method. If you set a media stop time that exceeds the duration, DES truncates the stop time.

SetStreamNumber Method (AMTimelineSrc Object)

AMTimelineSrc Object

Specifies which stream to read from the source file.

Syntax

object.SetStreamNumber(
    Val As Long
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
Val
The stream number, from the set of streams matching the media type of the parent group.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_INVALIDARG The Val parameter is less than zero.

Remarks

The Val parameter specifies a stream number from the set of streams that matches the parent group's media type, not from the entire set of streams in the source file. For example, suppose that a file contains two video streams and two audio streams. If the AMTimelineSrc object is inside a video group, setting Val to 0 selects the first video stream. The caller is responsible for specifying a valid stream number.

The stream number defaults to zero.

SetStretchMode Method (AMTimelineSrc Object)

AMTimelineSrc Object

Sets the stretch mode. The stretch mode determines how a video source is rendered if its size does not match the output dimensions.

Syntax

object.SetStretchMode(
    nStretchMode As Long
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
nStretchMode
Flag indicating the current stretch mode. Must be one of the following values:
  • RESIZEF_STRETCH
  • RESIZEF_CROP
  • RESIZEF_PRESERVEASPECTRATIO
  • RESIZEF_PRESERVEASPECTRATIO_NOLETTERBOX

Error Codes

If the method fails, an error is raised.

SpliceWithNext Method (AMTimelineSrc Object)

AMTimelineSrc Object

Joins the AMTimelineSrc object to another AMTimelineSrc object.

Syntax

object.SpliceWithNext(
    pNext As AMTimelineObj
)

Parts

object
Object expression that evaluates to an AMTimelineSrc object.
pNext
AMTimelineObj object to join to the current source.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Invalid argument.
E_NOINTERFACE | Object specified by pNext parameter is not a source object.

Remarks

As currently implemented, this method discards any effects on pNext.

For this method to succeed, pNext must be a match frame of the current source object:

  • It must share the same source file.
  • The media start time must equal the media stop time of the current source.
  • The playback rate must be the same. Playback rate is media duration divided by timeline duration.


AMTimelineTrack Object

Provides methods for manipulating tracks in Microsoft® DirectShow® Editing Services (DES).

A track contains a list of sources that are rendered in the final output. Sources within the same track may not overlap. Video tracks can have both effects and transitions. The render engine applies effects before it applies transitions. Audio tracks can have effects, but not transitions.

For more information, see The Timeline Model.

Methods

AreYouBlank | Determines whether the track is blank (contains no source objects).
GetNextSrc | Not supported for Visual Basic.
GetNextSrc2 | Searches the track for the next source that appears at the specified time or later.
GetNextSrcEx | Retrieves the next source after the specified source.
GetSourcesCount | Retrieves the number of sources in the track.
GetSrcAtTime | Not supported for Visual Basic.
GetSrcAtTime2 | Retrieves the source object nearest to the specified time, according to specified boundary conditions.
InsertSpace | Not supported in Visual Basic.
InsertSpace2 | Splits any objects that exist at the specified time and inserts space between them.
MoveEverythingBy | Not supported for Visual Basic.
MoveEverythingBy2 | Moves all objects in the track, starting at a specified time, by a specified distance along the timeline.
SrcAdd | Adds a source to the track.
ZeroBetween | Not supported for Visual Basic.
ZeroBetween2 | Removes everything from the track between the specified times.

AreYouBlank Method (AMTimelineTrack Object)

AMTimelineTrack Object

Determines whether the track is blank (contains no source objects).

Syntax

object.AreYouBlank(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineTrack object.
pVal
Variable that receives a value specifying whether the track is blank. If non-zero, the track is blank and contains no source objects. If zero, the track is not blank.

Error Codes

If the method fails, an error is raised.

GetNextSrc Method (AMTimelineTrack Object)

AMTimelineTrack Object

Not supported for Visual Basic.

Syntax

object.GetNextSrc(
    ppSrc AMTimelineObj,
    pInOut As <Unsupported variant type>
)

GetNextSrc2 Method (AMTimelineTrack Object)

AMTimelineTrack Object

Searches the track for the next source that appears at the specified time or later.

Syntax

object.GetNextSrc2(
    ppSrc As AMTimelineObj,
    pInOut As Double
)

Parts

object
Object expression that evaluates to an AMTimelineTrack object.
ppSrc
The AMTimelineObj object that receives the source object.
pInOut
Start time for the search, in seconds. If the method retrieves a source, it sets this variable to the stop time of the source. If the method does not retrieve a source, the value becomes invalid and the application should not use it.

Error Codes

If the method fails, an error is raised.

Remarks

If the time specified by pInOut falls between the start and stop times of a source, the method retrieves that source.

GetNextSrcEx Method (AMTimelineTrack Object)

AMTimelineTrack Object

Retrieves the next source after the specified source.

Syntax

object.GetNextSrcEx(
    pLast As AMTimelineObj,
    ppNext As AMTimelineObj
)

Parts

object
Object expression that evaluates to an AMTimelineTrack object.
pLast
The previous AMTimelineObj object, or Nothing to retrieve the first source in the track.
ppNext
The AMTimelineObj object that receives the next source.

Error Codes

If the method fails, an error is raised.

GetSourcesCount Method (AMTimelineTrack Object)

AMTimelineTrack Object

Retrieves the number of sources in the track.

Syntax

object.GetSourcesCount(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineTrack object.
pVal
Variable that receives the number of sources in the track.

Error Codes

If the method fails, an error is raised.

GetSrcAtTime Method (AMTimelineTrack Object)

AMTimelineTrack Object

Not supported for Visual Basic.

Syntax

object.GetSrcAtTime(
    ppSrc As AMTimelineObj,
    Time As <Unsupported variant type>,
    SearchDirection As Long
)

GetSrcAtTime2 Method (AMTimelineTrack Object)

AMTimelineTrack Object

Retrieves the source object nearest to the specified time, according to the specified boundary conditions.

Syntax

object.GetSrcAtTime2(
    ppSrc As AMTimelineObj,
    Time As Double,
    SearchDirection As Long
)

Parts

object
Object expression that evaluates to an AMTimelineTrack object.
ppSrc
The AMTimelineObj object that receives the source.
Time
Start time for the search, in seconds.
SearchDirection
Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_INVALIDARG Invalid argument.

InsertSpace Method (AMTimelineTrack Object)

AMTimelineTrack Object

Not supported in Visual Basic.

Syntax

object.InsertSpace(
    rtStart As <Unsupported variant type>,
    rtEnd As <Unsupported variant type>
)

InsertSpace2 Method (AMTimelineTrack Object)

AMTimelineTrack Object

Splits any objects that exist at the specified time and inserts space between them.

Syntax

object.InsertSpace2(
    rtStart As Double,
    rtEnd As Double
)

Parts

object
Object expression that evaluates to an AMTimelineTrack object.
rtStart
Time at which to create the split, and the starting point of the inserted space, in seconds.
rtEnd
End point of the inserted space, in seconds.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_INVALIDARG Invalid argument.

MoveEverythingBy Method (AMTimelineTrack Object)

AMTimelineTrack Object

Not supported for Visual Basic.

Syntax

object.MoveEverythingBy(
    Start As <Unsupported variant type>,
    MoveBy As <Unsupported variant type>
)

MoveEverythingBy2 Method (AMTimelineTrack Object)

AMTimelineTrack Object

Moves all objects in the track, starting at a specified time, by a specified distance along the timeline.

Syntax

object.MoveEverythingBy2(
    Start As Double,
    MoveBy As Double
)

Parts

object
Object expression that evaluates to an AMTimelineTrack object.
Start
Starting time of the move, in seconds. Only objects that begin at this time or later are moved.
MoveBy
Amount of time along the timeline to move the objects, in seconds.

Error Codes

If the method fails, an error is raised.

SrcAdd Method (AMTimelineTrack Object)

AMTimelineTrack Object

Adds a source to the track.

Syntax

object.SrcAdd(
    pSrc As AMTimelineObj
)

Parts

object
Object expression that evaluates to an AMTimelineTrack object.
pSrc
The AMTimelineObj object to add.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_NOINTERFACE The object specified by pSrc is not a source object.

Remarks

Set the source's start and stop times before calling this method. (Call the AMTimelineObj.SetStartStop method.)

Currently, DES cannot simultaneously render more than 75 sources that were compressed with Video Compression Manager (VCM) codecs. Also, if the project as a whole contains more than 75 such sources, you must use dynamic reconnection or DES cannot preview the project. For more information, see RenderEngine.SetDynamicReconnectLevel.

ZeroBetween Method (AMTimelineTrack Object)

AMTimelineTrack Object

Not supported for Visual Basic.

Syntax

object.ZeroBetween(
    rtStart As <Unsupported variant type>,
    rtEnd As <Unsupported variant type>
)

ZeroBetween2 Method (AMTimelineTrack Object)

AMTimelineTrack Object

Removes everything from the track between the specified times. This method splits any objects that span the specified time range and removes the pieces that fall within the range.

Syntax

object.ZeroBetween2(
    rtStart As Double,
    rtEnd As Double
)

Parts

object
Object expression that evaluates to an AMTimelineTrack object.
rtStart
Beginning of the range to clear, in seconds.
rtEnd
End of the range to clear, in seconds.

Error Codes

If the method fails, an error is raised.


AMTimelineTrans Object

Provides methods for manipulating transitions in Microsoft® DirectShow® Editing Services (DES).

A transition is a progression between one layer and the rendered composite of all the layers with a lower priority. The AMTimelineTrans object is a wrapper for any two-input Microsoft® DirectX® Transform object. To specify the DirectX Transform object, call the AMTimelineObj.SetSubObjectGUID method.

Timeline objects that can have transitions support the IAMTimelineTransable object.

Methods

GetCutPoint | Not supported for Visual Basic.
GetCutPoint2 | Retrieves the cut point.
GetCutsOnly | Determines whether the transition is rendered as a cut.
GetSwapInputs | Determines whether the transition inputs are swapped.
SetCutPoint | Not supported for Visual Basic.
SetCutPoint2 | Sets the cut point.
SetCutsOnly | Specifies whether the transition is rendered as a cut.
SetSwapInputs | Specifies whether the transition inputs are swapped.

GetCutPoint Method (AMTimelineTrans Object)

AMTimelineTrans Object

Not supported for Visual Basic.

Syntax

object.GetCutPoint(
    pTLTime As <Unsupported variant type>
)

GetCutPoint2 Method (AMTimelineTrans Object)

AMTimelineTrans Object

Retrieves the cut point. If you render a transition as a cut, the cut point is the time when the transition cuts from one source to the next. By default, this value is the middle of the transition. For example, in a transition that spans two seconds, the default cut point is one second into the transition.

Syntax

object.GetCutPoint2(
    pTLTime As Double
)

Parts

object
Object expression that evaluates to an AMTimelineTrans object.
pTLTime
Variable that receives the cut point, relative to the start time of the transition, in seconds.

Error Codes

If the method fails, an error is raised.

See Also

SetCutPoint2, GetCutsOnly, AMTimeline.TransitionsEnabled

GetCutsOnly Method (AMTimelineTrans Object)

AMTimelineTrans Object

Determines whether the transition is rendered as a cut. If so, the transition occurs instantaneously at the cut point.

Syntax

object.GetCutsOnly(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineTrans object.
pVal
Variable that receives a value indicating whether the transition is rendered as a cut. If non-zero, the transition is an instantaneous cut. If zero, the transition occurs over its normal duration.

Error Codes

If the method fails, an error is raised.

See Also

SetCutsOnly, GetCutPoint, AMTimeline.TransitionsEnabled

GetSwapInputs Method (AMTimelineTrans Object)

AMTimelineTrans Object

Determines whether the transition inputs are swapped.

By default, a transition goes from the composite of all lower-priority layers to the layer where the transition resides. You can reverse this progression, so the transition goes from the layer where it resides back to the composite of lower-priority layers.

Syntax

object.GetSwapInputs(
    pVal As Long
)

Parts

object
Object expression that evaluates to an AMTimelineTrans object.
pVal
Variable that receives a value indicating whether inputs are swapped. If the value is zero, the transition goes from the composite of all lower-priority layers to the transition layer. If the value is non-zero, the transition goes in the opposite direction. The default value is zero.

Error Codes

If the method fails, an error is raised.

SetCutPoint Method (AMTimelineTrans Object)

AMTimelineTrans Object

Not supported for Visual Basic.

Syntax

object.SetCutPoint(
    TLTime As <Unsupported variant type>
)

SetCutPoint2 Method (AMTimelineTrans Object)

AMTimelineTrans Object

Sets the cut point. If you render a transition as a cut, the cut point is the time when the transition cuts from one source to the next. By default, the cut point is the middle of the transition. For example, in a transition that spans two seconds, the default cut point is one second into the transition.

Syntax

object.SetCutPoint2(
    TLTime As Double
)

Parts

object
Object expression that evaluates to an AMTimelineTrans object.
TLTime
Cut point relative to the start of the transition, in seconds.

Error Codes

If the method fails, an error is raised.

SetCutsOnly Method (AMTimelineTrans Object)

AMTimelineTrans Object

Specifies whether the transition is rendered as a cut. If so, the transition occurs instantly at the cut point. If a transition takes a long time to render, you might want to preview it as a cut to speed preview.

Syntax

object.SetCutsOnly(
    Val As Long
)

Parts

object
Object expression that evaluates to an AMTimelineTrans object.
Val
Value that specifies whether to render the transition as a cut. If zero, the transition is rendered as an instantaneous cut. If non-zero, the transition renders over its normal duration.

Error Codes

If the method fails, an error is raised.

SetSwapInputs Method (AMTimelineTrans Object)

AMTimelineTrans Object

Specifies whether the transition inputs are swapped.

By default, a transition goes from the composite of all lower-priority layers to the layer where the transition resides. You can reverse this progression, so the transition goes from the layer where it resides back to the composite of lower-priority layers.

Syntax

object.SetSwapInputs(
    Val As Long
)

Parts

object
Object expression that evaluates to an AMTimelineTrans object.
Val
Value that specifies whether the inputs are swapped. If zero, the transition goes from the composite of all lower-priority layers to the transition layer. If non-zero, the transition goes in the opposite direction.

Error Codes

If the method fails, an error is raised.

Remarks

This method does not change the direction of the visual effect. For example, a left-to-right wipe will still go from left to right.


IAMTimelineEffectable Object

Provides methods for adding effects to a timeline object in Microsoft® DirectShow® Editing Services (DES), and for manipulating the effects on an object. Applies to timeline objects that can have effects applied to them, such as sources, tracks, and compositions.

Methods

EffectGetCount | Retrieves the number of effects applied to this object.
EffectInsBefore | Inserts an effect into the object at the specified priority level.
EffectSwapPriorities | Switches the priority levels of two effects.
GetEffect | Retrieves the effect at the specified priority level.

EffectGetCount Method (IAMTimelineEffectable Object)

IAMTimelineEffectable Object

Retrieves the number of effects applied to this object.

Syntax

object.EffectGetCount(
    pCount As Long
)

Parts

object
Object expression that evaluates to an IAMTimelineEffectable object.
pCount
Variable that receives the number of effects.

Error Codes

If the method fails, an error is raised.

IAMTimelineEffectable::EffectInsBefore Method (IAMTimelineEffectable Object)

IAMTimelineEffectable Interface

Inserts an effect into the object at the specified priority level.

Syntax

object.EffectInsBefore(
    pFX As AMTimelineObj,
    Priority As Long
)

Parts

object
Object expression that evaluates to an IAMTimelineEffectable object.
pFX
The AMTimelineObj object that specifies the effect.
Priority
Priority level at which to insert the effect. Use the value –1 to insert the effect at the end of the priority list.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_NOTIMPL The object specified by pFX is not an effect.

Remarks

The start and stop times of the effect are clipped within the bounds of the object's time range, if necessary.

If there is already an effect at the specified priority level, all the effects from that point on move down the priority list to make room for the new effect.

IAMTimelineEffectable::EffectSwapPriorities Method (IAMTimelineEffectable Object)

IAMTimelineEffectable Interface

Switches the priority levels of two effects.

Given two priority values, this method swaps the effects at those priorities. When the method returns, the effect that was at the first priority level is at the second priority level, and vice versa.

Syntax

object.EffectSwapPriorities(
    PriorityA As Long,
    PriorityB As Long
)

Parts

object
Object expression that evaluates to an IAMTimelineEffectable object.
PriorityA
First priority level at which to swap effects.
PriorityB
Second priority level at which to swap effects.

Error Codes

If the method fails, an error is raised, and Err.Number can be set the following value:

E_INVALIDARG Invalid argument.

IAMTimelineEffectable::GetEffect Method (IAMTimelineEffectable Object)

IAMTimelineEffectable Interface

Retrieves the effect at the specified priority level.

Syntax

object.GetEffect(
    ppFx As AMTimelineObj,
    Which As Long
)

Parts

object
Object expression that evaluates to an IAMTimelineEffectable object.
ppFX
The AMTimelineObj object that receives the effect.
Which
Priority level of the effect to retrieve.

Error Codes

If the method fails, an error is raised.


IAMTimelineSplittable Object

Splits a timeline object in Microsoft® DirectShow® Editing Services (DES). Sources, effects, transitions, and tracks support this object.

Methods

SplitAt | Not supported for Visual Basic.
SplitAt2 | Splits the object at the specified time.

SplitAt Method (IAMTimelineSplittable Object)

IAMTimelineSplittable Object

Not supported for Visual Basic.

Syntax

object.SplitAt(
    Time As <Unsupported variant type>
)

SplitAt2 Method (IAMTimelineSplittable Object)

IAMTimelineSplittable Object

Splits the object at the specified time.

Syntax

object.SplitAt2(
    Time As Double
)

Parts

object
Object expression that evaluates to an IAMTimelineSplittable object.
Time
Time at which to split the object, relative to the start of the object, in seconds.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.

Remarks

If you split a source, effect, or transition, this method creates a second object of the same type. The original object is truncated at the specified split time, and the new object replaces the truncated portion. The new object inherits all of the same properties. In a source object, the method also splits any effects that fall on the split time.

Calling this method on a track splits all the sources, effects, and transitions that are contained in the track at the specified split time. It does not create a second track (a track begins at time zero and extends to infinity). If the split time is later than everything in the track, the method has no effect.


IAMTimelineTransable Object

Adds transitions to an object in Microsoft® DirectShow® Editing Services (DES). Applies to objects that can have transitions applied to them, such as tracks, compositions, and groups. An object that supports transitions can have any number of transitions, but the transitions must not overlap in time.

Note Audio does not support transitions.

Methods

GetNextTrans | Not supported for Visual Basic.
GetNextTrans2 | Retrieves the first transition that appears at the specified time or later.
GetTransAtTime | Not supported for Visual Basic.
GetTransAtTime2 | Retrieves the transition nearest to the specified time, according to specified boundary conditions.
TransAdd | Adds a transition to the object.
TransGetCount | Retrieves the number of transitions on this object.

GetNextTrans Method (IAMTimelineTransable Object)

IAMTimelineTransable Object

Not supported for Visual Basic.

Syntax

object.GetNextTrans(
    ppTrans As AMTimelineObj,
    pInOut As <Unsupported variant type>
)

GetNextTrans2 Method (IAMTimelineTransable Object)

IAMTimelineTransable Object

Retrieves the first transition that appears at the specified time or later.

Syntax

object.GetNextTrans2(
    ppTrans As IAMTimelineObj,
    pInOut As Double
)

Parts

object
Object expression that evaluates to an IAMTimelineTransable object.
ppTrans
The AMTimelineObj object that receives the transition.
pInOut
On input, this parameter specifies the time from which to find the transition. On output, if a transition is retrieved, this parameter is set to the stop time of the transition.

Error Codes

If the method fails, an error is raised.

Remarks

The start time of the transition might be less than the time that you specify in pInOut, if the transition spans the specified time.

GetTransAtTime Method (IAMTimelineTransable Object)

IAMTimelineTransable Object

Not supported for Visual Basic.

Syntax

object.GetTransAtTime(
    ppObj As AMTimelineObj,
    Time As <Unsupported variant type>,
    SearchDirection As Long
)

GetTransAtTime2 Method (IAMTimelineTransable Object)

IAMTimelineTransable Object

Retrieves the transition nearest to the specified time, according to specified boundary conditions.

Syntax

object.GetTransAtTime2(
    ppObj As AMTimelineObj,
    Time As Double,
    SearchDirection As Long
)

Parts

object
Object expression that evaluates to an IAMTimelineTransable object.
ppObj
The IAMTimelineObj object that receives the transition.
Time
Time from which to begin the search, in seconds.
SearchDirection
Member of the DEXTERF_TRACK_SEARCH_FLAGS enumerated type that specifies the boundary conditions for the search.

Error Codes

If the method fails, an error is raised, and Err.Number is set to the following value:

E_INVALIDARG Invalid argument.

TransAdd Method (IAMTimelineTransable Object)

IAMTimelineTransable Object

Adds a transition to the object. An object can have multiple transitions, but they must not overlap in time. Transitions must fall within the time boundaries of the object.

Syntax

object.TransAdd(
    pTrans As AMTimelineObj
)

Parts

object
Object expression that evaluates to an IAMTimelineTransable object.
pTrans
The AMTimelineObj object that specifies the transition to add.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Cannot insert the transition.
E_NOINTERFACE | pTrans is not a transition.

Remarks

If the transition overlaps an existing transition, the method raises an E_INVALIDARG error.

TransGetCount Method (IAMTimelineTransable Object)

IAMTimelineTransable Object

Retrieves the number of transitions on this object.

Syntax

object.TransGetCount(
    pCount As Long
)

Parts

object
Object expression that evaluates to an IAMTimelineTransable object.
pCount
Variable that receives the number of transitions.

Error Codes

If the method fails, an error is raised.


IAMTimelineVirtualTrack Object

Provides methods for working with virtual tracks in Microsoft® DirectShow® Editing Services (DES). Compositions and tracks support this object.

Methods

SetTrackDirty | Not supported for Visual Basic.
TrackGetPriority | Retrieves the object's priority level.

SetTrackDirty Method (IAMTimelineVirtualTrack Object)

IAMTimelineVirtualTrack Object

Not supported for Visual Basic.

Syntax

object.SetTrackDirty()

TrackGetPriority Method (IAMTimelineVirtualTrack Object)

IAMTimelineVirtualTrack Object

Retrieves the object's priority level.

Syntax

object.TrackGetPriority(
    pPriority As Long
)

Parts

object
Object expression that evaluates to an IAMTimelineVirtualTrack object.
pPriority
Pointer to a variable that receives the priority level. If the object is not part of a timeline, the value is set to –1.

Error Codes

If the method fails, an error is raised.


IAMCollection Object

The filter graph manager exposes the IAMCollection object, which allows access to object collections. These collections contain IPinInfo, IFilterInfo, or IMediaTypeInfo objects.

Properties

Count Returns the number of items in the collection.

Methods

Item Retrieves the specified member of the collection.

Count Property (IAMCollection Object)

IAMCollection Object

Returns the number of items in the collection.

Syntax

objCollection.Count

Parts

objCollection
Object expression that evaluates to an IAMCollection object.

Item Method (IAMCollection Object)

IAMCollection Object

Retrieves the specified collection member and stores it in the passed-in object.

Syntax

 objCollection.Item lItem, objNew

Parts

objCollection
Object expression that evaluates to an IAMCollection object.
lItem
Index of the item to retrieve.
objNew
Object expression that can evaluate to an IFilterInfo, IPinInfo, or IMediaTypeInfo object depending on the collection type. This argument will contain the retrieved item.

Remarks

The index value ranges from 0 to (Count – 1).


IBasicAudio Object

The IBasicAudio object supports the audio component of the filter graph. It allows access to volume and balance functionality.

The Volume property is a value between –10,000 and 0 representing a set of linear steps. Not all devices support 10,000 distinguishable steps.

The Balance property is a value between –10,000 and 10,000. A value of –10,000 indicates that the right speaker has been disabled and only the left speaker is receiving an audio signal. A value of 0 indicates that both speakers are receiving equivalent audio signals. A value of 10,000 indicates that the left speaker has been disabled and only the right speaker is receiving an audio signal.

Properties

Balance | Sets or returns the balance for the audio signal.
Volume | Sets or returns the volume (amplitude) of the audio signal.

Balance Property (IBasicAudio Object)

IBasicAudio Object

Sets or returns the balance of the audio channel.

Syntax

objAudio.Balance [= lValue ]

Parts

objAudio
Object expression that evaluates to an IBasicAudio object.
lValue
New value for the Balance property.

Remarks

The Balance property is a value between –10,000 and 10,000. A value of –10,000 indicates that the right speaker has been disabled and only the left speaker is receiving an audio signal. A value of 0 indicates that both speakers are receiving equivalent audio signals. A value of 10,000 indicates that the left speaker has been disabled and only the right speaker is receiving an audio signal.

Note that not all devices support 10,000 distinguishable steps.

If you try to set the Balance property to values outside this range, the IBasicAudio object raises run-time error 5.

Volume Property (IBasicAudio Object)

IBasicAudio Object

Sets or returns the volume of the audio channel.

Syntax

objAudio.Volume [= lValue]

Parts

objAudio
Object expression that evaluates to an IBasicAudio object.
lValue
New value for the Volume property.

Remarks

The allowable input range is –10,000 to 0.

Full volume is 0; –10,000 is silence. The scale is linear. Values outside this range will return run-time error 5.

Note that not all devices support 10,000 distinguishable steps.


IBasicVideo Object

The filter graph manager exposes the IBasicVideo object, which supports the video properties of a generic video window. Generally, this is a video renderer that draws video into a window on the display.

The video renderer must be connected to use IBasicVideo object methods. If it isn't connected, all methods return run-time error 521. Properties set on a video renderer generally persist between successive connections and disconnections. All applications should ensure that they reset the renderer properties before starting a presentation.

When working with video, the application can select a portion of the video to use. This portion is the source rectangle that the IBasicVideo object controls. IBasicVideo allows the source rectangle to be set and retrieved. All IBasicVideo rectangles have top, left, width, and height properties. When no source rectangle has been set, the properties of the source rectangle return the full, native video size.

Properties

AvgTimePerFrame | Retrieves the average time between successive frames in 100-nanosecond units.
BitErrorRate | Retrieves an approximate bit error rate for the video stream.
BitRate | Retrieves an approximate bit rate for the video stream.
DestinationLeft | Sets or retrieves the x-axis coordinate for the destination video rectangle.
DestinationHeight | Sets or retrieves the height of the destination video rectangle.
DestinationTop | Sets or retrieves the y-axis coordinate for the destination video rectangle.
DestinationWidth | Sets or retrieves the width of the destination video rectangle.
SourceHeight | Sets or retrieves the height of the source video rectangle.
SourceLeft | Sets or retrieves the x-axis coordinate for the source video rectangle.
SourceTop | Sets or retrieves the y-axis coordinate for the source video rectangle.
SourceWidth | Sets or retrieves the width of the source video rectangle.
VideoHeight | Retrieves the current video height.
VideoWidth | Retrieves the current video width.

Methods

GetCurrentImage | Returns a copy of the image that is currently waiting at the renderer.
GetDestinationPosition | Retrieves the destination rectangle for the window.
GetSourcePosition | Retrieves the source video rectangle.
GetVideoPaletteEntries | Retrieves the color palette entries required by the video.
GetVideoSize | Retrieves the native video dimensions.
IsUsingDefaultSource | Indicates whether the default source is being used.
SetDefaultDestinationPosition | Sets the default destination position for the window.
SetDefaultSourcePosition | Informs the renderer to use the default source rectangle.
SetDestinationPosition | Sets the destination rectangle for the window.
SetSourcePosition | Sets the source video rectangle.

AvgTimePerFrame Property (IBasicVideo Object)

IBasicVideo Object

Retrieves the average time between successive frames in 100-nanosecond units.

Syntax

objVideo.AvgTimePerFrame

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.

BitErrorRate Property (IBasicVideo Object)

IBasicVideo Object

Retrieves a bit error rate for the video stream (one error for approximately this many bits).

Syntax

objVideo.BitErrorRate

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.

BitRate Property (IBasicVideo Object)

IBasicVideo Object

Retrieves an approximate bit rate for the video stream (in bits per second).

Syntax

objVideo.BitRate

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.

DestinationHeight Property (IBasicVideo Object)

IBasicVideo Object

Retrieves or sets the height of the destination rectangle.

Syntax

objVideo.DestinationHeight [= lValue]

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
lValue
New value for the destination rectangle height.

Remarks

Setting this coordinate does not affect the destination rectangle y-axis origin.

DestinationLeft Property (IBasicVideo Object)

IBasicVideo Object

Retrieves or sets the destination x-axis origin coordinate.

Syntax

objVideo.DestinationLeft [= lValue]

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
lValue
New value of the destination x-axis origin.

Remarks

Setting this coordinate does not affect the destination rectangle width.

DestinationTop Property (IBasicVideo Object)

IBasicVideo Object

Retrieves or sets the destination y-axis origin coordinate.

Syntax

objVideo.DestinationTop [= lValue]

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
lValue
New value of the y-axis origin.

Remarks

Setting this coordinate does not affect the destination rectangle height.

DestinationWidth Property (IBasicVideo Object)

IBasicVideo Object

Retrieves or sets the width of the destination rectangle.

Syntax

objVideo.DestinationWidth [= lValue]

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
lValue
New width value.

Remarks

Setting this coordinate does not affect the destination rectangle x-axis origin.

GetCurrentImage Method (IBasicVideo Object)

IBasicVideo Object

Retrieves the image currently waiting at the renderer.

Syntax

objVideo.GetCurrentImage BufferSize, DIBImage

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
BufferSize
Long value that specifies the size of the buffer the caller is passing in. GetCurrentImage sets this value to the actual number of bytes in the buffer before exiting.
DIBImage
Long value that will contain the buffer where the complete image will be stored in device-independent bitmap (DIB) format. You must pass the buffer by reference.

Remarks

Pause the video renderer before calling this method; calling this method in any other state returns run-time error 549. Depending on what data the source filter has available, the video renderer is not guaranteed to service this request.

An application can use this method to get a copy of the current image the video renderer holds when paused by calling the method with DIBImage set to Nothing.

GetDestinationPosition Method (IBasicVideo Object)

IBasicVideo Object

Retrieves the position of the destination rectangle in window coordinates.

Syntax

objVideo.GetDestinationPosition Left, Top, Width, Height

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
Left
Long integer value that will contain the destination window's x-axis origin.
Top
Long integer value that will contain the destination window's y-axis origin.
Width
Long integer value that will contain the destination window's width.
Height
Long integer value that will contain the destination window's height.

Remarks

This method has the same effect as individually retrieving the DestinationLeft, DestinationTop, DestinationWidth, and DestinationHeight properties.

GetSourcePosition Method (IBasicVideo Object)

IBasicVideo Object

Retrieves the source position that is clipped to the available video.

Syntax

objVideo.GetSourcePosition Left, Top, Width, Height

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
Left
Long integer value that will contain the source window's x-axis origin.
Top
Long integer value that will contain the source window's y-axis origin.
Width
Long integer value that will contain the source window's width.
Height
Long integer value that will contain the source window's height.

Remarks

This method has the same effect as retrieving the values of the SourceLeft, SourceTop, SourceWidth, and SourceHeight properties.

GetVideoPaletteEntries Method (IBasicVideo Object)

IBasicVideo Object

Retrieves the palette colors for the video.

Syntax

objVideo.GetVideoPaletteEntries StartIndex, Entries, Retrieved, Palette

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
StartIndex
Long integer value that specifies the start index for the palette.
Entries
Long integer value that specifies the number of palette entries required.
Retrieved
Long integer value that will contain the number of entries actually returned in Palette.
Palette
Long integer value that will contain a pointer to an array of Microsoft® Win32® PALETTEENTRY structures.

GetVideoSize Method (IBasicVideo Object)

IBasicVideo Object

Retrieves the native video dimensions.

Syntax

objVideo.GetVideoSize Width, Height

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
Width
Long integer value that will contain the video window's width.
Height
Long integer value that will contain the video window's height.

Remarks

Retrieves the native video width and height, disregarding any source rectangle that might have been set. ActiveX™ Controls or other applications can use this information to negotiate space in compound documents.

IsUsingDefaultSource Method (IBasicVideo Object)

IBasicVideo Object

Retrieves whether this object is using the default source.

Syntax

objVideo.IsUsingDefaultSource

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.

Return Value

True indicates that the IBasicVideo object is using the default source; False indicates that it is not.

SetDefaultDestinationPosition Method (IBasicVideo Object)

IBasicVideo Object

Sets the default destination position of the video window so that the renderer uses the entire window for playback.

Syntax

objVideo.SetDefaultDestinationPosition

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.

SetDefaultSourcePosition Method (IBasicVideo Object)

IBasicVideo Object

Informs the renderer to use the default source rectangle.

Syntax

objVideo.SetDefaultSourcePosition

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.

SetDestinationPosition Method (IBasicVideo Object)

IBasicVideo Object

Sets the destination rectangle in window coordinates.

Syntax

objVideo.SetDestinationPosition Left, Top, Width, Height

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
Left
Long value specifying the x-axis origin of the destination window, in pixels.
Top
Long value specifying the y-axis origin of the destination window, in pixels.
Width
Long value specifying the width of the destination window, in pixels.
Height
Long value specifying the height of the destination window, in pixels.

Remarks

This method has the same effect as setting the DestinationLeft, DestinationTop, DestinationWidth, and DestinationHeight properties individually.

SetSourcePosition Method (IBasicVideo Object)

IBasicVideo Object

Sets the source rectangle and is clipped against the available video.

Syntax

objVideo.SetSourcePosition Left, Top, Width, Height

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
Left
Long value specifying the x-axis origin of the source window.
Top
Long value specifying the y-axis origin of the source window.
Width
Long value specifying the width of the source window.
Height
Long value specifying the height of the source window.

Remarks

This method has the same effect as setting the SourceLeft, SourceTop, SourceWidth, and SourceHeight properties individually.

SourceHeight Property (IBasicVideo Object)

IBasicVideo Object

Retrieves or sets the height of the source rectangle.

Syntax

objVideo.SourceHeight [= lValue]

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
lValue
Long value specifying the current rectangle height, in pixels.

Remarks

Setting the height of the source rectangle has no effect on the width and other source values.

SourceLeft Property (IBasicVideo Object)

IBasicVideo Object

Retrieves or sets the source rectangle's x-coordinate.

Syntax

objVideo.SourceLeft [= lValue]

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
lValue
New value for the x-axis origin of the source rectangle.

Remarks

Changes to this property do not affect the width and other source values.

SourceTop Property (IBasicVideo Object)

IBasicVideo Object

Retrieves or sets the source rectangle y-axis origin coordinate.

Syntax

objVideo.SourceTop [= lValue]

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
lValue
Long value specifying the distance from the top of the display to the top of the current window, in pixels.

Remarks

Setting this method has no effect on the source rectangle height.

SourceWidth Property (IBasicVideo Object)

IBasicVideo Object

Retrieves or sets the source rectangle width.

Syntax

objVideo.SourceWidth [= lValue]

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.
lValue
Long value specifying the current width, in pixels.

Remarks

This method has no effect on the source rectangle x-axis coordinate.

VideoHeight Property (IBasicVideo Object)

IBasicVideo Object

Retrieves the native height of the video.

Syntax

objVideo.VideoHeight

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.

Remarks

This method returns the actual height of the video supplied to the renderer. It does not address any set source rectangle, but simply returns the native vertical dimension. It can be used by applications to negotiate size requirements with in-place container documents.

VideoWidth Property (IBasicVideo Object)

IBasicVideo Object

Retrieves the native width of the video.

Syntax

objVideo.VideoWidth

Parts

objVideo
Object expression that evaluates to an IBasicVideo object.

Remarks

This method returns the actual width of the video supplied to the renderer. It does not address any set source rectangle, but simply returns the native horizontal dimension. It can be used by applications to negotiate size requirements with in-place container documents.


IFilterInfo Object

IFilterInfo is an object that manages information about a filter and allows access to the filter object and IPinInfo object.

Properties

Filename | Retrieves or sets the file name associated with the source filter.
Filter | Retrieves the actual filter object.
IsFileSource | Indicates whether the filter is a file source filter.
Name | Retrieves the filter name.
Pins | Retrieves an IAMCollection object containing the IPinInfo objects for this filter.
VendorInfo | Retrieves a string containing optional information supplied by a vendor about the specified filter.

Methods

FindPin Locates a pin, given an identifier, and returns an object supporting IPinInfo.

Filename Property (IFilterInfo Object)

IFilterInfo Object

Retrieves or sets the name of the file containing the filter.

Syntax

objFilterInfo.Filename [= string]

Parts

objFilterInfo
Object expression that evaluates to an IFilterInfo object.
string
String expression that specifies the new file name.

Filter Property (IFilterInfo Object)

IFilterInfo Object

Retrieves the filter object.

Syntax

Set objFilter = objFilterInfo.Filter

Parts

objFilter
Object expression that evaluates to an IBaseFilter object.
objFilterInfo
Object expression that evaluates to an IFilterInfo object.

Remarks

No programmable object interface is offered for the IBaseFilter interface. However, Visual Basic® programmers can use the returned object as a parameter in calls to functions that take an IBaseFilter interface pointer as a parameter.

FindPin Method (IFilterInfo Object)

IFilterInfo Object

Locates a pin, given an identifier, and returns an IPinInfo object.

Syntax

objFilterInfo.FindPin string, objPin

Parts

objFilterInfo
Object expression that evaluates to an IFilterInfo object.
string
String that contains the name of the pin to find.
objPin
IPinInfo object that will contain the specified pin, if the pin exists.

Remarks

No programmable object interface is offered for the IPin interface. However, Visual Basic programmers can use the returned object as a parameter in calls to functions that take the IPin interface pointer as a parameter.

IsFileSource Property (IFilterInfo Object)

IFilterInfo Object

Determines if the file contains the source video.

Syntax

objFilterInfo.IsFileSource

Parts

objFilterInfo
Object expression that evaluates to an IFilterInfo object.

Return Value

The value True indicates that the file contains the source video. False indicates that the file does not contain the source video.

Name Property (IFilterInfo Object)

IFilterInfo Object

Retrieves the filter name.

Syntax

objFilterInfo.Name

Parts

objFilterInfo
Object expression that evaluates to an IFilterInfo object.

Remarks

The vendor specifies the filter name.

Pins Property (IFilterInfo Object)

IFilterInfo Object

Retrieves an IAMCollection object containing the IPinInfo objects for this filter.

Syntax

Set objPinCollection = objFilterInfo.Pins

Parts

objPinCollection
IAMCollection object that will contain the specific filter's pins.
objFilterInfo
IFilterInfo object that specifies the filter whose pins you want to retrieve.

Remarks

You can use the Count property and Item method to iterate through each of the pin objects in the collection.

VendorInfo Property (IFilterInfo Object)

IFilterInfo Object

Retrieves a string containing optional information supplied by a vendor about the specified filter.

Syntax

objFilterInfo.VendorInfo

Parts

objFilterInfo
Object expression that evaluates to an IFilterInfo object.

Remarks

This property contains any information the vendor chooses to supply. It is usually descriptive information about the filter.


IMediaControl Object

The filter graph exposes the IMediaControl object to allow applications to control the streaming of media through the filters in the graph. The interface provides methods for running, pausing, and stopping the streaming of data. It also provides applications with a simple method that builds graphs to play back media files.

Properties

FilterCollection | Retrieves a collection of IFilterInfo objects representing the current filters in the graph.
RegFilterCollection | Retrieves a collection of IRegFilterInfo objects representing the filters available in the registry.

Methods

AddSourceFilter | Adds to the graph the source filter that can read the given file name.
GetState | Retrieves the state of the filter graph.
Pause | Pauses all filters in the filter graph.
RenderFile | Adds and connects all filters needed to play the specified file.
Run | Switches the entire filter graph into run mode.
Stop | Switches all filters in the filter graph to a stopped state.

AddSourceFilter Method (IMediaControl Object)

IMediaControl Object

Adds the source filter that can read the given file name to the graph and returns the created IFilterInfo object.

Syntax

objMediaControl.AddSourceFilter string, objFilterInfo

Parts

objMediaControl
Object expression that evaluates to an IMediaControl object.
string
Name of the file containing the source media.
objFilterInfo
IFilterInfo object; the source filter created for the specified source file.

FilterCollection Property (IMediaControl Object)

IMediaControl Object

Retrieves a collection of IFilterInfo objects representing the filters in the graph. Returns an IAMCollection object.

Syntax

Set objCollection = objMediaControl.FilterCollection

Parts

objCollection
IAMCollection object that represents the collection of filters currently present in the filter graph.
objMediaControl
Object expression that evaluates to an IMediaControl object.

GetState Method (IMediaControl Object)

IMediaControl Object

Returns a Long integer indicating the current state value.

Syntax

objMediaControl.GetState msTimeout, State

Parts

objMediaControl
Object expression that evaluates to an IMediaControl object.
msTimeout
Duration of the time-out, in milliseconds.
State
Long value that will contain the current state. This argument will be one of the following:
State_Paused | The media source is paused.
State_Running | The media source is running.
State_Stopped | The media source is stopped.

Return Value

Returns run-time error 567 if the state transition is not complete, or 0 if it completed successfully.

Remarks

Not all state transitions are synchronous. For example, even though the Pause method returns immediately, the graph typically does not complete the transition into paused mode until data is ready at the renderer. This method will not return zero until the state transition has been completed.

If you specify a nonzero time-out, the method waits up to that number of milliseconds for the graph to leave the intermediate state. If the time-out expires before the state transition is complete, the return code will be 567, and the returned state will be the state into which the graph is transitioning (either State_Stopped, State_Paused, or State_Running).

RegFilterCollection Property (IMediaControl Object)

IMediaControl Object

Retrieves a collection of IRegFilterInfo objects representing the filters available in the registry.

Syntax

Set objCollection = objMediaControl.RegFilterCollection

Parts

objCollection
IAMCollection object that contains IRegFilterInfo objects.
objMediaControl
Object expression that evaluates to an IMediaControl object.

Return Value

Returns an IAMCollection object.

Pause Method (IMediaControl Object)

IMediaControl Object

Pauses all the filters in the filter graph.

Syntax

objMediaControl.Pause

Parts

objMediaControl
Object expression that evaluates to an IMediaControl object.

Remarks

In the paused state, filters process data but do not render it. Data is pushed down the filter graph and is processed by transform filters as far as buffering permits. No data is rendered (except that media types capable of being rendered statically, such as video, have a static, poster frame rendered in paused mode). Therefore, putting a filter graph into a paused state cues the graph for immediate rendering when put into a running state.

RenderFile Method (IMediaControl Object)

IMediaControl Object

Adds and connects filters needed to play the specified file.

Syntax

objMediaControl.RenderFile string

Parts

objMediaControl
Object expression that evaluates to an IMediaControl object.
string
Name of the file to render.

Remarks

This method allows an application to pass the name of a media file that it wants rendered to the filter graph manager. The filter graph manager will build a graph of the filters that are needed to play back this file.

Run Method (IMediaControl Object)

IMediaControl Object

Switches the entire filter graph into a running state.

Syntax

objMediaControl.Run

Parts

objMediaControl
Object expression that evaluates to an IMediaControl object.

Remarks

If the filter graph is in the stopped state, this method first pauses the graph before running.

If an error value is returned, some filters within the graph might have successfully entered the running state. In a multistream graph, entire streams might be playing successfully. The application must determine whether to stop execution or not.

Stop Method (IMediaControl Object)

IMediaControl Object

Switches all filters in the filter graph to a stopped state.

Syntax

objMediaControl.Stop

Parts

objMediaControl
Object expression that evaluates to an IMediaControl object.

Remarks

In this mode, filters release resources and no data is processed. If the filters are in a running state, this method pauses them before stopping them. This allows video renderers to make a copy of the current frame for poster frame display while stopped.


IMediaEvent Object

This object supports event notification from the filter graph and the filters within it to the application.

An event code and two parameters represent event notification information. This can be used for typical completion of asynchronous operations, errors that occur during asynchronous operation, or user-initiated events, such as when a user clicks a hot spot.

Filters within the filter graph and the filter graph itself raise event notifications. Possible events include playback completion or asynchronous playback errors. In addition, the filter graph provides a method to generate events at specific reference clock times.

Event notifications are placed in a queue. An application calls the IMediaEvent object's GetEvent method to retrieve the next notification from the queue. This method blocks until there is an event to return. The GetEvent method's time-out parameter allows the application to specify the time, in milliseconds, to wait for an event, including values of zero (do not wait) and infinite (wait forever).

In addition, applications can retrieve the event handle. GetEventHandle returns a handle to a manual-reset event created by the Microsoft® Win32® CreateEvent function. This event is in a signaled state as long as there are event notifications to collect. The event is cleared by the GetEvent method when there are no more event notifications to collect. This allows an application to use an application programming interface (API), such as MsgWaitForMultipleObjects, to wait for events and other occurrences at the same time. This event handle will be closed when the filter graph is released; therefore, applications should ensure that they are not using it after this point.

The filter graph handles some events raised by filters that are not passed to the application. One example of this is the EC_REPAINT event notification. The default handling for this event is to repaint the video renderer's static images by pausing the filter graph. An application can override default handling for a specific event by calling the CancelDefaultHandling method with the event value as a parameter. The RestoreDefaultHandling method reinstates default handling for the specified event value. These methods have no effect on events that have no default handling.

If an error occurs during the transition to a running state on any filter, an error value is returned by the Run method. In this case, some filters within the graph might be running successfully. The filter graph leaves it up to the application to determine whether to stop the graph in case of an error. After the Run method has returned, event notifications report any additional errors. The EC_ERRORABORT and EC_USERABORT event notifications indicate that playback has probably stopped in the graph (certainly in the filter that reported it). Other errors and events indicate that it is still running. Note, however, that in all cases the graph remains in running mode until the application explicitly changes it to stopped or paused mode.

If the streams in the filter graph detect the end of the stream, the streams report this by using the EC_COMPLETE event notification. The filter graph asks filters if they can report EC_COMPLETE via seekable renderers.

A seekable renderer is a renderer that supports the IMediaPosition object from the filter and has only input pins, or is a renderer whose input pins report that they are rendered at that point. The filter graph detects seekable renderers. A seekable renderer reports EC_COMPLETE once when all seekable streams on that filter have reached the end of the stream.

The filter graph manager will then not pass EC_COMPLETE to the application until an EC_COMPLETE event notification has been received from each stream. For example, if a live camera stream is playing as the background to a video playing out of a file, the application will be notified about EC_COMPLETE when the video and audio streams from the file have come to the end of the stream, even though the live source is still playing. In this case, too, the filter graph remains in running mode until the application explicitly calls the Pause or Stop method.

The aggregation of EC_COMPLETE messages can be disabled by calling CancelDefaultHandling with EC_COMPLETE as the parameter. In this case, all EC_COMPLETE events raised by the filters will be passed directly to the application.

For a list of system-defined event notifications, see the GetEvent method.

Methods

CancelDefaultHandling | Cancels any default handling of the specified event by the filter graph.
GetEvent | Retrieves the next notification event.
GetEventHandle | Retrieves a handle to a manual-reset event that will be signaled.
RestoreDefaultHandling | Restores default handling for this event.
WaitForCompletion | Waits until the filter graph's operation has completed.

CancelDefaultHandling Method (IMediaEvent Object)

IMediaEvent Object

Cancels default handling of the specified event by the filter graph and ensures that the event is passed to the application.

Syntax

objMediaEvent.CancelDefaultHandling lEvCode

Parts

objMediaEvent
Object expression that evaluates to an IMediaEvent object.
lEvCode
Long value specifying the event code which cancels default handling. The following values are valid.
  • EC_COMPLETE
  • EC_ERRORABORT
  • EC_PALETTE_CHANGED
  • EC_REPAINT
  • EC_USERABORT

Return Value

This method raises an error if the event does not have any default handling.

Remarks

Currently the filter graph manager only applies default handling to EC_COMPLETE and EC_REPAINT.

GetEvent Method (IMediaEvent Object)

IMediaEvent Object

Retrieves the next notification event.

Syntax

objMediaEvent.GetEvent lEventCode, lParam1, lParam2, msTimeout

Parts

objMediaEvent
Object expression that evaluates to an IMediaEvent object.
IEventCode
Returns the next event notification. The following values are valid.
  • EC_COMPLETE
  • EC_ERRORABORT
  • EC_PALETTE_CHANGED
  • EC_REPAINT
  • EC_USERABORT
lParam1
Long value specifying the first parameter of the event.
lParam2
Long value specifying the second parameter of the event.
msTimeout
Time, in milliseconds, to wait before assuming that there are no events. To return immediately, specify a time-out value of 0.

Remarks

This method removes the next event notification from the head of the queue and returns it. It waits up to msTimeout milliseconds if there are no events.

GetEventHandle Method (IMediaEvent Object)

IMediaEvent Object

Returns a handle to a manual-reset event that will be signaled as Long as there are event notifications to deliver.

Syntax

objMediaEvent.GetEventHandle hEvent

Parts

objMediaEvent
Object expression that evaluates to an IMediaEvent object.
hEvent
Long value that will contain the event handle.

Remarks

The event can be passed to the Win32 WaitForMultipleObjects or MsgWaitForMultipleObjects function to wait for event notifications at the same time as other messages and events on a single thread.

RestoreDefaultHandling Method (IMediaEvent Object)

IMediaEvent Object

Reinstates the normal default handling by a filter graph for the specified event if there is one.

Syntax

objMediaEvent.RestoreDefaultHandling lEvCode

Parts

objMediaEvent
Object expression that evaluates to an IMediaEvent object.
lEvCode
Event to restore. The following list contains system-defined event notifications.
  • EC_COMPLETE
  • EC_ERRORABORT
  • EC_PALETTE_CHANGED
  • EC_REPAINT
  • EC_USERABORT

Remarks

Events that have default handling in place, such as EC_REPAINT, are not typically passed to the application.

WaitForCompletion Method (IMediaEvent Object)

IMediaEvent Object

Waits until the filter graph's operation has completed.

Syntax

objMediaEvent.WaitForCompletion msTimeout, EvCode

Parts

objMediaEvent
Object expression that evaluates to an IMediaEvent object.
msTimeout
Long value that specifies the duration of the time-out, in milliseconds. To block indefinitely, pass –1. To return immediately, pass zero.
EvCode
Long value that will contain the value of the event completion code, such as EC_COMPLETE. A value of zero indicates that the operation has not completed.

Remarks

This method performs the equivalent of blocking by calling GetEvent repeatedly until the method receives the EC_COMPLETE, EC_ERRORABORT, or EC_USERABORT event notification, or until it reaches the time-out period, whichever comes first.

If the time-out value is reached, the method returns a completion code value of 0 and raises run-time error 287, "Application-defined or object-defined error." When setting the msTimeOut parameter to anything other than –1 (infinite), you are likely to get this run-time error. You can handle this error with an On Error Resume Next statement and then check the value of EvCode, which will be 0 if a time-out has occurred or 1 (EC_COMPLETE) or greater if completion has occurred. The following example illustrates using this method with a time-out of 0.

    Dim pME As IMediaEvent
    Dim EventCode As Long
    Set pME = pMC

    On Error Resume Next

    pME.WaitForCompletion 0, EventCode	'Return from WaitForCompletion immediately

    Set pME = Nothing

    If EventCode = 0 Then Exit Sub

To use an infinite time-out, check for a returned event code of 1 as in the following example.

    Dim pME As IMediaEvent
    Dim EventCode As Long
    Set pME = pMC

    pME.WaitForCompletion -1, EventCode	'Wait until EC_COMPLETE

    If EventCode = 1 Then Exit Sub

When the method returns, the filter graph is still in a running state. This method assumes that the application is not making separate calls to the IMediaEvent object. This method fails if the graph is not in or transitioning into a running state.


IMediaPosition Object

The filter graph exposes the IMediaPosition object if any of the filters within the graph are seekable (can seek to an arbitrary position in the stream). Filters will expose IMediaPosition if they can seek their data or if they connect to an output pin that represents a seekable stream.

Applications that communicate with the filter graph can call methods on this interface to set or retrieve properties such as the stream's duration, the start and stop times, the preroll time, the rate, and the current position. The filter graph uses these properties on seekable filters to control the playback of streams within the graph; where there are multiple streams, the filter graph sets them all to play in parallel, beginning at the same position, and will report the duration as being the duration of the longest stream. The parameters used in this interface are double values representing a fractional number of seconds. Internally, filters will store time to an accuracy of 100 nanoseconds.

Properties

CurrentPosition | Retrieves or sets the current position in terms of the total length of the media stream.
Duration | Retrieves the total duration of the media stream.
PrerollTime | Retrieves or sets the time prior to the start position at which nonrandom access devices should start rolling.
Rate | Retrieves or sets the playback rate, relative to normal playback of the media stream.
StopTime | Retrieves or sets the position within the media stream at which playback should stop.

Methods

CanSeekBackward | Retrieves whether or not you can seek backward in the current stream.
CanSeekForward | Retrieves whether or not you can seek forward in the current stream.

CurrentPosition Property (IMediaPosition Object)

IMediaPosition Object

Retrieves or sets the current position in terms of the total length of the media stream.

Syntax

objMediaPosition.CurrentPosition [=dblValue]

Parts

objMediaPosition
Object expression that evaluates to an IMediaPosition object.
dblValue
Double value specifying the new current position.

Remarks

The CurrentPosition property represents the position that playback has reached. It is a value between zero and the duration (that is, it has been adjusted for rate and start time). If the graph is paused, this is the position at which it will restart.

This property can also be used to set the start time. When used in this way, the current position indicates a position between zero and the duration of the media at which playback should begin when the Run method is called.

When the filter graph is stopped or paused, this property returns the position at which playback will recommence. When the filter graph is running, the filter graph manager returns the position according to the reference clock. If an individual filter implements this, it should return the stream time of the sample it is currently processing (that is, the offset time from the beginning) when paused or running.

After stopping or pausing, a run command causes playback to begin at the current position. This will be where playback stopped or paused, unless the application changes the CurrentPosition call in the meantime.

If this method is called when the filter graph manager is running, the filter graph manager will pause the graph, run the method, and then issue a new run command.

Setting the current position when paused or stopped causes playback to resume from the new start position when the run command is issued.

The current position is applied before the rate and therefore is the position at typical playback speed.

Duration Property (IMediaPosition Object)

IMediaPosition Object

Retrieves the total duration of the media stream.

Syntax

objMediaPosition.Duration

Parts

objMediaPosition
Object expression that evaluates to an IMediaPosition object.

Remarks

The duration assumes normal playback speed, and it is therefore unaffected by the rate.

PrerollTime Property (IMediaPosition Object)

IMediaPosition Object

Retrieves or sets the time prior to the start position that devices should start rolling.

Syntax

objMediaPosition.PrerollTime [=dblValue]

Parts

objMediaPosition
Object expression that evaluates to an IMediaPosition object.
dblValue
Double value for the PrerollTime property.

Remarks

Preroll time is the time prior to the start position at which nonrandom access devices, such as tape players, should start rolling.

Rate Property (IMediaPosition Object)

IMediaPosition Object

Retrieves or sets the playback rate relative to normal playback speed.

Syntax

objMediaPosition.Rate [= dblValue]

Parts

objMediaPosition
Object expression that evaluates to an IMediaPosition object.
dblValue
New value for the rate. Double.

Remarks

This property allows an application to speed up or slow down playback relative to the normal default playback speed. A rate of 1.0 indicates normal playback speed, a rate of 0.5 indicates half speed, and a rate of –1.0 indicates normal speed in reverse. Specifying 2.0 causes playback at twice the normal rate: a video created for 10 frames per second (fps) will be played back at 20 fps, if resources permit. Audio streams played back at above-normal speed increase the pitch rather than drop samples. A rate of 0.5 indicates half speed.

StopTime Property (IMediaPosition Object)

IMediaPosition Object

Retrieves or sets the time at which the media stream stops.

Syntax

objMediaPosition.StopTime [ = dblValue]

Parts

objMediaPosition
Object expression that evaluates to an IMediaPosition object.
dblValue
New value for the stop time.

Remarks

The stop time is a position between zero and the duration of the media at which playback should stop.

The stop position is applied before the rate and therefore is the position at typical playback speed.

CanSeekBackward Method (IMediaPosition Object)

IMediaPosition Object

Retrieves whether you can seek backward through the current stream.

Syntax

objMediaPosition.CanSeekBackward

Parts

objMediaPosition
Object expression that evaluates to an IMediaPosition object.

Remarks

The return value is of type Integer. If the value is 0, you cannot seek through the current stream. If the value is –1, you can seek. If you cannot seek through the stream, you can still set the stream's current position with CurrentPosition.

This method can return only –1 (True) with media streams that consist of a single media type, such as a WAV file or video-only MPEG file.

CanSeekForward Method (IMediaPosition Object)

IMediaPosition Object

Retrieves whether you can seek forward through the current stream.

Syntax

objMediaPosition.CanSeekForward

Parts

objMediaPosition
Object expression that evaluates to an IMediaPosition object.

Remarks

The return value is of type Integer. If the value is 0, you cannot seek through the current stream. If the value is –1, you can seek. If you cannot seek through the stream, you can still set the stream's current position with CurrentPosition.

This method can return only –1 (True) with media streams that consist of a single media type, such as a WAV file or video-only MPEG file.


IMediaTypeInfo Object

The filter graph manager exposes IMediaTypeInfo, which allows access to media type information such as the major GUIDs (globally unique identifiers).

Properties

Subtype | Retrieves the subtype GUID as a string.
Type | Retrieves the major type GUID as a string.

Subtype Property (IMediaTypeInfo Object)

IMediaTypeInfo Object

Retrieves the subtype GUID as a string.

Syntax

objMediaTypeInfo.Subtype

Parts

objMediaTypeInfo
Object expression that evaluates to an IMediaTypeInfo object.

Return Value

Returns a string that contains the subtype GUID.

Type Property (IMediaTypeInfo Object)

IMediaTypeInfo Object

Retrieves the major type GUID as a string.

Syntax

objMediaTypeInfo.Type

Parts

objMediaTypeInfo
Object expression that evaluates to an IMediaTypeInfo object.

Return Value

Returns a string containing the major type GUID.


IPinInfo Object

The filter graph manager exposes the IPinInfo object, which allows access to pin information such as the media type and the pin direction. It also allows control of pins, such as connecting, disconnecting, and rendering.

Properties

ConnectedTo | Retrieves the IPinInfo object for the pin to which the filter is connected.
ConnectionMediaType | Retrieves the media type on this connection.
Direction | Retrieves the pin direction.
FilterInfo | Retrieves the IFilterInfo object for the filter to which this pin belongs.
MediaTypes | Retrieves the IAMCollection object of preferred media types.
Name | Retrieves the name of this pin.
Pin | Retrieves the pin associated with this IPinInfo object.
PinID | Retrieves the pin identifier.

Methods

Connect | Connects to the following pin.
ConnectDirect | Connects directly to the specified pin.
ConnectWithType | Connects directly to the specified pin using the specified media type only.
Disconnect | Disconnects this pin and the corresponding connected pin from each other.
Render | Completes the filter graph downstream from this pin; that is, generates all filters and connections needed to generate a graph from this pin to the renderer filter.

Connect Method (IPinInfo Object)

IPinInfo Object

Connects two pins, using transform filters as necessary.

Syntax

objPinInfo.Connect objPin

Parts

objPinInfo
Object expression that evaluates to an IPinInfo object.
objPin
IPinInfo object specifying the other pin in the connection.

ConnectDirect Method (IPinInfo Object)

IPinInfo Object

Connects the two pins directly, without using transform filters.

Syntax

objPinInfo.ConnectDirect objPin

Parts

objPinInfo
IPinInfo object specifying the other pin in the connection.
objPin
IPinInfo object specifying the other pin in the connection.

ConnectedTo Property (IPinInfo Object)

IPinInfo Object

Retrieves the IPinInfo object for the pin to which the filter is connected.

Syntax

Set objConnectedPinInfo = objPinInfo.ConnectedTo

Parts

objConnectedPinInfo
IPinInfo object for the pin.
objPinInfo
Object expression that evaluates to an IPinInfo object.

ConnectionMediaType Property (IPinInfo Object)

IPinInfo Object

Retrieves the IMediaTypeInfo object for this connection.

Syntax

Set objMediaTypeInfo = objPinInfo.ConnectionMediaType

Parts

objMediaTypeInfo
IMediaTypeInfo object that will contain the new media type.
objPinInfo
IPinInfo object specifying the source pin; the objMediaTypeInfo object copies this pin's media type.

Remarks

The IMediaTypeInfo object contains information about the major type and subtype that this pin supports.

ConnectWithType Method (IPinInfo Object)

IPinInfo Object

Connects directly to the specified pin using the specified media type.

Syntax

objPinInfo.ConnectWithType objPin, objMediaType

Parts

objPinInfo
Object expression that evaluates to an IPinInfo object.
objPin
IPinInfo object specifying the other pin in the connection.
objMediaType
Value specifying the media type used in the connection. The objMediaType object must support IPinInfo.

Remarks

The Connect and ConnectDirect methods can also be used to connect pins.

Direction Property (IPinInfo Object)

IPinInfo Object

Retrieves the pin direction.

Syntax

objPinInfo.Direction

Parts

objPinInfo
Object expression that evaluates to an IPinInfo object.

Remarks

The value 0 indicates input, and the value 1 indicates output.

Disconnect Method (IPinInfo Object)

IPinInfo Object

Disconnects this pin and the corresponding connected pin from each other.

Syntax

objPinInfo.Disconnect

Parts

objPinInfo
Object expression that evaluates to an IPinInfo object.

Remarks

Each pin has its own connection to the other. This method disconnects both pins.

FilterInfo Property (IPinInfo Object)

IPinInfo Object

Retrieves the IFilterInfo object for the filter that contains the current pin.

Syntax

Set objFilterInfo = objPinInfo.FilterInfo

Parts

objFilterInfo
Object expression that evaluates to an IFilterInfo object.
objPinInfo
Object expression that evaluates to an IPinInfo object.

Remarks

For more information, see the reference entry for IFilterInfo.

MediaTypes Property (IPinInfo Object)

IPinInfo Object

Retrieves the IAMCollection object that specifies the preferred media types for the current pin.

Syntax

Set objCollection = objPinInfo.MediaTypes

Parts

objCollection
IAMCollection object that is returned.
objPinInfo
Object expression that evaluates to an IPinInfo object.

Name Property (IPinInfo Object)

IPinInfo Object

Retrieves the name of this pin.

Syntax

objPinInfo.Name

Parts

objPinInfo
Object expression that evaluates to an IPinInfo object.

Pin Property (IPinInfo Object)

IPinInfo Object

Returns the IPin object.

Syntax

Set objPin = objPinInfo.Pin

Parts

objPin
IPinInfo object that will contain the retrieved pin.
objPinInfo
Object expression that evaluates to an IPinInfo object.

Remarks

No IPin programmable object interface is offered for Visual Basic® programmers. This property is provided for use with DLLs that take an IPin parameter, and for use as a parameter in calls to the IPinInfo object's Connect, ConnectDirect, and ConnectWithType methods.

PinID Property (IPinInfo Object)

IPinInfo Object

Retrieves the pin identifier.

Syntax

objPinInfo.PinID

Parts

objPinInfo
Object expression that evaluates to an IPinInfo object.

Remarks

You can pass the PinID as a parameter to the FindPin method of the IFilterInfo object.

Render Method (IPinInfo Object)

IPinInfo Object

Builds a filter graph capable of rendering the media type belonging to this source filter output pin, adding all transform and rendering filters and establishing all connections that are needed.

Syntax

objPinInfo.Render

Parts

objPinInfo
Object expression that evaluates to an IPinInfo object.

Remarks

This method establishes only those connections that are needed downstream from the specified pin; that is, in the direction of the renderer filter. It differs from the RenderFile method, which establishes a complete filter graph for all pins.


IRegFilterInfo Object

The IRegFilterInfo object provides information about filters registered on this computer.

Properties

Name Retrieves the name of the filter.

Methods

Filter Creates an instance of this filter, adds it to the graph, and returns an IFilterInfo object for the newly added filter.

Filter Method (IRegFilterInfo Object)

IRegFilterInfo Object

Creates an instance of this filter and adds it to the graph.

Syntax

objRegFilterInfo.Filter objFilterInfo

Parts

objRegFilterInfo
Object expression that evaluates to an IRegFilterInfo object.
objFilterInfo
IFilterInfo object specifying the filter to add.

Name Property (IRegFilterInfo Object)

IRegFilterInfo Object

Retrieves the name of the filter.

Syntax

objRegFilterInfo.Name

Parts

objRegFilterInfo
Object expression that evaluates to an IRegFilterInfo object.

Return Value

Returns the name of the registered filter object.

Remarks

The vendor specifies the filter name.


IVideoWindow Object

The IVideoWindow object supports the video window properties of a video renderer. It is a dual interface, accessible through Microsoft® Visual Basic® and Microsoft® Visual C++®, that controls a generic video window. Generally, this is a video renderer that draws video into a window on the display.

The IVideoWindow object supports both properties and methods. When operations require several properties to be changed simultaneously; methods are provided that allow a number of related properties to be changed simultaneously. For example, setting the position and size of the window can be done by four individual property calls or by the single method SetWindowPosition.

The video renderer must be connected to use the IVideoWindow properties and methods.

Properties

AutoShow | Retrieves or sets the flag that specifies if the window will be automatically shown on the first state change.
BackgroundPalette | Retrieves or sets the flag that indicates whether the renderer realizes its palette in the background.
BorderColor | Retrieves or sets the border color for the video window.
Caption | Retrieves or sets the text caption on the playback window.
FullScreenMode | Retrieves or sets the type of full-screen mode.
Height | Retrieves or sets the height of the video window.
Left | Retrieves or sets the x-axis coordinate for the video window.
MessageDrain | Retrieves or sets a window handle that is used by the video window to receive or post messages.
NotifyOwnerMessage | Forwards messages that have been received by a parent window to a child window owned by a filter.
Owner | Retrieves or sets the owning parent window for the video playback window.
Top | Retrieves or sets the y-axis coordinates for the video window.
Visible | Retrieves or sets the visibility of the window.
Width | Retrieves or sets the width of the video window.
WindowState | Retrieves or sets the current window state (such as visible or minimized).
WindowStyle | Retrieves or sets the playback window style.
WindowStyleEx | Retrieves or sets the playback window's extended style bits.

Methods

GetMaxIdealImageSize | Gets the ideal maximum image size for the video image playback (client) area.
GetMinIdealImageSize | Gets the ideal minimum image size for the video image playback (client) area.
GetRestorePosition | Retrieves the restored video window size when maximizing and minimizing.
GetWindowPosition | Retrieves the video window position.
HideCursor | Hides the cursor.
IsCursorHidden | Retrieves whether the cursor is visible or not.
NotifyOwnerMessage | Passes palette and color change messages on the filter graph.
SetWindowForeground | Sets the video window as the foreground window and optionally gives it focus.
SetWindowPosition | Sets the video window position on the display.

AutoShow Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets information about whether the window will be automatically shown.

Syntax

objVideoWindow.AutoShow [= boolean]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
boolean
True means the window will be made visible when the state is changed.

Remarks

Many simple applications require a displayed window when a filter graph is set to the running state. This method is set on (–1) by default so that when the graph changes state to paused or running, the window will be made visible (it will also be set to be the foreground window). It will be shown on all subsequent state changes to paused or running unless the window is closed, in which case it will not be shown again until the renderer goes through a stopped state. If this property is set to off (0), the window will remain hidden until explicitly shown. You can do this by setting the Visible property.

BackgroundPalette Property (IVideoWindow Object)

IVideoWindow Object

Determines whether any palette required will be realized in the background.

Syntax

objVideoWindow.BackgroundPalette [= boolean]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
boolean
Flag that indicates whether the palette will be realized.

Remarks

If this is True (–1), the renderer realizes any required video palette in the background. This means that any colors the palette uses will change to their closest match in the display palette prior to drawing. This ensures that an application will not have its palette disturbed when playing a video. It does, however, impose severe performance penalties on the video and should not be used unless absolutely necessary. The default value for this property is False (0).

BorderColor Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets the border color for the video window.

Syntax

objVideoWindow.BorderColor [= Color]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
Color
New border color.

Remarks

When a destination rectangle that is set differs from the window's visible client area, a border is exposed around the edge. This method allows an application to change the border color. It is set to black by default. Any nonsystem color passed in is converted to its closest match, according to the current palette, before being used (this is not an issue on true-color devices). Setting this causes the window border to be repainted in the new color automatically.

Caption Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets the textual title string for the video window.

Syntax

objVideoWindow.Caption [= string]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
string
New value for the window title caption.

FullScreenMode Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets a flag indicating whether to use full-screen mode for the video window.

Syntax

objVideoWindow.FullScreenMode [= boolean]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
boolean
New flag value. True means use full-screen mode; False means do not use full-screen mode.

GetMaxIdealImageSize Method (IVideoWindow Object)

IVideoWindow Object

Retrieves the ideal maximum image size for the video image playback (client) area.

Syntax

objVideoWindow.GetMaxIdealImageSize Width, Height

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
Width
Long value that will contain the image width.
Height
Long value that will contain the image height.

GetMinIdealImageSize Method (IVideoWindow Object)

IVideoWindow Object

Gets the ideal minimum image size for the video image playback (client) area.

Syntax

objVideoWindow.GetMinIdealImageSize Width, Height

Parts

objVideoWindow
An object expression that evaluates to an IVideoWindow object.
Width
Long value that will contain the image width.
Height
Long value that will contain the image height.

GetRestorePosition Method (IVideoWindow Object)

IVideoWindow Object

Retrieves the size and position of the window when it is to be restored after being minimized.

Syntax

objVideoWindow.GetRestorePosition Left, Top, Width, Height

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
Left
Returns the x-axis origin of the video window.
Top
Returns the y-axis origin of the video window.
Width
Returns the width of the video window.
Height
Returns the height of the video window.

GetWindowPosition Method (IVideoWindow Object)

IVideoWindow Object

Retrieves the current window rectangle (not the client rectangle) in device coordinates.

Syntax

objVideoWindow.GetWindowPosition Left, Top, Width, Height

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
Left
Returns the x-axis origin of the window.
Top
Returns the y-axis origin of the window.
Width
Returns the width of the window.
Height
Returns the height of the window.

Remarks

This method has the same effect as individually setting the Left, Top, Width, and Height properties.

Height Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets the height of the video window.

Syntax

objVideoWindow.Height [= lValue]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
lValue
New value for the vertical dimension of the video window.

Remarks

Changes to the Height property are independent of the Width property (the y-coordinate of the video window).

HideCursor Method (IVideoWindow Object)

IVideoWindow Object

Specifies whether the cursor is visible or hidden when it passes over the video playback window.

Syntax

objVideoWindow.HideCursor bValue

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
bValue
Boolean value that specifies whether the cursor is visible or not; True hides the cursor and False makes it visible.

Remarks

When you use full-screen playback, it is common to hide the cursor to avoid distracting the user.

The following code fragment shows how to use this method.

    Dim o_objVideoWindow As IVideoWindow		'Initialize the IVideoWindow Object
    Dim g_objMediaControl As IMediaControl    	'Initialize the IMediaControl Object

    Set g_objVideoWindow = g_objMediaControl		 'Assign the playback window
                                                           'to the filter graph
    g_objVideoWindow.HideCursor (True)			'Hide the cursor

IsCursorHidden Method (IVideoWindow Object)

IVideoWindow Object

Retrieves whether the cursor is visible or not.

Syntax

objVideoWindow.IsCursorHidden bValue

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
bValue
Boolean value that will contain the cursor's state of visibility; True if the cursor is hidden and False if it is visible.

Remarks

When you use full-screen playback, it is common to hide the cursor to avoid distracting the user.

The following code fragment shows how to use this method.

    Dim o_objVideoWindow As IVideoWindow		'Initialize the IVideoWindow Object
    Dim g_objMediaControl As IMediaControl    	'Initialize the IMediaControl Object
    Dim bTest As Boolean					'Initialize the storage variable

    Set g_objVideoWindow = g_objMediaControl		'Assign the playback window
                                                          'to the filter graph
    g_objVideoWindow.IsCursorHidden (bTest)		'Check if the cursor is hidden

Left Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets the x-coordinate for the video window.

Syntax

objVideoWindow.Left [= lValue]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
lValue
New value for the x-axis coordinate.

Remarks

Calling this method does not affect the width of the video window.

MessageDrain Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets the window handle of the window that receives posted messages for the video window.

Syntax

objVideoWindow.MessageDrain [= handle]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
handle
New value for the window handle.

NotifyOwnerMessage Method (IVideoWindow Object)

IVideoWindow Object

Forwards messages that have been received by a parent window to a child window owned by a filter.

Syntax

objVideoWindow.NotifyOwnerMessage hwnd, uMsg, wParam, lParam

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
hwnd
Window handle.
uMsg
Message being sent.
wParam
Message's wParam.
lParam
Message's lParam.

Owner Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets the owning parent for the video window.

Syntax

objVideoWindow.Owner [= handle]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
handle
New value for the window handle.

Remarks

This property offers a way for applications to set the owner of the video window. This is often used when playing videos in compound documents.

SetWindowForeground Method (IVideoWindow Object)

IVideoWindow Object

Sets the video window as the foreground window and optionally gives it focus.

Syntax

objVideoWindow.SetWindowForeground Focus

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
Focus
Long value that specifies whether the video window will have focus. A value of –1 gives the window focus and 0 does not.

SetWindowPosition Method (IVideoWindow Object)

IVideoWindow Object

Sets the position of the video window (not the client rectangle position) in device coordinates.

Syntax

objVideoWindow.SetWindowPosition Left, Top, Width, Height

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
Left
Specifies the x-axis origin of the window.
Top
Specifies the y-axis origin of the window.
Width
Specifies the width of the window.
Height
Specifies the height of the window.

Remarks

Specify, in window coordinates, where the video should appear. For example, setting a destination of (100,50,200,400) positions the video playback at an origin of 100 pixels from the left of the client area, 50 pixels from the top, and with an overall size of 200 x 400 pixels. If the video is smaller than this (or a source rectangle has been specified that is smaller than the video), it will be stretched appropriately. Similarly, if the video is larger than the destination rectangle, the video is compressed into the visible rectangle. There are fairly severe performance penalties if an application does not keep the source and destination rectangles the same size.

Under typical circumstances, when no destination rectangle has been set, the video fills the entire visible client window area (regardless of how much the user has stretched the window). Also, the destination rectangle properties correctly return the size of the video window client area.

This method has the same effect as individually setting the Left, Top, Width, and Height properties.

Top Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets the y-axis coordinate of the video window.

Syntax

objVideoWindow.Top [= lValue]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
lValue
New value for the y-axis origin.

Remarks

Calling this method does not affect the height of the video window.

Visible Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets the visibility of the video window.

Syntax

objVideoWindow.Visible [= boolean]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
boolean
If set to True, the window is shown; if False, the window is hidden.

Width Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets the width of the video window.

Syntax

objVideoWindow.Width [= lValue]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
lValue
New value of the width.

Remarks

The Width property is independent of the video window's Height property (the x-coordinate).

WindowState Property (IVideoWindow Object)

IVideoWindow Object

Returns or sets the state of the video window.

Syntax

objVideoWindow.WindowState [= lValue]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
lValue
New value for the WindowState property.

WindowStyle Property (IVideoWindow Object)

IVideoWindow Object

Retrieves or sets the style parameters for the video window.

Syntax

objVideoWindow.WindowStyle [= lValue]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
lValue
New value for the WindowStyle property.

Remarks

For a complete list of window styles, see the CreateWindow function in the Microsoft® Platform Software Development Kit (SDK).

WindowStyleEx Property (IVideoWindow Object)

IVideoWindow Object

Changes the style parameters for the video window.

Syntax

objVideoWindow.WindowStyleEx [= lValue]

Parts

objVideoWindow
Object expression that evaluates to an IVideoWindow object.
lValue
New value for the flags. Valid values include only those flags that can be set by the GWL_STYLE value of the Microsoft Win32 GetWindowLong function.


MediaDet Object

Retrieves information about a media file, such as the number of streams and the type, duration, and frame rate of each stream. This interface also contains methods for retrieving poster frames from a video stream.

To obtain information about a file, perform the following steps:

  1. Create a new instance of the MediaDet object.
  2. Set the Filename property to specify the name of the source file.
  3. Retrieve the OutputStreams property to obtain the number of output streams in the source.
  4. Set the CurrentStream property to specify a particular stream.
  5. Retrieve any of the following properties: StreamType, StreamMediaType, StreamLength, or FrameRate.

To retrieve poster frames, call WriteBitmapBits. This method puts the MediaDet object into a new mode, called bitmap grab mode. The informational methods described previously do not work in this mode. Therefore, obtain any information you need before retrieving poster frames, or else create new instances of the MediaDet object for each stream.

The following code example shows how to use this object:

Dim Det As New MediaDet
Const VideoGUID As String = "{73646976-0000-0010-8000-00AA00389B71}"
bFoundVidStream = False

Det.FileName = "C:\Media\Example.avi"

' Look for a video stream.
For i = 0 To Det.OutputStreams - 1
    Det.CurrentStream = i
    StreamType = Det.StreamTypeB
    If StrComp(StreamType, VideoGUID, vbTextCompare) = 0 Then
        bFoundVidStream = True
        Exit For
    End If
Next

If bFoundVidStream Then
    ' Update the label with the duration.
    VideoInfo.Caption = Det.FileName + ": " + Str(Det.StreamLength) + " seconds"

    ' Load a poster frame.
    TempFile = "C:\Temp.bmp"
    Preview.ScaleMode = vbPixels  ' Scale twips to pixels.
    Det.WriteBitmapBits 0, Preview.ScaleWidth, Preview.ScaleHeight, TempFile
    Preview.Picture = LoadPicture(TempFile)
End If

Properties

CurrentStream | Stream number currently used by the MediaDet object.
Filename | Name of the source file currently used by the MediaDet object.
Filter | Not supported for Visual Basic.
OutputStreams | Number of output streams contained in the media source.
FrameRate | Frame rate of the current stream, in frames per second.
StreamLength | Duration of the current stream, in seconds.
StreamMediaType | Not supported for Visual Basic.
StreamType | Not supported for Visual Basic.
StreamTypeB | String representing the GUID of the media type for the current stream.

Methods

EnterBitmapGrabMode | Switches the MediaDet object to bitmap grab mode and seeks the filter graph to a specified time.
GetBitmapBits | Not supported for Visual Basic.
GetSampleGrabber | Not supported for Visual Basic.
WriteBitmapBits | Retrieves a poster frame at the specified media time and writes it to a file.

CurrentStream Property (MediaDet Object)

MediaDet Object

Stream number currently used by the MediaDet object. Read/write.

Syntax

object.CurrentStream As Long

Parts

object
Object expression that evaluates to a MediaDet object.

Filename Property (MediaDet Object)

MediaDet Object

Name of the source file currently used by the MediaDet object. Read/write.

Syntax

object.Filename As String

Parts

object
Object expression that evaluates to a MediaDet object.

Filter Property (MediaDet Object)

MediaDet Object

Not supported for Visual Basic.

Syntax

object.Filter As Unknown

FrameRate Property (MediaDet Object)

MediaDet Object

Frame rate of the current stream, in frames per second. Read-only.

Syntax

object.FrameRate As Double

Parts

object
Object expression that evaluates to a MediaDet object.

Remarks

The stream must be a video stream. This property is not valid for ASF files. The property is not valid if the MediaDet object is in bitmap grab mode (see EnterBitmapGrabMode).

Before retrieving this property, set the Filename and CurrentStream properties.

OutputStreams Property (MediaDet Object)

MediaDet Object

Number of output streams contained in the media source. Read-only.

Syntax

object.OutputStreams As Long

Parts

object
Object expression that evaluates to a MediaDet object.

Remarks

Before retrieving this property, set the Filename property.

This property is not valid if the MediaDet object is in bitmap grab mode (see EnterBitmapGrabMode).

StreamLength Property (MediaDet Object)

MediaDet Object

Duration of the current stream, in seconds.

Syntax

object.StreamLength As Double

Parts

object
Object expression that evaluates to a MediaDet object.

Remarks

Before retrieving this property, set the Filename and CurrentStream properties.

This property is not valid if the MediaDet object is in bitmap grab mode (see EnterBitmapGrabMode).

StreamMediaType Property (MediaDet Object)

MediaDet Object

Not supported for Visual Basic.

Syntax

object.get_StreamMediaType As _AMMediaType

StreamType Property (MediaDet Object)

MediaDet Object

Not supported for Visual Basic.

Syntax

object.StreamType As GUID

StreamTypeB Property (MediaDet Object)

MediaDet Object

String representing the GUID of the media type for the current stream. Read-only.

Syntax

object.StreamTypeB As String

Parts

object
Object expression that evaluates to a MediaDet object.

Remarks

The string formatted like the following: {73647561-0000-0010-8000-00AA00389B71}

Before retrieving this property, set the Filename and CurrentStream properties. This property is not valid if the MediaDet object is in bitmap grab mode (see EnterBitmapGrabMode).

EnterBitmapGrabMode Method (MediaDet Object)

MediaDet Object

Switches the MediaDet object to bitmap grab mode and seeks the filter graph to a specified time.

Syntax

object.EnterBitmapGrabMode(
    SeekTime As Double
)

Parts

object
Object expression that evaluates to a MediaDet object.
SeekTime
Time, in seconds, to which the graph seeks.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Invalid argument.
VFW_E_INVALIDMEDIATYPE | File does not have a video stream.
VFW_E_TIME_EXPIRED | Could not seek.

Remarks

Before calling this method, set the Filename and CurrentStream properties.

This method inserts the Sample Grabber filter into the filter graph. Once the MediaDet object enters bitmap grab mode, the various informational methods in MediaDet do not work.

The GetBitmapBits or WriteBitmapBits methods also put the object into bitmap grab mode.

GetBitmapBits Method (Media Object)

MediaDet Object

Not supported for Visual Basic.

Syntax

object.GetBitmapBits(
    StreamTime As Double,
    pBufferSize As Long,
    pBuffer As Byte,
    Width As Long,
    Height As Long
)

GetSampleGrabber Method (MediaDet Object)

MediaDet Object

Not supported for Visual Basic.

Syntax

object.GetSampleGrabber(
    ppVal As SampleGrabber
)

WriteBitmapBits Method (MediaDet Object)

MediaDet Object

Retrieves a poster frame at the specified media time and writes it to a file.

Syntax

object.WriteBitmapBits(
    StreamTime As Double,
    Width As Long,
    Height As Long,
    Filename As String
)

Parts

object
Object expression that evaluates to a MediaDet object.
StreamTime
Time at which to retrieve the poster frame, in seconds.
Width
Width of the poster frame image, in pixels.
Height
Height of the poster frame image, in pixels.
Filename
Path of the file in which to save the poster frame. If the file already exists, this method overwrites it.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_NOINTERFACE | Could not add the Sample Grabber filter to the graph.
E_FAIL | Failure.
E_OUTOFMEMORY | Insufficient memory.
E_UNEXPECTED | Unexpected error.
STG_E_ACCESSDENIED | Cannot overwrite file.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

Before calling this method, set the Filename and CurrentStream properties.

This method puts the MediaDet object into bitmap grab mode. Once this method has been called, the various stream information methods in IMediaDet do not work, unless you create a new instance of the object.


MediaLocator Object

Provides methods for validating file names in Microsoft® DirectShow® Editing Services (DES). You can use the MediaLocator object to ensure that a given file name and path correspond to an existing file. This object also provides a way to search for the file at other locations, and to display an Open dialog box so that the user can locate the file.

The timeline and the render engine also support file name validation through the following methods:

  • AMTimeline.ValidateSourceNames: Validates and updates file names in the timeline.
  • RenderEngine.SetSourceNameValidation: Specifies how the render engine validates file names at rendering time.

Typically, a DES application will call these methods rather than directly create an instance of the MediaLocator object.

Methods

FindMediaFile | Searches for a file and, if successful, retrieves the path to the file.
AddFoundLocation | Adds a directory to the directory cache.

AddFoundLocation Method (MediaLocator Object)

MediaLocator Object

Adds a directory to the directory cache.

Syntax

object.AddFoundLocation(
    DirectoryName As String
)

Parts

object
Object expression that evaluates to a MediaLocator object.
DirectoryName
Directory path to add to the cache.

Error Codes

If the method fails, an error is raised.

Remarks

The MediaLocator object keeps a cache of directory paths where it has successfully found files in past searches. When it successfully locates a file, it adds the directory to the cache.

FindMediaFile (MediaLocator Object)

MediaLocator Object

Searches for a file and, if successful, retrieves the path to the file.

Syntax

object.FindMediaFile(
    Input As String,
    FilterString As String,
    pOutput As String,
    Flags As Long
)

Parts

object
Object expression that evaluates to a MediaLocator object.
Input
File name, including path, where the file was last known to reside. For source objects in the timeline, use the current media name.
FilterString
String containing pairs of filter strings formatted as required by the lpstrFilter member of the Microsoft® Win32® OPENFILENAME structure. The media locator uses this filter if it displays an Open dialog box.
pOutput
Variable that receives the actual path to the file, if it differs from the value contained in Input and if the method successfully locates the file.
Flags
Bitwise combination of zero or more of the following flags:
  • SFN_VALIDATEF_NOFIND
  • SFN_VALIDATEF_POPUP
  • SFN_VALIDATEF_TELLME
  • SFN_VALIDATEF_USELOCAL

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_FAIL | Failure.
E_INVALIDARG | Argument is invalid.
E_POINTER | NULL pointer argument.

Remarks

If the SFN_VALIDATEF_POPUP flag is specified and the media locator cannot locate the file, this method displays an Open dialog box for the user to locate the file. If the user cancels the dialog box, the method raises an E_FAIL error. Your application should catch this error using an On Error statement:

If Err.Number = &H80004005 Then
    ' Did not locate the file.
End If

If the SFN_VALIDATEF_POPUP flag is not specified, and the media locator cannot locate the file, the method raises an E_FAIL error without displaying the dialog box.

The filter string for the Open dialog box, which is specified by the FilterString parameter, contains internal Null characters. For example, Video\0*.avi\0\0. You can use Chr(0) to specify the Null characters:

sNullStr = Chr(0)
sFilterStr = "Video" + sNullStr + "*.avi" + sNullStr + sNullStr


RenderEngine Object

Renders a Microsoft® DirectShow® Editing Services (DES) project by constructing a filter graph from a timeline.

DES provides two objects that rendering timelines:

  • The RenderEngine object creates uncompressed output. You can use the output for preview, or route it through compression filters and write it to a file.
  • The SmartRenderEngine object creates compressed output, using smart recompression. With smart recompression, a source file is recompressed only if its format differs from the output format. A source with a matching format is written directly to the output file. Depending on the scenario, smart recompression can greatly improve rendering time.

Although an application can create a filter graph and pass it to a render engine, the typical scenario is for the render engine to create the filter graph. Building the graph is a two-stage process. First, build the front end by calling the ConnectFrontEnd method. Then connect the output pins on the front end to the desired rendering filters:

  • Video and audio renderers for preview, or
  • Compressors, multiplexers, and file writers to generate the final output.

Methods

Commit | Not supported for Visual Basic.
ConnectFrontEnd | Builds the front end of the filter graph from the current timeline.
Decommit | Not supported for Visual Basic.
DoSmartRecompression | Not supported for Visual Basic.
GetCaps | Not supported for Visual Basic.
GetFilterGraph | Retrieves the filter graph that the render engine has constructed, if any.
GetGroupOutputPin | Retrieves the output pin for the specified group.
GetTimelineObject | Retrieves the timeline that the render engine is currently using.
GetVendorString | Retrieves the vendor string.
RenderOutputPins | Creates the previewing portion of the filter graph.
SetDynamicReconnectLevel | Sets the level of dynamic reconnection during rendering.
SetFilterGraph | Specifies a filter graph for the render engine to use.
SetInterestRange | Not supported for Visual Basic.
SetInterestRange2 | Not supported for Visual Basic.
SetRenderRange | Not supported for Visual Basic.
SetRenderRange2 | Sets the range of time on the timeline to be rendered.
SetSourceConnectCallback | Not supported for Visual Basic.
SetSourceNameValidation | Specifies how the render engine validates file names.
SetTimelineObject | Sets the timeline for the render engine to use.
ScrapIt | Discards the render engine's filter graph and all associated objects.
UseInSmartRecompressionGraph | Not supported for Visual Basic.

Commit Method (RenderEngine Object)

RenderEngine Object

Not supported for Visual Basic.

Syntax

object.Commit()

ConnectFrontEnd (RenderEngine Object)

RenderEngine Object

Builds the front end of the filter graph from the current timeline.

Syntax

object.ConnectFrontEnd()

Parts

object
Object expression that evaluates to a RenderEngine object.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | No timeline set for this render engine.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because the project was not rendered successfully.
E_UNEXPECTED | Unexpected error.
VFW_E_INVALIDMEDIATYPE | Invalid media type.

Remarks

This method does not build the rendering portion of the filter graph. The application must connect the output pins on the front end to the desired rendering filters:

  • To preview, call the RenderOutputPins method.
  • To output a file, call GetGroupOutputPin to retrieve the output pin for each group, then connect the pins to a multiplexer filter.

If you are using the RenderEngine object, the output pins on the front end produce uncompressed data. If you are using the SmartRenderEngine object, the output pins produce compressed data.

If you change the timeline after you build the filter graph, you must call ConnectFrontEnd again to rebuild the front end. The method preserves the rendering portion of the graph whenever possible. However, if you add or delete a group, or change the order of the groups, ConnectFrontEnd deletes the rendering portion and your application must rebuild it.

Decommit (RenderEngine Object)

RenderEngine Object

Not supported for Visual Basic.

Syntax

object.Decommit()

DoSmartRecompression (RenderEngine Object)

RenderEngine Object

Not supported for Visual Basic.

Syntax

object.DoSmartRecompression()

GetCaps (RenderEngine Object)

RenderEngine Object

Not supported for Visual Basic.

Syntax

object.GetCaps(
    Index As Long,
    pReturn As Long
)

GetFilterGraph (RenderEngine Object)

RenderEngine Object

Retrieves the filter graph that the render engine has constructed, if any.

Syntax

object.GetFilterGraph(
    ppFG As IGraphBuilder
)

Parts

object
Object expression that evaluates to a RenderEngine object.
ppFG
The FilgraphManager object that receives the filter graph.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_MUST_INIT_RENDERER Render engine failed to initialize.

GetGroupOutputPin (RenderEngine Object)

RenderEngine Object

Retrieves the output pin for the specified group.

Syntax

object.GetGroupOutputPin(
    Group As Long,
    ppRenderPin As IPin
)

Parts

object
Object expression that evaluates to a RenderEngine object.
Group
Zero-based index that specifies the group.
ppRenderPin
The IPin object that receives the output pin.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Invalid argument.
E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because project was not rendered successfully.
E_UNEXPECTED | Unexpected error.

Remarks

Before calling this method, call ConnectFrontEnd to build the front end of the graph. Each group represents a single media stream, and the front end has a corresponding output pin.

You can use this method to create the rendering portion of a file-writing graph. Connect the output pins to multiplexer filters and file writer filters. For more information, see Rendering a Project.

For preview, you don't need to call this method. Just call ConnectFrontEnd followed by RenderOutputPins.

GetTimelineObject (RenderEngine Object)

RenderEngine Object

Retrieves the timeline that the render engine is currently using.

Syntax

object.GetTimelineObject(
    ppTimeline As AMTimeline
)

Parts

object
Object expression that evaluates to a RenderEngine object.
ppTimeline
The AMTimeline object that receives the timeline.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_MUST_INIT_RENDERER Render engine failed to initialize.

GetVendorString (RenderEngine Object)

RenderEngine Object

Retrieves the vendor string.

Syntax

object.GetVendorString() As String

Parts

object
Object expression that evaluates to a RenderEngine object.

Return Value

Returns a string containing the vendor name.

Error Codes

If the method fails, an error is raised.

RenderOutputPins (RenderEngine Object)

RenderEngine Object

Creates the previewing portion of the filter graph.

Syntax

object.RenderOutputPins()

Parts

object
Object expression that evaluates to a RenderEngine object.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Invalid argument.
E_RENDER_ENGINE_IS_BROKEN | Operation failed because project was not rendered successfully.
E_UNEXPECTED | Unexpected error.

Remarks

Before calling this method, call ConnectFrontEnd to build the front end of the graph. To perform an operation other than preview, do not call this method. Instead, call GetGroupOutputPin to obtain pointers to the output pins.

ScrapIt (RenderEngine Object)

RenderEngine Object

Discards the render engine's filter graph and all associated objects.

Syntax

object.ScrapIt()

Parts

object
Object expression that evaluates to a RenderEngine object.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_MUST_INIT_RENDERER Render engine failed to initialize.

SetDynamicReconnectLevel (RenderEngine Object)

RenderEngine Object

Sets the level of dynamic reconnection during rendering.

Syntax

object.SetDynamicReconnectLevel(
    Level As Long
)

Parts

object
Object expression that evaluates to a RenderEngine object.
Level
Bitwise combination of zero or more Dynamic Reconnection Flags, specifying the level of dynamic reconnection.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_NOTIMPL Not implemented.

Remarks

By default, the RenderEngine object loads every source before rendering a project. This can result in a long start-up time. With dynamic reconnection, sources are loaded only when needed. This can shorten the start-up time, but possibly interfere with smooth playback. Generally, the more source clips that a project uses, the more you might benefit from dynamic reconnection.

The SmartRenderEngine object does not implement this method.

SetFilterGraph (RenderEngine Object)

RenderEngine Object

Specifies a filter graph for the render engine to use.

Syntax

object.SetFilterGraph(
    pFG As IGraphBuilder
)

Parts

object
Object expression that evaluates to a RenderEngine object.
pFG
The FilgraphManager object that specifies the filter graph.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Invalid argument.
E_MUST_INIT_RENDERER | Render engine failed to initialize.

Remarks

Most applications do not need to call this method. It is more typical to let the render engine build the graph for you, by calling the ConnectFrontEnd method.

This method fails if the render engine already has a filter graph.

Never retrieve a filter graph created by one render engine and then use it as the parameter to this method on another render engine. Doing so will cause unpredictable results.

SetInterestRange (RenderEngine Object)

RenderEngine Object

Not supported for Visual Basic.

Syntax

object.SetInterestRange(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

SetInterestRange2 (RenderEngine Object)

RenderEngine Object

Not supported for Visual Basic.

Syntax

object.SetInterestRange2(
    double Start As Double,
    double Stop As Double
)

SetRenderRange (RenderEngine Object)

RenderEngine Object

Not supported for Visual Basic.

Syntax

object.SetRenderRange(
    Start As <Unsupported variant type>,
    Stop As <Unsupported variant type>
)

SetRenderRange2 (RenderEngine Object)

RenderEngine Object

Sets the range of time on the timeline to be rendered. Objects that lie outside the specified range are not rendered, and resources are not allocated for them.

Syntax

object.SetRenderRange2(
    Start As Double,
    Stop As Double
)

Parts

object
Object expression that evaluates to a RenderEngine object.
Start
Start time, in seconds.
Stop
Stop time, in seconds.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_MUST_INIT_RENDERER Render engine failed to initialize.

SetSourceConnectCallback (RenderEngine Object)

RenderEngine Object

Not supported for Visual Basic.

Syntax

object.SetSourceConnectCallback(
    pCallback As IGrfCache
)

SetSourceNameValidation (RenderEngine Object)

RenderEngine Object

Specifies how the render engine validates file names.

Syntax

object.SetSourceNameValidation(
    FilterString As String,
    pOverride As MediaLocator,
    Flags As Long
)

Parts

object
Object expression that evaluates to a RenderEngine object.
FilterString
String containing pairs of filter strings formatted as required by the lpstrFilter member of the Microsoft® Win32® OPENFILENAME structure. The media locator uses this filter if it displays an Open dialog box.
pOverride
Optional MediaLocator object to use in place of the default. To use the default media locator, set the value of this parameter to NULL. See Remarks for more information.
Flags
Bitwise combination of flags specifying the behavior of the MediaLocator object. The SFN_VALIDATEF_CHECK flag must be present. The SFN_VALIDATEF_IGNOREMUTED flag has no effect with this method.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_MUST_INIT_RENDERER Render engine failed to initialize.

Remarks

Using the pOverride parameter, you can supply your own custom implementation of the MediaLocator object.

Currently, this method does not validate dynamically loaded sources. See SetDynamicReconnectLevel.

SetTimelineObject (RenderEngine Object)

RenderEngine Object

Sets the timeline for the render engine to use.

Syntax

object.SetTimelineObject(
    pTimeline As AMTimeline
)

Parts

object
Object expression that evaluates to a RenderEngine object.
pTimeline
An AMTimeline object that specifies the timeline.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_MUST_INIT_RENDERER | Render engine failed to initialize.
E_OUTOFMEMORY | Insufficient memory.

UseInSmartRecompressionGraph (RenderEngine Object)

RenderEngine Object

Not supported for Visual Basic.

Syntax

object.UseInSmartRecompressionGraph()


Xml2Dex Object

Saves and loads Microsoft® DirectShow® Editing Services (DES) project files in Extensible Markup Language (XML).

Requirements

Requires Internet Explorer 4.0 or later.

Methods

CopyXML | Not supported for Visual Basic.
CreateGraphFromFile | Not supported for Visual Basic.
Delete | Not supported for Visual Basic.
PasteXML | Not supported for Visual Basic.
PasteXMLFile | Not supported for Visual Basic.
ReadXML | Not supported for Visual Basic.
ReadXMLFile | Loads an XML project file.
Reset | Not supported for Visual Basic.
WriteGrfFile | Writes a filter graph to a file in .grf format.
WriteXML | Translates a timeline to an XML string.
WriteXMLFile | Translates a timeline to XML and writes the XML data to a file.
WriteXMLPart | Not supported for Visual Basic.

CopyXML Method (Xml2Dex Object)

Xml2Dex Object

Not supported for Visual Basic.

Syntax

object.CopyXML(
    pTimeline As Unknown,
    dStart As Double,
    dEnd As Double
)

CreateGraphFromFile Method (Xml2Dex Object)

Xml2Dex Object

Not supported for Visual Basic.

Syntax

object.CreateGraphFromFile(
    ppGraph As Unknown,
    pTimeline As Unknown,
    FileName As String
)

Delete Method (Xml2Dex Object)

Xml2Dex Object

Not supported for Visual Basic.

Syntax

object.Delete(
    pTimeline As Unknown,
    dStart As Double,
    dEnd As Double
)

PasteXML Method (Xml2Dex Object)

Xml2Dex Object

Not supported for Visual Basic.

Syntax

object.PasteXML(
    pTimeline As Unknown,
    dStart As Double
)

PasteXMLFile Method (Xml2Dex Object)

Xml2Dex Object

Not supported for Visual Basic.

Syntax

object.PasteXMLFile(
    pTimeline As Unknown,
    dStart As Double,
    FileName As String
)

ReadXML Method (Xml2Dex Object)

Xml2Dex Object

Not supported for Visual Basic.

Syntax

object.ReadXML(
    pXML As Unknown
)

ReadXMLFile Method (Xml2Dex Object)

Xml2Dex Object

Loads an XML project file. This method creates instances of all the objects expressed in the XML file and inserts them into the timeline. The method also applies any attributes given for the timeline, such as frame rate or default effect.

Syntax

object.ReadXMLFile(
    pTimeline As Unknown,
    XMLName As String
)

Parts

object
Object expression that evaluates to an Xml2Dex object.
pTimeline
The AMTimeline object that receives the timeline.
XMLName
String that specifies the name of the file to load.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

VFW_E_INVALID_FILE_FORMAT Invalid file format.

Remarks

The pTimeline parameter appears in the Microsoft® Visual Basic® Object Browser as type Unknown. In fact, however, this parameter represents an AMTimeline object. The following code example shows how to call this method:

Dim objTimeline as New AMTimeline
Dim objXmlParse as New Xml2Dex
objXmlParse.ReadXMLFile objTimeline, "C:\XTL\Example.xtl"

This method does not clear existing objects from the timeline before it inserts the new objects defined in the XML file. If you need to refresh an existing timeline, call IAMTimeline.ClearAllGroups first.

Reset Method (Xml2Dex Object)

Xml2Dex Object

Not supported for Visual Basic.

Syntax

object.Reset()

WriteGrfFile Method (Xml2Dex Object)

Xml2Dex Object

Writes a filter graph to a file in .grf format.

Syntax

object.WriteGrfFile(
    pGraph As Unknown,
    FileName As String
)

Parts

object
Object expression that evaluates to an Xml2Dex object.
pGraph
The FilgraphManager object that specifies the filter graph.
FileName
String that specifies the name of the file to write.

Error Codes

If the method fails, an error is raised.

Remarks

The pGraph parameter appears in the Microsoft® Visual Basic® Object Browser as type Unknown. In fact, however, this parameter represents a FilgraphManager object. GraphEdit files are intended for debugging use only. For more information, see Simulating Graph Building with GraphEdit.

WriteXML Method (Xml2Dex Object)

Xml2Dex Object

Translates a timeline to an XML string.

Syntax

object.WriteXML(
    pTimeline As Unknown,
    pbstrXML As String
)

Parts

object
Object expression that evaluates to an Xml2Dex object.
pTimeline
AMTimeline object that specifies the timeline.
pbstrXML
Variable that receives the translated XML string.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to the following value:

E_OUTOFMEMORY Insufficient memory.

Remarks

The pTimeline parameter appears in the Microsoft® Visual Basic® Object Browser as type Unknown. In fact, however, this parameter represents an AMTimeline object. The following code example shows how to call this method:

Dim objTimeline As New AMTimeline
' Create timeline (not shown).

Dim objXmlParser As New Xml2Dex
Dim sXml As String
objXmlParser.WriteXml objTimeline, sXml

WriteXMLFile Method (Xml2Dex Object)

Xml2Dex Object

Translates a timeline to XML and writes the XML data to a file.

Syntax

object.WriteXMLFile(
    pTimeline As Unknown,
    FileName As String
)

Parts

object
Object expression that evaluates to an Xml2Dex object.
pTimeline
The AMTimeline object that specifies the timeline.
FileName
String that specifies the name of the file to write.

Error Codes

If the method fails, an error is raised, and Err.Number can be set to one of the following values:

E_INVALIDARG | Invalid argument.
E_OUTOFMEMORY | Insufficient memory.

Remarks

This method generates an XML file that represents all the components in the timeline.

The pTimeline parameter appears in the Microsoft® Visual Basic® Object Browser as type Unknown. In fact, however, this parameter represents an AMTimeline object. The following code example shows how to call this method:

Dim objTimeline As New AMTimeline
' Create timeline (not shown).

Dim objXmlParser As New Xml2Dex
objXmlParser.WriteXmlFile objTimeline, "C:\XTL\Example.xtl"

WriteXMLPart Method (Xml2Dex Object)

Xml2Dex Object

Not supported for Visual Basic.

Syntax

object.WriteXMLPart(
    pTimeline As Unknown,
    dStart As Double,
    dEnd As Double,
    FileName As String
)


Further Reading

_CrtSetDbgFlag
Retrieves and/or modifies the state of the _crtDbgFlag flag to control the allocation behavior of the debug heap manager (debug version only). For more information, see the Microsoft® Visual C++® documentation.
BitBlt
The BitBlt function performs a bit-block transfer of the color data corresponding to a rectangle of pixels from the specified source device context into a destination device context. For more information, see the Microsoft Platform SDK documentation.
biHeight
A data member of the BITMAPINFOHEADER structure that specifies the height of a bitmap, in pixels. If biHeight is positive, the bitmap is a bottom-up DIB (device-independent bitmap) and its origin is the lower left corner. If biHeight is negative, the bitmap is a top-down DIB and its origin is the upper left corner.
biWidth
A data member of the BITMAPINFOHEADER structure that specifies the width of a bitmap, in pixels.
CAUUID
A structure that defines a counted array of UUID or GUID types. It has two members: The cElems member specifies the size of the array, and the pElems member contains a pointer to the array. For more information, see the Platform SDK.
CClassFactory
A class that implements the IClassFactory interface. The IClassFactory interface contains two methods intended to deal with an entire class of objects, and so it is implemented on the class object for a specific class of objects (identified by a CLSID). The first method, CreateInstance, creates an uninitialized object of a specified CLSID, and the second, LockServer, locks the object's server in memory, enabling quicker creation of new objects. For more information, see the IClassFactory interface documentation in the Platform SDK.
class factory
A COM object that implements the IClassFactory interface and that creates one or more instances of an object identified by a given class identifier (CLSID). See CClassFactory, IClassFactory.
CoCreateInstance
Creates a single uninitialized object of the class associated with a specified CLSID. For more information, see the Platform SDK documentation.
CoGetClassObject
Provides a pointer to an interface on a class object associated with a specified CLSID. CoGetClassObject locates, and if necessary, dynamically loads the executable code required to do this. For more information, see the Platform SDK documentation.
CoInitialize
Initializes the Component Object Model (COM) library. For more information, see the Platform SDK documentation.
COLORREF
A 32-bit value used to specify an RGB color. For more information, see the Platform SDK documentation.
CoTaskMemAlloc
Allocates a block of task memory in the same way that IMalloc::Alloc does. For more information, see the Platform SDK documentation.
CoTaskMemFree
Frees a block of task memory previously allocated through a call to the CoTaskMemAlloc or CoTaskMemRealloc function. For more information, see the Platform SDK documentation.
CreateDIBSection
Creates a device-independent bitmap (DIB) that applications can write to directly. The function gives you a pointer to the location of the bitmap's bit values. You can supply a handle to a file mapping object that the function will use to create the bitmap, or you can let the operating system allocate the memory for the bitmap. For more information, see the Platform SDK documentation.
CreateEvent
Creates a named or unnamed event object. For more information, see the Platform SDK documentation.
CreateFile
Creates or opens various objects and returns a handle that can be used to access the object. For more information, see the Platform SDK documentation.
CreateWindow
Creates an overlapped, pop-up, or child window. For more information, see the Platform SDK documentation.
CreateWindowEx
Creates an overlapped, pop-up, or child window with an extended style; otherwise, this function is identical to the CreateWindow function. For more information, see the Platform SDK documentation.
CRITICAL_SECTION
A critical section object, an object used to synchronize the threads of a single process. Only one thread at a time can own a critical-section object. For more information, see the Platform SDK documentation.
DDCOLORCONTROL
A structure that defines the color controls associated with a DirectDrawVideoPort object, an overlay surface, or a primary surface. For more information, see the DirectX SDK documentation.
DDPIXELFORMAT
A structure that describes the pixel format of a DirectDrawSurface object for the IDirectDrawSurface3::GetPixelFormat method. For more information, see the DirectDraw documentation in the DirectX SDK.
DDSCAPS
A structure that defines the capabilities of a DirectDrawSurface object. This structure is part of the DDCAPS structure that is used to describe the capabilities of the DirectDraw object. For more information, see the DirectDraw documentation in the DirectX SDK.
DDSURFACEDESC
A structure that contains a description of the surface to be created. This structure is passed to the IDirectDraw2::CreateSurface method. The relevant members differ for each potential type of surface. For more information, see the DirectDraw documentation in the DirectX SDK.
DDVIDEOPORTCONNECT
A structure that describes a video port connection. For more information, see the DirectX SDK documentation.
DefWindowProc
A member function that calls the default window procedure to provide default processing for any window messages that an application does not process. For more information, see the Platform SDK documentation.
DIBSECTION
A structure that contains information about a device-independent bitmap created by calling the CreateDIBSection function. For more information, see the Platform SDK documentation.
DirectDrawSurface
An object that represents an area in memory that holds data to be displayed on the monitor as images are moved to other surfaces. For more information, see "Surfaces" in the "DirectDraw Essentials" section of the DirectX SDK.
DISPPARAMS
A structure used by IDispatch::Invoke and CBasicAudio::Invoke to contain the parameters passed to a method or property. The CDispParams class implements this structure. For more information, see the Platform SDK documentation.
DllCanUnloadNow
A function that determines whether the DLL that implements this function is in use. If not, the caller can safely unload the DLL from memory. For more information, see the Platform SDK documentation.
DllGetClassObject
A function that is the entry point used by C++ file and stream handlers to create an instance of the handler. For more information, see the Platform SDK documentation.
DllRegisterServer
A function that instructs an in-process server to create its registry entries for all classes supported in this server module. For more information, see the Platform SDK documentation.
DllUnregisterServer
A function that instructs an in-process server to remove only those entries created through DllRegisterServer. For more information, see the Platform SDK documentation.
Err object
A Visual Basic object that contains information about run-time errors. When a run-time error occurs, the Err object's properties are filled with information that identifies the error. To generate a run-time error in your Visual Basic code, use the Raise method. For more information, see Microsoft® Visual Basic® documentation.
FILETIME
A structure that holds an unsigned 64-bit date and time value for a file. This value represents the number of 100-nanosecond units since the beginning of January 1, 1601. For more information, see the Platform SDK documentation.
FOURCC
A Four-Character Code used to identify Resource Interchange File Format (RIFF) chunks. A FOURCC is a 32-bit quantity represented as a sequence of one to four ASCII alphanumeric characters, padded on the right with blank characters. RIFF (Resource Interchange File Format) is a specification used to define standard formats for multimedia files and to prevent compatibility problems that often occur when file-format definitions change over time. Because each piece of data in the file is identified by a standard header, an application that does not recognize a given data element can skip over the unknown information. For more information, see the Platform SDK documentation.
GdiFlush
A function that flushes the calling thread's current batch. Batching enhances drawing performance by minimizing the amount of time needed to call GDI drawing functions that return Boolean values.
GetClassFile
A function that supplies the CLSID associated with the given file name. For more information, see the Platform SDK documentation.
GetClientRect
A function that retrieves the coordinates of a window's client area. For more information, see the Platform SDK documentation.
GetLastError
A function that returns the calling thread's last-error code value. For more information, see the Platform SDK documentation.
GetSystemPaletteEntries
A function that retrieves a range of palette entries from the system palette that is associated with the specified device context. For more information, see the Platform SDK documentation.
GetWindowLong
A function that retrieves information about the specified window. It also retrieves the 32-bit (long) value at the specified offset into a window's extra window memory. For more information, see the Platform SDK documentation.
GUID
A globally unique identifier used to uniquely identify objects, such as interfaces and plug-in distributors. Class identifiers (CLSIDs) and interface identifiers (IIDs) are GUIDs. You can generate GUIDs with the command-line utility program, UUIDGEN, provided with the Platform SDK, or with the Microsoft Foundation Class Library (MFC) sample application, GUIDGEN, provided with Microsoft Visual C++®.
HBITMAP
The handle of a bitmap. For more information, see the Platform SDK documentation.
Win32 HRESULT
A value returned from a function call to an interface, consisting of a severity code, context information, a facility code, and a status code that describes the result. For more information, see the Platform SDK documentation.
IBindCtx
An interface that provides access to a bind context, which is an object that stores information about a particular moniker binding operation. For more information, see the Platform SDK documentation.
ICAbout
A macro that notifies a video compression driver to display its About dialog box. For more information, see the Video for Windows Development Kit version 1.1.
ICConfigure
A macro that notifies a video compression driver to display its configuration dialog box. For more information, see the Video for Windows Development Kit version 1.1.
IClassFactory
An interface that contains two methods intended to deal with an entire class of objects, and so is implemented on the class object for a specific class of objects (identified by a CLSID). The first method, CreateInstance, creates an uninitialized object of a specified CLSID, and the second, LockServer, locks the object's server in memory, allowing new objects to be created more quickly. For more information, see the Platform SDK documentation.
IClassFactory::CreateInstance
A method that creates an uninitialized object. For more information, see the Platform SDK documentation.
ICSendMessage
A function that sends a message to a compressor. For more information, see the Video for Windows Development Kit version 1.1.
ICGetState
A macro that queries a video compression driver to return its current configuration in a block of memory. You can use this macro or explicitly call the ICM_GETSTATE message. For more information, see the Platform SDK documentation.
IDirectDraw
Applications use the methods of this interface to create DirectDraw objects and work with system-level variables. For more information, see the DirectX SDK.
IDirectDraw2
Applications use the methods of this interface to create DirectDraw objects and work with system-level variables. For more information, see the DirectX SDK.
IDirectSound
Applications use the methods of this interface to create DirectSound objects and set up the environment. For more information, see the DirectX SDK.
IDirectSoundBuffer
Applications use the methods of this interface to create DirectSoundBuffer objects and set up the environment. For more information, see the DirectX SDK.
IDispatch
An interface that exposes objects, methods, and properties to Automation programming tools and other applications. A dual interface derives from IDispatch and uses only Automation-compatible types. Like the IDispatch interface, a dual interface supports early and late binding. However, a dual interface differs in that it also supports vtable binding. For more information, see the Platform SDK documentation.
IEnumMoniker
An interface used to enumerate the components of a moniker or to enumerate the monikers in a table of monikers. For more information, see the Platform SDK documentation.
IEnumVARIANT
A dispatch interface that provides a way to iterate over collection objects. For more information, see the Platform SDK documentation.
IEnumXXXX
A set of enumeration interfaces that enable you to enumerate the number of items of a given type that an object maintains. There is one interface for each type of item. To use these interfaces, the client asks an object that maintains a collection of items to create an enumerator object. The interface on the enumeration object is one of the enumeration interfaces, all of which have a name of the form IEnumItem_name. The only difference among the enumeration interfaces is what they enumerate. There must be a separate enumeration interface for each type of item enumerated. All have the same set of methods, and are used in the same way. For more information, see the Platform SDK documentation.
IMoniker
An interface containing methods that enable you to use a moniker object, which contains information that uniquely identifies a COM object. An object that has a pointer to the moniker object's IMoniker interface can locate, activate, and get access to the identified object without having any other specific information on where the object is actually located in a distributed system. For more information, see the COM documentation in the Platform SDK.
IMoniker::BindToStorage
A method that retrieves an interface pointer to the storage that contains the object identified by the moniker. Unlike IMoniker::BindToObject, this method does not activate the object identified by the moniker. For more information, see the COM documentation in the Platform SDK.
IMoniker::BindToObject
A method that uses the moniker to bind to the object it identifies. The binding process involves finding the object, putting it into the running state if necessary, and supplying the caller with a pointer to a specified interface on the identified object. For more information, see the COM documentation in the Platform SDK.
IPersist
An interface with one method, GetClassID, which is designed to supply the CLSID of an object that can be stored persistently in the system. You must implement the single method of IPersist in implementing any one of the other persistence interfaces: IPersistStorage, IPersistStream, or IPersistFile. You can use IPersist when all that is required is to obtain the CLSID of a persistent object, as it is used in marshaling. For more information, see the Platform SDK documentation.
IPersistFile
An interface that provides methods that permit an object to be loaded from or saved to a disk file, rather than a storage object or stream. Typically, for example, you would implement IPersistFile on a linked object. For more information, see the Platform SDK documentation.
IPersistPropertyBag
An interface that works in conjunction with IPropertyBag and IErrorLog to define an individual property-based persistence mechanism. For more information, see the COM documentation in the Platform SDK.
IPersistStream
An interface that provides methods for saving and loading objects that use a simple serial stream for their storage needs. For more information, see the Platform SDK documentation.
IPropertyBag
An interface that provides an object with a property bag in which the object can persistently save its properties. For more information, see the Platform SDK documentation.
IPropertyPage
An interface that provides the main features of a property page object that manages a particular page within a property sheet. For more information, see the Platform SDK documentation.
IPropertyPageSite
An interface that provides the main features for a property page site object. For more information, see the Platform SDK documentation.
IsBadReadPtr
A Win32 function that verifies that the calling process has read access to the specified range of memory. For more information, see the Platform SDK documentation.
ISpecifyPropertyPages
An interface that indicates that an object supports property pages. For more information, see the Platform SDK documentation.
IStorage::OpenStream
A method that opens an existing stream object within this storage object using the specified access permissions in the grfMode parameter. For more information, see the Platform SDK documentation.
IStream
An interface that supports reading and writing data to stream objects. For more information, see the Platform SDK documentation.
ITypeInfo
An interface typically used for reading information about objects. For example, an object browser tool can use ITypeInfo to extract information about the characteristics and capabilities of objects from type libraries. For more information, see the Platform SDK documentation.
LoadLibrary
A function that maps the specified executable module into the address space of the calling process. For more information, see the Platform SDK documentation.
LONGLONG
A 64-bit signed integer. For more information, see the Platform SDK documentation.
LRESULT
A 32-bit value returned from a window procedure or callback function. For more information, see the Platform SDK documentation.
MainAVIHeader
A structure that contains global information for the entire AVI file. For more information, see the Platform SDK documentation.
moniker
An object that implements the IMoniker interface. A moniker acts as a name that uniquely identifies a COM object. In the same way that a path identifies a file in the file system, a moniker identifies a COM object in the directory namespace.
MoveWindow
A function that changes the position and dimensions of the specified window. For more information, see the Platform SDK documentation.
MSG
A structure that contains message information from a thread's message queue. For more information, see the Platform SDK documentation.
MsgWaitForMultipleObjects
A function that determines whether the wait criteria have been met. For more information, see the Platform SDK documentation.
MultiByteToWideChar
A function that maps a character string to a wide-character (Unicode) string. For more information, see the Platform SDK documentation.
OleCreatePropertyFrame
A function that invokes a new property frame; that is, a property sheet dialog box, whose parent is hwndOwner, where the dialog is positioned at the point (x,y) in the parent window and has the caption lpszCaption. For more information, see the Platform SDK documentation.
OPENFILENAME
A structure that contains information that the GetOpenFileName and GetSaveFileName functions use to initialize an Open or Save As common dialog box. For more information, see the Platform SDK documentation.
OutputDebugString
A function that sends a string to the debugger for the current application. For more information, see the Platform SDK documentation.
PALETTEENTRY
A structure that specifies the color and usage of an entry in a logical color palette. A logical palette is defined by a LOGPALETTE structure. For more information, see the Platform SDK documentation.
PCMWAVEFORMAT
A structure that describes the data format for PCM waveform-audio data. For more information, see the Platform SDK documentation.
PeekMessage
A function that checks a thread message queue for a message and places the message (if any) in the specified structure. For more information, see the Platform SDK documentation.
PostMessage
A function that places (posts) a message in the message queue associated with the thread that created the specified window, and then returns without waiting for the thread to process the message. For more information, see the Platform SDK documentation.
property bag
A container for persistent object descriptions that implements the IPropertyBag interface.
PROPPAGEINFO
A structure that contains parameters used to describe a property page to a property frame. For more information, see the Platform SDK documentation.
RECT
A structure that defines the coordinates of the upper-left and lower-right corners of a rectangle. For more information, see the Platform SDK documentation.
ReleaseSemaphore
A function that increases the count of the specified semaphore object by a specified amount. For more information, see the Platform SDK documentation.
RGBQUAD
A structure that describes a color consisting of relative intensities of red, green, and blue. For more information, see the Platform SDK documentation.
SendMessage
A function that sends the specified message to a window or windows. For more information, see the Platform SDK documentation.
SetDIBColorTable
A function that sets RGB (red, green, blue) color values in a range of entries in the color table of the device-independent bitmap (DIB) that is selected into a specified device context. For more information, see the Platform SDK documentation.
SetDIBitsToDevice
A function that sets the pixels in the specified rectangle on the device that is associated with the destination device context using color data from a device-independent bitmap (DIB). For more information, see the Platform SDK documentation.
SetDlgItemText
A function that sets the title or text of a control in a dialog box. For more information, see the Platform SDK documentation.
SetParent
A function that changes the parent window of the specified child window. For more information, see the Platform SDK documentation.
SetWindowLong
A function that changes an attribute of the specified window. The function also sets a 32-bit (long) value at the specified offset into the extra window memory of a window. For more information, see the Platform SDK documentation.
ShowWindow
A function that sets the specified window's show state. For more information, see the Platform SDK documentation.
SIZE
A structure that specifies the width and height of a rectangle. For more information, see the Platform SDK documentation.
StretchBlt
A function that copies a bitmap from a source rectangle into a destination rectangle, stretching or compressing the bitmap to fit the dimensions of the destination rectangle, if necessary. Windows stretches or compresses the bitmap according to the stretching mode currently set in the destination device context. For more information, see the Platform SDK documentation.
StretchDIBits
A function that copies the color data for a rectangle of pixels in a device-independent bitmap (DIB) to the specified destination rectangle. If the destination rectangle is larger than the source rectangle, this function stretches the rows and columns of color data to fit the destination rectangle. If the destination rectangle is smaller than the source rectangle, this function compresses the rows and columns by using the specified raster operation. For more information, see the Platform SDK documentation.
SysAllocString
A function that allocates a new string and copies the passed string into it. For more information, see the Platform SDK documentation.
SysFreeString
A function that frees a previously allocated string. For more information, see the Platform SDK documentation.
timeBeginPeriod
A function that sets the minimum timer resolution for an application or device driver. For more information, see the Platform SDK documentation.
timeGetTime
A function that retrieves the system time, in milliseconds. The system time is the time elapsed since Windows was started. For more information, see the Platform SDK documentation.
timeSetEvent
A function that starts a specified timer event. The multimedia timer runs in its own thread. After the event is activated, it calls the specified callback function. For more information, see the Platform SDK documentation.
TXTDT_MG
A structure that can contain text descriptions of the video. For more information, see Section 4.1.6 and Annex A of the DVD-Video specification. To obtain a copy of the specification, contact Toshiba Corporation at 1-1, Shibaura 1-Chrome, Minato-ku, Tokyo 105-01, Japan, Tel. +81-3-5444-9580, Fax. +81-3-5444-9430.
videoDialog
A function that displays a dialog box used to set configuration parameters for a video capture device driver. For more information, see the Video for Windows Development Kit version 1.1.
videoMessage
A function that sends messages to a video capture device driver. For more information, see the Video for Windows Development Kit version 1.1.
WaitForMultipleObjects
A Win32 function that determines whether wait criteria have been met. If the criteria have not been met, the calling thread enters a wait state. The function returns when any one or all of the specified objects are in the signaled state, or when the time-out interval elapses. For more information, see the Platform SDK documentation.
WaitForSingleObject
A Win32 function that checks the current state of the specified object. If the object's state is nonsignaled, the calling thread enters a wait state. The function returns when the specified object is in the signaled state, or when the time-out interval elapses. For more information, see the Platform SDK documentation.
WAVEFORMAT
A structure that describes the format of waveform-audio data. For more information, see the Platform SDK documentation.


DirectSetup

This section provides information about the Microsoft® DirectSetup® component of the Microsoft DirectX® application programming interface (API) in the Platform Software Development Kit (SDK) or the stand-alone DirectX SDK. Most of this section is oriented towards C++ developers. For information on Microsoft Visual Basic® setup, see Installing DirectX for Visual Basic Applications. This section includes the following topics:

  • About DirectSetup
  • DirectSetup Essentials
  • Installing DirectX for Visual Basic Applications
  • DirectSetup Reference
  • DirectSetup Samples


About DirectSetup

Microsoft® DirectSetup® is a simple API that provides one-call installation of the Microsoft DirectX® components. This is more than a convenience—DirectX is a complex product, and installing it is an involved task. You should not attempt to install DirectX manually.

DirectSetup includes several API functions and structures. It also includes a prototype DirectXSetupCallbackFunction that can be defined by an application to customize the user interface during the installation process. The DirectX SDK includes a sample application that demonstrates the use of this callback function. For more information, see Dinstall Sample.


DirectSetup Essentials

This section contains general information about the Microsoft® DirectSetup® component. The following topics are discussed:

  • Setup Overview for DirectSetup
  • Preparing the Setup Folder
  • Customizing Setup
  • Testing the Setup Program
  • Enabling AutoPlay


Setup Overview for DirectSetup

Applications and games that depend on Microsoft® DirectX® use the DirectXSetup function to install the necessary system components into an existing Microsoft Windows® installation. The function optionally updates the display and audio drivers for optimal support of DirectX. Typically, you would call DirectXSetup from the program that you are using to install your own application files.

Note The DirectXSetup function overwrites system components from previous versions of DirectX. For example, if you install DirectX 8.0 on a system that already has DirectX 7.0 components, all DirectX 7.0 components are overwritten. Because all DirectX components comply with Component Object Model (COM) backward-compatibility rules, software written for DirectX 7.0 continues to function properly.

The DirectXSetup function can tell when DirectX components, display drivers, and audio drivers need to be upgraded. It can also distinguish whether or not these components can be upgraded without adversely affecting the Windows operating system. This is said to be a safe upgrade. The upgrade is safe for the operating system, not necessarily for the applications running on the computer. Some hardware-dependent applications can be negatively affected by an upgrade that is safe for Windows.

By default, the DirectXSetup function performs only safe upgrades. If the upgrade of a device driver might adversely affect the operation of Windows, the upgrade is not performed.

During the setup process, DirectSetup creates a backup copy of the system components and drivers that are replaced. These can be restored if problems occur.

When display or audio drivers are upgraded, the DirectXSetup function uses a database created by Microsoft to manage the process. The database contains information on existing drivers that are provided by Microsoft, the manufacturers of the hardware, or the vendors of the hardware. This database describes the upgrade status of each driver, based on testing done at Microsoft and other sites.

Check the value returned by DirectXSetup. If it is DSETUPERR_SUCCESS_RESTART, notify the user that changes do not take effect without a restart, and offer the choice of restarting immediately. See Dinstall.c in the Dinstall sample application for an example of how to do this.


Preparing the Setup Folder

The DirectXSetup function takes a parameter, lpszRootPath, that points to the root directory of the installation. It can be NULL to indicate that the root path is the current directory—that is, the directory where your setup program resides.

The root directory must contain Dsetup.dll, and Dsetup32.dll. It must also have a folder named "DirectX" (this name is not case sensitive), containing all the redistributable files and drivers. To create the proper structure on your application setup disk, copy the entire contents of the Dxf\Redist\DirectX8 folder on the Microsoft® DirectX® SDK disk into the root path of your setup program. This folder was not copied to your development computer when you installed the SDK, so you have to get it from the original disk.


Customizing Setup

Microsoft® DirectSetup® enables you to define a callback function for customizing the Microsoft DirectX® setup process. In the DirectSetup documentation, this callback function is referred to as DirectXSetupCallbackFunction, but you can give it any name.

If a callback function is not provided by the setup program, the DirectXSetup function displays status and error information in a dialog box and obtains user input by calling the Microsoft Win32® MessageBox function. If a callback is provided, the information that would have been used to create the status dialog or message box is instead passed to the callback. The callback function is called once for each DirectX component and device driver that can be installed or upgraded.

You can use the callback function to do the following:

  • Employ a custom interface. Your setup program might display messages in ways other than by using MessageBox or standard Microsoft Windows® dialog boxes. The callback function enables you to integrate messages for the DirectX component of your installation into your own interface.
  • Update a progress indicator.
  • Suppress the display of status and error messages. Designers of programs for novice users might want to suppress error messages and let the setup program handle errors and make upgrade choices silently. This approach requires a greater development effort for the setup program, but it might be appropriate for the target audience.

The following topics help you customize your setup:

  • Creating a DirectSetup Callback Function
  • Setting the Callback Function
  • Using Upgrade Flags in the Callback Function
  • Overriding Defaults in the Callback Function


Creating a DirectSetup Callback Function

To customize the setup process, first create a callback function that conforms to the DirectXSetupCallbackFunction prototype, as in the following declaration:

DWORD WINAPI DirectXSetupCallbackFunction(
        DWORD dwReason,
        DWORD dwMsgType,
        LPSTR szMessage,
        LPSTR szName,
        void *pInfo);

In this example, adapted from the Dinstall sample application, the name of the function is the same as that of the prototype, but this is optional. The parameter names differ slightly from those in the prototype declared in the Dsetup.h header file and are used throughout the following discussion.

Parameters

The dwReason parameter indicates why the callback function has been called. The possible values are listed and explained in the reference for DirectXSetupCallbackFunction.

The dwMsgType parameter receives flags equivalent to those that Microsoft® DirectSetup® would, by default, pass to MessageBox, such as those controlling which buttons and icons are displayed. Of special interest are the button flags, which you use to determine what return values are expected. If this value is 0, the event never requires user input, and DirectSetup normally displays a status message.

The szMessage parameter receives the same text that DirectSetup would otherwise pass to the status dialog box or to MessageBox.

When a driver is a candidate for upgrading, its name is passed in the szName parameter, and pInfo points to information about how the upgrade is to be handled—for example, whether DirectSetup recommends that the old driver be kept or upgraded. For more information, see Using Upgrade Flags in the Callback Function.

The way your callback function interprets the parameters is entirely up to you. Typically, you would choose which messages to display (based on dwReason) and when to present the user with alternatives, and you would modify the interface accordingly.

Return Value

The value returned by your callback function must conform to the following rules:

  • When dwMsgType is 0, the return value must be IDOK. In this case, there are no choices to be made by the user. (Your application, of course, is free to display a status message, even though no input is required.)
  • If dwMsgType is nonzero, the return value must be the same as would have been returned by MessageBox, given the equivalent choice by the user.

To determine the appropriate return value in the second case, test dwMsgType for the buttons that would normally have been put in a message box. The following example, from the GetReply function in Dinstall, shows how this is done:

/* The global g_wReply identifies the custom dialog button
   that has been selected by the user. */

switch (dwMsgType & 0x0000000F)
{
   / * There would normally have been an OK and a Cancel button.
       IDBUT1 is equivalent to the OK button. If the user did not
       choose that, it was a Cancel. */
    case MB_OKCANCEL:
        wDefaultButton = (g_wReply == IDBUT1) ? IDOK : IDCANCEL;
        break;

    / * And so on with the other button combinations. */
    case MB_OK:
        wDefaultButton = IDOK;
        break;
    case MB_RETRYCANCEL:
        wDefaultButton = (g_wReply == IDBUT1) ? IDRETRY : IDCANCEL;
        break;
    case MB_ABORTRETRYIGNORE:
        if (g_wReply == IDBUT1)
            wDefaultButton = IDABORT;
        else if (g_wReply == IDBUT2)
            wDefaultButton = IDRETRY;
        else
            wDefaultButton = IDIGNORE;
        break;
    case MB_YESNOCANCEL:
        if (g_wReply == IDBUT1)
            wDefaultButton = IDYES;
        else if (g_wReply == IDBUT2)
            wDefaultButton = IDNO;
        else
            wDefaultButton = IDCANCEL;
        break;
    case MB_YESNO:
        wDefaultButton = (g_wReply == IDBUT1) ? IDYES : IDNO;
        break;
    default:
        wDefaultButton = IDOK;
}

This routine translates button clicks from the custom interface into the equivalent button identifiers in the standard dialog box that DirectSetup would otherwise create. The wDefaultButton variable is set to the identifier of the equivalent standard dialog box button, and this value is ultimately returned from the callback function.

You do not necessarily have to give the user a choice, even when dwMsgType is nonzero. You might decide, for example, to upgrade drivers automatically even if DirectSetup would normally ask for confirmation from the user. The Dinstall sample does this when the user has asked to see only problem messages and the driver upgrade is considered safe, as follows:

case DSETUP_CB_UPGRADE_SAFE:
    switch (dwMsgType & 0x0000000F)
    {
        case MB_YESNO:
        case MB_YESNOCANCEL:
            return IDYES;
        case MB_OKCANCEL:
        case MB_OK:
        default:
            return IDOK;
    }
    break;

The callback function returns either IDYES or IDOK, depending on which button would have represented a positive choice in a dialog box asking the user whether or not the upgrade should proceed.


Setting the Callback Function

Before calling DirectXSetup, notify Microsoft® DirectSetup® that you want to use a callback by calling the DirectXSetupSetCallback function, passing a pointer to the callback as a parameter. The following example shows how this is done:

DirectXSetupSetCallback(
        (DSETUP_CALLBACK) DirectXSetupCallbackFunction);


Using Upgrade Flags in the Callback Function

When the application-defined callback function DirectXSetupCallbackFunction is called by the DirectXSetup function, it is passed a parameter that contains the reason that the callback function was invoked. If the reason is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE, the pInfo parameter points to a DSETUP_CB_UPGRADEINFO structure containing flags that summarize the DirectXSetup function recommendations on how to perform the upgrade of Microsoft® DirectX® components and drivers. The structure member containing the flags is called UpgradeFlags.

The flags fall into the following categories:

Primary Upgrade Flags
These flags are mutually exclusive. One of them is always present in the UpgradeFlags structure member. You can extract it by performing a bitwise AND operation with DSETUP_CB_UPGRADE_TYPE_MASK.

DSETUP_CB_UPGRADE_FORCE

DSETUP_CB_UPGRADE_KEEP

DSETUP_CB_UPGRADE_SAFE

DSETUP_CB_UPGRADE_UNKNOWN

Secondary Upgrade Flags
Either one or both of these flags can be present.

DSETUP_CB_UPGRADE_CANTBACKUP

DSETUP_CB_UPGRADE_HASWARNINGS

Device Active Flag
This flag is present if the device whose driver is being upgraded is active. It can be combined with any of the others.

DSETUP_CB_UPGRADE_DEVICE_ACTIVE

Device Class Flags
These flags are mutually exclusive. One of them is always present.

DSETUP_CB_UPGRADE_DISPLAY

DSETUP_CB_UPGRADE_MEDIA

In summary: every time the Reason parameter has the value DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE, the UpgradeFlags member of the structure pointed to by pInfo contains one Primary Upgrade Flag, zero or more Secondary Upgrade Flags, zero or one Device Active Flag, and one Device Class Flag.

If the UpgradeFlags member is set to DSETUP_CB_UPGRADE_KEEP, the DirectX component or device driver cannot be upgraded without causing Microsoft Windows® to cease functioning properly. The DirectXSetup function does not perform an upgrade on the component or driver.

A value of DSETUP_CB_UPGRADE_FORCE in UpgradeFlags means that the component or driver must be upgraded for Windows to function properly. The DirectXSetup function upgrades the driver or component. It is possible that the upgrade might adversely affect some programs on the system. When the DirectXSetup function detects this condition, the UpgradeFlags member is set to (DSETUP_CB_UPGRADE_FORCE | DSETUP_CB_UPGRADE_HAS_WARNINGS). When this occurs, the DirectXSetup function performs the upgrade but issues a warning to the user.

Components and drivers are considered safe for upgrade if they do not adversely affect the operation of Windows when they are installed. In this case, the UpgradeFlags member is set to DSETUP_CB_UPGRADE_SAFE. It is possible that the upgrade can be safe for Windows but still cause problems for programs installed on the system. When DirectXSetup detects this condition, the UpgradeFlags member contains the value (DSETUP_CB_UPGRADE_SAFE | DSETUP_CB_UPGRADE_HAS_WARNINGS). If this condition occurs, the default action for the DirectXSetup function is not to perform the upgrade.


Overriding Defaults in the Callback Function

The application-defined function DirectXSetupCallbackFunction can override some of the default behaviors of the DirectXSetup function through its return value.

For example, the default behavior for DirectXSetup is not to install a component if the upgrade type in the structure pointed to by the pInfo parameter is set to (DSETUP_CB_UPGRADE_SAFE | DSETUP_CB_UPGRADE_HAS_WARNINGS). In this case, the MsgType parameter of the callback function is set to (MB_YESNO | MB_DEFBUTTON2). Without a callback function, Microsoft® DirectSetup® would present the user with a dialog box whose default button was No. If the callback function does not seek user input but accepts the default, it returns IDNO. To override the default, the callback function returns IDYES. If it does override the default, the DirectXSetup function notifies the user.


Testing the Setup Program

To test the Microsoft® DirectSetup® component of your setup program, compile a version in which the DSETUP_TESTINSTALL flag is passed to the DirectXSetup function. Set up the installation directory, as described in Preparing the Setup Folder.

When you run your setup program, DirectSetup goes through the motions of installing Microsoft DirectX®, including calls to a callback function if you have provided one, without actually installing any components.


Enabling AutoPlay

If you are building an AutoPlay compact disc title, copy the Autorun.inf file in the root directory of the Microsoft® DirectX® SDK compact disc to the root of your application directory. This text file contains the following information:

[autorun]
OPEN=SETUP.EXE

If your application's setup program is called Setup.exe, you do not have to make any changes to this file; otherwise, edit this file to contain the name of your setup program.


Installing DirectX for Visual Basic Applications

Although you can use the Microsoft® DirectSetup® functions in your Microsoft Visual Basic® application by declaring references to the functions in your module, the recommended method is to use the Application Wizard. To distribute your application through a compact disc, follow these steps.

Distributing your Visual Basic application

  1. Start the Application Wizard.
  2. Remove DxVBLib.dll from the dependency list.
  3. Add all the files in the Redist folder from the Microsoft DirectX® SDK CD located in \Dxf\Redist\Directx7 for retail and \Dxf\Debug for debug.
  4. Click Finish to exit the Application Wizard.
  5. Overwrite Setup1.exe (created by the Application Wizard) with Setup1.exe from the support folder on the DirectX SDK CD.
  6. If you are using Visual Basic 5.0, use the compress utility to compress Setup1.exe to Setup1.ex_. If you are developing on Visual Basic 6.0, run the batch file created by the Application Wizard.

The files are now ready to be distributed through a compact disc.


DirectSetup Reference

This section contains reference information for the Microsoft® DirectSetup® API elements. Reference material is divided into the following categories:

  • Functions
  • Structures
  • Return Values

This reference section is mainly used when programming in C++; for Microsoft DirectX® for Microsoft Visual Basic® setup information, see Installing DirectX for Visual Basic Applications.


Functions

This section contains information on the following global functions used with Microsoft® DirectSetup®:

  • DirectXRegisterApplication
  • DirectXSetup
  • DirectXSetupCallbackFunction
  • DirectXSetupGetVersion
  • DirectXSetupSetCallback
  • DirectXUnRegisterApplication


DirectXRegisterApplication

Registers an application as one designed to work with DirectPlayLobby.

int WINAPI DirectXRegisterApplication(
  HWND hWnd,
  LPDIRECTXREGISTERAPP lpDXRegApp
);

Parameters

hWnd
Handle of the parent window. If this parameter is set to NULL, the desktop is the parent window.
lpDXRegApp
Address of the DIRECTXREGISTERAPP structure that contains the registry entries that are required for the application to function properly with DirectPlayLobby.

Return Values

If this function succeeds, it returns TRUE.

If it fails, it returns FALSE. Call the GetLastError function to get extended error information.

Remarks

The DirectXRegisterApplication function has to have both Dsetup.dll and Dsetup32.dll. These files are not installed on the system, but they are included in the SDK.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

See Also

DirectXUnRegisterApplication


DirectXSetup

Installs one or more Microsoft® DirectX® components.

int WINAPI DirectXSetup(
  HWND  hWnd,
  LPSTR lpszRootPath,
  DWORD dwFlags
);

Parameters

hWnd
Handle of the parent window for the setup dialog boxes.
lpszRootPath
Address of a string that contains the root path of the DirectX component files. This string must specify a full path to the directory that contains the files Dsetup.dll, and Dsetup32.dll, as well as a "DirectX" (this name is not case sensitive) directory containing redistributable files. If this value is NULL, the current working directory is used.
dwFlags
One or more flags indicating which DirectX components should be installed. A full installation (DSETUP_DIRECTX) is recommended.
DSETUP_D3D | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DDRAW | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DDRAWDRV | Not used in DirectX 8.0.
DSETUP_DINPUT | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DIRECTX | Installs DirectX run-time components, as well as DirectX-compatible display and audio drivers.
DSETUP_DIRECTXSETUP | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DPLAY | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DPLAYSP | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DSOUND | Obsolete. DirectX programs that use this flag install all DirectX components.
DSETUP_DSOUNDDRV | Not used in DirectX 8.0.
DSETUP_DXCORE | Installs DirectX run-time components. Does not install DirectX-compatible display and audio drivers.
DSETUP_TESTINSTALL | Performs a test installation. Does not install new components.
DSETUP_USEROLDERFLAG | Enables the return of –14, which means that the installed version of DirectX is newer than the version being installed.

Return Values

If this function succeeds, it returns one of the following success codes:

DSETUPERR_SUCCESS | Success.
DSETUPERR_SUCCESS_RESTART | Success, but the user must restart the system for the changes to take effect.

If it fails, it returns an error value. For a list of possible return values, see Return Values.

Remarks

Before using the DirectXSetup function in your setup program, ensure that there is at least 15 MB of available disk space on the system. This is the maximum space required for DirectX to set up the appropriate files. If the system already contains the DirectX files, this space is not needed.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.


DirectXSetupCallbackFunction

A placeholder name for an optional callback function supplied by the setup program. If present, it is called once for each step in the setup process.

DWORD DirectXSetupCallbackFunction(
  DWORD  Reason,
  DWORD  MsgType,
  char  *szMessage,
  char  *szName,
  void  *pInfo
);

Parameters

Reason
Reason for the callback. It can be one of the following values:
DSETUP_CB_MSG_BEGIN_INSTALL
DirectXSetup is about to begin installing Microsoft® DirectX® components and device drivers.
DSETUP_CB_MSG_BEGIN_INSTALL_DRIVERS
DirectXSetup is about to begin installing device drivers.
DSETUP_CB_MSG_BEGIN_INSTALL_RUNTIME
DirectXSetup is about to begin installing DirectX components.
DSETUP_CB_MSG_BEGIN_RESTORE_DRIVERS
DirectXSetup is about to begin restoring previous drivers.
DSETUP_CB_MSG_CANTINSTALL_BETA
A prerelease Beta version of the Microsoft Windows® 95 operating system was detected. The DirectX component or device driver cannot be installed.
DSETUP_CB_MSG_CANTINSTALL_NOTWIN32
The operating system detected is not a Windows 32-bit operating system. DirectX is not compatible with Windows 3.x.
DSETUP_CB_MSG_CANTINSTALL_NT
The DirectX component or device driver cannot be installed on versions of the Microsoft Windows NT® operating system prior to version 4.0.
DSETUP_CB_MSG_CANTINSTALL_UNKNOWNOS
The operating system is unknown. The DirectX component or device driver cannot be installed.
DSETUP_CB_MSG_CANTINSTALL_WRONGLANGUAGE
The DirectX component or device driver is not localized to the language being used by Windows.
DSETUP_CB_MSG_CANTINSTALL_WRONGPLATFORM
The DirectX component or device driver is for another type of computer.
DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE
Driver is being considered for upgrade. Verification from user is recommended.
DSETUP_CB_MSG_FILECOPYERROR
Setup of the DirectX component or device driver file has failed during the copy process.
DSETUP_CB_MSG_INTERNAL_ERROR
An internal error has occurred. Setup of the DirectX component or device driver has failed.
DSETUP_CB_MSG_NOMESSAGE
No message to be displayed. The callback function should return.
DSETUP_CB_MSG_NOTPREINSTALLEDONNT
The DirectX component or device driver cannot be installed on the version of Microsoft Windows NT or Microsoft Windows 2000 in use.
DSETUP_CB_MSG_OUTOFDISKSPACE
Setup of the DirectX component has failed due to lack of disk space.
DSETUP_CB_MSG_PREINSTALL_NT
DirectX is already installed on the version of Windows NT or Windows 2000 in use.
DSETUP_CB_MSG_SETUP_INIT_FAILED
Setup of the DirectX component or device driver has failed.
MsgType
Flags that control the display of a message box. These flags can be passed to the MessageBox function. An exception is when MsgType is 0. In that case, the setup program can display status information but should not wait for input from the user.
szMessage
Pointer to a localized character string containing error or status messages that can be displayed in a dialog box created with the MessageBox function.
szName
NULL unless the Reason parameter is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE. In that case, szName contains a pointer to the name of the driver to be upgraded.
pInfo
Pointer to the address of a structure containing upgrade information. When Reason is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE, the setup program is upgrading a driver and asking the user whether the upgrade should take place. In this case, pInfo points to a DSETUP_CB_UPGRADEINFO structure containing information about the upgrade.

Return Values

The return value should be the same as the value that would be returned by the MessageBox function, with one exception. If this function returns 0, the DirectXSetup function performs the default action for upgrade of the DirectX component or driver.

Remarks

The name of DirectXSetupCallbackFunction is supplied by the setup program. The DirectXSetupSetCallback function is used to pass the address of the callback function to DirectSetup.

If MsgType is 0, the setup program can display status information, but it should not wait for user input. In this case, the function returns IDOK.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: User-defined.

See Also

MessageBox, DirectXSetupSetCallback, Customizing Setup


DirectXSetupGetVersion

Retrieves the version number of the Microsoft® DirectX® components that are currently installed.

INT WINAPI DirectXSetupGetVersion(
  DWORD  *pdwVersion,
  DWORD  *pdwRevision
);

Parameters

pdwVersion
Pointer to the address of a variable to receive the version number. This parameter can be NULL if the version number is not wanted.
pdwRevision
Pointer to the address of a variable to receive the revision number. This parameter can be NULL if the revision number is not wanted.

Return Values

If the function succeeds, it returns nonzero.

If it fails, it returns 0.

Remarks

The DirectXSetupGetVersion function can be used to retrieve the version and revision numbers before or after the DirectXSetup function is called. If it is called before DirectXSetup is invoked, it gives the version and revision numbers of the DirectX components that are currently installed. If it is called after DirectXSetup is called, but before the computer is restarted, it gives the version and revision numbers of the DirectX components that take effect after the computer is restarted.

The version number in the pdwVersion parameter is composed of the major version number and the minor version number. The major version number is in the 16 most significant bits of the DWORD when this function returns. The minor version number is in the 16 least significant bits of the DWORD when this function returns. The version numbers can be interpreted as follows:

DirectX version | Value pointed to by pdwVersion
DirectX 1 | 0x00000000
DirectX 2 | 0x00000000
DirectX 3 | 0x00000000
DirectX 5.0 | 0x00040005
DirectX 6.0 | 0x00040006
DirectX 7.0 | 0x00040007
DirectX 8.0 | 0x00040008

There is no version 4 of DirectX.

The version number in the pdwRevision parameter is composed of the release number and the build number. The release number is in the 16 most significant bits of the DWORD when this function returns. The build number is in the 16 least significant bits of the DWORD when this function returns.

The following sample code fragment demonstrates how the information returned by DirectXSetupGetVersion can be extracted and used.

DWORD dwVersion;
DWORD dwRevision;
if (DirectXSetupGetVersion(&dwVersion, &dwRevision))
{
    printf("DirectX version is %d.%d.%d.%d\n",
           HIWORD(dwVersion), LOWORD(dwVersion),
           HIWORD(dwRevision), LOWORD(dwRevision));
}

Version and revision numbers can be concatenated into a 64-bit quantity for comparison. The version number is in the 32 most significant bits and the revision number is in the 32 least significant bits.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

See Also

DirectXSetup


DirectXSetupSetCallback

Sets a pointer to a callback function that is periodically called by DirectXSetup. The callback function can be used for setup progress notification and to implement a custom user interface for an application's setup program. For more information, see DirectXSetupCallbackFunction. If a setup program does not provide a callback function, DirectXSetupSetCallback is not invoked.

INT WINAPI DirectXSetupSetCallback(
  DSETUP_CALLBACK  Callback
);

Parameters

Callback
Address of a callback function.

Return Values

Currently returns 0.

Remarks

To set a callback function, DirectXSetupSetCallback must be called before DirectXSetup is called.

The name of the callback function passed to DirectXSetupSetCallback is supplied by the setup program. However, it must match the prototype given in DirectXSetupCallbackFunction.

Requirements

Windows NT/2000: Requires Windows NT 4.0 SP3 or later.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

See Also

DirectXSetupCallbackFunction, DirectXSetup


DirectXUnRegisterApplication

Deletes the registration of an application designed to work with DirectPlayLobby.

int WINAPI DirectXUnRegisterApplication(
  HWND   hWnd,
  LPGUID lpGUID
);

Parameters

hWnd
Handle of the parent window. Set this to NULL if the desktop is the parent window.
lpGUID
Address of a GUID that represents the Microsoft® DirectPlay® application to be unregistered.

Return Values

If the function succeeds, the return value is TRUE. This means that the registration is successfully deleted.

If the function fails, the return value is FALSE.

Remarks

The DirectXUnRegisterApplication function has to have both Dsetup.dll and Dsetup32.dll. These two files are not installed on the system, but they are included in the SDK.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.
Import Library: Use Dsetup.lib.

See Also

DirectXRegisterApplication


Structures

This section contains information about the following structures used with Microsoft® DirectSetup®:

  • DIRECTXREGISTERAPP
  • DSETUP_CB_UPGRADEINFO

Note The memory for all Microsoft DirectX® structures must be initialized to 0 before use. In addition, all structures that contain a dwSize member must set the member to the size of the structure, in bytes, before use.


DIRECTXREGISTERAPP

Contains the registry entries needed for applications designed to work with DirectPlayLobby.

typedef struct _DIRECTXREGISTERAPP {
    DWORD  dwSize;
    DWORD  dwFlags;
    LPSTR  lpszApplicationName;
    LPGUID lpGUID;
    LPSTR  lpszFilename;
    LPSTR  lpszCommandLine;
    LPSTR  lpszPath;
    LPSTR  lpszCurrentDirectory;
} DIRECTXREGISTERAPP, *PDIRECTXREGISTERAPP, *LPDIRECTXREGISTERAPP;

Members

dwSize
Size of the structure. This member must be initialized to the size of the DIRECTXREGISTERAPP structure.
dwFlags
Reserved for future use.
lpszApplicationName
Name of the application.
lpGUID
Globally unique identifier (GUID) of the application.
lpszFilename
Name of the executable file to be called.
lpszCommandLine
Command-line arguments for the executable file.
lpszPath
Path of the executable file.
lpszCurrentDirectory
Current directory. This is typically the same as lpszPath.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.


DSETUP_CB_UPGRADEINFO

Passed as a parameter to the application-defined DirectXSetupCallbackFunction. It contains valid information only when the Reason parameter is DSETUP_CB_MSG_CHECK_DRIVER_UPGRADE. Callback functions can use it to get status information on the upgrade that is about to be done.

typedef struct _DSETUP_CB_UPGRADEINFO {
    DWORD UpgradeFlags;
} DSETUP_CB_UPGRADEINFO;

Members

UpgradeFlags
One or more flags indicating the status of the upgrade. The following values are defined:
DSETUP_CB_UPGRADE_CANTBACKUP
The old system components cannot be backed up. Upgrade can be performed, but the components or drivers cannot be restored later.
DSETUP_CB_UPGRADE_DEVICE_ACTIVE
The device is currently in use.
DSETUP_CB_UPGRADE_DEVICE_DISPLAY
The device driver being upgraded is for a display device.
DSETUP_CB_UPGRADE_DEVICE_MEDIA
The device driver being upgraded is for a media device.
DSETUP_CB_UPGRADE_FORCE
Microsoft® Windows® might not function correctly if the component is not upgraded. The upgrade will be performed.
DSETUP_CB_UPGRADE_HASWARNINGS
Microsoft DirectSetup® can upgrade the driver for this device, but doing so might affect one or more programs on the system. The szMessage parameter contains the names of the programs that might be affected. Upgrade not recommended.
DSETUP_CB_UPGRADE_KEEP
The system might fail if this device driver is upgraded. Upgrade not allowed.
DSETUP_CB_UPGRADE_SAFE
DirectSetup can safely upgrade this device driver. Upgrade recommended. A safe upgrade will not adversely affect the operation of Windows. Some hardware-dependent programs might be adversely affected.
DSETUP_CB_UPGRADE_UNKNOWN
DirectSetup does not recognize the existing driver for this device. This value occurs frequently. Upgrading might adversely affect the use of the device. It is strongly recommended that the upgrade not be performed.

Remarks

Use the DSETUP_CB_UPGRADE_TYPE_MASK value to extract the upgrade type (FORCE, KEEP, SAFE, or UNKNOWN) from UpgradeFlags.

Requirements

Windows NT/2000: Requires Windows 2000.
Windows 95/98: Requires Windows 95 or later. Available as a redistributable for Windows 95.
Header: Declared in Dsetup.h.

See Also

DirectXSetupCallbackFunction


Return Values

The DirectXSetup function can return the following values. It can also return a standard COM error.

DSETUPERR_SUCCESS
Setup was successful, and no restart is required.
DSETUPERR_SUCCESS_RESTART
Setup was successful, and a restart is required.
DSETUPERR_BADSOURCESIZE
A file's size could not be verified or was incorrect.
DSETUPERR_BADSOURCETIME
A file's date and time could not be verified or were incorrect.
DSETUPERR_BADWINDOWSVERSION
Microsoft® DirectX® does not support the Microsoft Windows® version on the system.
DSETUPERR_CANTFINDDIR
The setup program could not find the working directory.
DSETUPERR_CANTFINDINF
A required .inf file could not be found.
DSETUPERR_INTERNAL
An internal error occurred.
DSETUPERR_NEWERVERSION
A later version of DirectX has already been installed. Applications can safely ignore this error because the newer version is not overwritten and is fully compatible with applications written for earlier versions.
DSETUPERR_NOTADMIN
The current user does not have administrative privileges. On Windows 2000 systems, the user may need administrative privileges for some setup operations.
DSETUPERR_NOCOPY
A file's version could not be verified or was incorrect.
DSETUPERR_NOTPREINSTALLEDONNT
The version of Windows NT® or Windows 2000 on the system does not contain the current version of DirectX. An older version of DirectX might be present, or DirectX might be absent altogether.
DSETUPERR_OUTOFDISKSPACE
The setup program ran out of disk space during installation.
DSETUPERR_SOURCEFILENOTFOUND
One of the required source files could not be found.
DSETUPERR_UNKNOWNOS
The operating system on your system is not currently supported.
DSETUPERR_UNSUPPORTEDPROCESSOR
The processor type is unsupported. DirectX 8 supports only Pentium or K6-compatible or higher processors.
DSETUPERR_USERHITCANCEL
The Cancel button was pressed before the application was fully installed.


DirectSetup Samples

The following sample programs demonstrate the use and capabilities of Microsoft® DirectSetup®:

  • Dinstall Sample (C/C++)
  • DXVBSetup Sample (Microsoft Visual Basic®)

Although DirectX samples include Microsoft Visual C++® project workspace files, you might need to verify other settings in your development environment to ensure that the samples compile properly. For more information, see Compiling DirectX Samples and Other DirectX Applications.


Dinstall Sample

Description

Dinstall is an example of how to use Microsoft® DirectSetup® functions to install the Microsoft DirectX® subsystem. It shows how to use a callback function to present messages and get user input through a custom interface, in this case a simple modeless dialog box.

Path

Source: (SDK root)\Samples\Multimedia\Misc\DXInstall

User's Guide

  1. Copy the entire contents of the \Redist\DirectX8 folder from the DirectX SDK CD into the same folder as Dinstall.exe.
  2. In your development environment, set the working directory to this folder as well. (In Microsoft Visual C++®, this setting is on the Debug page of the Project Settings dialog box.)
  3. Run the program and, on the File menu, click Start Install. DirectSetup performs a simulated installation of DirectX (see Programming Notes below) and advises you of its progress in a modeless dialog box. You can use the Options menu to change the level of messages shown. However, if you are performing only a simulated installation, you will never see problem or update messages.
  4. On the File menu, click GET Version. The program shows the version and revision number of DirectX currently installed on the system.

Programming Notes

By default, the program passes DSETUP_TESTINSTALL to the DirectXSetup function. This means that no files are copied and the registry is not modified. To perform a real installation, delete this flag from the call.

Dinstall employs a callback function to monitor the progress of installation and intercept messages. Depending on the user's preferred warning level, as tracked in g_fStatus, messages may be ignored or presented to the user in a modeless dialog box. If user input is required, the appropriate buttons are displayed and the GetReply function monitors the message queue until one of the buttons is pressed.


DXVBSetup Sample

This section pertains only to application development in Microsoft® Visual Basic®. See Dinstall Sample.


Glossary

This section provides a glossary of technical terms used in the Microsoft® DirectX® SDK documentation.

A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z


A

alpha channel
The opacity of an image defined by an alpha value per pixel interleaved with the color components (for example, ARGB), an alpha value per pixel stored in a separate alpha surface, or a constant alpha value for the entire surface.
alpha color component
The portion of a 32-bit color that determines its opacity. In this case, the alpha value per pixel is interleaved with the color components (for example, ARGB). Less commonly, this term can also refer to an image with an alpha value per pixel stored in a separate alpha surface.
alpha constant
A level of opacity (alpha value) applied to an entire surface.
alpha edge blend
A particular use of alpha blending (and alpha channel information) to reduce aliasing by blending edges, based on pixel coverage information.
ambient
Description of a light source that illuminates everything in a scene, regardless of the orientation, position, and surface characteristics of the objects in the scene. Because it illuminates a scene with equal strength everywhere, the position and orientation of the frame that an ambient light source is attached to are inconsequential. Multiple ambient light sources are combined within a scene.
anisotropic filtering
A mipmap filtering mode that compensates for anisotropic distortion.
anisotropy
The distortion visible in the image of a 3-D object whose surface is oriented at an angle with respect to the viewing plane. The anisotropy is measured as the elongation (length divided by width) of a screen pixel that is inverse-mapped into texture space.
array object
A group of objects organized into an array. Array objects make it simpler to apply operations to the entire group. The COM interfaces that enable you to work with array objects contain the GetElement and GetSize methods. These methods retrieve a pointer to an element in the array and the size of the array, respectively.
attach
To connect multiple DirectDrawSurface objects into complex structures, such as those needed to support 3-D page flipping with z-buffers. Attachment is not bidirectional, and a surface cannot be attached to itself. Emulated surfaces (in system memory) cannot be attached to nonemulated surfaces. Unless one surface is a texture map, the two attached surfaces must be the same size.
attached
Physically connected to the system. A device may be installed but not currently attached.
attack
The period at the beginning of a force-feedback effect when the magnitude is reaching its basic or sustain level.


B

back buffer
A nonvisible surface to which bitmaps and other images can be drawn while the front buffer displays the currently visible image.
back clipping plane
The far boundary of a viewing frustum beyond which objects are not rendered. See also front clipping plane.
bank select
A MIDI controller that enables instruments to be chosen from different groups or banks, each identified by a 2-byte code.
billboard
A primitive inserted into a 3-D scene that is oriented so that one face is toward the viewer. A texture, usually an animated sprite, is applied to the billboard to give the appearance of a 3-D object in the scene.
billboarding
A 2-D technique of simulating the appearance of a 3-D object in a scene. An application inserts a primitive, typically rectangular, into the scene, orients it so that one face is toward the viewer, and applies a texture or a set of textures. The texture or set of textures gives the appearance of an animated 3-D object.
blend factor
The description of how each color component is blended in texture blending.
blend mode
The algorithm used to determine how a texture is blended with the colors of the surface to which the texture is applied.
blending stage
One step in a texture cascade. A blending stage includes one texture and a set of texture-blending operations that are used when blending multiple textures.
blit
A bit block transfer.
bounds checking
The process of checking that an on-screen image is displayed within the bounds of the screen.
bump mapping
A technique for simulating the appearance of rough surfaces in 3-D scenes. Variations in depth are stored in a texture and applied to a primitive, using standard texture-blending techniques.


C

camera
A Direct3DRMFrame object used by the viewport to define the viewing position and direction. The viewport renders only what is visible along the positive z-axis of the camera frame, with the up direction in the direction of the positive y-axis.
camera space
The frame of reference in which the viewer is at the origin, looking in the direction of the positive z-axis. Objects are transformed from world space to camera space by using the view transformation.
client/server session
A Microsoft® DirectPlay® session in which only the server stores the session's complete state, and each client has only a subset of the session's state. Each client receives only the information that is relevant to that computer from the server. When one computer changes something, it propagates the change to the server. The server then determines which clients it must inform of the change. See also peer-to-peer session.
clip list
A series of rectangles that describes the visible areas of the surface. The clip list cannot be set if a window handle is already associated with the DirectDrawClipper object.
clipper
A DirectDrawClipper object.
codec
Represents the phrase "compressor and decompressor."
collision detection
The process of determining if any pixels for two images share the same location on the screen. See also hit detection.
color key
A value indicating the color to be used for transparent or translucent effects. For example, when using a hardware blitter, all the pixels of a rectangular area are blitted, except the value that was set as the color key; this creates nonrectangular sprites on a surface.
color space
A model for representing color as three or more coordinates. Color-space models map color components onto a Cartesian coordinate system in three or more dimensions. A color space may use any of several types of color encoding and visualizing. The two most common types of color space models are RGB and YUV.
color-space conversion
A technique for converting a color in one color space to another color space. Typically, this conversion is from YUV colors from a video source to RGB for display.
color table
An array of n color values (normally RGB triples).
complex surface
The collective term for several DirectDrawSurface objects, all of which are attached to a root surface. The complex-surface structure can be destroyed only by destroying the root.
control segment
Musical segment that controls certain aspects of playback. Normally it is the primary segment, but a secondary segment can be designated as the control segment.
culling
Skipping a back face of a 3-D primitive during the rendering process.
curve
In Microsoft® DirectMusic®, a continuous series of events with a start and end value, such as volume fade.


D

dark light
A light source that removes illumination from a scene Dark light is created by specifying negative values for the colors of the light.
DCI
Display Control Interface. Defined by the Intel and Microsoft® corporations, DCI is an interface that offers improved graphics performance as a result of direct video memory access.
deadband
A zone around the offset of a force-feedback axis at which a condition is not active.
dead zone
An area within the physical range of an axis where the axis is considered to be at the center.
decal
A texture that is rendered directly, as a visual. Decals are rendered into a viewport-aligned rectangle.
destination color key
The color that (in the case of blitting) is replaced or (in the case of overlays) is covered on the destination surface.
device window
A visible application window that Microsoft® DirectDraw® uses for display. Applications can have a device window for each display device attached to a given computer. See also focus window.
directional
Description of a light source that is attached to a frame but appears to illuminate all objects with equal intensity, as if it were at an infinite distance from the objects. Directional light has orientation but no position, and it is commonly used to simulate distant light sources, such as the sun.
DirectPlay address
A data format that Microsoft® DirectPlay® uses to pass addressing information between lobby servers, applications, DirectPlay, and service providers. A DirectPlay address is a sequence of variable-length data chunks tagged with a globally unique identifier (GUID) that supplies all the address information needed by DirectPlay. Examples of address information are: the network address of a server, the network address of a player, the e-mail name of a player, and the network address of a session.
DLS
Downloadable Sounds. A standard for synthesizing wave sounds from digital samples stored in software. The DLS level 1 and level 2 standards are published by the MIDI Manufacturers Association.
DMO
Microsoft® DirectX® Media Object. A COM object that processes multimedia data streams from buffers allocated by the client.


E

emissive property
The material property that determines whether a material emits light. The emissive property of a material is one of two properties that determines how the material reflects light. See also specular property.
emissive setting
See emissive property.
enable frame
The frame to which a light applies.
envelope
In force feedback, a set of values that defines the shape of an effect by modifying the magnitude at the beginning (attack) and end (fade).

In audio, a set of values that defines the shape of the amplitude or pitch of a sound. DLS level 1 defines a four-segment envelope: attack, decay, sustain, and release (ADSR). DLS level 2 defines six segments: delay, attack, hold, decay, sustain, and release (DAHDSR).

even field
The second field comprising a video frame in an odd/even field set. Also known as field 2.
execute buffer
A fully self-contained, independent packet of information that describes a 3-D scene. An execute buffer contains a vertex list followed by an instruction stream. The instruction stream consists of operation codes, or opcodes, and the data that is operated on by those opcodes.


F

face
A single polygon in a mesh.
fade
The period between the central, or sustain, portion of a force-feedback effect and its end.
falloff
Light attenuation between a spotlight's inner and outer cones.
field
Data for one-half of a single video frame within a video stream. Each field contains data for every other scan line. Fields are sent and received in odd field, even field order.
field polarity
Quality determining whether a field is an even field or an odd field. In odd fields the trailing edge of the VREF does not occur during a scan line. In even fields the trailing edge of the VREF occurs during a scan line.
flimmering
A shimmering appearance on 3-D primitives that results from a poor separation of z values when doing decaling. Some pixels from the back texture are rendered onto the front texture and vice versa.
flip
The process of swapping the addresses associated with the back and front buffers. This effectively swaps the image in the back buffer to the front buffer, thus displaying the image.
flipping chain
A series of surfaces attached to each other that can be flipped. See also flip.
flipping surface
Any piece of memory that can be flipped. See also flip.
focus window
An application window, visible or not visible, that Microsoft® DirectDraw® uses to hook window messages. The focus window's message handler receives input messages forwarded by DirectDraw. Applications can have only one focus window. See also device window.
frame
An invisible box that provides a frame of reference for objects in a scene. Objects can be placed in a scene by specifying their spatial relationship to a relevant reference frame. Visual objects take their positions and orientations from frames.

In a movie or animation, a single image.

front buffer
A rectangle of memory that is translated by the graphics adapter and displayed on the monitor or other output device.
front clipping plane
The near boundary of a viewing frustum. Any object closer to the camera than the front clipping plane is not rendered. The height of the front clipping plane defines the field of view. See also back clipping plane.


G

genlocking
The process of synchronizing one video signal with another. Because they are synchronized, the genlocked signal can be mixed with the original signal, enabling dissolves, wipes, and other transition effects.
grid
Subdivision of a beat. The number of grids per beat is part of the Microsoft® DirectMusic® time signature.
groove level
A value given to music during style playback. The groove level determines which patterns can be selected at any given time. The author assigns a range of groove levels to each pattern.
group
A logical collection of players. Microsoft® DirectPlay® supports groups within a session. By creating a group of players, an application can send a single message to the group, and all players in the group receive the message. A group is the means by which a network's multicast capabilities are exposed to the application.

Groups can be used to organize players in a session. A player can belong to more than one group. DirectPlay provides methods for administering groups and their membership.


H

HAL
Hardware abstraction layer. The HAL consists of hardware and device driver mechanisms that insulate applications from device-specific implementation details. If a capability requested by an application is not implemented by the current hardware, the capability is emulated by the software.
hardware blitter
A hardware component, built into the display adapter, that performs efficient blit operations.
HEL
Hardware emulation layer. The HEL provides software-based emulation of features that are not present in hardware.
HID
Human Interface Device. A USB class representing devices that enable a human to control a computer.
hit detection
See collision detection.
host
In Microsoft® DirectPlay®, a virtual player whose ID is DPID_SYSMSG. The host manages system messages and messages sent to all players in a session.
HREF
Horizontal refresh. In a video stream, the HREF is active to signal that the display is to begin a new scan line. See also VREF.
HRTF
Head-related transfer function. A mathematical representation of the effect of the listener's physiology on the pitch and timing of sounds arriving from different directions.


I

Microsoft DirectX 8.0 (C++)

I, J, K

index palette
A DirectDrawPalette object whose entries are indexes into another palette object.
IPX service provider
A service provider that uses Windows Sockets to communicate over a local area network (LAN) using the Internetwork Packet Exchange (IPX) protocol. The service provider supports only nonguaranteed messaging. A single computer can host only one Microsoft® DirectPlay® session using IPX.
IRE scale
International Radio Engineers scale. A scale of values ranging from 0 to 100 that defines the brightness level of a broadcast video signal. The spectrum of low-to-high IRE values describes increasing brightness levels of a video signal. At 7.5 IRE brightness—the black cut-off threshold for a National Television System Committee (NTSC) signal—the electron guns of an NTSC display device are cut off and do not display images.


L

latency
A delay in response. For example, in Microsoft® DirectSound®, it is the interval between the time that a sound buffer plays and the time that the speakers actually reproduce the sound. In Microsoft DirectPlay®, it is the time that it takes for a packet to reach a given destination.
light map
A texture or group of textures that contain lighting information for a 3-D scene.
lobby-aware application
An application that, at a minimum, supports being launched from a lobby.
lobby client
Lobby management routines associated with the user's computer, including launching applications, updating the user interface, and communicating with the lobby server.
lobby provider
A client component (dynamic-link library) supplied by the developer of a lobby server. It implements communication functions with the lobby server, as requested by Microsoft® DirectPlay®.
lobby server
Lobby management routines associated with a remote server. The lobby server coordinates all the information about the users who are connected to a specific application.
lobby session
A connection to a lobby server on which clients and the server have not been specifically written to interoperate.


M

Mach bands
Bands of color that are not smoothly blended across a 3-D primitive.
material
A property that determines how a surface reflects light. A material has two components: an emissive property (whether it emits light) and a specular property, whose brightness is determined by a power setting.
mesh
A set of faces, each of which is described by a simple polygon.
mipmap
Also known as MIP map (Latin: multum in parvo, translated as "much in little"). A sequence of textures, each of which is a progressively lower-resolution, prefiltered representation of the same image. A higher-resolution image is used when a visible object is close to the viewer; as the object moves farther away (and gets smaller), lower-resolution images are used.
mixing
In Microsoft® DirectSound®, the process of combining sound buffers that are playing, and writing the result to the primary sound buffer, which supplies audio data to the sound hardware. There is no limit to the number of buffers that can be mixed, except the available processing time.
Mode X
A hybrid display mode derived from the standard VGA Mode 13. This mode allows the use of up to 256 KB of display memory (rather than the 64 KB allowed by Mode 13) by using the VGA display adapter's EGA multiple video plane system.
model coordinates
Coordinates that are relative to a local origin. See also model space and world coordinates.
model space
The frame of reference (used by model coordinates) that uses vertices relative to a single 3-D model's local origin.
multipass texture blending
The repeated rendering of a 3-D primitive while blending on a texture with each pass. This technique is widely used to achieve a variety of special effects.


N

nagling
An algorithm that causes the TCP/IP service provider to buffer small data packets into larger ones before sending. Nagling prevents a TCP/IP server from transmitting many very small packets by requiring the server to wait either until it has accumulated enough small data packets to combine them into a single large packet or until it has received an acknowledgment of the prior packet. Nagling can reduce message overhead (and decrease required bandwidth), but also causes a delay before small data packets are sent (increasing latency).
normal vector
An imaginary ray extending perpendicularly from a surface that defines the face's orientation.
NRPN
Nonregistered parameter number. Nonregistered parameters can be used for different functions by different manufacturers and are accessed through MIDI controllers. For more information, see the MIDI specification.


O

odd field
The first field comprising a video frame in an odd/even field set.
off-screen surface
A conceptually rectangular area in memory that is generally used to store bitmaps to be blitted to a back buffer before being displayed. Commonly used to store sprites.
opcode
Operation code that defines how to interpret the vertices in an execute buffer or how to change the state of the system.
overdraw
The average number of times to which a screen pixel is written.
overlay surface
A conceptually rectangular area in memory whose stored image information covers the image information of the primary surface to which it is applied. Overlays are assumed to be on top of all other screen components.
overlay z-order
Determines the order in which overlays clip each other, enabling a hardware sprite system to be implemented under Microsoft® DirectDraw®.


P

page flipping
See flip.
palette
The set of colors used by an object or application. In Microsoft® DirectX®, a DirectDrawPalette object.
palette index
An integer index into the palette table array that is used to select a particular color.
palettized surface
A DirectDrawSurface object that uses an attached palette to contain color information.
pan value
The relative volume, measured in hundredths of decibels, between the left and right audio channels.
parallel point
Description of a light source that illuminates objects with parallel light, but the orientation of the light is taken from the position of the parallel point light source. For example, two meshes on either side of a parallel point light source are lit on the side that faces the position of the source.
PChannel
Performance channel. A PChannel is a MIDI channel in a particular channel group on a particular port.
PCM
Pulse code modulation. An uncompressed wave data format in which each value represents the amplitude of the signal at the time of sampling.
peer-to-peer session
A Microsoft® DirectPlay® session in which the session's complete state is replicated on all the computers in the session. The session description data—the list of players and groups and the names and remote data associated with each session—are duplicated on every computer. When one computer changes something, it is immediately propagated to all the other computers. This is the default mode of communication for DirectPlay. See also client/server session.
perspective correction
The technique of applying a texture map to a polygon that is angled away from the camera, interpolating so that the texture is stretched onto the polygon appropriately for the apparent depth of the polygon. Microsoft® Direct3D® supplies perspective correction automatically.
pick
To search for visuals in a scene, given a 2-D coordinate in a viewport.
PID
Physical interface device. A USB class that enables humans to feel force feedback from a computer.
pitch
The distance, in bytes, between an address that represents the beginning of a bitmap line and the beginning of the next line. Do not confuse memory pitch and memory width because not all display memory is laid out as one linear block. For example, with rectangular memory, the pitch of the display memory could include the width of the bitmap plus part of a cache. See also width and stride.
player
A single participant in a Microsoft® DirectPlay® session. Each player is associated with a player ID that enables messages to be exchanged among players.
player ID
A unique number that is assigned to each participant in a Microsoft® DirectPlay® session when the participant is created. The application can exchange messages among players by using player IDs. The host is always assigned the DPID_SYSMSG player ID.
PNG
Portable Network Graphics. A non-proprietary bitmap format using lossless compression.
point light
A light source that radiates equally in all directions from its origin.
point list
The simplest 3-D primitive. A collection of unconnected points in 3-D space.
power
In the specular property of a material, the value that determines the sharpness of specular highlights. A value of 5 gives a metallic appearance, and higher values give a more plastic appearance.
primary sound buffer
An object that mixes and plays the final audio output. The primary buffer is generally used to mix sound from secondary buffers, but it can be accessed directly for custom mixing or other specialized activities.
primary surface
The area in memory containing the image being displayed on the monitor.
projection space
Frame of reference containing vertices after they are modified from their world space locations by the projection transformation. Projection space is a homogeneous cuboid space in which all vertices in a scene have x- and y-coordinates that range from –1.0 to 1.0, and a z-coordinate that ranges from 0.0 to 1.0. Projection space is sometimes referred to as post-perspective homogeneous space.
projection transformation
The application of a matrix to vertices to change them from camera space to projection space.


Q

quaternion
A fourth element added to the [x, y, z] values that define a vector. Quaternions define a 3-D axis and a rotation around that axis.


R

reference count
A control for a Component Object Model (COM) object. When an object is created, its reference count is set to 1. Every time an interface is bound to the object, its reference count is incremented; when the interface connection is destroyed, the reference count is decremented. The object is destroyed when the reference count reaches 0. All interfaces to that object are then invalid.
region
In DLS, a range of notes for which a particular digital sample is used in synthesizing an instrument's timbre.
root frame
A frame in Microsoft® Direct3D® that has no parent frame; it is at the top of a hierarchy of frames. The root frame contains the entire set of objects that make up a scene. See also scene.
RPN
Registered parameter number. Registered parameters have been assigned a function by the MIDI Manufacturers Association and can be accessed through controllers. For more information, see the MIDI specification.


S

saturation
In input and force feedback, adjustment to an axis range so that minimum or maximum values are retrieved or set before the physical extremities are reached. If the maximum value in a range is 1,000 and the maximum saturation point is set to 900, the maximum value is reached after 90 percent of the travel in that direction.
scene
The entire set of objects that make up a virtual environment, including visible objects, sounds, lights, and frames. In Microsoft® Direct3D®, the entire set of objects is contained in a root frame.
screen space
Frame of reference in which coordinates are related directly to 2-D locations in the frame buffer, to be displayed on a monitor or other viewing device. Projection space coordinates are converted to screen space coordinates, using a transformation matrix created from the viewport parameters.
secondary sound buffer
An object that manages a single sound or audio stream and plays it to the primary sound buffer.
secure session
A session in which all users have been authenticated against a database of known users before being allowed to join a session. In a secure session, all Microsoft® DirectPlay® system messages are digitally signed to verify the identity of the sender. Certain system messages that carry sensitive information are encrypted. System messages that originate from one player and need to be broadcast to all the other players in the session are first sent to the server. The server then puts its signature on the message and forwards the message to all the other computers in the session. Player-to-player messages are not signed by default and are not routed through the server.
send
(n.) A sound effect for a buffer that is applied by sending the sound data to a second buffer.
service provider
A dynamic-link library used by Microsoft® DirectPlay® to communicate over a network. The service provider contains all the network-specific code required to send and receive messages. Online services and network operators can supply service providers to use specialized hardware, protocols, communications media, and network resources.
session
In Microsoft® DirectPlay®, an instance of several applications on remote computers communicating with each other. Before an application can start communicating with other computers, it must be part of a session. An application can enumerate all the existing sessions on a network and join one of them, or it can create a new session and wait for other computers to join it. Once the application is part of a session, it can create a player and exchange messages with all the other players in the session.
sound buffer
An object that manages Microsoft® DirectSound® audio data.
source color key
A color that (in the case of blitting) is not copied to, or (in the case of overlays) not visible on, the destination.
specular property
The material property that determines how a point of light on a shiny object corresponds to the reflected light source. The specular property of a material is one of two properties that determines how a material reflects light. See also emissive property.
spotlight
A light source that emits a cone of light. Only objects within the cone are illuminated. The cone produces light of two degrees of intensity, with a central brightly lit section that acts as a point source, and a surrounding dimly lit section that merges with the surrounding deep shadow.
static buffer
A secondary sound buffer that contains an entire sound. Typically it is filled with data only once. Compare streaming buffer.
sticky focus
In Microsoft® DirectSound®, the ability to play sound buffers when the owning application does not have the input focus. For example, a DirectSound application could continue to play a sound buffer while the user is working in another application.
streaming buffer
A secondary sound buffer that contains only part of a sound. Its data must be refreshed as it is playing. Compare static buffer.
stretching
Blitting an image into a destination with different dimensions. This operation is supported directly by some hardware.
stride
Synonymous with pitch. See also width.
surface
Memory that represents visual images. This is often display memory, but it can also be system memory. See also complex surface, off-screen surface, overlay surface, and primary surface.
sustain
The period during which the basic magnitude of a force-feedback effect is attained, after the attack and before the fade.
system message
In Microsoft® DirectPlay®, a message from the player ID DPID_SYSMSG. All system messages begin with a DWORD value.


T

TCP/IP service provider
A service provider that uses Windows Sockets to communicate over the Internet or local area network (LAN), using the TCP/IP protocol. It uses User Datagram Protocol (UDP) packets for nonguaranteed messaging and TCP for guaranteed messaging. Using TCP/IP, a single computer can host multiple Microsoft® DirectPlay® sessions.
tearing
A visual artifact produced when the screen refresh rate is out of sync with an application's frame rate. The top portion of one frame is displayed at the same time as the bottom portion of another frame, with a discernible tear between the two partial images.
tessellating
Breaking an image into small square regions for processing or output.
texel
A single element in a texture. When a texture has been applied to an object, the texels rarely correspond to pixels on the screen. Applications can use texture filtering to control how the system interpolates between texels to create pixels in a scene.
texture
A rectangular array of pixels that is applied to a visual object in Microsoft® Direct3D®.
texture blending
The technique of combining the colors of a texture with the colors of the surface to which the texture is applied.
texture coordinates
The coordinates that determine which texel in each texture is assigned to each vertex in an object.
texture filtering
The process of mapping texel colors from one or more textures onto the pixels that comprise the image of a 3-D primitive.
texture mapping
The application of a texture to an object. Because a texture is a flat image and the object is often not, the texture must be mapped to the surface of the object, using texture coordinates and wrapping flags. See also texture coordinates and wrap.
thrashing
Removing textures used in the current frame to reclaim texture memory for subsequent frames.
throttling
Restricting the number of messages to avoid sending them faster than the underlying transport can deliver them.


U

unit vector
A vector with a magnitude (length) of 1.0.
USB
Universal serial bus.


V

VBI
Vertical blanking interval. In broadcast video, a small period of time that elapses between video frames during which a display device refreshes its display for the next frame.
velocity
In music, the speed at which a MIDI key is pressed. This is roughly equivalent to the dynamic level at which the note is played in some instrumental timbres.

In 3-D sound, for purposes of calculating Doppler shift, velocity is the speed at which a sound source or listener is considered to be moving.

vertex
A point in 3-D space.
video frame
A single image in a video stream, comprised of one odd field and one even field. See also field.
view space
See camera space.
view transformation
The application of a matrix to a model's vertices to change its orientation from world space to view space.
viewing frustum
A 3-D volume in a scene positioned relative to the viewport's camera. Objects within the frustum are visible. For perspective viewing, the viewing frustum is the volume of an imaginary pyramid that is between the front clipping plane and the back clipping plane. For orthographic viewing, the viewing frustum is cubic.
viewport
A rectangle that defines how a 3-D scene is rendered into a 2-D window. A viewport also defines an area on a device into which objects are rendered.
VREF
Vertical refresh. In a video stream, the VREF is active to signal that the display is to begin a new screen. See also HREF.


W

width
The distance between two addresses in memory that represent the beginning of a line and the end of the line of a stored bitmap. This distance represents only the width of the bitmap in memory. It does not include any extra memory required to reach the beginning of the next line of the bitmap, such as a cache in rectangular memory.
world coordinates
Coordinates that are relative to the origin of a scene. See also model coordinates and world space.
world space
The frame of reference, used by world coordinates, that declares vertices relative to a single origin within a 3-D scene.
world transformation
The application of a matrix to a model's vertices to change its orientation from model space to world space.
wrap
The procedure used to calculate texture coordinates for a face or mesh. The basic wrapping types are flat, cylindrical, spherical, and chrome.


Z

Microsoft DirectX 8.0 (C++)

X, Y, Z

z-buffer
A buffer that stores a depth value for each pixel in a scene. Pixels with a small z-value overwrite pixels with a large z-value.
z fighting
See flimmering.


Locator

Microsoft DirectX 8.0

Locator Object

Locator objects contain information about the tuning space. Locator objects are generally used by the Network Provider filter to help a tuner find and acquire the transport stream. Applications do not use Locator objects except possibly for debugging purposes.

Method or Property Name | Description
CarrierFrequency | Sets or retrieves the carrier frequency(DecaHertz).
Clone | Copies the Locator.
InnerFEC | Sets or retrieves the inner FEC type.
InnerFECRate | Sets or retrieves the inner FEC rate.
Modulation | Sets or retrieves the modulation type.
OuterFEC | Sets or retrieves the outer FEC type.
OuterFECRate | Sets or retrieves the outer FEC rate.
SymbolRate | Sets or retrieves the QPSK symbol rate.

Locator.CarrierFrequency Property

Locator Object

Carrier Frequency(DecaHertz).

Syntax

Locator.CarrierFrequency

Remarks

This property is read-write.

See Also

Locator.Clone Method

Locator Object

Copy the Locator.

Syntax

Locator.Clone(NewLocator);

Parameters

NewLocator paramDesc

Return Value

Remarks

See Also

Locator.InnerFEC Property

Locator Object

Inner FEC Type.

Syntax

Locator.InnerFEC

Remarks

This property is read-write.

See Also

Locator.InnerFECRate Property

Locator Object

Inner FEC Rate.

Syntax

Locator.InnerFECRate

Remarks

This property is read-write.

See Also

Locator.Modulation Property

Locator Object

Modulation Type.

Syntax

Locator.Modulation

Remarks

This property is read-write.

See Also

Locator.OuterFEC Property

Locator Object

Outer FEC Type.

Syntax

Locator.OuterFEC

Remarks

This property is read-write.

See Also

Locator.OuterFECRate Property

Locator Object

Outer FEC Rate.

Syntax

Locator.OuterFECRate

Remarks

This property is read-write.

See Also

Locator.SymbolRate Property

Locator Object

Sets or retrieves the QPSK symbol rate.

Syntax

Locator.SymbolRate

Remarks

This property is read-write. QPSK modulates symbols onto the RF signal. These symbols are detected by the demodulator and used to reconstruct a bit stream. QPSK allows the rate at which symbols are (de)modulated to be changed.

See Also


Reference Times

Microsoft® DirectShow® Editing Services (DES) uses two formats to specify reference times, REFERENCE_TIME values and REFTIME values.

  • REFERENCE_TIME: a LONGLONG (64-bit unsigned integer) value representing approximately 100 nanoseconds. (A nanosecond is 1 X 10-9 second, so one second is 1 X 107 or 10,000,000 units of reference time.)
  • REFTIME: a floating-point double value representing a fractional number of seconds.

Some methods take REFERENCE_TIME parameters; others take REFTIME parameters. In some cases, there are two different versions of a method, one for each type of reference time.


DVD Application Development in DirectShow

Microsoft® DirectShow® encapsulates the low-level complexity of DVD navigation in a component called the DVD Navigator source filter. The DVD Navigator has all the capabilities that you find on a full-featured stand-alone DVD player, plus additional capabilities specific to playing DVDs on personal computers. Using the DVD Navigator, C++ and scripting developers can create full-featured DVD player applications without referring to the DVD specification.

C++ developers control the DVD Navigator directly through the Component Object Model (COM) interfaces it exposes. Developers using a scripting language or Microsoft® Visual Basic® control the DVD Navigator indirectly through the MSWebDVD ActiveX® control.

Note DirectShow provides all the filters necessary to navigate and play DVD-Video except the MPEG-2 decoder. To play DVDs using an application based on DirectShow, users must have installed on their system a third-party hardware or software decoder that is DirectShow-compatible.

This section contains the following topics.

  • What Background Do I Need to Write a DVD Player Application?
  • DVD Navigation Topics
  • Writing a DVD Player Application in C++
  • DVD API Reference for C++ Applications
  • Writing a Script-Based DVD Player Application
  • MSWebDVD ActiveX Control API Reference


A

advise
A request for an asynchronous notification that a period of time has elapsed.
alpha
The measure of a pixel's opacity. A pixel with a maximum alpha value is opaque, one with a value of zero is transparent, and one with an intermediate value is translucent.
application notification
An event that the application retrieves from the event notification queue.
asynchronous reader filter
A file source filter that does no parsing on its own, but simply reads data from a media file.
ATR
Audio tape recorder.


B

backing object
In multimedia streaming, either the Microsoft® DirectDraw® surface for video or the IAudioData object for audio.
bi-phase mark
A method of encoding digital data such that clock timing and bit stream data are encoded into a square wave. Because it can be read over a wide range of play speeds, it is used for LTC signals (originally known as Manchester-1 code).
blackburst
A video signal that can be used to synchronize multiple video sources. Blackburst contains the vertical sync, horizontal sync, and the chroma burst information, but no active picture information.
blit
Bit block transfer. Used to transfer all or part of a bitmap from a source such as memory or the screen, to a destination such as another memory or display surface.
bob
A method of displaying interlaced video fields on a progressive monitor. In bob mode, one field is displayed at a time, the even lines alternating with the odd lines. The lines are stretched by a factor of two, to fit the entire display area.


C

chase mode
A mode of operation in video tape recorders and other transports, in which one or more devices are synchronized to a master device.
chroma burst
Provides color information about the active line of video to the color decoder.
codec
Compressor/decompressor.
color key
A value indicating the color to be used for transparent or translucent effects. When using a hardware blitter, for example, all of the pixels of a rectangular area are blitted except for the value that was set as the color key, thereby creating nonrectangular sprites on a surface.
composition
A collection of tracks and (optionally) other compositions. At rendering time, the sources in a composition are composited into a single image.
compression filter
A specialized type of transform filter that accepts data, uses a compression scheme to transform the data, and passes the compressed data downstream.


D

debug build
The largest and slowest type of build, but one that provides better facilities for debugging new code and tracking problems.
debug level
A DWORD value indicating the relative importance of a debug output, where zero is the most important level.
DIB sequence
A series of device-independent bitmap (DIB) images rendered in a sequence, as if they were successive frames in a video.
downsample
Decrease the number of samples or pixels, by applying an operation such as averaging.
downstream filter
The next filter in line to receive data from an upstream filter. The upstream filter sends data from its output pin to the connected input pin of the downstream filter.


E

edit decision list (EDL)
A list of items, called events, that describes a video sequence, audio sequence, or both, using SMPTE timecode to identify the video and audio source material.
effect filter
A filter that applies an effect to media data, but doesn't change the media type.
end-of-stream protocol
A protocol that defines how filters generate and process end-of-stream information and how the filter graph manager is notified.
error detection and reporting protocol
A protocol that defines how errors are handled by filters and propagated to the filter graph manager.
event notification
A system-defined event sent from a filter to the filter graph manager.


F

field
A portion of an interlaced video frame. With interlaced video, the scan lines of even-numbered fields fall spatially halfway between the scan lines of odd-numbered fields.
file writer
The section of a filter graph that consists of the multiplexer and file writer filters.
flushing protocol
A protocol that defines how filters flush data through the filter graph.
format type
A GUID indicating the contents of a format block.
frame blitting
Blitting (bit block transferring) media data to the client area of the application window on the primary surface.


G

gamma
The curve in the function that maps changes in voltage level to changes in brightness level on a phosphor display screen. The change in voltage level needed to produce a given change in brightness is not constant across voltage levels.
group
A top-level collection of compositions and tracks, all representing the same media type. Each group produces a separate stream in the rendered project.


H

hue
Color produced by visible light. The common color terms such as green, red, or orange refer to hue.


I

input pin
A pin that accepts data into the filter.
intelligent connect
Logic implemented by the Filter Graph Manager in calls to IGraphBuilder methods including Connect, Render, and RenderFile. This logic automates the graph building process by determining which filters are required to render a given file or output pin, or which intermediate filters are required in order to connect two specified pins.
instructing DirectShow to insert a set of filters between the source and renderer that will do the correct media type conversions.
interlace
Raster scan involving frames that are composed of two fields.
interleaving
The arrangement of corresponding video frames and audio samples in a file. Typically, one or more frames of video data are intermixed in the file with a certain number of samples of audio data. Interleaving affects playback efficiency and the ability to stream the file.
interpolation
A mathematical method that generates missing or needed information by estimating intermediate values between two known values in a sequence.


K

kernel mode
The processor mode that allows full, unprotected access to the system. A driver or thread running in kernel mode has access to system memory and hardware.
key frame
A frame of video data that contains all the data necessary to construct that frame. In contrast, delta frames contain data relating to changes from the last key frame and do not contain enough information by themselves to construct a complete frame.


L

latency
Of a filter, the amount of time it takes the filter to process a sample.
letterbox
Video display format in which the video is sized as large as possible inside the display window, without any cropping or stretching.
locked audio
A digital video format in which the number of audio samples in a frame follows a specific distribution. For example, in NTSC 48-kHz locked audio, frame 1 contains 1600 samples and frames 2–5 each contain 1602 samples. Unlocked audio allows the number of samples to vary, although the average must equal the stated sample rate.
lookahead
Using data from later in the stream to process the current data. (For example, using the next key frame to calculate a delta frame.)
LTC
Linear Timecode (formerly known as Longitudinal Timecode). Timecode is stored on a separate audio track and is one video frame time in duration.


M

major type
A GUID value that describes the overall class of media data for a data stream.
merit
A value that controls the order in which the filter graph manager tries to connect filters.
media sample protocol
A protocol that defines the way that media samples are allocated and passed between filters.
media time
A term used to refer to positions within a seekable medium. Media time can be expressed in a variety of units, and indicates a position within the data in the file.
medium
A medium identifies a hardware data path between devices on the host system. The path may be between two devices on the same internal card, for example between a crossbar and a tuner on a TV card, or it may be between two separate cards or external devices. When connecting pins on kernel-mode filters based on the Windows® Driver Model, mediums are used instead of media types when the connection is based on a particular data path provided in the hardware.
monotonic
Describes a sequence that never increases or never decreases. In a monotonically increasing sequence, each element is equal to or larger than the previous element. In a monotonically decreasing sequence, each element is equal to or less than the previous element.
multiplexer (MUX)
A filter that combines multiple input streams into one output stream.


N

new segment protocol
A protocol that defines a way to present start and stop times and data rate information to the filter in advance of the data, so that a filter can adjust its processing accordingly.
NTSC
National TV Systems Committee analog composite color television standard. Uses a rate of 29.97 frames per second and 59.94 fields per second. North America, Japan, and many other countries use NTSC.


O

output pin
A pin that provides data to other filters.


P

PAL
Analog composite color television standard, with a rate of 25 frames per second, and 50 fields per second. Much of Europe, Australia, and other parts of the world use PAL.
pan-scan
DVD-Video display format in which a 16 × 9 video is cropped for display in a 4 × 3 window, using parameters defined by the video author.
parser filter
A filter that pulls information from a disk by using the asynchronous file reader filter, or from the Internet by using the URL moniker filter.
periodic advise
A regular series of advise calls.
pixel doubling
Scaling an image by a factor of two.
plug-in distributor (PID)
An object that exposes a control interface and implements it by enumerating the filters in the filter graph, finding which filters expose the same interface, and communicating directly with those filters.
preroll
The queuing of data in advance of the desired playback time or position.
preroll time
The time prior to the start position at which nonrandom access devices should start rolling.
presentation time
The stream time at which the packets of data that a filter receives should be presented downstream or rendered.
preview section
The portion of the filter graph from the capture filter's preview pin downstream to and including the video renderer.
primary surface
The area in memory containing the image being displayed on the monitor. In Microsoft® DirectX®, the primary surface is represented by the primary DirectDrawSurface object.


Q

quality control
A mechanism for adjusting the rate of data flow in response to run-time conditions.
quality sink
An object designated to receive quality control messages.


R

reference clock
An object that provides a clock and supports the scheduling of events in the filter graph.
reference time
An absolute time established by a reference clock in the filter graph.
REFTIME
A floating-point value of type double that represents a number of seconds.
renderer
A filter that renders media data to some location, such as a computer monitor, a sound card, or a file.
retail build
The smallest and fastest type of build. Generally less robust than a debug build.


S

saturation
Color purity. A completely pure color has 100 percent saturation. The less saturation, the closer the color appears to gray.
SECAM
Analog composite color television standard, with a rate of 25 frames per second, and 50 fields per second. Much of Europe, Australia, and other parts of the world use SECAM.
seekable renderer
A renderer that reports EC_COMPLETE when all seekable streams on that filter have reached the end of the stream.
servo
The electromechanical system that maintains the proper speed and phase of a VCR's video head and tape transport.
sink file
The current file into which media samples will be written.
source filter
A filter that takes data from some source such as the hard drive, network, or the Internet, and introduces it into the filter graph.
smart recompression
Decompressing and recompressing a source file only when its format does not match the output format.
stream notification
An event that occurs in the media stream and is passed from one filter to the next.
stream time
The time since the filter graph was last started. By definition, stream time equals reference time minus the previous start time. Stream time is relevant only in a running filter graph.
subtype
A GUID value that describes the specific format of media data for a data stream. Also called minor type.
synchronization point
A media sample that can be decoded without examining any other samples. For example, a key frame.


T

tearing
A visual rip effect that occurs when one displayed video frame contains parts of two different source video frames. It is usually caused by improper synchronization between video rendering and the graphics display.
time stamp
Time on a media sample indicating when it was recorded and when it should be scheduled for playback. Time stamps are measured in 100-nanosecond units (REFERENCE_TIME) and are normalized so that zero indicates when the graph is run.
timecode
A series of digital frame address values, flags, and additional data applied to a video or audio stream; defined in ANSI/SMPTE 12-1986. Its purpose is to provide a machine-readable address for video and audio. Also called SMPTE timecode.
timeline
The root node in a video editing project; the container for all the other objects in the project.
track
A collection of nonoverlapping sources with a uniform media type (audio or video).
transform filter
A filter that takes data, processes it, and then passes it along to the next filter in the filter graph.
transform-inplace filter
A transform filter that can perform its operation in place (without copying data or altering the data's media type).
transport
The mechanism that channels audio data, video data, or both from an external device to the computer and from the computer to the external device.


U

upsample
Increase the number of samples or pixels, by applying an operation such as interpolation.
upstream filter
The filter that passes data from its output pin to the connected input pin of the next filter in the filter graph.
URL moniker filter
A source filter that reads from an Internet server.
userbits
Undefined bits in the SMPTE timecode. These bits can be used for any information the user wants to encode, so that it travels with the source material throughout the post-production process. Often, userbits contain original film and audio tape information.


V

VITC
Vertical Interval Timecode. Timecode information stored in a video signal's vertical blanking interval. It is usually located on one or two lines somewhere between lines 10 and 20.
vertical blanking interval
A synchronizing period in the video signal when no active picture information is transmitted.
virtual track
An object that can act as a track within a composition. Compositions and tracks are virtual tracks.
VPE
Video port extensions. Extensions to the Microsoft® DirectDraw® application programming interface (API) to control the video stream from the video port, within the context of VGA memory.
VTR
Video tape recorder.


W

weave
A method of displaying interlaced video fields on a progressive monitor. In weave mode, two successive fields are displayed at a time. The horizontal scan lines alternate between the two fields.
white balance
Adjustment of the color levels in an image so that white areas in the original image display correctly as white.


GLOSSARY HEAD

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z


CDisp Class

CDisp class hierarchy

The CDisp class provides methods for displaying a number of data types for debugging. It provides a constructor for each type, and can be cast to the LPCTSTR type for use as a string in a debug statement.

For example, the following code fragment:

int MyFunc(REFERENCE_TIME rt, IPin *pPin)
{
    DbgLog((LOG_TRACE, 2, TEXT("MyFunc(%s, %s)"),
        (LPCTSTR) CDisp(CRefTime(rt)),
        (LPCTSTR) CDisp(pPin)));
...
}

could output the following reference time and pin information onto the debug log:

Quartz.dll(tid d7) : MyFunc(1.003 sec,
    CLSID_AudioRender(Audio Input pin (rendered)))

Member Functions

CDisp Constructs a CDisp object.

Operators

LPCTSTR Casts to an LPCTSTR type for use in a debug string.

CDisp::CDisp

CDisp Class

Constructs a CDisp object.

Syntax

CDisp(
    LONGLONG ll,
    int Format = CDISP_HEX
    );
CDisp(
    REFCLSID clsid
    );
CDisp(
    double d
    );
CDisp(
    CRefTime t
    );
CDisp(
    IPin *pPin
    );

Parameters

ll
LONGLONG value for display.
Format
Value indicating whether the value should be displayed in decimal (CDISP_DEC) or (by default) hexadecimal (CDISP_HEX).
clsid
Class identifier to display.
d
The double value to display.
t
Reference time to display. Passing a value of type REFERENCE_TIME will use the LONGLONG constructor.
pPin
Pointer to the IPin interface to display a pin as "CLSID of the filter(Pin name)"; for example, CLSID_AudioRenderer(Audio input pin).

Return Value

No return value.

Remarks

Various constructors are provided, which enables information to be displayed in the most suitable way.

CDisp::LPCTSTR

CDisp Class

Casts the CDisp object to an LPCTSTR value for use in a debug string.

Syntax

operator LPCTSTR();

Return Value

Returns the string representation of the variable used in the constructor.


CDispBasic

CDispBasic class hierarchy

CDispBasic is an internal class used to implement the CDisp class.

Protected Data Members

m_PString | Points to the string to be displayed. Initially, this points to m_String, but larger strings might cause this to be updated to point to dynamically-allocated storage instead.
m_String[50] | Initial buffer area for this object.

Member Functions

CDispBasic Constructor for the CDispBasic class.

CDispBasic::CDispBasic

CDispBasic

Instantiates an object of this class.

Syntax

CDispBasic( );


DirectShow File Writer Filter

Writes files to disk when capturing video or authoring files.

Filter Interfaces | IAMFilterMiscFlags, IBaseFilter, IFileSinkFilter, IFileSinkFilter2, IMediaSeeking, IPersistStream
Input Pin Media Types | MEDIATYPE_Stream
Input Pin Interfaces | IMemInputPin, IPin, IQualityControl, IStream
Output Pin Media Types | Not applicable.
Output Pin Interfaces | Not applicable.
Filter CLSID | CLSID_FileWriter
Property Page CLSID | No property page.
Executable | quartz.dll
Merit | MERIT_DO_NOT_USE
Category | CLSID_LegacyAmFilterCategory

Remarks

Video Capture devices that capture an Audio/Video stream to disk using DirectShow use the DirectShow File Writer filter to write to the disk.


IConfigAsfWriter Interface

The IConfigAsfWriter interface is implemented by the DirectShow ASF Writer filter and provides methods for getting and setting the Advanced Streaming Format (ASF) profiles the filter will use to write files.

When the ASF Writer filter is created, it is configured automatically with a default ASF audio-visual profile based on the incoming streams. A profile describes various attributes of an ASF file such as bit rate, number and type of streams, compression quality, and so on. The filter uses the profile to determine what kind of ASF file to write, how many input pins it must set up, and what media types they can accept. In most cases, the default profile should be suitable, but if it is not, an application can modify it using the filter's IConfigAsfWriter interface methods. For full details on ASF profiles, see the Microsoft® Windows Media™ Software Development Kit (SDK).For more information on how to write ASF files, see Creating ASF Files in DirectShow.

Requirements

Requires Dshowasf.h, Windows Media Format SDK.

Methods in Vtable Order

IUnknown methods | Description
QueryInterface | Retrieves pointers to supported interfaces.
AddRef | Increments the reference count.
Release | Decrements the reference count.
IConfigAsfWriter methods | Description
ConfigureFilterUsingProfileId | Configures the filter to write an ASF file with a profile identifier (ID) index from the system profile list. (For Windows Media Format 4.0 profiles only.)
GetCurrentProfileId | Retrieves the current ASF profile ID. (For Windows Media Format 4.0 profiles only.)
ConfigureFilterUsingProfileGuid | Configures the filter to write an ASF file based on the specified predefined Windows Media Format SDK profile GUID.
GetCurrentProfileGuid | Retrieves the current ASF profile GUID defined by the Windows Media Format SDK.
ConfigureFilterUsingProfile | Configures the filter to write an ASF file based on the specified application-defined profile.
GetCurrentProfile | Retrieves the application-defined ASF profile.
SetIndexMode | Enables the application to control whether the file will be indexed and therefore seekable.
GetIndexMode | Retrieves the current index mode.

IConfigAsfWriter::ConfigureFilterUsingProfile

IConfigAsfWriter Interface

Configures the filter to write an ASF file based on the specified application-defined profile.

Syntax

HRESULT ConfigureFilterUsingProfile(
  IWMProfile *pProfile
);

Parameters

pProfile
[in] IWMProfile interface pointer to the application-defined profile.

Return Value

Returns one of the following values.
S_OK | Success.
VFW_E_WRONG_STATE | The graph is stopped.
E_POINTER | The IWMProfile interface pointer is invalid.

Remarks

IWMProfile is defined in the Windows Media Format SDK.

If successful, this method will cause an EC_GRAPH_CHANGED event notification to be sent to the application.

IConfigAsfWriter::ConfigureFilterUsingProfileGuid

IConfigAsfWriter Interface

Configures the filter to write an ASF file based on the specified predefined profile.

Syntax

HRESULT ConfigureFilterUsingProfileGuid(
  REFGUID guidProfile
);

Parameters

guidProfile
[in] Profile GUID as defined in the Windows Media Format SDK header file Wmsysprf.h.

Return Value

Returns one of the following values.
S_OK | Success.
E_FAIL | The profile is invalid.
VFW_E_WRONG_STATE | The filter graph is stopped.

IConfigAsfWriter::ConfigureFilterUsingProfileId

IConfigAsfWriter Interface

Configures the filter to write an ASF file with a profile identifier (ID) index from the system profile list. (For Windows Media Format 4.0 profiles only.)

Syntax

HRESULT ConfigureFilterUsingProfileId(
  DWORD dwProfileId
);

Parameters

dwProfileId
[in] Profile ID as defined in the Windows Media Format SDK.

Return Value

Returns one of the following values.
S_OK | Success.
E_FAIL | The profile is invalid.
VFW_E_WRONG_STATE | The filter graph is stopped.

Remarks

This method is now obsolete because it assumes version 4.0 Windows Media Format SDK profiles. To configure the filter for version 7.0 and later profiles, use ConfigureFilterUsingProfile or ConfigureFilterUsingProfileGuid.

IConfigAsfWriter::GetCurrentProfile

IConfigAsfWriter Interface

Retrieves the application-defined ASF profile.

Syntax

HRESULT GetCurrentProfile(
  IWMProfile **ppProfile
);

Parameters

ppProfile
[out] Address of a pointer that receives the IWMProfile interface of the application-defined profile.

Return Value

Returns S_OK if successful, or an HRESULT error code otherwise.

Remarks

If the method succeeds, the IWMProfile pointer that it returns has an outstanding reference count. Be sure to release the interface when you are finished using it.

IConfigAsfWriter::GetCurrentProfileGuid

IConfigAsfWriter Interface

Retrieves the current ASF profile ID.

Syntax

HRESULT GetCurrentProfileGuid(
  GUID *pProfileGuid
);

Parameters

pProfileGuid
[out] Pointer to a variable of type GUID that receives the profile ID.

Return Value

Returns S_OK if successful, or an HRESULT error code otherwise.

IConfigAsfWriter::GetCurrentProfileId

IConfigAsfWriter Interface

Retrieves the current ASF profile ID. (For Windows Media Format 4.0 profiles only.)

Syntax

HRESULT GetCurrentProfileId(
  DWORD *pdwProfileId
);

Parameters

pdwProfileId
[out] Pointer to a variable of type DWORD that receives the current profile ID.

Return Value

Returns S_OK if successful, or an HRESULT error code otherwise.

Remarks

This method is now obsolete because it assumes version 4.0 Windows Media Format SDK profiles. Use GetCurrentProfile or GetCurrentProfileGuid instead to correctly identify a profile for version 4.0, 7.0 and later.

IConfigAsfWriter::GetIndexMode

IConfigAsfWriter Interface

Retrieves the current index mode.

Syntax

HRESULT GetIndexMode(
  BOOL *pbIndexFile
  );

Parameters

pbIndexFile
[out] Pointer to a variable of type BOOL that receives the index mode setting. A value of TRUE indicates that the ASF Writer is configured to write indexed files.

Return Value

Returns S_OK if successful, or an HRESULT error code otherwise.

Remarks

Use this method to determine whether the ASF Writer is currently configured to write indexed ASF files. See the Remarks for SetIndexMode for more information.

IConfigAsfWriter::SetIndexMode

IConfigAsfWriter Interface

Enables the application to control whether the file will be indexed and therefore seekable.

Syntax

HRESULT SetIndexMode(
  BOOL bIndexFile
);

Parameters

bIndexFile
[in] Variable of type BOOL; TRUE specifies that the file will be indexed.

Return Value

Returns S_OK if successful, or an HRESULT error code otherwise.

Remarks

By default, the ASF Writer creates indexed ASF files. It performs the indexing when the graph stops. You can disable this behavior if you want to do your own indexing as a post-processing step.


DVD_AudioAttributes Structure

Structures

The DVD_AudioAttributes structure is used in IDvdInfo2::GetAudioAttributes to receive the various audio attributes of the disc.

Syntax

typedef struct tagDVD_AudioAttributes
{
    DVD_AUDIO_APPMODE   AppMode;
    DVD_AUDIO_FORMAT    AudioFormat;
    LCID                Language;
    DVD_AUDIO_LANG_EXT  LanguageExtension;
    BOOL                fHasMultichannelInfo;
    DWORD               dwFrequency;
    BYTE                bQuantization;  0 is unknown
    BYTE                bNumberOfChannels;
    DWORD               dwReserved[2];
} DVD_AudioAttributes;

Members

AppMode
Indicates the current audio mode. If the mode returned is DVD_AudioMode_Karaoke, call IDvdInfo2::GetKaraokeAttributes to get more info.
AudioFormat
Describes the format (encoding mode) of the audio stream.
Language
An LCID value indicating the language of the audio stream. Will be zero if no language is present.
LanguageExtension
A DVD_AUDIO_LANG_EXT enumeration that will be filled in if any information is available on the disc.
fHasMultichannelInfo
Indicates whether multichannel attributes are present. If TRUE, it means there is additional mixing information available, such as for SurroundSound. Call IDvdInfo2::GetTitleAttributes to retrieve the multichannel information.
dwFrequency
The frequency in hertz (48k, 96k) of the audio stream.
bQuantization
The resolution of the audio stream (16, 20, 24 bits, etc.) Zero indicates the resolution is unknown.
bNumberOfChannels
The number of channels. For example, 5.1 Dolby AC-3 has six channels.
dwReserved
Currently not used.


Performance Macros

The Measure.h header file in the Microsoft® DirectShow® base classes provides macros that help record performance data by maintaining a circular log of the start and stop times of certain events.

MSR_START | Records the start time of the event.
MSR_STOP | Records the stop time of the event.

MSR_START

Performance Macros

Records the start time of the event with the given registered ID by adding the start time to the circular log and recording the time in StatBuffer.

Syntax

#define MSR_START(
  int Id
  )

Parameters

Id
Registered ID of the event whose start is to be recorded.

Remarks

This macro does not update the statistical information. That happens when MSR_STOP is called.

MSR_STOP

Performance Macros

Records the stop time of the event with the given registered ID by adding the stop time to the circular log, and adding a StopTime-StartTime entry to the statistical record StatBuffer.

Syntax

#define MSR_STOP(
  int Id
  )

Parameters

Id
Registered ID of the event whose stop is to be recorded.


Stream Integer Functions

The Pstream.h header file in the Microsoft® DirectShow® base classes contains a set of stream integer functions. These functions encode an integer in a stream object as 11 Unicode™ characters followed by one Unicode space. The interface to these functions might truncate to 32 bits. Values such as (unsigned) 0x80000000 would be written as -2147483648, but would still load as 0x80000000 again through ReadInt.

ReadInt | Reads a Unicode string-encoded integer from a stream.
WriteInt | Writes an integer to a stream encoded as a Unicode string.

ReadInt

Stream Integer Functions

Reads an integer from an IStream.

Syntax

STDAPI_(
  int
  )ReadInt(
  IStream *pIStream,
  HRESULT &hr
  );

Parameters

pIStream
Pointer to an IStream from which the encoded integer is to be read.
hr
Reference to an HRESULT value (output).

Return Value

Returns the integer value (truncated to 32 bits), or zero if an error occurred.

Remarks

This function is a stripped-down subset of what sscanf can do, without requiring the overhead of the complete C run-time library.

The ReadInt function can be used to read the value written by WriteInt.

WriteInt

Stream Integer Functions

Writes an integer to an IStream, encoded as described in Stream Integer Functions.

Syntax

STDAPI WriteInt(
  IStream *pIStream,
  int n
  );

Parameters

pIStream
Pointer to an IStream to which the encoded integer is to be written.
n
Integer value to be written.

Return Value

Returns an HRESULT value.

Remarks

The ReadInt function can be used to read the value written by WriteInt.


Requirements

Many topics that introduce the syntax of an API element contain information about the build and run-time requirements for using the element. The format is as follows:

Windows NT/2000: Requires Windows NT 3.1 or later.
Windows 95/98: Requires Windows 95 or later.
Windows CE: Requires version 1.0 or later.
Header: Declared in winuser.h.
Import Library: Use user32.lib.
Unicode: Implemented as Unicode and ANSI versions on Windows NT/2000.

The first line indicates the versions of Windows NT on which an element is supported. This information may include required service packs, option packs, or components such as Internet Explorer. If an element is not supported, the line reads "Windows NT/2000: Unsupported."

The second line indicates whether an element is supported on Windows 95 or Windows 98. This information may include required OEM service releases, redistributables, or components such as Internet Explorer. If an element is not supported, the line reads "Windows 95/98: Unsupported."

The third line indicates the versions of Windows CE on which an element is supported. If an element is not supported, the line reads "Windows CE: Unsupported."

The fourth line indicates the file that defines an element. This value can be an .h file, .idl file, or .odl file. If the header file is supplied by the user, the line reads "Header: User-defined."

The fifth line indicates the file used to resolve calls to a function or member. This value can be a .lib file, .dll file, or .tlb file. If the import library is supplied by the user, the line reads "Import Library: User-defined." For element types that do not require an import library, this line is omitted.

The sixth line indicates whether an element exists as both a Unicode (W) version and an ANSI (A) version. If Unicode support is not available, this line is omitted.


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

    Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

    Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

    Remedy: Insert the MSDN Library CD into the CD-ROM drive.

Built on Friday, July 28, 2000